C Nested Loops

A nested loop means a loop inside another loop. The inner loop runs completely for every single iteration of the outer loop.


Basic Syntax

// Outer loop
for(int i = 1; i <= 3; i++) {
// Inner loop
for(int j = 1; j <= 3; j++) {
printf("%d,%d ", i, j);
}
printf("\n");
}

Output:

1,1 1,2 1,3
2,1 2,2 2,3
3,1 3,2 3,3

How it works:

  • i=1 → inner loop runs j=1,2,3 → prints 1,1 1,2 1,3
  • i=2 → inner loop runs j=1,2,3 → prints 2,1 2,2 2,3
  • i=3 → inner loop runs j=1,2,3 → prints 3,1 3,2 3,3

Total iterations = Outer iterations × Inner iterations = 3 × 3 = 9


Types of Nested Loops

CombinationUse Case
for inside forMatrices, tables, patterns
while inside whileComplex data traversal
for inside whileMixed control flows
do-while inside forInput validation loops

Practical Example 1: Multiplication Table

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

Output:

  1   2   3   4   5
2   4   6   8  10
3   6   9  12  15
4   8  12  16  20
5  10  15  20  25

Practical Example 2: Triangle Pattern

#include <stdio.h>
int main() {
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
return 0;
}

Output:

*
* *
* * *
* * * *
* * * * *

Notice: Inner loop runs i times, not a fixed number.


Practical Example 3: Sum of All Elements in 2D Array

#include <stdio.h>
int main() {
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
int sum = 0;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 4; j++) {
sum += matrix[i][j];
}
}
printf("Total sum: %d\n", sum);
return 0;
}

Output:

Total sum: 78

Practical Example 4: Find Prime Numbers (Break in Nested Loops)

#include <stdio.h>
int main() {
printf("Prime numbers from 2 to 50:\n");
for(int n = 2; n <= 50; n++) {
int isPrime = 1;
for(int i = 2; i <= n/2; i++) {
if(n % i == 0) {
isPrime = 0;
break;  // Breaks inner loop only
}
}
if(isPrime) {
printf("%d ", n);
}
}
return 0;
}

Output:

Prime numbers from 2 to 50:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

Important Rules

RuleExplanation
BreakOnly exits the innermost loop
ContinueSkips to next iteration of innermost loop
IndentationAlways indent inner loops for readability
PerformanceBe careful—complexity multiplies (O(n²) or higher)

Breaking Out of Multiple Loops

#include <stdio.h>
int main() {
// Method 1: Using a flag variable
int found = 0;
for(int i = 0; i < 5 && !found; i++) {
for(int j = 0; j < 5; j++) {
if(i == 2 && j == 3) {
found = 1;
break;  // Exits inner loop
}
printf("%d,%d ", i, j);
}
}
printf("\n\nMethod 2 - Using goto:\n");
// Method 2: Using goto (controversial but effective)
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++) {
if(i == 2 && j == 3) {
goto exit_all;
}
printf("%d,%d ", i, j);
}
}
exit_all:
return 0;
}

Common Pitfalls

MistakeProblemFix
Wrong loop boundsOff-by-one errorsUse <= or < carefully
Missing bracesOnly first line in inner loopAlways use {}
Same variable nameConflict/unexpected behaviorUse i, j, k distinct names
Infinite loopsOuter or inner loop never endsVerify update statements

Quick Summary

  • Nested loop = loop containing another loop
  • Total iterations = outer iterations × inner iterations
  • Use cases: matrices, patterns, searching, sorting
  • Break/continue affect only the innermost loop
  • Performance declines quickly as nesting depth increases

Complete Guide to Core & Advanced C Programming Concepts (Functions, Strings, Arrays, Loops, I/O, Control Flow)

https://macronepal.com/bash/building-blocks-of-c-a-complete-guide-to-functions/
Explains how functions in C work as reusable blocks of code, including declaration, definition, parameters, return values, and modular programming structure.

https://macronepal.com/bash/the-heart-of-text-processing-a-complete-guide-to-strings-in-c-2/
Explains how strings are handled in C using character arrays, string manipulation techniques, and common library functions for text processing.

https://macronepal.com/bash/the-cornerstone-of-data-organization-a-complete-guide-to-arrays-in-c/
Explains arrays in C as structured memory storage for multiple values, including indexing, initialization, and efficient data organization.

https://macronepal.com/bash/guaranteed-execution-a-complete-guide-to-the-do-while-loop-in-c/
Explains the do-while loop in C, where the loop body executes at least once before checking the condition.

https://macronepal.com/bash/mastering-iteration-a-complete-guide-to-the-for-loop-in-c/
Explains the for loop in C, including initialization, condition checking, and increment/decrement for controlled iteration.

https://macronepal.com/bash/mastering-iteration-a-complete-guide-to-while-loops-in-c/
Explains the while loop in C, focusing on condition-based repetition and proper loop control mechanisms.

https://macronepal.com/bash/beyond-if-else-a-complete-guide-to-switch-case-in-c/
Explains switch-case statements in C, enabling multi-branch decision-making based on variable values.

https://macronepal.com/bash/mastering-conditional-logic-a-complete-guide-to-if-else-statements-in-c/
Explains if-else statements in C for decision-making and controlling program flow based on conditions.

https://macronepal.com/bash/mastering-the-fundamentals-a-complete-guide-to-arithmetic-operations-in-c/
Explains arithmetic operations in C such as addition, subtraction, multiplication, division, and operator precedence.

https://macronepal.com/bash/foundation-of-c-programming-a-complete-guide-to-basic-input-output/
Explains basic input and output in C using scanf and printf for interacting with users and displaying results.

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper