Using do...while Loop Structure
Submitted by GeePee on Wednesday, May 20, 2015 - 21:43.
The following Java program is a do…while Loop structure. In Java, do is a reserved word. As with the other repetition structures, a do…while statement can be either a simple or compound statement. If it is compound statement, enclose it between curly brackets. The expression is called loop condition. I will be using the JCreator IDE in developing the program.
To start in this tutorial, first open the JCreator IDE, click new and paste the following code:
Sample run:
The statements
Is the if…else condition where outputs the program if it is divisible by 3 or not, and divisible by 9 or not.
- import java.util.*;
- public class doWhile
- {
- {
- int num, temp, sum;
- num = console.nextInt();
- temp = num;
- sum = 0;
- do
- {
- sum = sum + num % 10;
- num = num / 10;
- } while (num > 0);
- if (sum % 3 == 0)
- else
- if (sum % 3 == 0)
- else
- }
- }
Enter a positive integer: 320
The sum of the digits = 5
320 is not divisble by 3
320 is not divisble by 9
This program works as follows:
The statement System.out.print("Enter a positive integer: ");
prompts the user to enter a positive integer.
The statement num = console.nextInt();
store the next number in the variable num.
The statement temp = num;
temp is equals to variable num.
The statement sum = 0;
sets the value of variable sum to 0.
The statement sum = sum + num % 10;
extracts the last digit and add it to sum.
The statement num = num / 10;
remove the last digit.
The statement - do
- {
- sum = sum + num % 10;
- num = num / 10;
- } while (num > 0);<java> is the beginning and the end of the do..while loop.
Add new comment
- 54 views