Menu
Coddy logo textTech

Nested Loops

Part of the Fundamentals section of Coddy's C journey — lesson 43 of 63.

Nested loops are loops placed inside another loop. For each iteration of the outer loop, the inner loop executes completely.

Create an outer loop that runs 3 times:

for (int i = 0; i < 3; i++) {
    // Outer loop code here
}

Add an inner loop that runs 2 times for each outer loop iteration:

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
        printf("%d,%d ", i, j);
    }
    printf("\n");
}

The output will be:

0,0 0,1 0,2 
1,0 1,1 1,2 

Notice how the inner loop completes its iterations before the outer loop moves to its next iteration.

challenge icon

Challenge

Easy

Create a program that prints a rectangle pattern of asterisks (*) based on the number of rows and columns provided by the user.

Your program should:

  1. Read two integers from the user: rows and columns.
  2. Use nested loops to print a rectangle pattern of asterisks where the outer loop handles rows and the inner loop handles columns.
  3. Print a newline after each row.

For example, if the input is 3 rows and 4 columns, the output should be:

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

Cheat sheet

Nested loops are loops placed inside another loop. For each iteration of the outer loop, the inner loop executes completely.

Basic nested loop structure:

for (int i = 0; i < outer_limit; i++) {
    for (int j = 0; j < inner_limit; j++) {
        // Inner loop code
    }
    // Outer loop code
}

Example with output:

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
        printf("%d,%d ", i, j);
    }
    printf("\n");
}

Output:

0,0 0,1 0,2 
1,0 1,1 1,2

The inner loop completes all its iterations before the outer loop moves to its next iteration.

Try it yourself

#include <stdio.h>

int main() {
    int rows, columns;
    scanf("%d", &rows);
    scanf("%d", &columns);
    
    // Write your code here to print the pattern
    
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals