The java program given below will print the odd numbers between 1-100. I have used a do...while loop to print the odd numbers one by one. An if statement is also there inside the do...while loop to check whether the number is odd or even.
All the numbers is being checked by the condition if(i%2==1). That means all the numbers are being divided by 2 to check if any remainder found.
We know if remainder 1 found after dividing a number by 2, then it is obviously an odd number. So the program is written to print those numbers only.
In the condition there is written while (i<=100);, that means the loop will continue 100 times. If we change 100 to 50, then all the odd numbers between 1-50 will be printed.
public class OddNum{
public class OddNum{
public static void main(String arg []){ //a simple message System.out.println("The odd numbers are:"); //initializing integer type variable i int i=1; //do...while loop do{ //if statement to check the numbers for remainder if(i%2==1){ //displaying the expected numbers System.out.print(i+", "); } i++; } while (i<=100);//condition for do...while loop //for two line break System.out.println("\n\n"); } }
No comments:
Post a Comment