Print the Row
In this step, you'll enhance the Pascal's Triangle program to format and print the row with proper spacing and alignment, making the output visually appealing.
Open the existing file:
cd ~/project
nano pascal_triangle.c
Replace the previous code with the following implementation:
#include <stdio.h>
// Function to compute binomial coefficient
int binomialCoeff(int n, int k) {
if (k == 0 || k == n)
return 1;
return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k);
}
// Function to print Pascal's Triangle row
void printPascalRow(int rowNumber) {
// Print leading spaces for alignment
for (int space = 0; space < rowNumber; space++) {
printf(" ");
}
// Generate and print coefficients
for (int k = 0; k < rowNumber; k++) {
int coefficient = binomialCoeff(rowNumber - 1, k);
printf("%4d ", coefficient);
}
printf("\n");
}
int main() {
int rowNumber;
printf("Enter the row number for Pascal's Triangle (1-10): ");
scanf("%d", &rowNumber);
if (rowNumber < 1 || rowNumber > 10) {
printf("Please enter a row number between 1 and 10.\n");
return 1;
}
printf("Pascal's Triangle Row %d:\n", rowNumber);
// Print the specified row
printPascalRow(rowNumber);
return 0;
}
Compile and run the program:
gcc pascal_triangle.c -o pascal_triangle
./pascal_triangle
Example output:
Enter the row number for Pascal's Triangle (1-10): 5
Pascal's Triangle Row 5:
1 4 6 4 1
Code Explanation:
printPascalRow()
function handles row formatting
- Added leading spaces for visual alignment
- Used
%4d
format specifier for consistent column width
- Added input validation to limit row numbers
- Prints the entire row with proper spacing
Key Points:
- Formatting improves readability of Pascal's Triangle
- Input validation prevents unexpected behavior
- Demonstrates basic formatting techniques in C