This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Wednesday, March 15, 2023

Print format using C++ program

 Write a program to print the following output using for loops.
1
22
333
4444
55555

Here's a program in C++ to print the pattern using nested for loops:

#include <iostream>
using namespace std;

int main() {
    int rows;

    cout << "Enter the number of rows: ";
    cin >> rows;

    for(int i = 1; i <= rows; i++) {
        for(int j = 1; j <= i; j++) {
            cout << i;
        }
        cout << endl;
    }
    return 0;
}

Output for the pattern with 5 rows:

1
22
333
4444
55555

Explanation:

  • We first prompt the user to enter the number of rows they want to print for the pattern.
  • We use nested for loops to iterate through each row and column of the pattern.
  • The outer for loop runs from 1 to the number of rows input by the user.
  • The inner for loop runs from 1 to the current row number.
  • For each inner loop iteration, we print the current row number using cout << i.
  • After the inner loop completes for each row, we print a new line using cout << endl to move to the next row.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget