The following C code generates on standard output a Pascal Triangle as specified on this wiki page.
Specifically output in following format is generated:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/* The following code is used to print the Pascal triangle for as many rows as input by the user. */ #include<stdio.h> // begin the main function for this program int main() { // declare the required variable int num, i, j; // Display message to enter the number of rows printf("Enter the number of rows: "); // prompt and get the value from user scanf("%d", &num); // declare array of size equal to that of // given input number int ar[num]; // initialize the array to all zeros for(i=0; i<num-1; i++) { ar[i] = 0; // also print the first line // which will always have trivial value printf(" "); } // set the last element of the array to be 1 ar[i] = 1; // print the last element of the first row printf("%d\n",ar[i]); // loop for the remaining n-1 rows to be printed for(i=0; i<num-1; i++) { // loop through each character position // to be printen in current row for(j=0; j<num-1; j++) { // set the current element as the sum of // current and next element's sum ar[j] += ar[j+1]; // check for printing whether the current value // is more than zero or not. // if yes then print the value // else print a single space if(ar[j] > 0) printf("%d ",ar[j]); else printf(" "); } // end of inner for loop // print the last element in row which would remain 1. printf("%d\n", ar[j]); } // end of outer for loop } // end of main function |