Repetition (While-Loop) [ccd@ku version] 01204111 Computer and Programming Department of Computer Engineering Kasetsart University Cliparts are taken from http://openclipart.org Please comment or report errors to ccd@ku.ac.th
Outline While loop structure Two types of controlled loops Do-while loop structure
Code.org Revisited: Artist The Artist must be ordered to draw a hexagon by repeating the forward and turn-right commands 6 times! static void Main() { Forward(100); TurnRight(60); Forward(100); TurnRight(60); Forward(100); TurnRight(60); Forward(100); TurnRight(60); Forward(100); TurnRight(60); Forward(100); TurnRight(60); } Try it at https://studio.code.org/s/artist/stage/1/puzzle/4
Using a Loop Structure The previous code has a lot of repetitions Want to change the size of the hexagon, 6 places need change With a loop structure, the code can be made much shorter, clearer, and more flexible E.g., what if we want to draw a 10-gon, or n-gon instead static void Main() { int repeat = 0; while (repeat < 6) { Forward(100); TurnRight(60); repeat = repeat + 1; } }
Fundamental Control Structures We have already learned and used these three control structures. Sequence Subroutine Selection (or Branching) Repetition (or Iteration or Loop)
Fundamental Control Structures Sequence Subroutine Selection Repetition
Repetition (or Iteration or Loop) Within a method, we can alter the flow of control using either selections or loops. In C#, the loop statements while, do-while, for, and foreach allow us execute a statement or a block repeatedly. Like selections, a loop uses a boolean expression to control how the loop repeats.
Task: Hello World n times Write a program to write Hello World! n times, where n 0 is the input. After that, write Goodbye! once. Sample Run Sample Run Sample Run How many times? 4 Hello World! Goodbye! How many times? 0 Goodbye! How many times? 1 Hello World! Goodbye!
Hello World n times – Topmost Level The Main method: Reads a nonnegative integer n. Write Hello World n times. Write Goodbye! static void Main() { int n = ReadInt("How many times? "); WriteHello(n); Console.WriteLine("Goodbye!"); Console.ReadLine(); }
Hello World n times – Input Our good old ReadInt() method: static int ReadInt(string prompt) { Console.Write(prompt); return int.Parse(Console.ReadLine()); }
Hello World n times – Program (so far) using System; class Hello { static void Main() { int n = ReadInt("How many times? "); WriteHello(n); Console.WriteLine("Goodbye!"); Console.ReadLine(); } static int ReadInt(string prompt) { Console.Write(prompt); return int.Parse(Console.ReadLine()); } static void WriteHello(int n) { } } Code for the WriteHello()
WriteHello() method – Steps The WriteHello() method: receives n as its parameter. repeats writing Hello World! n times. How to do that? Let’s devise a “counter” scheme.
WriteHello() method – Steps Designing a counter-controlled loop: A variable count records the number of times Hello World has been written so far. Devise the scheme and experiment with it. Let’s say n is 2 round n count next round? action updated Pre-loop 2 #1 2 0 Yes Write once 1 #2 2 1 Yes Write once 2 #3 2 2 No So, the loop exits
WriteHello() – Constructing a loop Pre-loop statements round n count next round? action updated Pre-loop 2 #1 Yes Write once 1 #2 #3 No n is given count = 0 count < n Write “Hello World” count = count+1 F T Write once 2 loop condition This column implies that the condition for doing another round is _________ Loop-body statements count < n
WriteHello() – Check Boundary Cases round n count next round? action updated Pre-loop n is given count = 0 count < n Write “Hello World” count = count+1 F T #1 0 0 No Yes, it works! The loop-body statements will never be executed at all. We should also check the boundary cases when n is 0 (or negative) to see if our loop still works.
WriteHello() – Code it in C# n is given count = 0 count < n Write “Hello World” count = count+1 F T To express the loop in C#, we need a new statement: The while statement static void WriteHello(int n) { int count = 0; } while (count < n) { Console.WriteLine("Hello World!"); count = count+1; }
The while Statement while (condition) statement; C# Syntax Semantics while (condition) statement; condition F T statement condition must be a boolean expression The while statement as a whole is actually a single C# statement
A block of statements within while C# Syntax Semantics while (condition) condition F T statement { statement; . . statement; }
Example: while statement in WriteHello() n is given count = 0 count < n Write “Hello World” count = count+1 F T count < n Write “Hello World” count = count+1 F T while (count < n) { Console.WriteLine("Hello World!"); count = count+1; }
Types of Controlled Loop Counter-controlled loop A counter variable controls the number of times the loop will repeat. Event-controlled loop The loop continues to repeat until some event occurs.
Counter-controlled Loop The loop uses a counter variable to control the number of times the loop will repeat. The number of times the loop will repeat can be determined before the loop starts.
Counter-controlled Loop - Pattern Initialize the counter counter is within the limit? Update the counter F T Some computations Initialize the counter; while (counter is within the limit) { Update the counter; } Some computations
WriteHello() uses a counter-controlled Loop Initialize the counter; while (counter is within the limit ) { Update the counter; } Some computations static void WriteHello(int n) { int count = 0; while ( count < n ) { Console.WriteLine("Hello World!"); count = count+1; } }
counter-controlled loops More Example Another example on counter-controlled loops ณ. บัดนาว!
Task: Print a Fahrenheit-to-Celcius Table Print a conversion table from Fahrenheit to Celcius from 212 F to 32 F, decreasing by 20 F. Sample Run
Print a Fahrenheit-to-Celcius Table- Ideas The formula to convert fahrenheit to celcius: celcius = (5/9)*(fahrenheit-32) We’ll write a method PrintFahToCel() to do the task. We’ll construct a counter-controlled loop in which the fahrenheit value itself is the counter. Note that for each repetition through the loop, the counter is decreasing by 20 from 212 to 32.
PrintFahToCel() method – Loop Design Designing a counter-controlled loop: A variable fah that stores the value of farenheit is the counter and is also used in the computation. So, the condition for doing another round is …………... Devise the loop algorithm fah >= 32 round fah next round? action updated Pre-loop 212 #1 212 Yes Compute for 212 192 #2 192 Yes Compute for 192 172 … … … … … #Last 32 Yes Compute for 32 12 #Last+1 12 No So, the loop exits
PrintFahToCel() – from design to code round fah next round? action updated Pre-loop 212 #1 Yes Compute for 212 192 #2 Compute for 192 172 … #Last 32 Compute for 32 12 #Last+1 No fah = 212; while (fah >= 32.0) { cel = (5.0/9)*(fah-32); Console.WriteLine("{0} {1}", fah, cel); fah = fah - 20; }
PrintFahToCel() – The Complete Code static void PrintFahToCel() { double cel, fah; Console.WriteLine("{0,12}{1,12}", "fahrenheit", "celcius"); Console.WriteLine("{0,12}{1,12}", "----------", "-------"); fah = 212.0; while (fah >= 32.0) { cel = (5.0 / 9) * (fah - 32); Console.WriteLine("{0,12:f1}{1,12:f1}", fah, cel); fah = fah - 20; } Console.WriteLine("{0,12}{1,12}", "----------", "-------"); } Please write the Main method by yourself.
Event-Controlled Loop The loop continues to repeat until some event occurs, which breaks the loop conditon. The number of times the loop will repeat is hard (or impossible) to predict before the loop starts.
Event-Controlled Loop - Pattern Pre-loop setup Condition (still holds?) F T Some computations Pre-loop setup; while (Condition) { } Some computations Computation inside the loop must eventually trigger an event that breaks the loop condition. Otherwise, the loop will repeat infinitely.
event-controlled loops Example An example on event-controlled loops ณ. บัดนาว!
Task: Score Average We want to write a program to read all students’ scores and compute the average of them. Suppose we don’t know in advance how many students there are. How can the program know that the input has ended? One possible solution: use a special value called a sentinel to indicate “the end of data entry” We’ll use -1 as the sentinel in this program. The sentinel must be chosen so that it cannot be a normal input value.
Score Average – I/O Specification Enter score (-1 to end): 75 Enter score (-1 to end): 94 Enter score (-1 to end): 97 Enter score (-1 to end): 88 Enter score (-1 to end): 70 Enter score (-1 to end): 64 Enter score (-1 to end): -1 The average of 6 score(s) is 81.33 Sample Run Sample Run Enter score (-1 to end): 64 Enter score (-1 to end): -1 The average of 1 score(s) is 64.00 Sample Run Enter score (-1 to end): -1 No score entered
Score Average – Topmost Steps The Main() method’s Algorithm: Calls the method ReadScoresAndFindAverage() to read all the scores, then compute and return the number of input scores and the score average. Print the number of input scores and the average. Also take care of the case when there are no scores entered.
Score Average – Topmost Steps static void Main() { double average; // the score average int nscores; // the number of input scores ReadScoresAndFindAverage(out nscores, out average); if (nscores > 0) Console.WriteLine( "The average of {0} score(s) is {1:f2}", nscores, average); else Console.WriteLine("No score entered"); Console.ReadLine(); // you know why by now. }
ReadScoresAndFindAverage() – Design The method ReadScoresAndFindAverage(): What has to be done by this method: It has two output parameters, count and average, that will send back the number of input scores and the average, respectively. It uses a loop to read a new score into the variable score repeatedly until -1 is entered. Since average = (the sum of all scores)/count, it needs another variable sum to store the sum of all scores. Each iteration of the loop must add the newly read score into sum. Important variables
ReadScoresAndFindAverage() – Loop Design Use an event-controlled loop: The event that breaks the condition of the loop is when the input is -1. Let’s say The inputs are 20, 12, 15, -1 Devise the loop algorithm: round score next round? count sum (read) Pre-loop 20 #1 20 Yes 1 (0)+20 12 #2 12 Yes 2 (0+20)+12 15 #3 15 Yes 3 (0+20+12)+15 -1 #4 -1 No So, the condition for doing another round is …………... So, the loop exits score != -1
ReadScoresAndFindAverage() – Loop Design Check a boundary case: The inputs are 20, -1 round score next round? count sum (read) Pre-loop 20 #1 20 Yes 1 (0)+20 -1 #2 -1 No It works perfectly! loop exits Check a boundary case: The input is only -1 round score next round? count sum (read) Pre-loop -1 #1 -1 No loop exits
ReadScoresAndFindAverage() – From Design to Code round score next round? count sum (read) Score Pre-loop 20 #1 Yes 1 #2 12 (0)+20 #3 -1 No 2 (0+20)+12 15 #4 3 (0+20+12)+15 count = 0; int sum = 0; int score = ReadInt("Enter score (-1 to end): "); while (score != -1) { count = count + 1; sum = sum + score; score = ReadInt("Enter score (-1 to end): "); }
ReadScoresAndFindAverage() – Complete Code static void ReadScoresAndFindAverage(out int count, out double average) { count = 0; int sum = 0; int score = ReadInt("Enter score (-1 to end): "); while (score != -1) { count = count+1; sum = sum+score; score = ReadInt("Enter score (-1 to end): "); } if (count > 0) average = (double)sum / count; else average = 0; }
Caveats: Infinite Loop int i = 0; int n = ReadInt("Enter a input n: "); while (i < n) { Console.WriteLine(i); i = i - 1; } What is the output if user enters 5? i becomes -1, -2, -3,… The infinite loop occurs when the condition of the loop is always true.
Next Topic ณ. บัดนาว! What if some computation is to be executed repeatedly but at least once? ณ. บัดนาว!
Code for the CheckPassword() method Task: Check Password Write the method CheckPassword() that keeps asking for a password until the correct one is entered Enter password: I hate coding Enter password: Coding is hard Enter password: In code we trust Password correct using System; class Program { static void Main() { CheckPassword("In code we trust"); Console.WriteLine(“Password correct"); Console.ReadKey(true); } static void CheckPassword(string password) { } } 1: 2: 3: 4: 5: 6: 7: 8: 9: . Code for the CheckPassword() method
CheckPassword() – Steps: version 1 Read input from user Show a prompt BEGIN END true false input != password? We need to read the input once before we can check the condition.
CheckPassword() – Code: version 1 static void CheckPassword(string password) { string input; Console.Write("Enter password: "); input = Console.ReadLine(); while (input != password) { Console.Write("Enter password: "); input = Console.ReadLine(); } } Code gets repeated
Loop: do-while Statement C# Syntax Semantics do statement; while (condition); condition False True statement Condition must be a boolean expression
A block of Statements within do-while C# Syntax Semantics condition False True statement do while (condition); { statement; . . statement; }
CheckPassword() – Steps: version2 Use a do-while structure Read input from user Show a prompt BEGIN END true false input != password
CheckPassword() – code: version 2 static void CheckPassword(string password) { string input; do { Console.Write("Enter password: "); input = Console.ReadLine(); } while (input != password); } Code becomes slimmer. No duplicates.
Compare two kinds of loops int i = 0; while (i < 5) { Console.WriteLine(i); i = i + 1; } Console.WriteLine("->{0}", i); 1 2 3 4 ->5 Output: int i = 0; do { Console.WriteLine(i); i = i + 1; } while (i < 5); Console.WriteLine("->{0}", i); 1 2 3 4 ->5 Output:
Compare two kinds of loops int i = 5; while (i < 5) { Console.WriteLine(i); i = i + 1; } Console.WriteLine("->{0}", i); Output: ->5 int i = 5; do { Console.WriteLine(i); i = i + 1; } while (i < 5); Console.WriteLine("->{0}", i); Output: 5 ->6
Conclusion Comparing the two loop structures: Types of controlled loops Counter-controlled loop Event-controlled loop while do-while Condition is checked before each iteration. Condition is checked after each iteration. Execute loop body zero or more times. Execute loop body one or more times. No ending semicolon if loop body is a block. Always ending with a semicolon.