C++程序 打印不重新分配数字

C++程序 打印不重新分配数字

在这里,我们将使用两种方法构建一个C++程序来打印未重新分配数字的数字模式,即:

  1. 使用 for循环
  2. 使用 while循环

1. 使用for循环

输入:

n = 5

输出 :

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15  

第一个for循环用于迭代行数,第二个for循环用于重复列数,然后打印数字并增加数字以打印下一个数字。

// C++ program to print number pattern
// without re assigning using for loop
#include <iostream>
using namespace std;
 
int main()
{
 
    int rows, columns, number = 1, n = 5;
   
    // first for loop is used to identify number of rows
    for (rows = 0; rows <= n; rows++) {
       
        // second for loop is used to identify number of
        // columns and here the values will be changed
        // according to the first for loop
        for (columns = 0; columns < rows; columns++) {
           
            // printing number pattern based on the number
            // of columns
            cout << number << " ";
           
            // incrementing number at each column to print
            // the next number
            number++;
        }
       
        // print the next line for each row
        cout << "\n";
    }
    return 0;
}  

输出

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 

2. 使用while循环

输入:

n = 5

输出 :

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15  

while循环检查条件,直到条件为假。如果条件为真,那么它就进入循环并执行语句。

// C++ program to print number without
// reassigning patterns using while loop
#include <iostream>
using namespace std;
 
int main()
{
    int rows = 1, columns = 0, n = 5;
   
    // 1 value is assigned to the number
    // helpful to print the number pattern
    int number = 1;
   
    // while loops check the condition and repeat
    // the loop until the condition is false
    while (rows <= n) {
       
        while (columns <= rows - 1) {
           
            // printing number to get required pattern
            cout << number << " ";
           
            // incrementing columns value
            columns++;
           
            // incrementing number value to print the next
            // number
            number++;
        }
        columns = 0;
       
        // incrementing rows value
        rows++;
        cout << endl;
    }
    return 0;
}  

输出

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

C++ 示例