Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the following series. 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

Java Code Example — Series Programs

ADVERTISEMENT

Java Program to print the following series. 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5

Objective

Write a Java program to print the repeating number series: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4...

Algorithm / Approach

  1. Start an outer for loop with i running from 1 to 5.
  2. Inside, start an inner for loop with j running from 1 to i.
  3. Inside the inner loop, print the value of i followed by a space.
  4. Do not print a newline.
Test.java
class Test {
 public static void main(String[] a)
 {
  for(int i = 1; i<=5; i++) {
   for(int j = 1; j<=i; j++) {
    System.out.print(i+"  ");
   }
  }
 }
}

Expected Output

1  2  2  3  3  3  4  4  4  4  5  5  5  5  5

Explanation of the Program

  • This sequence is essentially a number pyramid pattern that has been flattened onto a single line.
  • The outer loop determines the number we want to print (i).
  • The inner loop determines how many times we print it. Because it runs up to i, the number 1 prints once, 2 prints twice, 3 prints three times, and so on.

Complexity

Time Complexity O(n2)
Space Complexity O(1)
ADVERTISEMENT