c
  1. c-nested-loops

C Nested Loops

Syntax

for (init; condition; increment/decrement) {
  for (init; condition; increment/decrement) {
      /* code to be executed */
  }
}

Example

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

Output

Value of i: 1, Value of j: 1
Value of i: 1, Value of j: 2
Value of i: 1, Value of j: 3
Value of i: 2, Value of j: 1
Value of i: 2, Value of j: 2
Value of i: 2, Value of j: 3
Value of i: 3, Value of j: 1
Value of i: 3, Value of j: 2
Value of i: 3, Value of j: 3

Explanation

In C programming, nested loops are loops that are executed inside the body of a main loop. The syntax of a nested loop consists of one loop inside another loop. The outer loop is executed first and then the inner loop is executed.

Use

In general, nested loops are used when we want to perform a certain action more than once and we want to perform another action inside that action. In other words, when we want to run a loop inside another loop, we use nested loops. It is very useful when dealing with multi-dimensional arrays or when we want to perform operations on data which is stored in a matrix format.

Important Points

  • Nested loops can be used when we want to repeat a set of iterations for a large number of times.
  • Nested loops are useful when dealing with multi-dimensional arrays.
  • Nested loops may result in a longer execution time.

Summary

C Nested Loops are loops that execute inside the body of another loop. They are primarily used when we want to perform a certain action more than once and then perform another action inside that action. They are useful when dealing with multi-dimensional arrays or when we want to perform operations on data which is in matrix format. The syntax of a nested loop consists of one loop inside another loop.

Published on: