Coding Practice

Write a Java program to print all-natural numbers from 1 to n. - using while loop

Print all-natural numbers from 1 to n. - using while loop
Sample Output
Print all natural numbers from 1 to n. - using while loop.

Enter a number: 7
1
2
3
4
5
6
7
Java-Source Code
//package loopinjava;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        
        int number, n;
        
        Scanner input = new Scanner(System.in);
        
        System.out.println("Print all natural numbers in reverse (from n to 1). - using while loop.\n");
        
        System.out.print("Enter a number: ");
        number = input.nextInt();

        n = number;
        while (n >= 1) {
            System.out.println(n);
            n--;
        }
    }
}
Sample Output
Print all natural numbers from 1 to n. - using while loop.

Enter a number: 7
1
2
3
4
5
6
7

No comments:

Post a Comment

Change Theme
X