C program — coding the figure given n when n is odd? - c

I have to display the following figure (The two triangles intercept) for a n given by the user, where n is odd. The figure is in this link: http://i.imgur.com/mQxarLz.jpg
*******
*****
***
*
*
***
*****
*******
I already wrote this code, but I don't know how to give the n, where n is odd. And my code doesn't compile; it says: "In the fifth row, syntax error before for".
#include <stdio.h>
int main (void) {
int n,i,k,m;
for(m=0;m<2;m++)
for (i=1;i<=n;i++){
if(m==0){
for(k = 1; k<=n-i; k++){
printf(" ");
}
}
}
for (k=1;k<2*i;k++){
printf("%s","*");
//printf("%d",i);
}
scanf("%d",&n);
for (k = 1; k<=i;k++)
for (k=1;k<(n-i)*2;k++)
for (i=1;i<=n;i++) {
printf("\n$");
}
return 0;
}

First, the answer to "how do I check whether an integer is odd": you simply divide by 2 and check if the remainder is 0 (even) or 1 (odd). In C and most related languages, this is what the modulo operator "%" does:
if ((n % 2) == 1) {
// The number is odd.
}
But you should make sure that you read your n right at the start, because in the code that you have submitted, n is read in your second "for" loop before you have actually written something to it. And that means, n contains garbage at that point.

Good programming is to solve problems in the most simple way you can find. This particular algorithm is really fundamental stuff, thus you shouldn't end up with anything much more complicated than this:
#include <stdio.h>
#include <stdbool.h>
void print_chars (char symbol, int n)
{
for(int i=0; i<n; i++)
{
printf("%c", symbol);
}
}
void print_triangle (int base_size, int height, bool pointing_up)
{
int star_count = pointing_up ? 1 : base_size;
for(int row = 0; row < height; row++)
{
int spaces = base_size - star_count;
print_chars (' ', spaces/2);
print_chars ('*', star_count);
print_chars (' ', spaces/2);
printf("%\n");
star_count += pointing_up ? 2 : -2;
}
}
int main (void)
{
print_triangle(7, 4, false);
print_triangle(7, 4, true);
}
Note that the above code will behave strange if the triangle's base isn't in sync with its height - I left that out intentionally, feel free to improve the program further with such.

#include <stdio.h>
void printAsterisk(int n, int length){
int i, slen = (length - n)/2;
for(i=0;i < slen;++i)
putchar(' ');
for(i=0;i < n;++i)
putchar('*');
putchar('\n');
}
/* non-recursive
void printTriangle(int n, int length){//n isn't required as an argument
int d= -2;
for(; n < length + 1; n += d){
if(n < 0) n += (d *= -1);
printAsterisk(n, length);
}
}
*/
void printTriangle(int n, int length){
if(n < 1) return;
printAsterisk(n, length);
printTriangle(n - 2, length);
printAsterisk(n, length);
}
int main(void){
int n;
do{
printf("input odd number:");
scanf("%d", &n);
}while(n % 2 == 0);
printTriangle(n, n);
return 0;
}

Related

The fastest and most efficient way to find the number of distinct elements of a 1D array

So I'm very new to programming and the C language, and I would like to find the simplest, fastest, and most efficient way to count all the distinct elements of a 1D array. This was actually for a school assignment, but I've been stuck on this problem for days, since my program was apparently too slow for the online judge and it got a TLE. I've used regular arrays and dynamically allocated arrays using malloc, but neither worked.
Anyways, here's the latest code of it(using malloc):
#include <stdio.h>
#include <stdlib.h>
int distinct(int *arr, int N){
int j, k, count = 1;
for(j = 1; j < N; j++){
for(k = 0; k < j; k++){
if(arr[j] == arr[k]){
break;
}
}
if(j == k){
count++;
}
}
return count;
}
int main(){
int T, N, i = 0;
scanf("%d", &T);
do{
scanf("%d", &N);
int *arr;
arr = (int*)malloc(N * sizeof(int));
for(int j = 0; j < N; j++){
scanf("%d", &arr[j]);
}
int count = distinct(arr, N);
printf("Case #%d: %d\n", i + 1, count);
i++;
}while(i < T);
return 0;
}
The most efficient way depends on too many unknown factors. One way is to sort the array and then to count distinct elements in there, skipping the duplicates as you go. If you have sorted the array and gotten this:
1 1 1 1 2 2 2 2 3 3
^ ^ ^
+-skip--+-skip--+-- end
... you can easily see that there are 3 distinct values in there.
If you don't have a favourite sorting algorithm handy, you could use the built-in qsort function:
void qsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
Example:
#include <stdio.h>
#include <stdlib.h>
int compar(const void *l, const void *r) {
const int* lhs = l;
const int* rhs = r;
if(*lhs < *rhs) return -1; // left side is less than right side: -1
if(*lhs > *rhs) return 1; // left side is greater than right side: 1
return 0; // they are equal: 0
}
int distinct(int arr[], int N){
// sort the numbers
qsort(arr, N, sizeof *arr, compar);
int count = 0;
for(int i=0; i < N; ++count) {
int curr = arr[i];
// skip all numbers equal to curr as shown in the graph above:
for(++i; i < N; ++i) {
if(arr[i] != curr) break;
}
}
return count;
}
int main() {
int T, N, i = 0;
if(scanf("%d", &T) != 1) return 1; // check for errors
while(T-- > 0) {
if(scanf("%d", &N) != 1) return 1;
int *arr = malloc(N * sizeof *arr);
if(arr == NULL) return 1; // check for errors
for(int j = 0; j < N; j++){
if(scanf("%d", &arr[j]) != 1) return 1;
}
int count = distinct(arr, N);
free(arr); // free after use
printf("Case #%d: %d\n", ++i, count);
}
}

