Home » Java solved programs » Core java programs

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



This is an Example of java for loop - In this java program, we are going to print numbers from 1 to N using for loop.
Submitted by Chandra Shekhar, on March 09, 2018

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 for 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, using for loop from 1 to N to print the numbers from 1 to N.

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

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

import java.util.Scanner;

public class Print_1_To_N_UsingFor
{
	public static void main(String[] args)
	{
		//create object of scanner class
		Scanner scanner = new Scanner(System.in);

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

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

		System.out.println("Numbers are : " );
		for(int i=1; i<=n; i++) 
		{
			System.out.println(i);
		}
	}
}

Output

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





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.

Comments and Discussions




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.