Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to print the following series.1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

C++ Code Example — Series Programs

ADVERTISEMENT

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

  1. Use an outer loop i from 1 to 5.
  2. Use an inner loop j from 1 to i.
  3. Print i inside the inner loop.
  4. 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 i times, the number 1 prints once, 2 prints twice, 3 prints three times, etc.

Complexity

Time Complexity O(n^2)
Space Complexity O(1)
ADVERTISEMENT