Java Program to Print the Series 1 11 111 1111 … N

In this article we are going to see how to print the series  1 11 111 1111 … N using Java programming language.

Java Program to Print the Series 1 11 111 1111 … N

In this series the it can be seen that numbers at each position i ‘1’ is  repeated i times.

For example:

If at 1st position there is only one ‘1’, at 5th position there are 5 ‘1’s.

Let’s see different ways to print the series.

Method-1: Java Program to Print the Series 1 11 111 1111 … N By Using User Input Value

Approach:

  • Create Scanner class object.
  • Prompt the user to enter a number.
  • Initialize a variable term to 1.
  • Run a for loop i=1 to n.
  • Inside the loop, print the term and the update term as term = term * 10 + 1

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();
        // initialize the variable term to 1
        int term = 1;
        // loop to print the series
        for (int i = 1; i <= n; i++) 
        {
            System.out.print(term + " ");
            // update the value of term
            term = term * 10 + 1;
        }
    }
}
Output:

Enter the number of terms: 5
1 11 111 1111 11111

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

Approach:

  • Create Scanner class object.
  • Prompt the user to enter a number.
  • Call the method to print the series.
  • In the method, Initialize a variable term to 1.
  • Run a for loop i=1 to n.
  • Inside the loop, print the term and the update term as term = term * 10 + 1

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 printSeries method
        printSeries(n);
    }
    // method to print the series
    private static void printSeries(int n)
    {
        // initialize the variable term to 1
        int term = 1;
        // loop to print the series
        for(int i = 1; i <= n; i++) 
        {
            System.out.print(term + " ");
            // update the value of term
            term = term * 10 + 1;
        }
    }
}

Output:

Enter the number of terms: 5
1 11 111 1111 11111

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease

Leave a Comment