Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.

Slides:



Advertisements
Similar presentations
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 4 – C Program Control Outline 4.1Introduction.
Advertisements

Computer Science 1620 Loops.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 5: Control Structures II (Repetition)
COMP 14 Introduction to Programming Miguel A. Otaduy May 20, 2004.
Chapter 5: Control Structures II (Repetition)
COMP 110 Introduction to Programming Mr. Joshua Stough September 24, 2007.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
CHAPTER 5 CONTROL STRUCTURES II (Repetition). In this chapter, you will:  Learn about repetition (looping) control structures  Explore how to construct.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 5: Control Structures II (Repetition)
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
Unit 4 Repetition and Loops. Key Concepts Flowcharting a loop Types of loops Counter-controlled loops while statement Compound assignment operator for.
Lecture 10: Reviews. Control Structures All C programs written in term of 3 control structures Sequence structures Programs executed sequentially by default.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Control Structures Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5 Control Structure (Repetition). Objectives In this chapter, you will: Learn about repetition (looping) control structures Explore how to construct.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Control Structures II (Repetition). Objectives In this chapter you will: Learn about repetition (looping) control structures Explore how to construct.
Loop.  While Loop  Do-while Loop  For Loop Continue Statement Conclusion Loop Loop.
1 ELEC 206 Chapter 3 Control Structures 5-Step Problem Solving Methodology 1. State the problem clearly. 2. Describe the input and output. 3. Work a.
 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.
Control Structures - Selections - Repetitions/iterations (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition)
5.1 Introduction Problem Solving –Requires understanding of: Building blocks Program-construction principles BZUPAGES.COM.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
LECTURE # 8 : REPETITION STATEMENTS By Mr. Ali Edan.
 2002 Prentice Hall. All rights reserved. 1 Chapter 5 – Control Structures: Part 2 Outline 5.1Introduction 5.2 Essentials of Counter-Controlled Repetition.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 5 Control Structures II: Repetition.
Chapter Looping 5. The Increment and Decrement Operators 5.1.
Lecture 7 – Repetition (Loop) FTMK, UTeM – Sem /2014.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 5: Control Structures II (Repetition)
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Chapter 4 Repetition Statements Program Development and Design Using C++, Third Edition.
Sesi 0607EKT120/4 Computer Programming Week 5 – Repetition / Loops.
ECE122 Feb 10, Unary Operator An operator that takes only a single operand Plus: + Minus: – Cast: (type). E.g. (double)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
C Program Control September 15, OBJECTIVES The essentials of counter-controlled repetition. To use the for and do...while repetition statements.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 23, 2005 Lecture Number: 11.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
1 Chapter 4 - Control Statements: Part 1 Outline 4.1 Introduction 4.4 Control Structures 4.5 if Selection Structure 4.6 if/else Selection Structure 4.7.
CHAPTER 2.2 CONTROL STRUCTURES (ITERATION) Dr. Shady Yehia Elmashad.
Branching statements.
Chapter 4 – C Program Control
REPETITION CONTROL STRUCTURE
Engineering Problem Solving with C++, Etter/Ingber
Control Structures II (Repetition)
Ch 7: JavaScript Control Statements I.
JavaScript: Control Statements.
JavaScript: Control Statements I
Programming Fundamentals Lecture #6 Program Control
Alternate Version of STARTING OUT WITH C++ 4th Edition
3 Control Statements:.
Control Statements Paritosh Srivastava.
Presentation transcript:

Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection repetition A sequence control structure uses compound statements (blocks) to specify sequential flow. A compound statement, a block of codes, is used to specify sequential flow. { statement1; statement2; statement3; } Sequence .

Selection Use if or switch statements to select one from many alternatives. if selection structure if (grade >= 60) cout << “Passes” << endl; if structure Grade >= 60 T print”Passed” F

If/else structure if / else selection structure if / else structure if (grade >= 60) cout << “Passes” << endl; else cout << “Failed” << endl; if / else structure Grade >= 60 T print”Failed” print”Passed” F

if / else if / else Selection Structure if ( grade >= 90 ) cout << “A grade” << endl; else if (grade >= 80) cout << “B grade” << endl; else if ( grade >= 70) cout << “C grade” << endl; else if ( grade >= 60) cout << “D grade” << endl; else cout << “F grade” << endl;

Conditions In general, condition has the following form: p1 op p2 Where p1 = variable p2 = variable / constant op = relational ( <, >, <=, >=) or equality operator (==, != ). Example: 1. x <= 100 2. num != SENTINEL

Logical Operators (&&, ||, !) With the help of logical operators you can form more complicated conditions or logical expressions. 3 logical operators are && (and), || (or), ! (not) Truth table for && operator Op2 Op1 && Op2 Op1 T F When both of the operands are true, the result will be true.

