Q:

Java program to print numbers from 1 to N using while loop

0

To print numbers from 1 to N, we need to read the value of N by the user and then run a loop (we are using while loop here), logic to print numbers:

  • First, we are creating an object named scanner of Scanner class to read the input.
  • Declared a variable named n to store the value, given by the user, to read the input – we are using scanner.nextInt() – Here, nextInt() is the method of Scanner class, that will read an integer value.
  • Then, we are initializing loop counter (i) by 1 and checking condition within while till less than or equal to N and printing the numbers.

Example:

    Input:
    Enter the value of N: 15
    Numbers from 1 to 15
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to print the number from 1 to N using while loop in java

import java.util.Scanner;

public class Print_1_To_N_UsingWhile 
{
	public static void main(String[] args)
	{
		//loop counter initialisation
		int i =1;

		//create object of scanner class
		Scanner Sc = new Scanner(System.in);

		// enter the value of " n "
		System.out.print("Enter the value n : ");

		// read the value.
		int n = Sc.nextInt();

		System.out.println("Numbers are : ");

		while(i<=n)
		{
			System.out.println(i);
			i++;
		}
	}
}

Output

Enter the value n : 15
Numbers are : 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Core Java Example programs for Beginners and Professionals

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to find addition and subtraction of t... >>
<< Java program to print numbers from 1 to N using fo...