Java Program to Print Series 1,2,5,10,17

How to print this series?

Below is the logic for printing this series,

1 = (0 * 0) + 1
2 = (1 * 1) + 1
5 = (2 * 2) + 1
10 = (3 * 3) + 1
17 = (4 * 4) + 1

We are going to see two solutions here to print this series,

Solution #1:

package com.javacodepoint.series;

import java.util.Scanner;

/**
 * Series pattern: 1, 2, 5, 10, 17
 * 
 * @author javacodepoint.com
 *
 */
public class SeriesPattern1 {

	public static void main(String[] args) {
		
		// Create scanner object to read user inputs
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter no. of elements you want in the series: ");
		int n = sc.nextInt();
		
		System.out.print("Series: ");
		for (int i = 0; i < n; i++) {
			
			// Calculate the element of the series
			int element = (i*i) + 1;
			
			// Print the element with comma(,) separator
			System.out.print(element + ", ");
		}
	}
}

OUTPUT:

Enter no. of elements you want in the series:
6
Series: 1, 2, 5, 10, 17, 26,

Solution #2:

By using Math.pow() method,

package com.javacodepoint.series;

import java.util.Scanner;

/**
 * Series pattern: 1, 2, 5, 10, 17
 * 
 * @author javacodepoint.com
 *
 */
public class SeriesPattern2 {

	public static void main(String[] args) {
		
		// Create scanner object to read user inputs
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter no. of elements you want in the series: ");
		int n = sc.nextInt();
		
		System.out.print("Series: ");
		for (int i = 0; i < n; i++) {
			
			// Calculate the element of the series
			int element = (int) (Math.pow(i, 2) + 1);
			
			// Print the element with comma(,) separator
			System.out.print(element + ", ");
		}
	}
}

OUTPUT:

Enter no. of elements you want in the series:
5
Series: 1, 2, 5, 10, 17,

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *