Reputation: 29
I'm trying to write code that prints the following :
Here's what I have tried :
#include <stdio.h>
int main() {
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d", &rows);
for (i = rows; i >= 0; i--) {
for (j = 1; j <= i; ++j) {
printf("* ");
}
printf("\n");
}
return 0;
}
How do I do this ?
Upvotes: 1
Views: 598
Reputation: 144740
Here is a simple example:
#include <stdio.h>
int main() {
int rows, i, j, w;
printf("Enter number of rows: ");
if (scanf("%d", &rows) != 1) // get the number of rows, exit if input error
return 1;
int coeff[rows + 1]; // array to store the binomial coefficients
for (i = 0; i < rows; i++) {
coeff[i] = 1; // initialize the last coefficient to 1
for (j = i - 1; j > 0; j--) {
coeff[j] += coeff[j - 1]; // add adjacent coefficients to get the new value
}
w = (rows - i) * 3; // output 3 extra leading spaces for each row from the end
for (j = 0; j <= i; j++) { // output i+1 coefficients
printf(" %*d", w, coeff[j]);
w = 5; // output more coefficients on 1+5 characters
}
printf("\n");
}
return 0;
}
Output:
Enter number of rows: 6 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
Upvotes: 5