Presentation is loading. Please wait.

Presentation is loading. Please wait.

Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand.

Similar presentations


Presentation on theme: "Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand."— Presentation transcript:

1 Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand

2 Iteration & Loop Statements 2 What is loop? An iteration or looping structure can execute a (one) statement repeatedly. There are TWO kinds of iteration statements: –definite iteration statements –conditional iteration statements

3 Iteration & Loop Statements 3 Iteration Do..while Loop While Loop For Loop

4 Iteration & Loop Statements 4 Do..while Statement : Syntax do { Statement; }while (condition); condition true false Statement Maybe boolean constant,or boolean variable,or boolean expression

5 Iteration & Loop Statements 5 Do..while Statement : Example

6 Iteration & Loop Statements 6  Do..while statement is a conditional iteration statements  The loop body of a do..while statement will be executed first before the exit condition is checked  Do..while loop is also called a post-conditional loop because the condition is checked after the loop body  A do..while statement will execute at least once Do..while Statement : Remark

7 Iteration & Loop Statements 7 Do..while statement: Example1 n = 0; do { Console.Write(n); n++; } while (n > 5); n > 5 False True n = n +1 write n

8 Iteration & Loop Statements 8 Do..while statement: Example2 flag = true; do{ s=Console.ReadLine(); n=Convert.ToInt32(s); if (n > 0) Console.Write(n) else flag = false; }while (flag == true); flag == false false true read n n < 0 true write n false set flag = flase

9 Iteration & Loop Statements 9 Do..while statement : Remark Do..while loop is also called a post- conditional loop because the condition is checked after the loop body A do..while statement will execute at least once

10 Iteration & Loop Statements 10 While Statement : Syntax while (condition ) { Statement; } condition false true Statement Maybe boolean constant,or boolean variable,or boolean expression

11 Iteration & Loop Statements 11 While Statement : Example

12 Iteration & Loop Statements 12  Since the condition is checked before the execution of the loop body, a while-do loop is also called a pre-conditional loop.  As long as the entry condition is still true, the while loop will be repeated.  Zero loop will be executed if the entry condition is false at the beginning.  while statements are conditional iteration statements which execute the loop body only if the entry condition is true. While Statement : Remark

13 Iteration & Loop Statements 13 While Statement : Example1 n = 0; while (n <= 5) { Console.Write(n); n++; } n <= 5 False True write n n := n +1

14 Iteration & Loop Statements 14 While Statement : Example2 flag = true; while (flag==true) { s=Console.ReadLine(); n=Convert.ToInt32(s); if (n > 0) Console.Write(n) else flag = false; } flag == true false true read n n > 0 True Write n False flag = false

15 Iteration & Loop Statements 15 More about variable Declaration syntax ; A local variable is not automatically initialized and thus has no default value Lifetime of a local variable is into the block where variable is declared, and disappear after that block is achieved Duplicate name of variables declaration is not allow in same block

16 Iteration & Loop Statements 16 Sentinel-Controlled Loops Template: Read the first value of input variable while (input variable is not equal to sentinel) {... Read next value of input variable }

17 Iteration & Loop Statements 17 Sentinel-Controlled Loops Example: –Collecting Exam Scores: 1.Initialize Sum to 0 2.Read the first score into score 3.While Score is not the sentinel (e.g. -1) do 3.1 Add Score to Sum 3.2 Read the next score into Score

18 Iteration & Loop Statements 18 Use of Sentinel  A sentinel is a value used to control the termination of a loop.  E.g. User can choose to use –1 as the sentinel value to terminate the iteration. total =0; Convert.Write("Enter score (-1 to end): "); score=Convert.ToInt32(Console.ReadLine()); while (score != -1) { total := total + score; Convert.Write("Enter score (-1 to end): "); score=Convert.ToInt32(Console.ReadLine()); } Sentinel-Controlled Loops

19 Iteration & Loop Statements 19  Declare a string constant Password with value ‘computer’  Declare a string variable Entry  Output the statement ‘Enter the password:’  Read the user input  Compare the Entry and Password,  If they are the same, output ‘Valid password’  If not, repeat the following process until you have obtain the correct password  output ‘Invalid password! Enter again:’  Read the user input Sentinel-Controlled : Example

20 Iteration & Loop Statements 20 Sentinel-Controlled Loop: Example1

21 Iteration & Loop Statements 21 Sentinel-Controlled Loop: Example2

