Search⌘ K

Nested Loop

Explore how nested loops work in C++ to create efficient repetitive programs. This lesson helps you understand the syntax and flow of nested for loops, with an example that prints times tables, enabling you to write nested loop structures confidently.

Introduction

Suppose you want to print the times tables of 6, 7, and 8 in a program. First, we need to choose the number whose table we want to print. Then, we print the table for that number. How can we do this task?

In C++, we can use nested loops to accomplish such tasks.


A loop inside the body of another loop is called a nested loop.


Syntax

Let’s go over the syntax of the nested for loop.

In the figure above, we have the following two for loops:

  • Outer for loop
  • Inner for loop

The outer for loop ...