UEE1302 (1102) F10 Introduction to Computers and Programming



Similar documents
QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

While Loop. 6. Iteration

6. Control Structures

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Lecture 2 Notes: Flow of Control

Basics of I/O Streams and File I/O

Two-way selection. Branching and Looping

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

Chapter 5. Selection 5-1

Chapter One Introduction to Programming

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Moving from C++ to VBA

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

C++ Input/Output: Streams

Passing 1D arrays to functions.

JavaScript: Control Statements I

Common Beginner C++ Programming Mistakes

ALGORITHMS AND FLOWCHARTS

The While Loop. Objectives. Textbook. WHILE Loops

LOOPS CHAPTER CHAPTER GOALS

Chapter 8 Selection 8-1

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Appendix K Introduction to Microsoft Visual C++ 6.0

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

VB.NET Programming Fundamentals

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Sequential Program Execution

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

13 Classes & Objects with Constructors/Destructors

TIP: To access the WinRunner help system at any time, press the F1 key.

Conditions & Boolean Expressions

Member Functions of the istream Class

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Curriculum Map. Discipline: Computer Science Course: C++

Iteration CHAPTER 6. Topic Summary

Visual Logic Instructions and Assignments

Using C++ File Streams

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Writing Control Structures

Moving from CS 61A Scheme to CS 61B Java

Object Oriented Software Design

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Statements and Control Flow

Selection Statements

Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Senem Kumova Metin & Ilker Korkmaz 1

What is the consequences of no break statement in a case.

Comp151. Definitions & Declarations

F ahrenheit = 9 Celsius + 32

Compiler Construction

Informatica e Sistemi in Tempo Reale

Computer Programming C++ Classes and Objects 15 th Lecture

1.3 Conditionals and Loops

Ch 7-1. Object-Oriented Programming and Classes

Answers to Review Questions Chapter 7

C++ INTERVIEW QUESTIONS

if and if-else: Part 1

Introduction to Java

Shell Scripts (1) For example: #!/bin/sh If they do not, the user's current shell will be used. Any Unix command can go in a shell script

Perl in a nutshell. First CGI Script and Perl. Creating a Link to a Script. print Function. Parsing Data 4/27/2009. First CGI Script and Perl

Sources: On the Web: Slides will be available on:

[Refer Slide Time: 05:10]

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

C# programming. Introduction. By Per Laursen

Syllabus OBJECT ORIENTED PROGRAMMING C++

Introduction to Computers and Programming. Testing

PYTHON Basics

Lab 2: Swat ATM (Machine (Machine))

Python Evaluation Rules

C++FA 5.1 PRACTICE MID-TERM EXAM

The if Statement and Practice Problems

CS 101 Computer Programming and Utilization

Computer Programming I

AP Computer Science Java Subset

El Dorado Union High School District Educational Services

While and Do-While Loops Summer 2010 Margaret Reid-Miller

C++ Language Tutorial

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Flowchart Techniques

CISC 181 Project 3 Designing Classes for Bank Accounts

7.7 Case Study: Calculating Depreciation

Solving Problems Recursively

PHP Tutorial From beginner to master

Chapter 9 Text Files User Defined Data Types User Defined Header Files

Transcription:

Computational Intelligence on Automation Lab @ NCTU UEE1302 (1102) F10 Introduction to Computers and Programming Programming Lecture 03 Flow of Control (Part II): Repetition while,for & do..while Learning Objectives In this chapter you will: Learn about repetition (looping) control structures, i.e. while, for and dowhile Explore how to construct and use (1) countcontrolled, (2) sentinel-controlled, (3) flagcontrolled, and (4) EOF-controlled repetition structures Examine break and continue statements Discover how to form and use nested control structures PRO_03 PROF. HUNG-PIN(CHARLES) WEN 2 Flow of Execution statement 1 false true bool_expr statement 2 statement N stmt_no stmt_yes false loop_cond true stmt_loop (A) sequence (B) selection (C) repetition PRO_03 PROF. HUNG-PIN(CHARLES) WEN 3 Why Is Repetition Needed? Repetition (a.k.a. Loop) allow you to efficiently use variables can input, add, and average multiple numbers using a limited number of variables For example, to add five numbers: declare a variable for each number, input the numbers and add the variables together create a loop that reads a number into a variable and adds it to a variable that contains the sum of the numbers PRO_03 PROF. HUNG-PIN(CHARLES) WEN 4