22 Iteration & Loop Statements 22 Loops Controlled by Boolean Flags Flag: –A Boolean variable whose value is changed from False to True when a particular event occurs Boolean Flags Template: Initialize flag to false while (flag is still False) {... Reset flag to True if event being monitored occurs }

23 Iteration & Loop Statements 23 Loops Controlled by Flags : Example Reading data characters and save the first digit character read DigitRead = false; while (!DigitRead) { Console.Write ("Enter another data character >"); st = Console.ReadLine(); NextChar = Convert.ToChar(st); DigitRead =(('0'<=NextChar) && (NextChar<='9')) }

24 Iteration & Loop Statements 24 For Statement : Syntax for( [initializers] ; [condition] ; [iterators] ) { statement; } condition false true Statement iterators Intializers

25 Iteration & Loop Statements 25 For Statement : Syntax initializers –A comma separated list of expressions or assignment statements to initialize the loop counters. expression –An expression that can be implicitly converted to bool or a type that contains overloading of the true and false operators. The expression is used to test the loop-termination criteria.true false iterators –Expression statement(s) to increment or decrement the loop counters.

26 Iteration & Loop Statements 26 For Statement : Remark The for statement executes the statement repeatedly as follows: First, the initializers are evaluated. Then, while the expression evaluates to true, the statement(s) are executed and the iterators are evaluated. When the expression becomes false, control is transferred outside the loop.

27 Iteration & Loop Statements 27 For Statement : Example1 public class ForLoopTest { public static void Main() { for(int i = 1; i <= 5; i++){ Console.WriteLine(i); } Output 1 2 3 4 5

28 Iteration & Loop Statements 28 For Statement : Example2 Output the following line to the screen using one writeln statement only A B. Z

29 Iteration & Loop Statements 29 For Statement : Example3 Write a program to find the summation of a series of numbers and output the following 1+2+…..+99 = 4950

30 Iteration & Loop Statements 30 Do..while vs. While condition false true Statement condition true false Statement Do..while statementWhile statement

31 Iteration & Loop Statements 31 While vs. For condition false true Statement While statementFor statement condition false true Statement iterators Intializers

32 Iteration & Loop Statements 32  A nested loop is formed by placing an inner loop inside an outer loop.  The outer loop is executed first.  If the inner loop is reached, the outer loop is suspended and the inner loop is executed.  After the inner loop is terminated, the program continues to execute the remaining statement(s) in the outer loop Nested Loops

33 Iteration & Loop Statements 33 for (int outer = 1; outer <= 4; outer++) { for (int inner = 1; inner <=5; inner++) { Console.WriteLine("Outer = {1} & Inner = {0}", inner, outer); } Nested for loops  Do not use the same control variable in the outer loop and the inner loop Nested Loops : Example

34 Iteration & Loop Statements 34 int outer = 1; while (outer <= 4) { int inner = 1 ; while (inner <= 5) { Console.WriteLine("Outer = {1} & Inner = {0}", inner,outer); inner := inner +1; } outer := outer +1; } Nested while loops Nested Loops : Example

35 Iteration & Loop Statements 35 int outer = 1; do { int inner = 1; do { Console.WriteLine("Outer = {1} & Inner = {0}", inner,outer); inner := inner +1 } while (inner < 6); outer := outer + 1; inner := 1 }while (outer < 5); Nested Loops : Example Nested do..while loops

36 Iteration & Loop Statements 36 Infinite looping  No statements in the loop body can update the value of the entry condition. (E.g. omit counter = counter +1)  The statement(s) in the loop body make(s) the variable become far away from the stopping condition. (E.g. counter = counter – 1)

37 Iteration & Loop Statements 37 Break Statement The break statement terminates the closest enclosing loop or switch statement in which it appears Control is passed to the statement that follows the terminated statement

38 Iteration & Loop Statements 38 Break Statement : Example

39 Iteration & Loop Statements 39 Break Statement : Example

40 Iteration & Loop Statements 40 Continue Statement The continue statement passes control to the next iteration of the enclosing iteration statement in which it appears

41 Iteration & Loop Statements 41 Continue Statement : Example

42 Iteration & Loop Statements 42


Download ppt "Iteration & Loop Statements 1 Iteration or Loop Statements Dept. of Computer Engineering Faculty of Engineering, Kasetsart University Bangkok, Thailand."

Similar presentations


Ads by Google