C 语言打印数字图案 3 程序

编写一个 C 语言程序来打印数字图案 3,并附带示例。为此,我们将使用 For 循环和 While 循环。

使用 For 循环打印数字图案 3 的 C 程序

此程序允许用户输入他们想要将其打印为矩形的行数和列数。接下来,编译器将打印数字图案。

/* C program to Print Number Pattern 3 */

#include<stdio.h>
 
int main()
{
    int i, j, rows, columns;
     
    printf(" \nPlease Enter the Number of Rows : ");
    scanf("%d", &rows);
    
    printf(" \nPlease Enter the Number of Columns : ");
    scanf("%d", &columns);
     
    for(i = 1; i <= rows; i++)
    {
    	for(j = i; j < i + columns; j++)
		{
			printf("%d", j);     	
        }
        printf("\n");
    }
    return 0;
}
C program to Print Number Pattern 3 1

让我们看看 嵌套 for 循环

for(i = 1; i <= rows; i++)
{
   	for(j = i; j <= i + columns; j++)
	{
		printf("%d", j);     	
        }
        printf("\n");
}

外循环 – 第一次迭代

从上面的 C 编程 屏幕截图中,您可以看到,i 的值为 5,条件 (i <= 5) 为 True。因此,它将进入第二个 for 循环。

内层循环 – 第一次迭代

j 的值为 1,条件 (1 <= 6) 为 True。因此,它将开始执行循环内的语句。

printf("%d", j);

接下来,我们使用 自增运算符 j++ 将 J 值增加 1。这将一直进行,直到内部 for 循环中的条件失败。接下来,迭代将从头开始,直到内部循环和外部循环的条件都失败。

使用 while 循环打印数字图案 3 的程序

在此 程序 中,我们只是将 For 循环替换为 While 循环。我建议您参考 While Loop 文章来理解其中的逻辑。

/* C program to Print Number Pattern 3 */

#include<stdio.h>
 
int main()
{
    int i, j, rows, columns;
     
    printf(" \nPlease Enter the Number of Rows : ");
    scanf("%d", &rows);
    
    printf(" \nPlease Enter the Number of Columns : ");
    scanf("%d", &columns);
    
	i = 1;
	 
    while(i <= rows)
    {
    	j = i;
    	
    	while(j < i + columns)
		{
			printf("%d", j);
			j++;     	
        }
        i++;
        printf("\n");
    }
    return 0;
}
 
Please Enter the Number of Rows : 5
 
Please Enter the Number of Columns : 6
123456
234567
345678
456789
5678910