Write a program that gets an integer from the user. Count from 0 to that number. Use a for loop to do it.
Solution:
//Importing the Scanner Class
import java.util.Scanner;
public class ForLoopExample {
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{
for(int j=0;j<=i;j++){
//Printing the result
System.out.print(j + " ");
}
}
}
}
No comments:
Post a Comment