HomeJava

Write a program to print first n number in Java

Write a program to print first n number in Java
Like Tweet Pin it Share Share Email

This program helps to introduce the usage of looping structures in java, the following program will print the first n numbers from the number system, you can change the value of n by editing the value that is assigned to the variable “n”, ideally this parameter could be passed from outside and make the program more independent and need not edit the code.

There are several ways to perform this activity, please find below the different code snippets.

Way 1 – Print the first n numbers with a “for” loop

import java.lang.*;

public class PrintN
{
    public static void main (String rs[ ] )
    {
        int n = 10; // you can edit the code here and give a different number as per your interest
        // for iterates 10 times as value of n is 10 and prints values from 1 to 10 
        // i is incremented as part of the for loop syntax it self, need not separately increment value of i inside the for loop
        for(int i =1;i<=n;i++) 
        {
             System.out.println("Value:" + i ); // Print the value
        }
    }
}

Way 2 - Print the first n numbers with a "while" loop

import java.lang.*;

public class PrintN
{
    public static void main (String rs[ ] )
    {
        int n = 10; // you can edit the code here and give a different number as per your interest
        int i = 1;
        // for iterates 10 times as value of n is 10 and prints values from 1 to 10 
        while ( i < = n )
        {
             System.out.println("Value:" + i ); // Print the value
             i = i + 1; // increment value of i with steps of 1
        }
    }
}

Way 3 - Print the first n numbers with a "do-while" loop

import java.lang.*;

public class PrintN
{
    public static void main (String rs[ ] )
    {
        int n = 10; // you can edit the code here and give a different number as per your interest
        int i = 1;
        // for iterates 10 times as value of n is 10 and prints values from 1 to 10 
        do
        {
             System.out.println("Value:" + i ); // Print the value
             i = i + 1; // increment value of i with steps of 1
        } while ( i < = n );
    }
}

There are still more ways by creating a method in a class and then calling the method, where ever you need. Please feel to share any of your queries in form of comments, we would be more than happy to help you out.

Comments (0)

Leave a Reply

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