Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.

Slides:



Advertisements
Similar presentations
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Advertisements

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
 2006 Pearson Education, Inc. All rights reserved Control Statements: Part 1: Selection statements: if, if…else, switch.
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Selection Structures: if and switch Statements Problem Solving,
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Chapter 4 Making Decision Csc 125 C++ programming language Fall 2005.
Chapter 05 (Part III) Control Statements: Part II.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
Copyright 2003 Scott/Jones Publishing Making Decisions.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
COS120 Software Development Using C++ AUBG Fall semester 2010 Ref book: Problem Solving, Abstraction and Design Using C++ Authors: Frank Friedman, Elliot.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions.
Chapter Making Decisions 4. Relational Operators 4.1.
CHAPTER 5 MAKING DECISION Hidayah Elias BFC2042 – Computer Programming.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
If Statements Programming. COMP104 Lecture 7 / Slide 2 Review: Rules for Division l C++ treats integers different than doubles. 100 is an int. l 100.0,
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Lecture 6 – Selection FTMK, UTeM – Sem /2014.
Chapter 4 Selection Structures: if and switch Statements Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Condition – any expression that evaluates to true/false value Relational operators are BINARY.
 By the end of this section you should be able to: ◦ Differentiate between sequence, selection, and repetition structure. ◦ Differentiae between single,
LECTURE # 7 : STRUCTURED PROGRAMMING Selection Statements Tr.Hadeel.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Branching statements.
Chapter 3 Selection Statements
CNG 140 C Programming (Lecture set 3)
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
Chapter 4: Making Decisions.
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Making Decisions.
Topics The if Statement The if-else Statement Comparing Strings
Chapter 4: Control Structures I (Selection)
Control Structures: Selection Statement
Chapter 7 Conditional Statements
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
Decision I (if Statement)
Chapter 3 Selections Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.
Structured Program Development in C++
Control Statements Paritosh Srivastava.
Control Structures: Selection Statement
Chapter 4: Selection Structures: if and switch Statements
Branching statements Kingdom of Saudi Arabia
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution Three types Sequential Selection Repetition

Sequential Execution A compound statement is used to specify sequential control Compound statement A “grouping” of statements Each statement is executed in sequence Enclosed in braces “{ }” main() is a compound statement!!! { statement1; statement2; … statementn; } Compound Statement

Scope (and globals) #include <iostream> using namespace std; // global variable int iglobal= 10; // main function int main() { int imain= 20; cout << "In main:" << endl; cout << " iglobal= " << iglobal << endl; cout << " imain = " << imain << endl; cout << endl; // compound statement block { int icomp= 30; cout << "In control:" << endl; cout << " icomp = " << icomp << endl; } // uncomment the following - it will not compile!!!! // cout << "icomp = " << icomp << endl; Variables (incl. functions) defined with a compound statement “block” are “local” to that block They are not available outside the block, however… Variables defined in an enclosing block can be seen in the enclosed block Example: function parameters!!! And any variables defined in a function

Selection statements Control structures that conditionally execute statements Enables decision making if statement Uses a Boolean expression to decide whether the statements inside a compound statement should be executed switch statement Executes statements based on whether a value matches one of a list of specified alternatives

“if/else” statement A selection statement that conditionally executes based on whether a Boolean expression evaluates to true or false if (condition) statement; Example: if (age >= 21) cout << “legal!!!” << endl; if (condition) statement1; else statement2; Example: if (age >= 21) cout << “legal!!!” << endl; else cout << “Sorry!!!” << endl; Logical (Boolean) expression With an “else” condition

Selection (“if/else”, with a compound statement) Logical (Boolean) expression if (condition) { statement1; statement2; … } else { alternative; } Compound Statement Compound Statement

Relational and Equality Operators Used to construct Logical, or Boolean, expressions Expressions are used to perform tests to determine whether/which statements should be executed Typical forms: variable relational-operator variable A > B variable relational-operator constant A > 5 variable equality-operator variable A == B variable equality-operator constant A == 5 Evaluate to Boolean (bool) value of true or false

Selection (with a compound statement) Logical (Boolean) expression “A>B” Relational operator “>” if (A > B) { statement1; statement2; … } Compound Statement

Rational and Equality Operators

Example x y x >= y -5 7 -5 7 false

Logical Operators && (and) || (or) ! (not) Used to form more complex conditions, e.g. (salary < minSalary) || (dependents > 5) (temperature > 90.0) && (humidity > 0.90) winningRecord && (!probation)

&& Operator (and)

|| Operator (or)

