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

1-2-4-7-11-16-22: In the previous article, we have discussed about Java Program to Print Series 1 11 111 1111 11111 …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, 1 2 4 7 11 series in java, How to print series in java, series program in java, 1 4 9 16 series in java, Number series program in java or number series java program, number series program in java example, series program in java using for loop,

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 series programs in the java language.

Try yourself: 

  1. Write A Program To Print Series In Java
  2. Series Questions In Java
  3. Print The Series In Java

Related Java Programs:

Leave a Comment