Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the following series. 0 1 3 6 10 15 21... upto n terms

Java Code Example — Series Programs

ADVERTISEMENT

Java Program to print the following series. 0 1 3 6 10 15 21... upto n terms

Objective

Write a Java program to print the triangular number series: 0, 1, 3, 6, 10, 15, 21...

Algorithm / Approach

  1. Prompt the user for the number of terms N.
  2. Initialize an accumulator x to 0.
  3. Start a for loop with i = 1 up to n.
  4. Print the current value of x.
  5. Add i to x (x = x + i) to prepare it for the next iteration.
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter N: ");
  int n = s.nextInt();
  int x = 0;
  for(int i = 1; i<=n; i++) {
   System.out.print(x+"  ");
   x = x+i;
  } 
 }
}

Expected Output

Enter N: 10
0  1  3  6  10  15  21  28  36  45

Explanation of the Program

  • Triangular numbers represent objects that can form an equilateral triangle.
  • The difference between consecutive terms increases by 1 each time. (Difference between 0 and 1 is 1; between 1 and 3 is 2; between 3 and 6 is 3, etc.).
  • By printing the accumulator x and then adding the loop index i to it, we mathematically construct this expanding gap perfectly.

Complexity

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