nested loop c++ program example
Here is an example of a nested loop program in C++:
#include <iostream>
int main() {
int rows, columns;
std::cout << "Enter the number of rows: ";
std::cin >> rows;
std::cout << "Enter the number of columns: ";
std::cin >> columns;
for (int i = 1; i <= rows; ++i) {
for (int j = 1; j <= columns; ++j) {
std::cout << "(" << i << "," << j << ") ";
}
std::cout << std::endl;
}
return 0;
}
Explanation:
- The program starts by including the necessary header file
iostream
, which provides input/output stream functionality. - The
main()
function is the entry point of the program. It returns an integer value. - Two variables
rows
andcolumns
are declared to store the user input for the number of rows and columns. - The program prompts the user to enter the number of rows and columns using
std::cout
. - The user input for
rows
andcolumns
are read usingstd::cin
. - The outer for loop initializes a variable
i
to 1 and continues the loop as long asi
is less than or equal torows
. After each iteration,i
is incremented by 1. - Inside the outer loop, there is another for loop that initializes a variable
j
to 1 and continues the loop as long asj
is less than or equal tocolumns
. After each iteration,j
is incremented by 1. - Inside the inner loop, the program outputs the current values of
i
andj
enclosed in parentheses usingstd::cout
. - After the inner loop, the program outputs a newline character using
std::endl
to move to the next line. - The outer loop continues until
i
exceeds the value ofrows
. - Finally, the
main()
function returns 0, indicating successful program execution.
This program generates a grid-like pattern of coordinates, where each coordinate is enclosed in parentheses. The number of rows and columns is determined by user input.