p12 - iterations
TRANSCRIPT
![Page 1: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/1.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 1 of 10
Iterations (12)
while, do-while, for
During programming, certain code (or a block of statements) might need to be repeated for several times,
for instance inputting the marks of a whole class. However, rather than typing the same statement over and
over again, loops are used.
There are three different types of loops (or iterations) which are for, while and do-while. First while and do-
while are compared with each other.
while do-while
Repeats statements while its condition is true. Repeats statements while its condition is true.
The condition is tested at the start. The condition is tested at the end.
So, there is a chance that the statements are not
executed at all if the condition starts as false.
So, the statements have to be carried out at least
once since the condition is checked at the end.
Is Condition
True?
Statements to
Execute
True
False
Is Condition
True?
Statements to
Execute
True
False
![Page 2: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/2.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 2 of 10
Syntax
while (condition) {
//do this
//do this
}
Syntax
do {
//do this
//do this
} while (condition);
Example
class While {
public static void main (String args[]){
int n=10;
while (n>0) {
System.out.println(“n=”+n);
n--;
}
}
}
Example
class DoWhile {
public static void main (String args[]){
int n=10;
do {
System.out.println(“n=”+n);
n--;
} while (n>0);
}
}
The while loop
This loop keeps iterating while the condition is true. If the condition is false, the loop will stop and move on
to the next line after the loop (after the closing curly bracket) of the loop. Consider the following program.
class GuessNum {
public static void main (String args[]){
final int NUM=7;
int guess=0;
while (guess!=NUM) {
System.out.println(“Guess number (1-10)”);
guess=Keyboard.readInt();
}
System.out.printl(“Well done! You guessed”);
}
}
![Page 3: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/3.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 3 of 10
This program will keep asking the user to input a number from 1 to 10 and keep on asking for a number
until 7 is inputted.
The do-while loop
Sometimes it may be necessary to execute the body of the loop at least once, even if the condition is false
at the beginning; this can be useful in a menu situation. Consider the following program.
class DoWhileGuess {
public static void main (String args[]){
final int NUM=7;
int guess=0;
do {
System.out.println(“Guess number (1-10)…”);
guess=Keyboard.readInt();
} while (guess!=NUM);
System.out.println(“Well done! You Guessed”);
}
}
The do-while is very suitable for handling menu selection. The following flowchart depicts a program that
shows a menu and performs an arithmetic function depending on the user’s choice. The menu keeps on
showing until the user decides to quit.
![Page 4: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/4.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 4 of 10
Start
Input num1,
num2
Display
Menu
Input
Choice
Choice=1
?
Choice=2
?
Choice=3
?
Choice=4
?
num1+
num2
num1-
num2
num1*
num2
num1/
num2
End
Y Y Y Y
N N N N
![Page 5: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/5.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 5 of 10
class Menu {
public static void main (String args[]){
char choice;
boolean quit = false;
System.out.println(“Enter first number “);
int num1 = Keyboard.readInt();
System.out.println(“Enter second number “);
int num2 = Keyboard.readInt();
do {
System.out.println(“Menu”);
System.out.println(“1. Addition”);
System.out.println(“2. Subtraction”);
System.out.println(“3. Multiplication”);
System.out.println(“4. Division”);
System.out.println(“5. Quit”);
System.out.println(“Enter your choice 1-5:”);
choice = Keyboard.readChar();
switch (choice) {
case ‘1’ : System.out.println(num1+num2); break;
case ‘2’ : System.out.println(num1-num2); break;
case ‘3’ : System.out.println(num1*num2); break;
case ‘4’ : System.out.println(num1/num2); break;
case ‘5’ : quit = true;
default : System.out.println(“Invalid Choice”);
}
System.out.println();
} while (!quit);
}
}
![Page 6: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/6.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 6 of 10
The for loop
This loop is used when you know exactly the number of times you want to repeat a set of statements. The
for loop is structured as
for (initialization; condition; iteration)
statement;
During the iteration of the for loop, if the result of the test in the condition is true, then the for loop
continues to iterate but if the test is false, it stops. The iteration expression determines how the loop
control variable is changed each time the loop iterates. Consider the statement
for ( x = 0; x<10; x ++)
System.out.println(i);
The first part x=0 is used to initialize the start of the loop, in this case x=0; so it will start from 0.
The second part contains the condition that needs to be tested, in this case it is checking if it is less
than 10 (if it is the loop will continue)
The third part is to increment (add a one) the variable used in the loop
So, if this statement in incorporated in a small program:
class ForLoop {
public static void main(String args[]){
int x;
for (x=0; x<10; x++) {
System.out.println(“x =”+x);
}
}
}
The following program shows another example of a loop which prints letters from a to z.
class ForLoop {
public static void main(String args[]){
for (char low=’a’; low<=’z’; low++) {
System.out.println(low);
}
}
}
![Page 7: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/7.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 7 of 10
Activities
1. Draw a flowchart and then write an application using the while loop (condition at the start) to ask
the user to input a list of integer marks until -1 is inputted. Note that -1 is a rogue (sometimes called
dummy or terminator value) and is not to be considered as a mark.
2. Now change the application (1) to input also a list of integer marks and use a do-while loop to stop
entry of data when -1 is inputted.
3. Use application (2) above to find the sum of the marks entered.
4. Create a password program and include a while loop which allows the user three attempts to enter
the password. The program stops either if the password is correct (“Access Granted”) or if the user
enters the wrong password (“Access Denied”) after three consecutive tries.
5. Develop a program using a for loop to generate 5 random numbers between 1 and 43 for the Super
Five lottery.
6. Develop an application using a for loop to simulate the tossing of a coin 100 times and count how
many times you get Heads and how many times you get Tails.
7. Consider the program
1 class UseFor {
2 public static void main (String args[]){
3 int choice = 1;
4 System.out.println(“Enter a list of numbers, type 0 to stop”);
5 for (int i=1; (i<=10) && (choice!=0); i++) {
6 System.out.print(“ i =”+i+” : “);
7 choice = Keyboard.readInt();
8 }
9 }
10 }
a) In which lines are variables directly initialized?
b) Which type of loop is being used in this program?
c) Write down the line numbers that represent a loop.
d) Which line is outputting a prompt?
e) What happens if the semicolon at the end of line 3 is left out?
f) To what value is the control variable of the loop initialized in line 5?
g) Write down the condition part of the loop in line 5.
h) What is the i++ doing in line 5?
![Page 8: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/8.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 8 of 10
i) What do the && mean in the condition and what is it called?
j) Explain exactly when the double condition will result in false.
k) What does the user have to type to stop data entry?
l) What test data would you use to check that the program is working properly?
m) What happens if the user keeps on entering the data without typing a zero?
8. Draw a flowchart to ask the user to input 10 marks, to find out how many marks are equal to or
above 50 and how many marks are below 50. Hence, output the number of failures and the number
of passes. Code the program, try it and test it.
9. Ask the user to input two integer numbers, num1 and num2, and output all the multiples of four
between those two numbers. You need to use a for loop from num1 to num2.
![Page 9: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/9.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 9 of 10
10. Write a program to input 10 integer marks in the range of 0 to 100 and output the highest based on
the following flowchart.
11. Change the flowchart for question 10 above to output the lowest mark. Then change the program
as well.
12. Now combine the flowcharts in question 10 and 11 above to input 10 integer marks in the range of
0 to 100 and the output the highest and the lowest, then write the program to do it.
13. Develop the program in question 12 to input 10 marks, find and output the sum, the average, the
highest and the lowest mark.
Start
N=0 HI =0
Input Next Num
Num>HI
?
HI=NUM
N=N+1
N<10?
Output HI
Start
N
Y
Y
N
![Page 10: P12 - Iterations](https://reader036.vdocuments.us/reader036/viewer/2022081804/55328a8c55034615638b463f/html5/thumbnails/10.jpg)
Computer Studies 2013 Syllabus
Mr. A. Gatt Page 10 of 10
14. Draw a flowchart then develop a program to create the following application to display the
following menu:
a. Enter Marks
b. Display Statistics
c. Display Grades
d. Quit
Then using a do-while, ask the user to enter a choice and through the use of a switch, depending on
the choice, output a single line as follows:
If 1 is chosen, output “You chose to enter marks”
If 2 is chosen, output “You chose to display sum, highest, lowest, average”
If 3 is chosen, output “You chose to display the grades”
If 4 is chosen output “End of Program”
15. Study carefully this pseudo-code:
a. Generate a number between 1 and 100
b. Ask the user to enter a guess
c. If number is guessed, then output “Number guessed” and go to step f
d. If the number is not guessed, then output “Number is higher” if the guess is lower or
output “Number is lower” if the guess is higher
e. Go to step (b)
f. Stop
Draw a flowchart to do the same task as the pseudo-code above.
Develop an application to implement this algorithm.
The number of tries can be reduced if the person guessing the number uses the techniques of a
‘binary search’. Find out what this is and try it out when running the program to try and guess
the number in as few tries as possible. If properly applied then you can guess the number in 7
or at most 8 tries!
***