! Operator (not)

Examples int age; bool a, b; … … If (age > = 16) { If (a && b) { cout << “you can drive!”; } bool a, b; … If (a && b) { cout << “both true!”; } Note: it is possible to set a bool variable to the result of a logical expression! Ex: bool istrue= !a && age > 21;

Operator Precedence

Example x y z flag 3.0 4.0 2.0 false x + y / z <= 3.5 2.0 5.0 false

Example ! flag || (y + z >= x - z) x y z flag 3.0 4.0 2.0 false true 6.0 1.0 true true

English Conditions as C++ Expressions

Comparing Characters and Strings Letters are in typical alphabetical order Upper and lower case significant Digit characters are also ordered as expected String objects require string library Compares corresponding pairs of characters Based on numerical comparisons of ASCII integer values

Examples of Comparisons

Boolean Assignment Assignment statements have general form variable = expression; E.g.: (for variable called same of type bool) same = true; same = (x == y);

Additional Examples inRange = (n > -10) && (n < 10); isLetter = ((‘A’ <= ch) && (ch <= ‘Z’)) || ((‘a’ <= ch) && (ch <= ‘z’)); even = (n % 2 == 0);

Writing bool Values Boolean values are represented by integer values in C++ 0 for false non-zero (typically 1) for true Outputting (or inputting) bool type values is done with integers

Short Circuit Evaluation Evaluation of a logical expression concludes immediately when the result is determined (single == ‘y’ && gender == ‘m’ && age >= 18) If single is false, gender and age are not evaluated (single == ‘y’ || gender == ‘m’ || age >= 18) If single is true, gender and age are not evaluated

Intro to nesting and multiple alternative void displayGrade (int score) { if (score >= 90) cout << "Grade is A " << endl; if (score >= 80) cout << "Grade is B " << endl; if (score >= 70) cout << "Grade is C " << endl; if (score >= 60) cout << "Grade is D " << endl; else cout << "Grade is F " << endl; } What is wrong with this? what happens if: score = 75? score = 50?

Does this fix it? Each if statement covers a non-overlapping range. void displayGrade (int score) { if (score >= 90 && score <= 100) cout << "Grade is A " << endl; if (score >= 80 && score < 90) cout << "Grade is B " << endl; if (score >= 70 && score < 80) cout << "Grade is C " << endl; if (score >= 60 && score < 70) cout << "Grade is D " << endl; if (score < 60) // no more else! cout << "Grade is F " << endl; } Each if statement covers a non-overlapping range.

Another Solution is to use “nesting” Nested logic is one control structure containing another similar control structure

Writing a Nested if as a Multiple-Alternative Decision Nested if statements can become quite complex. If there are more than three alternatives and indentation is not consistent, it may be difficult to determine the logical structure of the if statement. So, another approach is to use “multiple-alternative” coding

Multiple-Alternative Decision Form if (condition1) statement1; else if (condition2) statement2; . else if (conditionn) statementn; else statemente;

Using Multiple Alternative void displayGrade (int score) { if (score >= 90) cout << "Grade is A " << endl; else if (score >= 80) cout << "Grade is B " << endl; else if (score >= 70) cout << "Grade is C " << endl; else if (score >= 60) cout << "Grade is D " << endl; else cout << "Grade is F " << endl; }

Order of Conditions Matters if (score >= 60) cout << "Grade is D " << endl; else if (score >= 70) cout << "Grade is C " << endl; else if (score >= 80) cout << "Grade is B " << endl; else if (score >= 90) cout << "Grade is A " << endl; else cout << "Grade is F " << endl;

The switch Control Statement switch ( switch-expression ) { case label1: statements1; break; case label2: statements2; . case labeln: statementsn; default: statementsd; // optional }

Switch Control Statement Alternative to multiple if statements in some cases Most useful when switch selector is single variable or simple expression Switch selector must be an integral type (int, char, bool)

Switch Control Statement Switch selector value compared to each case label. When there is an exact match, statements for that case are executed. If no case label matches the selector, the entire switch body is skipped unless it contains a default case label. break is typically used between cases to avoid fall through.

switch statement to determine life expectancy of a lightbulb

Avoid Programming Errors Use parentheses to clarify complex expressions Use logical operators only with logical expressions Use brackets { } to group multiple statements for use in control structures

Avoid Programming Errors When writing a nested if statement, use multiple-alternative form if possible if conditions are not mutually exclusive, put the most restrictive condition first Make sure switch selector and case labels are the same type. Provide a default case for a switch statement whenever possible.