A First Look of Loops 3 types of loop structures in C++ 1.while most flexible no restrictions 2.do-while least flexible always execute loop body at least once 3.for natural counting loop while Loop Example count = 0; // Initialization while (count < 3) // Loop Condition cout << "Hi "; // Loop Body count++; // Update expression Loop body executes how many times? PRO_03 PROF. HUNG-PIN(CHARLES) WEN 5 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 6 do-while Loop Example count = 0; do // Initialization cout << "Hi "; // Loop Body count++; // Update expression while (count < 3); // Loop Condition Loop body executes how many times? do-while loops always execute body at least once! PRO_03 PROF. HUNG-PIN(CHARLES) WEN 7 for Loop Example for (count=0; count<3; count++) cout << "Hi "; // Loop Body How many times does loop body execute? Initialization, loop condition and update are all built into the for-loop structure! A natural "counting" loop PRO_03 PROF. HUNG-PIN(CHARLES) WEN 8

false entry_cond true stmt_while The while Loop (1/2) Syntax of the while statement is: while (entry_cond) statement_while; Statement statement_while can be either simple or compound body of the loop Expression entry_cond acts as a decision maker and is usually a Boolean expression The parentheses () are part of the syntax PRO_03 PROF. HUNG-PIN(CHARLES) WEN 9 The while Loop (2/2) Expression entry_cond provides an entry condition Statement statement_while executes if the expression initially evaluates to true Loop condition entry_cond is then reevaluated Statement continues to execute until the expression entry_cond is no longer true Infinite loop: continues to execute endlessly can be avoided by including statements in the loop body that assure exit condition will eventually be true PRO_03 PROF. HUNG-PIN(CHARLES) WEN 10 while Loop Example (1/2) idx = 0; while (idx < 10) cout << 2*idx << ; idx += 2; // idx= idx + 2 cout << endl; Sample Run: >./a.out 0 4 8 12 16 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 11 while Loop Example (2/2) idx = 20; while (idx < 20) //never satisfy entry_cond cout << idx << ; idx += 5; cout << endl; Sample Run: >./a.out _ PRO_03 PROF. HUNG-PIN(CHARLES) WEN 12

while (1): Counter-ControlledControlled If you know exactly how many pieces of data need to be read, the while loop becomes a counter-controlled loop Example of counter-controlled loop: counter = 0; // initialize loop control while (counter < Limit) // test loop control statements; counter++; // update loop control while (2): Sentinel-Controlled Sentinel variable is tested in the condition and loop ends when sentinel is encountered Example of sentinel-controlled loop: cin >> target; // initialize loop control while (target!= sentinel) //test loop control statements; cin >> target; // update loop control PRO_03 PROF. HUNG-PIN(CHARLES) WEN 13 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 14 while (3): Flag-Controlled A flag-controlled while loop uses a bool variable to control the loop Example of flag-controlled loop: loop_stop = false; // initialize loop control while (!loop_stop) // test loop control if (expression) // update loop control loop_stop = true; while (4): EOF-Controlled A EOF-controlled while loop uses a EOF (End-of-File) to control the loop The logical value returned by cin can determine if the program has ended input Example of EOF-controlled loop: cin >> var; // initialize loop control while (cin) // cintest does loop not reach control EOF cin >> var; // update loop control Or use while (!cin.eof()) PRO_03 PROF. HUNG-PIN(CHARLES) WEN 15 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 16

