BCA SCHOOL
Programming Tutorials • Notes • Practical • Books
LATEST TUTORIALS

Nesting of Loops in C Language: Syntax, Patterns & Examples (Unit 2)

by BCA School



BCA Sem 1  |  Unit 2  |  Computer Concepts & C Programming

Nesting of Loops in C Language — BKNMU Junagadh

Understanding Outer vs. Inner Loops, Matrix Manipulation, Star Pattern Logic, and Performance Calculations

BKNMU Junagadh NEP 2020 Unit 2 Nested Loops Pattern Printing Matrix Operations
In simple words: Welcome to Unit 2! Nesting of Loops refers to placing one loop statement entirely inside the body of another loop statement. In C, you can nest any loop type (for, while, or do...while) inside another to work with multi-dimensional structures like rows and columns, grids, matrices, and geometric patterns.
📖 Core Mechanics of Nested Loops

To master nested loops, you need to understand how the inner and outer loops interact:

Outer Loop

1. Controls Rows / Higher Dim

Executes slower. For every single iteration of the outer loop, the inner loop must run through all of its iterations completely.

Inner Loop

2. Controls Columns / Inner Steps

Executes faster. It resets, runs to completion, and exits repeatedly on every single pass of the outer loop.

N × M Iterations

3. Total Pass Calculation

If the outer loop runs N times and the inner loop runs M times, the code inside the inner loop runs a total of N × M times.

Mixed Nesting

4. Any Loop Combination

C allows mixing loop types—such as nesting a while loop inside a for loop or a do...while inside another for loop.

1️⃣ Master Summary: Outer vs. Inner Loop Roles

Here is a structural comparison showing how responsibilities are divided between outer and inner loops:

Loop LevelPrimary Scope / FunctionalityExecution Order & Reset Behavior
Outer LoopControls overall rows, high-level iterations, or matrix horizontal levels.Increments once per complete cycle of the inner loop. Does NOT reset during execution.
Inner LoopControls individual column entries, character printing, or element processing.Resets its counter variable completely to initial value on EVERY outer loop pass.
Internal StatementsCode placed strictly inside the inner loop block.Runs (Outer Count × Inner Count) total times during complete program execution.
ℹ️ The Golden Rule of Nesting: An inner loop MUST be completely enclosed within the body of the outer loop! Loops can never overlap or cross boundaries (e.g., closing the outer loop before closing the inner loop causes severe compilation errors).
💻 Code Examples & Practical Applications

1. Classic Star Pattern (Right-Angled Triangle):

#include <stdio.h>

int main() {
    int i, j, rows = 5;

    // Outer loop controls total rows
    for (i = 1; i <= rows; i++) {
        // Inner loop prints stars equal to current row number
        for (j = 1; j <= i; j++) {
            printf("* ");
        }
        printf("\n"); // Move to next line after completing row
    }

    return 0;
}

2. Number Grid Pattern (Matrix Layout):

#include <stdio.h>

int main() {
    int i, j;

    // Printing a 3x3 number grid
    for (i = 1; i <= 3; i++) {
        for (j = 1; j <= 3; j++) {
            printf("(%d,%d) ", i, j);
        }
        printf("\n");
    }

    return 0;
}

3. Multiplication Table Grid (1 to 5):

#include <stdio.h>

int main() {
    int i, j;

    for (i = 1; i <= 5; i++) {
        for (j = 1; j <= 5; j++) {
            printf("%4d", i * j);
        }
        printf("\n");
    }

    return 0;
}
🔄 Step-by-Step Execution Sequence
1

Step 1: Outer Loop Initializing

Outer loop variable is initialized and its condition tested. If True, control passes to the inner loop.

2

Step 2: Inner Loop Full Execution Cycle

The inner loop initializes its variable and runs repeatedly until its test condition becomes False.

3

Step 3: Outer Loop Update & Reset

Control exits the inner loop, runs any remaining outer code (like printf("\n")), updates the outer counter, and repeats Step 1.

💡 Exam Tip on Pattern Printing: In BKNMU exam papers, always remember: the outer loop index represents the row count (vertical height), while the inner loop index represents the column count (horizontal items printed per row)!
⚠️ Common Bug (Reusing Counter Variables): Never use the same variable for both loops (e.g., using for(i=0;...) for outer AND inner loops)! The inner loop will alter the outer counter, destroying your loop flow.
📝 Quick Revision — Key Exam Points
  • Definition: Writing one loop statement inside the body of another loop statement.
  • Supported Loops: for inside for, while inside while, or mixed combinations.
  • Execution Formula: Inner loop completes all iterations for EVERY SINGLE iteration of the outer loop.
  • Primary Applications: 2D Arrays, Matrices, Star/Number Patterns, Sorting Algorithms (Bubble Sort).
  • Performance Impact: Deep nesting (3 or more levels) drastically increases execution time (O(N²), O(N³)).