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

Slides:



Advertisements
Similar presentations
Computer Science 1620 Loops.
Advertisements

Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 6 - Repetition. Introduction u Many applications require certain operations to be carried out more than once. Such situations require repetition.
Chapter 5: Loops and Files.
Loops – While, Do, For Repetition Statements Introduction to Arrays
Loops Repeat after me …. Loops A loop is a control structure in which a statement or set of statements execute repeatedly How many times the statements.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
ECE122 L9: While loops March 1, 2007 ECE 122 Engineering Problem Solving with Java Lecture 9 While Loops.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Control Structures II. Why is Repetition Needed? There are many situations in which the same statements need to be executed several times. Example: Formulas.
1 What is a loop? A loop is a repetition control structure that causes a single statement or block to be executed repeatedly Loops.
Java Programming: From the Ground Up
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
Iteration (Loop) partI Thanachat Thanomkulabut. Consider the following program! using System; Namespace SimPleExample { class SimPleC { class SimPleC.
Programming Logic and Design Fifth Edition, Comprehensive
Chapter 5 Loops.
Mr. Dave Clausen1 La Cañada High School Chapter 6: Repetition Statements.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
1 Conditionals In many cases we want our program to make a decision about whether a piece of code should be executed or not, based on the truth of a condition.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
Chapter 5: Control Structures: Iteration Visual Basic.NET Programming: From Problem Analysis to Program Design.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
CMP 131 Introduction to Computer Programming Violetta Cavalli-Sforza Week 10.
Loops cause a section of a program to be repeated a certain number of times. The repetition continues while a condition remains true. When a condition.
CONTROL STATEMENTS LOOPS. WHY IS REPETITION NEEDED?  There are many situations in which the same statements need to be executed several times.  Example:
Repetition Statements (Loops) The do while Loop The last iteration structure in C++ is the do while loop. A do while loop repeats a statement or.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
Copyright © 2012 Pearson Education, Inc. Chapter 5: Loops.
Repetition Repetition allows you to repeat an operation or a series of operations many times. This is called looping and is one of the basic structured.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Repetition Statements (Loops). 2 Introduction to Loops We all know that much of the work a computer does is repeated many times. When a program repeats.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
COMP Loop Statements Yi Hong May 21, 2015.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
1 st Semester Module4-1 Iteration statement - while อภิรักษ์ จันทร์สร้าง Aphirak Jansang Computer.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
Introduction to Programming G50PRO University of Nottingham Unit 6 : Control Flow Statements 2 Paul Tennent
Chapter 7 Control Structures. Java has very flexible three looping mechanisms. You can use one of the following three loops:  while Loop  do...while.
Computer Programming -1-
Lecture 4b Repeating With Loops
REPETITION CONTROL STRUCTURE
Week 4 – Repetition Structures / Loops
CiS 260: App Dev I Chapter 4: Control Structures II.
JavaScript: Control Statements.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Looping.
Control Statements Loops.
Chapter 6: Repetition Statements
Control Statements Loops.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
PROGRAM FLOWCHART Iteration Statements.
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Iteration (Loop) part II
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

Iteration & Loop Statements 11 While Statement : Example

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

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

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

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

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 }

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

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

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

Iteration & Loop Statements 20 Sentinel-Controlled Loop: Example1

Iteration & Loop Statements 21 Sentinel-Controlled Loop: Example2

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 }

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')) }

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

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.

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.

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

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

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

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

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

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

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

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

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

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)

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

Iteration & Loop Statements 38 Break Statement : Example

Iteration & Loop Statements 39 Break Statement : Example

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

Iteration & Loop Statements 41 Continue Statement : Example

Iteration & Loop Statements 42