A LESSON IN LOOPING What is a loop? A portion of a program that repeats a statement or group of statements
while statement (while-loop) TYPES OF LOOPS while statement (while-loop) Action that is coded in braces (body of the while loop) is repeated (in order) until the condition of the while loop is met. Repetition is called an iteration of the loop
CODING EXAMPLE How many greetings? Ask the user how many ‘hello’ statements they want to print and execute. Print ‘That’s All!’ when finished.
SYNTAX while(condition) { Insert code to repeat here }
EXAMPLE
TYPES OF LOOPS do while statement Similar to while statement, except that the loop body is always executed at least once. Do ‘this’ (at least once), while ‘this’ is true
Hello! Do you want another? CODING EXAMPLE Hello! Do you want another? Greet the user – ‘Hello!’, ask if they would like another greeting – input 1(yes) or 2(no)? Execute until user enters 2(no)
SYNTAX do { Insert code to repeat here }while(condition);
EXAMPLE