Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming.

Slides:



Advertisements
Similar presentations
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Advertisements

Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
True or false A variable of type char can hold the value 301. ( F )
Branching Constructs Review l what are branching constructs? what type of branching constructs have we studied? l what is nested if? l what is multiway.
Computer Science 1620 Loops.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 Lecture 11:Control Structures II (Repetition) (cont.) Introduction to Computer Science Spring 2006.
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.
1 Chapter 3 Flow of Control. 2 Outline  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound statement.
Summary of Loops Programming. COMP102 Prog Fundamentals I: Summary of Loops /Slide 2 Which Loop to Use? l for loop n for calculations that are repeated.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
Chapter 5: Control Structures II (Repetition)
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
Introduction to Computer Programming in c
CONTROL FLOW IN C++ Satish Mishra PGT CS KV Trimulgherry.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
Department of Computer Science and Engineering, HKUST 1 HKUST Summer Programming Course 2008 C++ Control Statements ~ Selection and Iteration.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 02 (Part III) Introduction to C++ Programming.
Quiz Answers 1. Show the output from the following code fragment: int a = 5, b = 2, c = 3; cout
Looping II (for statement). CSCE 1062 Outline  for statement  Nested loops  Compound assignment operators  Increment and decrement operators.
Copyright © Nancy Acemian 2004 For Loops-Break-Continue COMP For loop is a counter controlled loop. For loop is a pretest loop. Used when number.
 Wednesday, 9/18/02, Slide #1 CS106 Introduction to CS1 Wednesday, 9/18/02  QUESTIONS?? HW #1 due today at 5!!  Today: Loops, and two new data types.
Chapter 5 Loops. Overview u Loop Statement Syntax  Loop Statement Structure: while, for, do-while u Count-Controlled Loops u Nested Loops u Loop Testing.
C++ for Engineers and Scientists, Third Edition1 Objectives In this chapter, you will learn about: Basic loop structures while loops Interactive while.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
CSE1222: Lecture 7The Ohio State University1. logExample.cpp // example of log(k) for k = 1,2,..,8... int main() { cout
Introduction to Loops Iteration Repetition Counting Loops Also known as.
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.
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.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
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.
Chapter 6 - Repetition. while Loop u Simplest loop u Two parts: test expression and loop body u Pre-tested loop –Execute loop body if test true –Bypass.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Flow of Control Joe McCarthy CSS 161: Fundamentals of Computing1.
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.
CONTENTS Loop Statements Parts of a loop Types of Loops Nested Loops
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
Looping I (while statement). CSCE 1062 Outline  Looping/repetition construct  while statement (section 5.1)
Branching statements.
REPETITION CONTROL STRUCTURE
CHAPTER 4 REPETITION CONTROL STRUCTURE / LOOPING
Chapter 3 Loops Section 3.3 Slides prepared by Rose Williams, Binghamton University Kenrick Mock, University of Alaska Anchorage.
Chapter 2.2 Control Structures (Iteration)
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Looping.
Conditinoal Constructs Review
Conditinoal Constructs Review
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Repetition Control Structure
Chapter 2.2 Control Structures (Iteration)
Computing Fundamentals
Alternate Version of STARTING OUT WITH C++ 4th Edition
2.6 The if/else Selection Structure
Objectives You should be able to describe: The while Statement
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Branching statements Kingdom of Saudi Arabia
CSC215 Lecture Control Flow.
Looping and Repetition
Presentation transcript:

Dr. Yang, Qingxiong (with slides borrowed from Dr. Yuen, Joe) LT4: Control Flow - Loop CS2311 Computer Programming

Outlines 2 While and Do While loop For loop

Outcomes 3 Able to express repeating task with a loop statement in C++ Clearly define the loop condition and loop body

Syntax Summary 4 Keywords while, do, for Punctuators,

Loop 5 Beside sequential execution and branch execution, looping is another common control flow in programming. When the execution enters a loop, it will execute a block of code repeatedly until the exit loop condition is matched

Loop 6 In general, a program loop consists of: Initialization statements Body Exit condition Post loop statements (stepping forward to exit loop condition)

Loop 7 Set x=0; cout << “Hello World\n” If (X>10) then exit the loop Add 1 to X Loop back

8 An example program of while #include using namespace std; void main() { int cnt = 0, n; float max, x; cout << "The maximum value will be computed.\n"; cout << "How many numbers do you wish to enter? "; cin >> n; while (n <= 0) /* ensure a positive number is entered */ { cout << "\nERROR: Positive integer required.\n\n"; cout << "How many numbers do you wish to enter? "; cin >> n; } /* To be continued in next page */

An example program of while (cont’d) 9 cout << "\nEnter “ << n << “ real numbers: "; cin >> x; /* read 1st number */ max = x; /* pick the largest number in while-loop */ while (++cnt < n) { cin >> x; /* read another number */ if (max < x) max = x; } cout << "\nMaximum value: " << max << endl; }

do statement 10  General form of do statement (repetition statement) do statement while (expression); q Semantics: statement is executed first; thus the loop body is run at least once If the value of expression is non-zero (true), the loop repeats; otherwise, the loop terminates

