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
- Start an outer
forloop withirunning from 1 to 5. - Inside, start an inner
forloop withjrunning from 1 toi. - Inside the inner loop, print the value of
ifollowed by a space. - 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)