do while loops in java with examples

0

 

 

 

what is the output of this code:

int num = 4; 
do { 
 System.out.println(num); 
 num*=2; 
} while (num <= 20); 

 

answer:

4 
8 
16

 

 

All Contributions

print hello world 10 times using do while loop:

public class Main
{
	public static void main(String[] args) {
	 int i=1;
	    do{
		System.out.println("Hello World");
		i++;
	    }
            while(i<=10);
	}
}

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)

New to examplegeek.com?

Join us