Logical Operator || (or) When both operands are false, the result will be false, otherwise true. Truth table for || operator T F Op1 Op2 Op1 || Op2

Logical operator ! (not) Has a single operand. Yields the logical complement or negation. Example: !(flag) it evaluates to 1 if flag = 0. Truth Table for !Operator T F Op1 !Op1

Operator Precedence Operator Precedence function calls highest ! + - & ! + - & * / % + - < <= >= > == != && || = lowest

Short-Circuit Evaluation C++ evaluates only part of the expression. An expression a || b is true if a is true. C++ stops evaluating when it determines a =1. An expression a && b is false if a is false. C++ stops evaluating when it determines a = 0. This technique is called short-circuit evaluation.

Example !flag || (y + z >= x - z) This expression is of the form a || b. a = !flag C++ would stop evaluating when it determines a = !flag = 1. From the truth table, the value of the expression does not depend on b if a = 1. !flag || (y + z >= x - z) = 1. x y z flag 3.0 4.0 2.0

Complementing a Logical Expressions Temp is in the range 60 to 70 F, inclusive. Logical expression: 60 <= temp && temp <= 70 Evaluation: (temp = 65): 1 && 1 => 1 (temp = 45): 0 && 1 => 0 Temp is outside the range 60 to 70 F (complement). Logical expression: ! (60 <= temp && temp <= 70) Alternative 60 > temp || temp > 70 Evaluation: (temp = 65): ! (1 && 1) => 0 (temp = 45): ! (0 && 1) => 1 Alternative (temp = 65): (0 || 0) => 0 (temp = 45): (1 || 0) => 1

