C documentation V1 Help

Nested Loops and Loop Control

In C programming, nested loops and loop control statements (break and continue) provide additional flexibility for handling complex scenarios. Let's delve into the syntax and usage of nested loops and loop control statements.

Nested Loops

#include <stdio.h> int main() { // Example of nested loops for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { printf("(%d, %d) ", i, j); } printf("\n"); } return 0; }

Explanation of the Program:

  1. The outer loop (for (int i = 1; i <= 3; i++)) is responsible for iterating through rows.

  2. The inner loop (for (int j = 1; j <= 3; j++)) iterates through columns for each row.

  3. The nested loops together create a grid of values, printing pairs of (i, j).

Loop Control Statements

Break Statement

#include <stdio.h> int main() { // Example of break statement for (int i = 1; i <= 5; i++) { if (i == 3) { break; // Exit the loop when i equals 3 } printf("Iteration %d\n", i); } return 0; }

The break statement is used to exit a loop prematurely based on a certain condition. In this example, the loop terminates when i becomes 3.

Continue Statement

#include <stdio.h> int main() { // Example of continue statement for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip the rest of the loop body when i equals 3 } printf("Iteration %d\n", i); } return 0; }

The continue statement is used to skip the rest of the loop body and move to the next iteration. Here, the loop continues for all values of i except when it equals 3.

Practical Tips

  • Nested loops are useful for dealing with matrices, grids, or multi-dimensional data.

  • break and continue statements provide control over loop execution based on specific conditions.

Understanding and effectively utilizing nested loops and loop control statements enhance the versatility of loop structures in C programming. If you have specific questions or if there are additional topics you'd like to explore, feel free to ask. Happy coding!

Last modified: 25 February 2024