Right Align Pascal’s Triangle in C
To achieve right alignment of Pascal’s Triangle, you can follow these steps:
- First, determine the number of rows, n, of the Pascal’s Triangle to be printed, either through user input or direct assignment.
- Use a two-dimensional array to store the numbers at each position in Pascal’s triangle. It is important to note that each row in Pascal’s triangle has one more number than the row number, therefore the number of columns in the array should be n+1.
- To calculate the numbers at each position in Pascal’s Triangle, use two nested loops. The outer loop controls the rows, while the inner loop controls the columns. The specific formula for calculation is: arr[i][j] = arr[i-1][j-1] + arr[i-1][j], where i represents the row number and j represents the column number.
- Print Pascal’s Triangle. To align the output to the right, you need to add the appropriate number of spaces before each number in each row. This can be achieved using a loop to control the number of spaces. The specific number of spaces can be calculated based on the row and column numbers.
Here is an example of C language code that implements right-aligned Pascal’s Triangle.
#include <stdio.h>
#define MAX_ROWS 10
int main() {
int n, i, j;
int arr[MAX_ROWS][MAX_ROWS+1];
printf("请输入杨辉三角形的行数:");
scanf("%d", &n);
// 计算杨辉三角形中每个位置的数字
for (i = 0; i < n; i++) {
for (j = 0; j <= i; j++) {
if (j == 0 || j == i) {
arr[i][j] = 1;
} else {
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
}
}
}
// 打印杨辉三角形
for (i = 0; i < n; i++) {
// 输出空格
for (j = 0; j < n - i - 1; j++) {
printf(" ");
}
// 输出数字
for (j = 0; j <= i; j++) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
return 0;
}
This code can print the corresponding number of rows of Pascal’s Triangle based on the user input, with right alignment.