Monday, November 4, 2013

Java do-while Loop example

Write a program that gets an integer from the user. Count from 0 to that number.
You must use a do-while loop.

Example:

Count to: 8
0 1 2 3 4 5 6 7 8


Solution:

//Importing the Scanner Class
import java.util.Scanner;

public class Question2UsingDoWhileLoop {
   
    public static void main(String args[]){
       
        //Creating Scanner object
        Scanner input = new Scanner(System.in);
        //Prompting user for input
        System.out.print("Please inter the number:");
        //Reading the input
        int i = input.nextInt();
        //Checking the received number
        if(i<0)
            System.out.println("Invalid input!!");
        else{
            int j=0;
            do{
                //Printing the result
                System.out.print(j + " ");
                j++;
            }
            while(j<=i);
        }
    }
}

No comments:

Post a Comment