Control Flow: Loops (for, while, do-while)

Implementing repetitive tasks using `for`, `while`, and `do-while` loops.


Nested For Loops in C

Understanding Nested For Loops

A nested `for` loop is a `for` loop placed inside another `for` loop. The inner loop will execute completely for each iteration of the outer loop. This structure is crucial for iterating over multi-dimensional data structures, such as matrices (2D arrays) or for generating patterns.

Think of it like a clock. The outer loop represents the hours, and the inner loop represents the minutes. For each hour, the minutes go through a complete cycle of 0 to 59.

How Nested For Loops Work

The syntax for a nested `for` loop is straightforward:

 for (initialization_outer; condition_outer; increment_outer) {
          // Code to be executed by the outer loop

          for (initialization_inner; condition_inner; increment_inner) {
            // Code to be executed by the inner loop
          }

          // More code to be executed by the outer loop
        } 

The outer loop initializes, checks its condition, and executes its code (including the inner loop) before incrementing. The inner loop initializes, checks *its* condition, executes *its* code, and increments *before* the outer loop moves to its next iteration.

Practical Examples

1. Matrix Operations (Addition)

This example demonstrates how to add two matrices using nested `for` loops.

 #include <stdio.h>

        int main() {
          int matrix1[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
          int matrix2[3][3] = {{9, 8, 7}, {6, 5, 4}, {3, 2, 1}};
          int sum[3][3];

          // Iterate through rows
          for (int i = 0; i < 3; i++) {
            // Iterate through columns
            for (int j = 0; j < 3; j++) {
              sum[i][j] = matrix1[i][j] + matrix2[i][j];
              printf("%d ", sum[i][j]); // Print the element
            }
            printf("\n"); // New line after each row
          }

          return 0;
        } 

Explanation: The outer loop iterates through the rows of the matrices (from `i = 0` to `2`), and the inner loop iterates through the columns (from `j = 0` to `2`). Inside the inner loop, the corresponding elements of `matrix1` and `matrix2` are added, and the result is stored in the `sum` matrix. The result is also printed to the console.

2. Pattern Generation (Triangle)

This example shows how to generate a right-angled triangle pattern using nested `for` loops.

 #include <stdio.h>

        int main() {
          int rows = 5;

          for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= i; j++) {
              printf("* ");
            }
            printf("\n");
          }

          return 0;
        } 

Explanation: The outer loop iterates through the rows of the triangle (from `i = 1` to `5`). The inner loop iterates from `j = 1` to `i`. So, in each row, the inner loop prints an increasing number of asterisks based on the current row number. The `printf("\n");` after the inner loop moves the cursor to the next line, creating the triangle shape.

3. Pattern Generation (Rectangle)

This example shows how to generate a rectangle pattern using nested `for` loops.

 #include <stdio.h>

                int main() {
                    int rows = 5;
                    int cols = 10;

                    for (int i = 0; i < rows; i++) {
                        for (int j = 0; j < cols; j++) {
                            printf("*");
                        }
                        printf("\n");
                    }

                    return 0;
                } 

Explanation: The outer loop iterates through the rows of the rectangle. The inner loop iterates through the columns. The `printf("*");` prints a asterisk, The `printf("\n");` after the inner loop moves the cursor to the next line, creating the rectangle shape.

4. Searching a 2D Array

This example demonstrates how to search for a specific value within a 2D array.

 #include <stdio.h>

        int main() {
          int matrix[3][4] = {{10, 20, 30, 40}, {50, 60, 70, 80}, {90, 100, 110, 120}};
          int search_value = 70;
          int found = 0; // Flag to indicate if the value is found
          int row_index = -1;
          int col_index = -1;

          for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 4; j++) {
              if (matrix[i][j] == search_value) {
                found = 1;
                row_index = i;
                col_index = j;
                break; // Exit the inner loop when found
              }
            }
            if (found) {
              break; // Exit the outer loop when found
            }
          }

          if (found) {
            printf("Value %d found at row: %d, column: %d\n", search_value, row_index, col_index);
          } else {
            printf("Value %d not found in the matrix.\n", search_value);
          }

          return 0;
        } 

Explanation: The loops iterate through the rows and columns of the `matrix`. The `if` statement checks if the current element `matrix[i][j]` is equal to the `search_value`. If it's found, the `found` flag is set to 1, the row and column indices are stored, and the inner and outer loops are exited using `break` statements to optimize the search (once the value is found, there's no need to continue searching). If the value is found the row and column are stored, if not the found variable remains at zero and an error message is printed.