📜  带有示例的C++中的嵌套循环

📅  最后修改于: 2021-05-30 14:14:06             🧑  作者: Mango

嵌套循环表示另一个循环语句中的循环语句。这就是为什么嵌套循环也称为“循环内循环”的原因。

嵌套For循环的语法:

for ( initialization; condition; increment ) {

   for ( initialization; condition; increment ) {
      
      // statement of inside loop
   }

   // statement of outer loop
}

嵌套While循环的语法:

while(condition) {

   while(condition) {
      
      // statement of inside loop
   }

   // statement of outer loop
}

嵌套Do-While循环的语法:

do{

   do{
      
      // statement of inside loop
   }while(condition);

   // statement of outer loop
}while(condition);

句法:

do{

   while(condition) {
      
      for ( initialization; condition; increment ) {
      
         // statement of inside for loop
      }

      // statement of inside while loop
   }

   // statement of outer do-while loop
}while(condition);

下面是一些示例来演示嵌套循环的用法:

示例1:下面的程序使用嵌套的for循环打印3×3的2D矩阵。

// C++ program that uses nested for loop
// to print a 2D matrix
  
#include 
using namespace std;
  
#define ROW 3
#define COL 3
  
// Driver program
int main()
{
  
    int i, j;
  
    // Declare the matrix
    int matrix[ROW][COL] = { { 1, 2, 3 },
                             { 4, 5, 6 },
                             { 7, 8, 9 } };
    cout << "Given matrix is \n";
  
    // Print the matrix using nested loops
    for (i = 0; i < ROW; i++) {
  
        for (j = 0; j < COL; j++)
            cout << matrix[i][j];
  
        cout << "\n";
    }
  
    return 0;
}
输出:
Given matrix is 
123
456
789

示例2:下面的程序使用嵌套的for循环来打印数字的所有素数。

// C++ Program to print all prime factors
// of a number using nested loop
  
#include 
using namespace std;
  
// A function to print all prime factors of a given number n
void primeFactors(int n)
{
    // Print the number of 2s that divide n
    while (n % 2 == 0) {
        cout << 2;
        n = n / 2;
    }
  
    // n must be odd at this point. So we can skip
    // one element (Note i = i +2)
    for (int i = 3; i <= sqrt(n); i = i + 2) {
        // While i divides n, print i and divide n
        while (n % i == 0) {
            cout << i;
            n = n / i;
        }
    }
  
    // This condition is to handle the case when n
    // is a prime number greater than 2
    if (n > 2)
        cout << n;
}
  
/* Driver program to test above function */
int main()
{
    int n = 315;
    primeFactors(n);
    return 0;
}
输出:
3357
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”