基于模式的程序的思想是理解for循环的嵌套概念,以及如何以及在何处放置字母/数字/星号以形成所需的模式。
编写程序以使用for循环以以下方式打印数字模式
1
232
34543
4567654
567898765
在几乎所有类型的模式程序中,必须注意两件事:
- 行数
- 如果模式是每行增加还是减少?
执行
C++
// C++ program to illustrate the above
// given pattern of numbers.
#include
using namespace std;
int main()
{
int n = 5, i, j, num = 1, gap;
gap = n - 1;
for ( j = 1 ; j <= n ; j++ )
{
num = j;
for ( i = 1 ; i <= gap ; i++ )
cout << " ";
gap --;
for ( i = 1 ; i <= j ; i++ )
{
cout << num;
num++;
}
num--;
num--;
for ( i = 1 ; i < j ; i++)
{
cout << num;
num--;
}
cout << "\n";
}
return 0;
}
//This code is contributed by Shivi_Aggarwal
C
// C program to illustrate the above
// given pattern of numbers.
#include
int main()
{
int n = 5, i, j, num = 1, gap;
gap = n - 1;
for ( j = 1 ; j <= n ; j++ )
{
num = j;
for ( i = 1 ; i <= gap ; i++ )
printf(" ");
gap --;
for ( i = 1 ; i <= j ; i++ )
{
printf("%d", num);
num++;
}
num--;
num--;
for ( i = 1 ; i < j ; i++)
{
printf("%d", num);
num--;
}
printf("\n");
}
return 0;
}
Java
// Java Program to illustrate the
// above given pattern of numbers
import java.io.*;
class GFG {
public static void main(String args[])
{
int n = 5, i, j, num = 1, gap;
gap = n - 1;
for ( j = 1 ; j <= n ; j++ )
{
num = j;
for ( i = 1 ; i <= gap ; i++ )
System.out.print(" ");
gap --;
for ( i = 1 ; i <= j ; i++ )
{
System.out.print(num);
num++;
}
num--;
num--;
for ( i = 1 ; i < j ; i++)
{
System.out.print(num);
num--;
}
System.out.println();
}
}
}
// This code is contributed
// by Nikita tiwari.
Python3
# Python Program to illustrate the
# above given pattern of numbers.
n = 5
num = 1
gap = n - 1
for j in range(1, n + 1) :
num = j
for i in range(1, gap + 1) :
print(" ", end="")
gap = gap - 1
for i in range(1, j + 1) :
print(num, end="")
num = num + 1
num = num - 2
for i in range(1, j) :
print(num, end="")
num = num - 1
print()
# This code is contributed
# by Nikita tiwari.
C#
// C# Program to illustrate the
// above given pattern of numbers
using System;
class GFG {
public static void Main()
{
int n = 5, i, j, num = 1, gap;
gap = n - 1;
for (j = 1; j <= n; j++) {
num = j;
for (i = 1; i <= gap; i++)
Console.Write(" ");
gap--;
for (i = 1; i <= j; i++) {
Console.Write(num);
num++;
}
num--;
num--;
for (i = 1; i < j; i++) {
Console.Write(num);
num--;
}
Console.WriteLine();
}
}
}
// This code is contributed
// by vt_m.
PHP
Javascript
输出:
1
232
34543
4567654
567898765
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。