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:

  1. The program starts by including the necessary header file iostream, which provides input/output stream functionality.
  2. The main() function is the entry point of the program. It returns an integer value.
  3. Two variables rows and columns are declared to store the user input for the number of rows and columns.
  4. The program prompts the user to enter the number of rows and columns using std::cout.
  5. The user input for rows and columns are read using std::cin.
  6. The outer for loop initializes a variable i to 1 and continues the loop as long as i is less than or equal to rows. After each iteration, i is incremented by 1.
  7. Inside the outer loop, there is another for loop that initializes a variable j to 1 and continues the loop as long as j is less than or equal to columns. After each iteration, j is incremented by 1.
  8. Inside the inner loop, the program outputs the current values of i and j enclosed in parentheses using std::cout.
  9. After the inner loop, the program outputs a newline character using std::endl to move to the next line.
  10. The outer loop continues until i exceeds the value of rows.
  11. 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.