C++ Nested Loops

C++ Loops

One loop can be nested inside another loop. C++ allows at least 256 nesting levels.

Syntax

In C++Nested for loopSyntax of statements:

for ( init; condition; increment ) { for ( init; condition; increment ) { statement(s); } statement(s); // You can place more statements }

In C++Nested while loopSyntax of statements:

while(condition) { while(condition) { statement(s); } statement(s); // You can place more statements }

In C++Nested do...while loopSyntax of statements:

do { statement(s); // You can place more statements do { statement(s); }while( condition ); }while( condition );

One thing worth noting about nested loops is that you can nest any type of loop inside any other type of loop. For example, a for loop can be nested inside a while loop, and vice versa.

Example

The following program uses a nested for loop to find prime numbers from 2 to 100:

Example

#include <iostream> using namespace std; int main () { int i, j; for(i=2; i<100; i++) { for(j=2; j <= (i/j); j++) { if(!(i%j)) { break; // If found, it is not a prime number } } if(j > (i/j)) { cout << i << "is a prime number\n"; } } return 0; }

When the above code is compiled and executed, it will produce the following result:

2 是质数
3 是质数
5 是质数
7 是质数
11 是质数
13 是质数
17 是质数
19 是质数
23 是质数
29 是质数
31 是质数
37 是质数
41 是质数
43 是质数
47 是质数
53 是质数
59 是质数
61 是质数
67 是质数
71 是质数
73 是质数
79 是质数
83 是质数
89 是质数
97 是质数

C++ Loops

other extensions