3. Write a program that will input a number and will display the numbers from 1 to input number. Use while / do while / for loop. Ex. Enter a number 5 Output: 1 2 3 4 5

PHOTO EMBED

Sun Dec 08 2024 11:15:59 GMT+0000 (Coordinated Universal Time)

Saved by @John_Almer

package displaynumbers;

import java.util.Scanner;
public class DisplayNumbers {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = input.nextInt();

        // Using a for loop
        for (int i = 1; i <= n; i++) {
            System.out.print(i + " ");
        }

        // Using a while loop
        int i = 1;
        while (i <= n) {
            System.out.print(i + " ");
            i++;
        }

        // Using a do-while loop
        i = 1;
        do {
            System.out.print(i + " ");
            i++;
        } while (i <= n);

        System.out.println();
    }
}
content_copyCOPY