WAP to print the following series.1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Objective
Write a C++ program to print a repeating number series: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4...
Algorithm / Approach
- Use an outer loop
ifrom 1 to 5. - Use an inner loop
jfrom 1 toi. - Print
iinside the inner loop. - Do NOT print a newline after the inner loop finishes.
main.cpp
#include<iostream>
using namespace std;
int main() {
for(int i = 1; i<=5; i++) {
for(int j = 1; j<=i; j++) {
cout<< i<<" ";
}
}
cout<< endl;
return 0;
}
Expected Output
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
Explanation of the Program
- This is actually just a standard Right Half Pyramid pattern code, but printed on a single continuous line!
- Because the inner loop runs
itimes, the number 1 prints once, 2 prints twice, 3 prints three times, etc.
Complexity
Time Complexity
O(n^2)
Space Complexity
O(1)