Java TOPIC 19 – WHILE LOOPS LESSON NOTE LOOP In
programming, a loop is a structure that permits the repetition of
statements. PSEUDOCODE EXAMPLE Here is a
pseudocode example of a loop that would display “Hello” one hundred times. Loop 100 times Display “Hello” End Loop THREE TYPES OF LOOPS IN
JAVA There are
three types of loops in Java:
We will focus
on the while loop in this lesson. We
will also briefly visit the do-while loop. ITERATION Loops allow
us to repeat a section a code multiple times. Each repetition is referred to
as an iteration (or simply as a
“pass”). WHILE LOOP TEMPLATE Here is the
template for the while loop: while (condition) { //statement block } The statement
block continues to be executed as long as the condition is true. INFINITE LOOP If the condition
is such that it always remains true, the program will loop forever. This is called an infinite loop. Example 1 – An infinite loop
{ System.out.println("Forever"); }
Example 2 – Another infinite loop
{ System.out.println("Still forever"); }
EXAMPLES OF PROGRAMS
WITH LOOPS Example 1 – Write a program that will display
“Mr. Campeau rocks” ten times on screen.
(You can make it display 100 times if you really want to.) Use a loop. int x = 1; { System.out.println("Mr. Campeau rocks"); } Example 2 – Write a program that will output
numbers 1 to 100 to screen. int x = 1; while (x <= 100) { System.out.println(x); x++; } Example 2B – Write a program that will output
numbers 1 to n to screen. The value of n is to be
provided for the user.
int max = scr.nextInt();
while (x <= max) { System.out.println(x); x++; } Example 3 – Write a program that will output all
even numbers starting at 20 going down to 0. Solution 1 int y
= 20; while
(y >= 0) { System.out.println(y); y = y – 2; } Solution 2 int y
= 20; while
(y >= 0) { if (y % 2 == 0) { System.out.println(y); } y = y – 1; } Example 4 – Write a program that outputs the
sequence tn = 3n + 1 for n ranging from 0 to
10. So, the program should output 1,
4, 7, 10, …, 31 int n = 0; while (n <= 10) { tn = 3 * n + 1; System.out.println(tn); n++; }
int x = 0; while (x <= 1000) { if (x %
17 == 0 || x % 29 == 0) { System.out.println(x); } x++;
//increment by 1 } |
|
|