编写一个C语言程序,使用while循环、for循环和函数来打印左帕斯卡三角形星形图案,并附带示例。下面的左帕斯卡程序使用多个嵌套的for循环来迭代行并打印星形图案。由于存在代码重复,我们创建了一个具有逻辑的独立函数。
#include<stdio.h>
void loopLogic(int rows, int i)
{
for (int j = i; j < rows; j++)
{
printf(" ");
}
for (int k = 1; k <= i; k++)
{
printf("* ");
}
printf("\n");
}
int main(void)
{
int i, rows;
printf("Enter Rows to Print Left Pascal Triangle = ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
loopLogic(rows, i);
}
for (i = rows - 1; i >= 1; i--) {
loopLogic(rows, i);
}
}

C语言使用while循环打印左帕斯卡三角形星形图案
在这个左帕斯卡三角形星形图案程序中,我们用while循环替换了for循环。
#include<stdio.h>
void loopLogic(int rows, int i)
{
int j = i;
while (j < rows)
{
printf(" ");
j++;
}
int k = 1;
while (k <= i)
{
printf("* ");
k++;
}
printf("\n");
}
int main(void)
{
int i, rows;
printf("Enter Rows to Print Left Pascal Triangle = ");
scanf("%d", &rows);
i = 1;
while ( i <= rows ) {
loopLogic(rows, i);
i++;
}
i = rows - 1;
while ( i >= 1 ) {
loopLogic(rows, i);
i--;
}
}
输出
Enter Rows to Print Left Pascal Triangle = 10
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
在下面的左帕斯卡三角形星形图案程序中,用户定义的函数接受行数和字符,使用符号打印图案。
#include<stdio.h>
void loopLogic(int rows, int i, char ch)
{
for (int j = i; j < rows; j++)
{
printf(" ");
}
for (int k = 1; k <= i; k++)
{
printf("%c ",ch);
}
printf("\n");
}
int main(void)
{
int i, rows;
char ch;
printf("Enter Character = ");
scanf("%c", &ch);
printf("Enter Rows to Print Left Pascal Triangle = ");
scanf("%d", &rows);
for (i = 1; i <= rows; i++) {
loopLogic(rows, i, ch);
}
for (i = rows - 1; i >= 1; i--) {
loopLogic(rows, i, ch);
}
}
输出
Enter Character = $
Enter Rows to Print Left Pascal Triangle = 15
$
$ $
$ $ $
$ $ $ $
$ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $ $ $
$ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $ $
$ $ $ $ $ $ $
$ $ $ $ $ $
$ $ $ $ $
$ $ $ $
$ $ $
$ $
$