Java program to print the Arithmetic Progression series

Java program to print the Arithmetic Progression series:

In this post, we will learn how to print the Arithmetic Progression series in Java. An arithmetic progression series starts with a start item and calculates other items based on its position and another value called common difference.

For example, if the first item is a and common difference is d, then the nth item in the arithmetic progression is a + (n - 1)*d. We can also get the next value if we add the common difference with the current value.

In this post, we will take the values of a, d and n as inputs from the user. This program will then print the arithmetic progression from a to n values.

We will learn different ways to solve this problem. Let’s check one by one:

Method 1: By using a for loop:

Let’s try to print this series by using a for loop. Below is the complete program:

import java.util.Scanner;

class Main {
    static void printAP(int a, int d, int n) {
        for (int i = 1; i <= n; i++) {
            System.out.print(a + (i - 1) * d + " ");
        }
    }

    public static void main(String[] args) {
        int a, d, n;
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the values of a, d and n : ");
        a = sc.nextInt();
        d = sc.nextInt();
        n = sc.nextInt();

        printAP(a, d, n);
    }
}

It will print output as like below:

Enter the values of a, d and n :
1
2
5
1 3 5 7 9

Here,

  • We are reading the values of a, d and n from the user and storing these in variables a, d, and n.
  • printAP method is used to print the Arithmetic progression. This method uses a for loop that runs from i = 1 to i = n. For each value of i, it calculates the current value by using the formula we have discussed before and prints that.

Method 2: By using a recursive method:

We can also solve it recursively. A recursive method calls itself again and again untill a endpoint is reached. Below program solves it recursively:

import java.util.Scanner;

class Main {
    static void printAP(int d, int n, int current) {
        System.out.print(current + " ");

        if (n == 0) return;

        printAP(d, n - 1, current + d);
    }

    public static void main(String[] args) {
        int a, d, n;
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter the values of a, d and n : ");
        a = sc.nextInt();
        d = sc.nextInt();
        n = sc.nextInt();

        printAP(d, n - 1, a);
    }
}

Here,

  • printAP is a recursive method. It calls itself again and again until the value of n is equal to 0.
  • current is the current value that we want to print. This value is incremented by d on each recursive call, i.e. it is changed to the next value.

If you run this program, it will print similar output as the above program.

You might also like: