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
- Prompt the user for the number of terms
N. - Initialize an accumulator
xto 0. - Start a
forloop withi = 1up ton. - Print the current value of
x. - Add
itox(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
xand then adding the loop indexito it, we mathematically construct this expanding gap perfectly.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)