Академический Документы
Профессиональный Документы
Культура Документы
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 dowhile are compared with each other. while Repeats statements while its condition is true. The condition is tested at the start. do-while Repeats statements while its condition is true. The condition is tested at the end.
So, there is a chance that the statements are not So, the statements have to be carried out at least executed at all if the condition starts as false. once since the condition is checked at the end.
Statements Execute
to Statements Execute to
Is Condition True?
True
Is Condition True?
False False
True
Mr. A. Gatt
Page 1 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); } }
Mr. A. Gatt
Page 2 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 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 users choice. The menu keeps on showing until the user decides to quit.
Mr. A. Gatt
Page 3 of 10
Start
Display Menu
Input Choice
End
Mr. A. Gatt
Page 4 of 10
Computer Studies 2013 Syllabus 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); } }
Mr. A. Gatt
Page 5 of 10
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
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); } } } Mr. A. Gatt Page 6 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 2 3 4 5 6 7 8 9 10 } } } class UseFor { public static void main (String args[]){ int choice = 1; System.out.println(Enter a list of numbers, type 0 to stop); for (int i=1; (i<=10) && (choice!=0); i++) { System.out.print( i =+i+ : ); choice = Keyboard.readInt();
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?
Mr. A. Gatt Page 7 of 10
i) j)
What do the && mean in the condition and what is it called? 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.
Mr. A. Gatt
Page 8 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.
Start
N=0 HI =0
Num>HI ?
HI=NUM
N N=N+1
N<10?
N Output HI
Start
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.
Mr. A. Gatt
Page 9 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! ***
Mr. A. Gatt
Page 10 of 10