Printing pascal's triangle in C

I have to print the pascal's triangle given a certain number of levels desired. The max levels that will be asked for is 28. I am able to print the some of the rows correctly but then it starts printing negative numbers in the rest of my rows. I can't figure out why, help would be much appreciated!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
char pascalTriangle[28][28];
for (int k = 1; k <= numLevels; ++k) {
for (int i = 0; i < k; ++i) {
int val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %d", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}
Change char pascalTriangle[28][28]; to int pascalTriangle[28][28];. You're going over the max char value so it goes to negative.
There is no "array" type, only a collection of pointers. You can also change char to short, long, etc.
Also, change k <= numLevels to k < numLevels. This prevents the segmentation fault. To fix the logic, you have to change for(int i = 0; to for(int i = -1;
The fixed code is:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void printTriangle() {
int numLevels;
printf("Please enter how many levels of Pascal's Triangle you would like to see: ");
scanf("%d", &numLevels);
long long pascalTriangle[28][28];
for (int k = 0; k < numLevels; ++k) {
for (int i = -1; i < k; ++i) {
long long val = (i == 0) || (i == k - 1) ? 1 : (pascalTriangle[k-1][i-1] + pascalTriangle[k-1][i]);
pascalTriangle[k][i] = val;
printf(" %lld", val);
}
printf("\n");
}
}
int main() {
printTriangle();
}

How to change iterations to recursion [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I've got a problem. I've tried to write program. This is command:
The user specifies a whole number n>0.
Program:
Allocates two arrays of numbers of type int size n+1
Using only these arrays and a small number of statically allocated variables, the program calculates recursively the n line of the Pascal triangle (all binomial symbols with an upper parameter equal to n)
Prints out the calculated values
Memory slowing down
Example
input: 5
output: 1 5 10 10 5 1
I wrote iteration, but I have no idea how change this for recursion.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,k;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0') printf("%d", 1);
if(n=='1') printf("%d %d", 1, 1);
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = 1;
array_1[1] = 1;
k=1;
while(k!=n)
{
for(i=0; i<=k+1; i++)
{
if(i==0)
{
array_2[0] = 1;
}
else if(i==n)
{
array_2[i] = 1;
}
else
{
array_2[i] = array_1[i] + array_1[i-1];
}
}
for(i=0; i<=n; i++)
{
array_1[i] = array_2[i];
array_2[i] = 0;
}
k++;
}
for(i=0; i<=n; i++)
{
printf("%d ", array_1[i]);
}
free(array_1);
free(array_2);
return 0;
}
The recursive version could look something like the following, with the actual work being left to fill-in under the two /* ... */ comments. The missing code essentially exists in the iterative version as posted, it just needs to be retrofitted here.
void recurse(int k, int n, int *array_1, int *array_2)
{
/*
print previously calculated k-th row in array_1
*/
// nothing left to do
if (k == n + 1) return;
/*
calculate next (k+1)-th row in array_2
*/
// swap arrays and repeat
recurse(k + 1, n, array_2, array_1);
}
int main()
{
int n, *array_1, *array_2;
if(scanf("%d", &n) != 1) return 1; // input error
if (n < 0) return 1; // invalid input
array_1 = (int*)calloc(n + 1, sizeof(int));
array_2 = (int*)calloc(n + 1, sizeof(int));
array_1[0] = 1;
recurse(1, n, array_1, array_2);
free(array_1);
free(array_2);
return 0; // done
}
Thanks everyone for answer :). This is my code:
#include <stdio.h>
#include <stdlib.h>
void recurse (int k, int n, int *array_1, int *array_2)
{
int i;
if(k==n+1) return;
for(i=1; i<=k+1; i++) array_2[i] = array_1[i] + array_1[i-1];
recurse(k+1, n, array_2, array_1);
}
void output(int n, int *array_1, int *array_2)
{
int i;
if(n%2!=0)
for(i=0; i<=n; i++) printf("%d ", array_1[i]);
else
for(i=0; i<=n; i++) printf("%d ", array_2[i]);
}
int main()
{
int n;
int * array_1;
int * array_2;
scanf("%d",&n);
if(n=='0')
{
printf("%d", 1);
return 0;
}
else if(n=='1')
{
printf("%d %d", 1, 1);
return 0;
}
array_1 = (int*)calloc(n+1,sizeof(int));
array_2 = (int*)calloc(n+1,sizeof(int));
array_1[0] = array_1[1] = array_2[0] = 1;
recurse(1, n, array_1, array_2);
output(n, array_1, array_2);
free(array_1);
free(array_2);
return 0;
}

C program shows different result in Linux and online compiler

I wrote a program in C to arrange the data in ascending order. When I compiled the code it showed no error but when it runs it shows a very different result than expected. However, when I ran the code in online C compiler it shows the correct result. I entered 5 different numbers 2 ,3 ,1 ,5 ,4.
Result in Linux: 0 1 2 3 4
Result in online compiler: 1 2 3 4 5
Why is this happening?
#include<stdio.h>
int * array(int x[],int l){
int i,j,k;
for(i=0;i<l;i++){
for(j=0;j<l;j++){
if(x[j]>x[j+1]){
k=x[j];
x[j]=x[j+1];
x[j+1]=k;
}
}
}
return x;
}
void main(){
int i,n;
int *b;
printf("enter n\n");
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
scanf("%d",&a[i]);
b=array(a,n);
printf("the ascending order is: ");
for(i=0;i<n;i++){
fflush(stdout);
printf("%d\t",b[i]);
}
}
Your code accesses memory beyond your array:
for(j=0;j<l;j++){
if (x[j] > x[j + 1]) {
x[j] = x[j + 1];
x[j + 1] = k;
In your case, when n = 5, you allocate the array for 5 elements with indices 0,1,2,3,4. The latest element of the array is x[4]. But when your code runs and j == l-1, you try to compare and even modify the element x[5]. In fact, your program should crash as it tries to access the "unallocated" memory. But probably because of aligning, the "x[5]" addresses the allocated memory. And, probably, x[5] = 0 on your computer, and your algorithm uses this element as a part of the sorting process. So your function array() returns the array of [0,1,2,3,4,5] and then your main() prints first five elements of this array.
That's why you've got sorted elements [0,1,2,3,4] instead of [1,2,3,4,5].
BTW, the bubble algorithm can be optimized to not touch already sorted elements.
Also, remember the array doesn't copy to pass into the function, the array always passes by its address, so it is not needed to "return" the modified array.
So, the final code can look like:
#include <stdio.h>
void array(int x[], int l)
{
int i, j, k;
for (i = l; i > 1; i--) {
for (j = 1; j < i; j++) {
if (x[j - 1] > x[j]) {
k = x[j - 1];
x[j - 1] = x[j];
x[j] = k;
}
}
}
}
void main()
{
int i, n;
printf("enter n\n");
scanf("%d", &n);
int a[n];
for (i = 0; i < n; i++)
scanf("%d",&a[i]);
array(a, n);
printf("the ascending order is:");
for (i = 0; i < n; i++) {
printf(" %d", a[i]);
fflush(stdout);
}
printf("\n");
}
Of course, there are lots of things to be done in this code, like human-readable variables, formatting, further optimization. But I hope you can do it yourself.
You may find it easier to write programs to get their input from the command line instead of prompting for it. Using C11, you can allocate an array using the length provided by argc, and process the argv array directly:
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] ) {
if( argc == 1 ) {
errx(EXIT_FAILURE, "syntax: %s values...", argv[0]);
}
int a[argc - 1];
for( int i=0; i < argc-1; i++ ) {
if( 1 != sscanf(argv[i + 1], "%d", a + i) ) {
errx(EXIT_FAILURE, "could not scan '%s'", argv[i + 1]);
}
}
array(a, sizeof(a)/sizeof(a[0]));
printf("the ascending order is:");
for (i = 0; i < n; i++) {
printf(" %d", a[i]);
fflush(stdout);
}
printf("\n");
}

Problems printing out this star shape

While practicing I came across an assignment that required me to write a code which would print out the following shape:
https://postimg.cc/hJ7Hc72W
I tried a method where I had two for loops. I know the basic guidelines when it comes to printing star shapes but I simply can't complete this one. Whatever I do, I can just print out the left portion of the shape(the left pyramid) but the right one ends up being "warped".
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n,i,j;
printf("Enter n: ");
scanf("%d", &n);
int length=2*n-1, width=2*n+1;
for(i=0; i<length; i++) {
for(j=0; j<width; j++) {
//The left side of the "||" separated condition prints the left pyramid,
// while the right side of the "||" should print out the right pyramid
if( (i>=j && i<=length-1-j) || (i<=j && i>=length-1-j) )
printf("*");
else printf(" ");
}
printf("\n");
}
return 0;
}
However, what I end up with is always this: https://postimg.cc/628SY4G1
Any idea where I might be wrong? Thanks so much!
Instead of looping over everywhere and filtering to determine which character to print (as you have noticed, this is surprisingly tricky to get right), break the figure down into sections.
Start with printing a single line, width wide and with stars stars.
This can be done with three loops:
void print_line(int width, int stars)
{
for (int i = 0; i < stars; i++)
printf("*");
for (int i = 0; i < width-2*stars; i++)
printf(" ");
for (int i = 0; i < stars; i++)
printf("*");
printf("\n");
}
Then write a loop for the top n-1 lines and a loop for the bottom n-1 lines, with one full-width line inbetween:
int width = 2*n+1;
for (int i = 1; i <= n-1; i++)
print_line(width, i);
print_line(width, n);
for (int i = n-1; i >= 1; i--)
print_line(width, i);
This way works:
#include <stdio.h>
int main()
{
int n,i,j,k;
printf("Enter n: ");
scanf("%d", &n);
int length=2*n-1;
int reqd_no_of_stars;
for(i=0; i<=length; i++)
{
if(length+1-i<i)
{
reqd_no_of_stars=length+1-i;
}
else
{
reqd_no_of_stars=i;
}
for(k=0; k<reqd_no_of_stars; k++)
printf("*");//print left set of stars equal to the number of reqd_no_of_stars
for(k=0; k<(2*n+1)-2*reqd_no_of_stars; k++)
printf(" ");//print required spaces=total_width-required_width_for_stars=((2*n+1)-2*reqd_no_of_stars) in between stars of both sides
for(k=0; k<reqd_no_of_stars; k++)
printf("*");//print right set of stars equal to the number of reqd_no_of_stars
printf("\n");
}
return 0;
}
If you structure your code, you'll have very little problem in painting the ties:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static const char AST[] = "**********";
static const char BLK[] = " ";
void paint_line(const char *s, int n)
{
int l = strlen(s);
while (n >= l) {
fputs(s, stdout);
n -= l;
}
/* n < l */
if (n > 0)
printf("%.*s", n, s);
}
void paint_tie(int n)
{
int row;
for(row = 1; row <= n; row++) {
paint_line(AST, row);
paint_line(BLK, 2*(n-row) + 1);
paint_line(AST, row);
printf("\n");
}
for (row = n-1; row > 0; row--) {
paint_line(AST, row);
paint_line(BLK, 2*(n-row) + 1);
paint_line(AST, row);
printf("\n");
}
}
int main(int argc, char **argv)
{
int i;
for (i = 1; i < argc; i++) {
int n = atoi(argv[i]);
paint_tie(n);
}
}
The routine main() just extracts the sizes of the ties from the command line. I've not included code to check if atoi(3) returns the proper value, but for sure you can complete the exercise.
The routine paint_tie() prints one tie, it just prints the lines with the number of characters that are requested, growing up to n, then waning to zero again.
Finally, the routine paint_line just paints a sequence of chars, selected from a string passed as a parameter. It prints as many complete strings (just trying to be efficient) using the function fputs(3) until there's no more place for a full string, it then uses (only once, as that's expensive) the %.*s format, which allows me to get the first part of the string, up to the trailing characters that are not multiple of the string length. You can download the example here.
BTW, why do you ask this? Is it a homework exercise, or you are just practicing (as you say in your question) Any case, you are doing bad just asking here, as you are not exercising yourself. Why do you auto ask to do an exercise, and then come here to look for the answer? Cannot understand.

Resources