De Morgan Theorem  60 > temp || temp > 70 Rule 1 Using De Morgan theorem, you can simplify the logical expression. Rule 1: ! (expr1 && expr2)  !expr1 || !expr2 Rule 2: ! (expr1 || expr2)  !expr1 && !expr2 Example: ! (60 <= temp && temp <= 70)  60 > temp || temp > 70 Rule 1 !(temp < = 30 || (condition == ‘R’)  temp > 30 && condition != ‘R’ Rule 2

if and if /else statements One alternative: if ( x != 0.0) product = product * x; Double alternatives: if (temp > 32.0) cout << “Above freezing” << endl; else cout << “Freezing” << endl;

Nested if statements Multiple alternatives if (x < 0.0) { cout << “negative”; absx = -x; } else if (x == 0.0) cout<< “zero”; absx = 0.0; else cout << “positive”; absx = x; if (x < 0.0) { cout << “negative”; absx = -x; } else if (x == 0.0) cout << “zero”; absx = 0.0; cout << “positive”; absx = x;

Nested if vs.sequence of ifs More readable and efficient if (x < 0.0) { cout << “negative”; absx = -x; } if (x == 0.0) cout << “zero”; absx = 0.0; if (x > 0.0) cout << “positive”; absx = x; Sequence of ifs Nested if if (x < 0.0) { cout << “negative”; absx = -x; } else if (x == 0.0) cout << “zero”; absx = 0.0; cout << “positive”; absx = x;

Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression can be type int or char, but not type double. First the expression is evaluated, then the list of case labels is searched until one matches the expression value. Statements following the matching case level are executed until a break statement is encountered. The break causes an exit from the switch statement. Execution continues with the statement that follows the closing brace of the switch statement body. If no case level matches the controlling expression value, the statement following the default label are executed. If there is no default label, the entire switch statement body is skipped.

Switch structure switch (grade) { case ‘A’ : cout << “Excellent” << endl; break; case ‘B’ : cout << “Good” << endl; case ‘C’ : cout << ”O.K.” << endl; case ‘D’ : cout << “Poor” << endl; case ‘F’ : cout << “Failed” << endl; default : cout << “Invalid letter grade” << endl; }

Flowchart for switch structure Case A Excellent break Case B Good break Case C O.K. break Case D Poor break Case F Failed break invalid

Switch structure How many lines of output will be produced by the following program fragment ? int x; x = 0; switch (x) { case 0 : cout << "got 0“ << endl; case 1 : cout << "got 1“ << endl; case 2 : cout << "got 2“ << endl; default : cout << "do not have 0, 1 or 2“ << endl; }

Switch and if /else if /else structure { case 5 : c = c + b; case 2 : c = c + 2*b; break; case 3 : c = 7; case 6 : break; case 7 : c = c + 9; case 4 : case 1 : c *= c; default : c %= 2; } if (a == 5) { c = c + b; c = c + 2*b; } else if (a == 2) c = c +2*b; else if (a == 3) c = 7; else if (a == 6) ; else if (a == 7) c = c + 9; else if ((a == 4) || (a == 1) c * = c; else c % = 2;

if /else and switch structures if / else structure Switch structure Switch (i) { case 1 : case 2 : j = k - 2; k += 3; break; case 3 : j = k + 3; ++k; j = k - 2; k += 3; case 4 : j = k + 3; default : j = k + 5; } if ((i > 0) && ( i < 5)) { if ( i > 2) j = k + 3; ++k; } if ( i < 4) j = k - 2; k += 3; else j = k + 5;

Repetition & Loop Statement A type of program control structure. A loop is a group of instructions the computer executes repeatedly while some loop-continuation condition remains true. Be sure to verify that a loop’s repetition condition will eventually become false, otherwise an infinite loop may result. Three C++ loop control structures are: while do / while for

Flow Diagram of Loop Choice No No loop required Any steps repeated ? Yes Use of the conditional loop: - sentinel-controlled End-of-file-controlled Flag-controlled - input validation - general conditional Know in advance how many times to repeat ? No Yes Use a counting loop

Counter-Controlled Repetition A control variable is used to count the number of repetitions. The control variable is incremented (or decremented) each time the group of instructions is performed. When the value of the control variable indicates that the correct number of repetitions has been performed, the loop terminates. Counter controlled repetition requires: Name of a control variable (loop counter). Initial value of the control variable. Increment (or decrement) by which the control variable is modified each time through the loop. Condition that tests for the final value of the control variable.

Counter-Controlled repetition with the while Loop #include <iostream> int main() { int counter = 1; // intitialization while (counter <= 10) // repetition condition cout << counter << endl; ++counter; // increment } return 0;

Flowchart for while structure ++counter <= 10 cout << counter << endl; T F

Do/While Repetition Structure #include <iostream> int main() { int counter = 1; do cout << setw(2) << counter ; } while (++counter <= 10) cout << endl; return 0; } Do-while always executes at least once. Use a do-while only when there is a possibility of zero loop iterations. output 1 2 3 4 5 6 7 8 9 10

Flowchart for do / while Structure ++counter <= 10 cout << counter; T F

Counter-Controlled repetition with the for Loop #include <iostream> int main() { int counter; for (counter = 1; counter <= 10; counter++) initialization repetition condition increment cout << counter << endl; return 0; }

Flowchart of a for structure Establish initial value of control variable counter = 1 Test if final value of control variable has been reached counter <= 10 T cout << counter; counter++ F Body of loop Increment the control variable

The Break Statement #include <iostream> Output int main() { int x; for (x = 1; x <= 10; x++) if (x == 5) break; // break loop only if x == 5 cout << setw(2) << x; } cout << endl; cout << “Broke out loop at x == “ << x << endl; return 0; Output 1 2 3 4 Broke out of loop at x == 5

The Continue Statement #include <iostream> int main() { int x; for (x = 1; x <= 10; x++) if (x == 5) continue; // skip remaining code in loop // only if x == 5 cout << x; } cout << endl; cout << “Used continue to skip printing the value 5” << endl; return 0; Output 1 2 3 4 6 7 8 9 10 Used continue to skip printing the value 5

Sentinel-Controlled Loop Sentinel values are used to control repetition when the precise number of repetitions is not known in advance. The loop includes statements that obtain data each time the loop is performed. Sentinel value indicates “end of data”. Sentinel is entered after all regular data items have been supplied to the program. Sentinels must be distinct from regular data items.

Sentinel-Controlled while Loop #include <iostream> const SENTINEL = - 99; int main() { int sum = 0, score; cout << “Enter first score or “ << SENTINEL << “to quit”<< endl; cin >> score; while (score != SENTINEL) sum += score; cout << “Enter next score or “<< SENTINEL<< “to quit”<< endl; cin>> score; } cout << "Sum of exam scores is “ << sum << endl; return (0);

End-Of-File-Controlled Loop #include <iostream> #include <fstream> int main() { char inchar; ifstream myinfile; myinfile.open("C:input.dat"); if (!myinfile) cout <<"cannot open file"<< endl; return 1; }

End-Of-File-Controlled Loop myinfile.get(inchar); while (myinfile) { cout <<inchar; } return 0;

Flag-Controlled Loop #include <iostream> int main() { int num; bool found = false; while (!found) cout << “Enter a number” << endl; cin >> num; if (num == 4) cout << “Target found”<< endl; found = true; }

Validating input using do-while statement Get data value. If data value isn’t in the acceptable range, go back to first step. do { cout << “Enter a letter from A through E>”; cin >> letter_choice; } while (letter_choice < ‘A’ || letter_choice > ‘E’);

General Conditional Loop Initialize loop control variable. As long as exit condition hasn’t been met, continue processing. for ( radiation_lev = init_radiation; radiation_lev > min_radiation; radiation_lev /= 2.0) { if (radiation_lev > SAFE_RAD) cout << “Unsafe”<< endl; else cout << “Safe” << endl; }