Java Program to Print the Series Print Series 1 2 4 7 11 … N

In this article we are going to see how to print the series Print Series 1 2 4 7 11 … N using Java programming language

Java Program to Print the Series Print Series 1 2 4 7 11 … N

In this series the it can be seen that numbers at each position i, the term is calculated as 1+ (i × (i + 1))/2

For example:

If at 3rd position the term is 1+(3 × (3 + 1))/2 = = 7,

and at 5th position the term is 1+(5 × (5 + 1))/2 = = 16

Let’s see different ways to print the series.

Method-1: Java Program to Print the Series Print Series 1 2 4 7 11 … N By Using User Input Value

Approach:

  • Create Scanner class object.
  • Prompt the user to enter a number.
  • Run a for loop i=1 to n.
  • Inside the loop, print 1 + ((i * (i + 1)) / 2)

Program:

import java.util.Scanner;
public class Main
{
    public static void main(String[] args) 
    {
        // create a Scanner object
        Scanner sc = new Scanner(System.in);
        // prompt the user to enter the number of terms
        System.out.print("Enter the number of terms: ");
        int n = sc.nextInt();
        // loop to print the series
        for (int i = 0; i < n; i++)
        {
            System.out.print(1 + ((i * (i + 1)) / 2) + " ");
        }
    }
}

Output:

Enter the number of terms: 7
1 2 4 7 11 16 22

Method-2: Java Program to Print the Series Print Series 1 2 4 7 11 … N By Using User-Defined Method

Approach:

  • Use the same approach as method 1 but move the loop inside an user defined method.

Program:

import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
        // create a Scanner object
        Scanner sc = new Scanner(System.in);
        // prompt the user to enter the number of terms
        System.out.print("Enter the number of terms: ");
        int n = sc.nextInt();
        // call the method to print the series
        printSeries(n);
    }
    // method to print the series
    private static void printSeries(int n)
    {
        // loop to print the series
        for (int i = 0; i < n; i++)
        {
            System.out.print(1 + ((i * (i + 1)) / 2) + " ");
        }
    }
}

Output:

Enter the number of terms: 7
1 2 4 7 11 16 22 

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Leave a Comment