Write a Java program that asks the user to enter an integer number N and successively display all the odd numbers that are less than or equal to N.
Improve the program so that it also displays the number of odd numbers
less than or equal to N.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = in.nextInt();
int count = 0;
while (true) {
if (number % 2 != 0) {
System.out.println(number);
count++;
}
if (number == Integer.MIN_VALUE) {
break;
}
number--;
}
System.out.println("The number of odd numbers: " + count);
}
}
Comments
Leave a comment