While & Do-While Loops

OliverE

Power member.
Reputation
0
While & Do-While Loops

While Loops

Pseudo Example
WHILE there are customer entries
read customer data
process invoice
END-WHILE


Example
The example below is a very simple while loop.
It asks the user if they want to enter the while loop If the user enters 'Y' then the loop is entered. If they enter 'N' then the loop is skipped and the program ends.
Upon entering the loop they are then asked if they want to stay in the loop. If the user enters 'Y' the loop is repeated or looped. If the user enters 'N' then then they exit the loop and the program ends.

[java]import java.util.*;
public class Whileloop
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
char ans;

System.out.println("Do you want to go into the loop [Y/N] > ");
ans = sc.next()charAt(0);

while( ans == 'Y')
{
System.out.println("Do you want to stay in the loop [Y/N] > ");
ans = sc.next()charAt(0);
}
System.out.println(" Program finished");
}
}[/java]

Do-While Loops

Pseudo Example
DO
read a character
process character
WHILE full stop is not encountered


Example
The difference between a while and do while loop is that a do-while loop does the action first, hence do-while. In a while loop you check the condition first then the action, with do whiles you do the action and then check the condition.
The the example below you are asked to pick a number betwwen 1 and 100. It then checks the value to make sure if its between 1 and 100. If its not then it loops back and asks again, if it is then it closes the program.
[java]import java.util.*;
public class doWhileloop
{
public static void main(String args[ ])
{
Scanner sc = new Scanner(System.n);
int guess;

do
{
System.out.println("I'm thinking of a number between 1 and 100" );
System.out.println("What do you think it is?");
guess = sc.nextInt();
}
while((guess < 1) || (guess > 100)) ; // Process guess value
System.out.println("Program finished");
}
}[/java]

Let me know if you have any questions
 
Back
Top