The eof Function When a program is reading from a disk file, eof can determine the end of file status When reading from input devices like keyboard, use ctrl+z or ctrl+d denotes eof eof is a member of data type istream iostream includes header files ofistream, ostream and others Syntax for the function eof is: istreamobj.eof() istreamobj is an input stream variable, such as cin. EX:cin.eof() cin.clear();to reset eof and restart reading from input devices PRO_03 PROF. HUNG-PIN(CHARLES) WEN 17 while Pitfalls: Misplaced ; Watch the misplaced ; (semicolon) Example: while (response!= 0); cout << "Enter val: "; cin >> response; Notice the ";" after the while condition! Result here: INFINITE LOOP! PRO_03 PROF. HUNG-PIN(CHARLES) WEN 18 while Pitfalls: Infinite Loops Loop condition must evaluate to false at some iteration through loop If not infinite loop while (1) cout << "Hello "; a perfectly legal C++ loop always infinite! Sometimes, infinite loops can be desirable e.g., "Embedded Systems" PRO_03 PROF. HUNG-PIN(CHARLES) WEN 19 false init_stmt loop_cond true stmt_for update_stmt The for Loop Syntax of for statement: for (init_stmt;lp_cond;update_stmt) statement_for; init_stmt: initialize ctrl variable lp_cond: compare ctrl variable update_stmt : update ctrl variable Action statement stmt_for can be a compound statement much more typical PRO_03 PROF. HUNG-PIN(CHARLES) WEN 20

for versus while (1/2) Rewrite for statement in while loop: init_stmt; while (lp_cond) stmt_for; update_stmt; Rewrite while statement in for loop: for ( ; entry_cond; ) stmt_while; PRO_03 PROF. HUNG-PIN(CHARLES) WEN 21 for versus while (2/2) Components of for statement are optional but semicolons ; must always be present omissions doing nothing in init_stmt and update_stmt or being true in lp_cond EX: for ( ; ; ) statements; is valid Differentiate for from while: initialization statements grouped as first set of items init_stmt within the for s () loop condition and loop statements are fixed: no change in for update statements as the last set of items update_stmt within the for s () PRO_03 PROF. HUNG-PIN(CHARLES) WEN 22 for Loop Example 1 (1/3) Example 1: for (count=2; count<=20; count+=2) cout << count << ; Modified Example 1a: count = 2; for ( ; count<=20; count+=2) cout << count << ; Sample Run: >./a.out 2 4 6 8 10 12 14 16 18 20 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 23 for Loop Example 1 (2/3) Example 1: for (count=2; count<=20; count+=2) cout << count << ; Modified Example 1b: count = 2; for ( ; count<=20; ) cout << count << ; count +=2; PRO_03 PROF. HUNG-PIN(CHARLES) WEN 24

for Loop Example 1 (3/3) Example 1: for (count=2; count<=20; count+=2) cout << count << ; Modified Example 1c: count = 2; for (count=2; count<=20; cout << count <<, count+=2) ; for Loop Example 2 (1/2) Example 2: for (idx=1; idx<=5; idx++) cout << Hello! << endl; cout << * << endl; What will happen? Example 2a: for (idx=1; idx<=5; idx++) cout << Hello! << endl; cout << * << endl; What will happen? PRO_03 PROF. HUNG-PIN(CHARLES) WEN 25 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 26 Example 2: for Loop Example 2 (2/2) for (idx=1; idx<=5; idx++) cout << Hello! << endl; cout << * << endl; Example 2b: for (idx=1; idx<=5; idx++) ; cout << Hello! << endl; cout << * << endl; What will happen? PRO_03 PROF. HUNG-PIN(CHARLES) WEN 27 Comments on for loop If loop condition lp_cond is initially false do nothing Ex: for (idx=0; idx > 0; idx++) Update statement update_stmt eventually sets the value of lp_cond to false otherwise, this for loop will run forever. Ex: for (idx=0; idx<100; idx--) If ctrl variable is float/double, then different computers may yield different results on ctrl variable should avoid using such variable. Ex: for (double idx=0.1; idx<1.2; idx+=0.05) PRO_03 PROF. HUNG-PIN(CHARLES) WEN 28

