Skip to main content

Command Palette

Search for a command to run...

Java Programming : Print natural numbers using for loop

Updated
1 min readView as Markdown
Java Programming : Print natural numbers using for loop

Example

Input
5
Output
1
2
3
4
5

Required to know

Use of Variables, Use of different operators like assignment or arithmetic operators, Use of methods like System. out.print(), and use for loop, and Use of Data types.

Steps

  • Take range as 5.

  • Run a for loop with the range 5, without any incrementation of 2. Such that it prints only natural numbers.

  • Print the 5 natural numbers.

Case 1: - this one is when the range is already mentioned, like how many numbers you have to print.

import java.util.Scanner; 
public class number {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        int n = 5; 
        for(int i = 1; i<=5;i++){
            System.out.println(+i); 
        }
    }
}

Case 2: - this one is when the range is not defined, but we are taking it as an input from the user.

import java.util.Scanner; 
public class number {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in); 
        int n; 
        System.out.print("Enter the number"); 
        n = sc.nextInt(); 
        for(int i = 1; i<=5;i++){
            System.out.println(+i); 
        }
    }
}

More from this blog

TheCodingcoder

60 posts

Empowering the coding community by simplifying complex tasks.