|
| |
while type Loops & Questions
while loop
A while loop differs from the for loop, in that it only contains a condition, and that the condition is tested at the beginning of the loop. This means that if the condition evaluates to false, it will not be executed at all. We call this a
pre-tested loop, because the test is made before executing the sequence of statements contained within.
int i = 1;
while (i <= 5) {
System.out.println ("count : " + i);
i++;
}
do...while loops
A variation on the while loop is the post-tested version. Two keywords are used for this loop, the
do and the while keywords.
int i = 1;
do {
System.out.println ("count : " + i);
i++;
} while (i <= 5)
Example of a menu using a do...while loop

There is no difference between a while, and a do...while loop other than pre-testing and post-testing.
Note that both must have:
- one or more control variables in the condition (int i);
- the control variable(s) must have been initialized to the correct value
(i = 1); and
- in the loop there must be a way to change the value of (at least one of)
the control variable(s) (i++).
| Try these ones: you should be able to use either type of
while loop |
- Make a Fahrenheit to Celsius conversion table, in columns, from -40
to 100 degrees Fahrenheit in 5-degree increments. Use C = (F - 32) * 5
/ 9
- Print the odd numbers from 100 down to 1.
- Create a table of values for the equation y = 2.135 x + 4.53 for
values of x from -10 to 10 in steps of 0.5.
- Create a table of values for the equation y = 3(x3 - 1.5x2
+ 4x - 1) for values of x from 2 to -4, changing by 1 each time.
- The square of a number can be found by adding successive odd
integers. For example, to find 42, add the first four odd
integers:
42 = 1 + 3 + 5 + 7 = 16
To find 62, add the first six odd integers:
62 = 1 + 3 + 5 + 7 + 9 + 11 = 36
Create a program that asks for a number and then uses a for loop to
calculate its square using this method.
- Add up the numbers from 1 to 100. Display the answer.
- Create a program that asks for a number and then uses a for loop to
calculate the sum of the numbers from 1 to the inputted number.
- Create a program that asks for a digit. If the user enters a letter
instead the loop should stop. Otherwise, it should ask for another
number. Hint: you may want to use a
String method that will test and see if the entered item is
in the String "0123456789" and
end or continue looping based on the result.
- Same as #8, but this time it only stops if the user enters a capital
X.
- Same as #8, but either an 'X' or an 'x' should stop the program.
- Same as #8, but this time add up the digits.
- Same as #8, but this time count the digits.
|
|