#include <stdio.h>
int main() {
int rows, coef = 1, i, j;
// Asking the user to input the number of rows
printf("Enter the number of rows for Pascal's Triangle: ");
scanf("%d", &rows);
// Outer loop to handle the number of rows
for (i = 0; i < rows; i++) {
// Print spaces for formatting the triangle
for (j = 0; j <= rows - i; j++) {
printf(" ");
}
// Inner loop to print each number in the row
for (j = 0; j <= i; j++) {
// Compute the binomial coefficient
if (j == 0 || i == j)
coef = 1; // The first and last elements in each row are always 1
else
coef = coef * (i - j + 1) / j; // Formula for calculating binomial coefficient
printf("%4d", coef); // Print the current number with formatting
}
printf("\n"); // Move to the next row after each row is printed
}
return 0;
}
Explanation:
Variables:
rows: Holds the number of rows for Pascal’s Triangle.
coef: Stores the binomial coefficient (starts at 1).
i and j: Loop variables for controlling rows and elements.
User Input:
The user is prompted to enter the number of rows, which is stored in rows.
Outer Loop (Rows):
Iterates over each row, printing the corresponding numbers.
Inner Loop (Calculating Binomial Coefficients):
For the first and last elements in each row, coef is set to 1.
For other elements, coef is calculated using the binomial coefficient formula.
Printing:
The program prints numbers in a triangular format, using spaces for alignment.
Output:
Pascal’s Triangle is printed, with each row containing the binomial coefficients.
Output:
Enter the number of rows for Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1