Example of do statement 11 int error; /* no Boolean type support */ int n; do { cout << “Input a positive integer: “; cin >> n; if (error = (n <= 0)) cout << “\nError: negative input!\n”; } while (error);...

While vs Do while 12

For-loop statement 13 for (expr1 ; expr2; expr3){ loop statements; } The loop statements is executed as long as expr2 is true. When expr2 becomes false, the loop ends. expr1 : Executed before entering the loop. Often used for variable initialization. expr3 : For each iteration, expr3 is executed after executing the loop body. Often used to update the counter variables.

For-loop statement 14 expr1 and expr3 can contain multiple statements. Each statement is separated by a comma ',' Example for(i=0, j=0; i<10; i++, j++) …… expr1: i=0, j=0 expr2: i<10 expr3: i++, j++

Examples of for 15 #include using namespace std; void main() { int i; for (i = 0; i <10; i++) cout << i << endl; } #include using namespace std; void main() { int i; for (i = 0; i <10; i++){ if (i%2==0) cout << i << endl; }

Nested for-loop 16 #include using namespace std; void main(){ int i,j; for (i=0;i<3; i++){ cout << "Outer for:\n"; for (j=0;j<2; j++){ cout << "Inner for:"; cout << "i=“ << I << ", j=" << j << endl; } cout << endl; } Outer for: Inner for:i=0, j=0 Inner for:i=0, j=1 Outer for: Inner for:i=1, j=0 Inner for:i=1, j=1 Outer for: Inner for:i=2, j=0 Inner for:i=2, j=1 The outer loop is executed 3 times. For each iteration of the outer loop, the inner loop is executed 2 times

Exercise 17 Write a program to generate a multiplication of n rows and m column (where n and m is input by the user). Assume n>1 and m<=9. E.g. when n=4, m=3, the following table is generated

Answer 18 void main(){ int m, n; // n is no. of rows, m no. of columns int i, j; // i is row index, j is column index for (i = 1;i <= n; i++){ // print each row for (j = 1;j <= m; j++){ // print each column cout << i*j << “\t”; } cout << endl; // each row ends with an endl }

break statement 19  the break statement causes an exit from the innermost enclosing loop or switch statement (discussed already) while (1) { cin >> n; if (n < 0) break; /* exit loop if x is negative */ cout << n << endl; } /* If break is run, jumps to here */

continue statement 20  continue statement causes the current iteration of a loop to stop and the next iteration to begin immediately  It can be applied in a while, do-while or for statement

Example of continue statement 21 /* read in and sum 10 not-too-small numbers. */ cnt = 0; while (cnt < 10) { cin >> x; if (x > && x < 0.01) continue; /* discard small values */ ++cnt; sum += x; /* continue transfer control here */ }

Continue, break 22

Comma operator (,) 23 q It has the lowest precedence of all operators in C++ and is evaluated from left to right q General form is expr1, expr2 q The comma expression as a whole has the value and type of its right operand  Sometimes used in for statements to allow multiple initializations and multiple processing of indices q The comma operator is rarely used q Not all commas in a C++ program are comma operators

Examples of comma operator 24 sum=0; for (j=1; j<=10; j++) sum += j; and for (sum=0,j=1; j<=10; j++) sum += j; and for (sum=0,j=1; j<=10; sum += j, j++) ; are equivalent

Common errors 25  Mix up assignment = with equality operator == q Mix up the comma operator with the semi-colon q Unaware of extra semi-colons, e.g., sum=0; for (j=1; j<=10; j++) sum += j; is not the same as sum=0; for (j=1; j<=10; j++); sum += j;

Common errors (cont ’ d) 26 q Fail to ensure that the termination condition of a loop is reachable  infinite loop q Misuse of relational operators int k=8; if (2 < k < 7) cout >> “true”; /* print true */ else cout >> “false”;  Use (2 < k && k < 7) for the correct answer

Further remarks 27 q Use a relational expression, if possible, rather than an equality expression to control a loop or a selection statement, e.g., Don ’ t use while (j!=4) {... } Use while (j<4) {... }

Further remarks 28  Don ’ t use a variable of any floating point data type to control a loop because real numbers are represented in their approximate values internally q Infinite loop can be made

Programming style 29 Follow the normal rules of English (e.g. putting a space after a comma) Put one space on each side of a binary operator (e.g. = > < ) for readability Indent code in a consistent fashion to indicate the flow of control (use the tab key) Note the multiple levels of indentation

Indentation 30 void main(){ int i; for (i = 0; i < 100; i++) { if (i>3) cout << i; } 1 st level (1 tab) 2 nd level (2 tabs) 3 rd level (3 tabs)

Formatting programs 31 Indent the code properly as you write the program to reflect the structure of the program. Improve readability and increase the ease for debugging the program In assignment, marks will be allocated for indentation. To indent in visual studio, you may press the tab button You may select multiple lines of statements and press tab to indent all of them To move back one level to the left, press shift+tab

Summary 32 In C++, repeating task could be expressed with while(…){…} do {…}while(…); for (…;…;…){…} A complete looping structure may consist of Loop initialization statements Loop Body Exit condition Post Loop statements