The dowhile Loop (1/2) The dowhile Loop (2/2) stmt_dowhile rep_cond false true Syntax of dowhile statement: do stmt_dowhile; while (rep_cond); Statement stmt_dowhile executes first, and then rep_cond is evaluated If rep_cond evaluates to true,, the statement stmt_dowhile runs again As long as rep_cond in a dowhile statement is true, the statement stmt_dowhile executes To avoid an infinite loop, the loop body stmt_dowhile must contain a update statement that makes rep_cond to be false The statement stmt_dowhile can be simple or compound If compound, it must be in braces dowhile loop typically has an exit condition and iterates at least once (unlike for and while) PRO_03 PROF. HUNG-PIN(CHARLES) WEN 29 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 30 Example 1: dowhile Loop Example idx = 1; do cout << idx << ; idx *= 2; while (idx <= 20); What will be displayed on screen? Answer: 1 2 4 8 16 dowhile Loop vs while Loop Example 2a: idx = 15; do idx %= 8; while (idx > 15); cout << idx << endl; Example 2b: idx = 15; while (idx > 15) idx %= 8; cout << idx << ; What will be displayed on screen? Answer: 7 Answer: 15 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 31 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 32

break & continue in Repetition Flow of Control Recall how loops provide "graceful" and clear flow of control in and out In RARE instances, can alter natural flow break force the loop to exit immediately. continue skip the rest of loop body These statements violate natural flow only used when absolutely necessary! PRO_03 PROF. HUNG-PIN(CHARLES) WEN 33 break in Loop break: forces immediate exits from structures: in switch statements: the desired case is detected/processed in while, for and dowhile statements: an unusual condition is detected for (idx=10; idx<=50; idx+=2) if (idx%9 == 0) break; cout << idx << ; What will be displayed on screen? 10 12 14 16 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 34 continue in Loop continue: cause the next iteration of the loop to begin immediately execution transferred to the top of the loop apply only to while, for and dowhile statements idx = 0; while (idx < 100) idx++; if (idx == 50) continue; cout << idx << endl; What will be displayed on screen? 1 248 49 51 5298 99 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 35 Nested Loops (1/2) A loop contained within another loop Print 9x9 multiples for (idx=1; idx<=9; idx++) //outer loop cout << idx << -multiples: << endl; for (jdx=1; jdx<=9; jdx++) //inner loop cout << idx*jdx << ; // end of inner loop // end of outer loop PRO_03 PROF. HUNG-PIN(CHARLES) WEN 36

Outer (first) Loop: Nested Loops (2/2) controlled by value of idx Inner (second) Loop: controlled by value of jdx Rules: For each single trip through outer loop, inner loop runs through its entire sequence Different variables to control each loop Inner loop statements contained within outer loop Summary (1/3) C++ has three looping (repetition) structures: while, for and dowhile while, for and dowhile are reserved words while and for loops are called pre-test loops dowhile loop is called a post-test loop while and for may not execute at all, but dowhile always executes at least once PRO_03 PROF. HUNG-PIN(CHARLES) WEN 37 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 38 Summary (2/3) while: expression is the decision maker, and the statement is the body of the loop In a counter-controlled while loop, Initialize counter before loop Body must contain a statement that changes the value of the counter variable A sentinel-controlled while loop uses a sentinel to control the while loop An EOF-controlled while loop executes until the program detects the end-of-file marker Summary (3/3) for: simplifies the writing of a countcontrolled while loop Executing a break statement in the body of a loop immediately terminates the loop Executing a continue statement in the body of a loop skips to the next iteration After a continue statement executes in a for loop, the update statement is the next statement executed PRO_03 PROF. HUNG-PIN(CHARLES) WEN 39 PRO_03 PROF. HUNG-PIN(CHARLES) WEN 40