Java Program to Print Series 3,9,27,81,243

In this series, we can see the number is getting tripled from its previous number in each step. So the logic for this series pattern will be as follow:

element = element * 3 (in a loop) and the element should be initialized with 1 before starting the loop.

Solution:

package com.javacodepoint.series;

import java.util.Scanner;

/**
 * Series pattern: 3, 9, 27, 81, 243
 * 
 * @author javacodepoint.com
 *
 */
public class SeriesPattern {

	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();

		// Initialize element
		int element = 1;
		System.out.print("Series: ");
		for (int i = 0; i < n; i++) {

			// Calculate the element of the series
			element = element * 3;

			// Print the element with comma(,) separator
			System.out.print(element + ", ");
		}
	}
}

OUTPUT:

Enter no. of elements you want in the series:
6
Series: 3, 9, 27, 81, 243, 729,

Java logical programs list


Java Basic Programs

Java String Programs

Java Miscellaneous Programs

Leave a Reply

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