do while loops in java with examples
All Contributions
Use a do..while loop to write a java program that asks the user to input a sequence of integers. Then, it will find and display each of the following:
- The number of integers.
- The sum of the integers.
- The number of odd integers.
- The number of even integers.
Hint: Use (-1) as a sentinel value to end the sequence and skip an endless loop
import java.util.Scanner;
public class Exercise3{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int number, odd = 0, even = 0, sum = 0, count = 0;
do {
System.out.println("Enter an integer :");
number = input.nextInt();
if (number == -1)
break;
if (number % 2 == 0)
even++;
else
odd++;
sum += number;
count++;
} while (true);
System.out.println("Number of integers is " + count);
System.out.println("Sum of integers is " + sum);
System.out.println("Number of odd integers is " + odd);
System.out.println("Number of even integers is " + even);
}
}
total contributions (2)
print hello world 10 times using do while loop: