YouTip LogoYouTip

Cpp Nested Loops

# C++ Nested Loops In C++, a loop can be nested inside another loop. This powerful programming concept allows you to perform multi-dimensional operations, such as iterating over grids, matrices, or combinations of data. C++ allows at least **256 levels of nesting**, though in practice, you will rarely need more than two or three levels. --- ## Syntax 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. ### 1. Nested `for` Loop A nested `for` loop is most commonly used when the number of iterations is known beforehand (e.g., traversing a 2D array). ```cpp for ( init; condition; increment ) { for ( init; condition; increment ) { // Statement(s) executed in the inner loop } // Statement(s) executed in the outer loop } ``` ### 2. Nested `while` Loop A nested `while` loop is useful when the loops depend on dynamic conditions rather than fixed counters. ```cpp while(condition) { while(condition) { // Statement(s) executed in the inner loop } // Statement(s) executed in the outer loop } ``` ### 3. Nested `do...while` Loop A nested `do...while` loop guarantees that the body of both the outer and inner loops will execute at least once before checking their respective conditions. ```cpp do { // Statement(s) executed in the outer loop do { // Statement(s) executed in the inner loop } while( condition ); } while( condition ); ``` --- ## Practical Code Example The following program uses a nested `for` loop to find and print all prime numbers between 2 and 100. The outer loop runs through the numbers to be checked ($2$ to $100$), while the inner loop checks if the current number has any divisors other than 1 and itself. ```cpp #include using namespace std; int main () { int i, j; // Outer loop to iterate through numbers from 2 to 99 for(i = 2; i < 100; i++) { // Inner loop to check for factors for(j = 2; j <= (i / j); j++) { if(!(i % j)) { break; // If a factor is found, it is not prime; exit the inner loop } } // If no factors were found, j will be greater than (i/j) if(j > (i / j)) { cout << i << " is prime\n"; } } return 0; } ``` ### Output When the above code is compiled and executed, it produces the following output: ```text 2 is prime 3 is prime 5 is prime 7 is prime 11 is prime 13 is prime 17 is prime 19 is prime 23 is prime 29 is prime 31 is prime 37 is prime 41 is prime 43 is prime 47 is prime 53 is prime 59 is prime 61 is prime 67 is prime 71 is prime 73 is prime 79 is prime 83 is prime 89 is prime 97 is prime ``` --- ## Key Considerations & Best Practices 1. **Performance and Complexity**: Each level of nesting multiplies the total number of iterations. A loop running $N$ times nested inside another loop running $N$ times results in $O(N^2)$ time complexity. Be mindful of performance when nesting loops with large datasets. 2. **Variable Scope**: Ensure that loop control variables (like `i` and `j`) have unique names. Reusing the same variable name in nested loops can cause unexpected behavior or compilation errors. 3. **The `break` and `continue` Statements**: * A `break` statement inside an inner loop only exits the **inner** loop, returning control to the outer loop. * A `continue` statement inside an inner loop skips the remaining statements of the current iteration of the **inner** loop only. 4. **Readability**: Deeply nested loops (more than 3 levels) can make code difficult to read and maintain. If your nesting goes too deep, consider refactoring the inner loop's logic into a separate function.
← Cpp Break StatementCpp Do While Loop β†’