Menu
CoddyTech

Nested Loops

Part of the Fundamentals section of Coddy's C++ journey. Lesson 48 of 74.

A nested loop is simply a loop inside another loop. The inner loop will complete all its iterations for each single iteration of the outer loop.

A good analogy for this is a clock: for each hour (outer loop), the minute hand (inner loop) must complete its full 60-minute cycle.

Example of a nested loop:

int rows = 2;
int cols = 2;
for (int x = 0; x < rows; x++) {
	for (int y = 0; y < cols; y++) {
		std::cout << x << " " << y << std::endl;
	}
}
// This will output:
// 0 0
// 0 1
// 1 0
// 1 1

The outer loop (x) runs rows times, and for each of those times, the inner loop (y) runs cols times. Each loop has its own counter: y starts again from 0 every time the outer loop runs, while rows and cols stay the same and only tell the loops when to stop.

challenge icon

Challenge

Beginner

Write a program that prints a rectangle of asterisks (*) with a given width and height.

Input: Two integers: width and height (the starter code already reads them).

For example:

If width = 5 and height = 3, the output should be:

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

If width = 4 and height = 6, the output should be:

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

Use a new counter for each loop (for example i for the rows and j for the stars in a row) and compare it with height or width. Don't change height and width themselves: every row needs width again.

Try it yourself

#include <iostream>

int main() {
    int width, height;
    std::cin >> width >> height;
    // Write your code below

    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

Practice on your own: Online C++ compiler