CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.

Slides:



Advertisements
Similar presentations
Chapter 4: Control Structures I (Selection)
Advertisements

C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I Instructor: Mohammad Mojaddam
Chapter 4 Control Structures I. Objectives ► Examine relational and logical operators ► Explore how to form and evaluate logical (Boolean) expressions.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
1 Lecture 8:Control Structures I (Selection) (cont.) Introduction to Computer Science Spring 2006.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
C++ Programming: Program Design Including Data Structures, Second Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection)
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
C++ Programming, Namiq Sultan1 Chapter 4 Making Decisions Namiq Sultan University of Duhok Department of Electrical and Computer Engineerin Reference:
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Chapter 4 Making Decisions
EGR 2261 Unit 4 Control Structures I: Selection  Read Malik, Chapter 4.  Homework #4 and Lab #4 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
IXA 1234: C++ PROGRAMMING CHAPTER 3. O BJECTIVES In this chapter you will: Learn about control structures Examine relational and logical operators Explore.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 4: Control Structures I (Selection)
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.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 4: Control Structures I
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
Chapter 4 Selection Structures: Making Decisions.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 4: Control Structures I (Selection)
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
 Learn about control structures  Examine relational and logical operators  Explore how to form and evaluate logical (Boolean) expressions  Learn how.
Control Structures 1. Control Structures Java Programming: From Problem Analysis to Program Design, D.S. Malik 2.
Chapter 4: Control Structures SELECTION STATEMENTS.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
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.
Programming 1 DCT 1033 Control Structures I (Selection) if selection statement If..else double selection statement Switch multiple selection statement.
TK 1914 : C++ Programming Control Structures I (Selection)
Chapter Making Decisions 4. Relational Operators 4.1.
Quiz 3 is due Friday September 18 th Lab 6 is going to be lab practical hursSept_10/exampleLabFinal/
Java Programming: From Problem Analysis to Program Design, 3e Chapter 4 Control Structures I: Selection.
Chapter 4 Control Structures I. Chapter Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate.
ICT Introduction to Programming Chapter 4 – Control Structures I.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
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,
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CHAPTER#3 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc 1101.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 4: Control Structures I (Selection)
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
CHAPTER 4 CONTROL STRUCTURES I Selection. In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how.
Chapter 4: Control Structures I J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational operators – Discover.
Chapter 4: Control Structures I (Selection)
Chapter 4: Control Structures I
Chapter 4: Control Structures I (Selection)
Chapter 3 Control Statements
Chapter 4: Control Structures I
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 4: Control Structures I
Chapter 4: Control Structures I (Selection)
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
Control Structure Chapter 3.
Control Structure.
Presentation transcript:

CHAPTER 4 CONTROL STRUCTURES I Selection

In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean) expressions Discover how to use the selection control structures if, if... else, and switch in a program Learn to use the assert function to terminate a program

CONTROL STRUCTURES Three ways that a computer can proceed: In sequence; Selectively- by making a choice; also called a branch; Repetitively (or iteratively)- performing a statement over and over; this is called a loop. In C++, a condition is represented by a logical (Boolean) expression. An expression that has a value of either true or false is called a logical (Boolean) expression. true and false are logical (Boolean) values.

RELATIONAL OPERATORS A relational operator allows you to make comparisons in a program.

Relational Operators in Logical Expression ExpressionMeaningValue 8 < 158 is less than 15true 6 != 66 is not equal to 6false ‘R’ > ‘T’ ASCII 82 is greater than 84 false “Hello”>“Hen”string comparison false When C++ evaluates a logical expression, it returns an integer value of 1 if the logical expression evaluates to true ; it returns an integer value of 0 otherwise. In C++, any nonzero value is treated as true.

LOGICAL (BOOLEAN) OPERATORS AND LOGICAL EXPRESSIONS  Logical (Boolean) operators enable you to combine logical expressions  In C++, there are three logical (Boolean) operators :  Logical operators take only logical values as operands and yield only logical values as results.  The operator ! is unary, so it has only one operand.  The operators && and || are binary operators.

Precedence of Operators  Because relational and logical operators are evaluated from left to right, the associativity of these operators is said to be from left to right.

Example 4-4 bool found = true; bool flag = false; int num = 1; double x = 5.2; double y = 3.4; int a = 5, b = 8; int n = 20; char ch = 'B'; ExpressionValue !foundfalse x > 4.0true !numfalse !found && (x >= 0)false !(found && (x >= 0))false x + y <= 20.5true (n >= 0) && (n <= 100)true ('A' <= ch && ch <= 'Z')true (a + 2 <= b) && !flagtrue

Example 4-6 Evaluate the following expression: (17 < 4 * 3 + 5) || (8 * 2 == 4 * 4) && !(3 + 3 == 6) (17 < 4*3+5) || (8*2 == 4*4) && !(3+3 == 6) =(17 < 12+5) || (16 == 16) && !(6 == 6) =(17 < 17) || true && !(true) =false || true && false =false || false =false

Short-circuit evaluation (of a logical expression): A process in which the computer evaluates a logical expression from left to right and stops as soon as the value of the expression is known. Example 4-7 Consider the following expressions: 1. 5 >= 3) || ( x = = 5) 2. (2 == 3) && (x >= 7) In statement 1, because (5 >= 3) is true and the logical operator used in the expression is ||, the expression evaluates to true. The computer does not evaluate (x == 5). In statement 2, because (2 == 3) is false and the logical operator used in the expression is &&, the expression evaluates to false. The computer does not evaluate (x >= 7).

Selection: if... else  In C++, there are two selections, or branch control structures: if statements and the switch structure.  First we discusses how if and if...else statements can be used to create one-way selection, two-way selection, and multiple selections.

One-way Selection The syntax of one-way selection is: if(expression) statement if(score >= 90) grade = 'A';

Two-way Selection Two-way selection takes the form: if(expression) statement1 else statement2 if ( x>=0 ) cout << “Positive number”; else cout << “Negative number”;

Compound (Block of) Statement A compound statement (also called a block of statements) takes the form { statement1; statement2;. statementn; }  A compound statement is considered a single statement.

Thus, instead of a simple two-way selection as represented by if(age > 18) cout<<"Eligible to vote."<<endl; else cout<<"Not eligible to vote."<<endl; we may substitute the compound statements: if(age > 18) { cout<<" Eligible to vote."<<endl; cout<<" No longer a minor."<<endl; } else { cout<<"Not eligible to vote."<<endl; cout<<"Still a minor."<<endl;

Multiple Selections: Nested if There is a way of considering multiple selections using if...else, if we permit the action statement itself to be an if... statement. When one control statement is within another, it is said to be nested. Consider the following statement. (Assume that all variables are properly declared.)

if(score >= 90) cout<<"The grade is A"<<endl; else if(score >= 80) cout<<"The grade is B"<<endl; else if(score >= 70) cout<<"The grade is C"<<endl; else if(score >= 60) cout<<"The grade is D"<<endl; else cout<<"The grade is F"<<endl; Pairing an else with an if : In a nested if statement, C++ associates an else with the most recent incomplete if —that is, the most recent if that has not been paired with an else

if(temperature >= 50) if(temperature >= 80) cout<<"Good day for swimming."<<endl; else cout<<"Good day for golfing."<<endl; else cout<<"Good day to play tennis."<<endl; if(temperature >= 70) //Line 1 if(temperature >= 80)//Line 2 cout<<"Good day for swimming."<<endl;//Line 3 else//Line 4 cout<<"Good day for golfing."<<endl; //Line 5 if(GPA >= 2.0) if(GPA >= 3.9) cout<<"Dean\’s Honor List."<<endl; else cout<<"Current GPA below graduation requirement. " <<"\nSee your academic advisor."<<endl;

if(cin) cout<<"Input is OK."<<endl; will print Input is OK. if the last input from the standard input device succeeded. If infile is an ifstream variable, then the statement if(!infile) cout<<"Input failed."<<endl; will print Input failed. if the last input associated with the stream variable infile failed.

Confusion Between the Equality Operator ( == ) and the Assignment Operator ( = )  C++ allows any expression that can be evaluated to either true or false to be used as an expression in the if statement. Consider the statement if(x = 5) cout<<"The value is five."<<endl; The expression x = 5 is called an assignment expression First, the right side of the operator = is evaluated to 5. The value 5 is then assigned to x. The value 5 also becomes the value of the expression in the if statement. Because 5 is nonzero, the expression in the if statement evaluates to true, so the statement part of the if statement outputs: The value is five.

The Conditional Operator (? :) In C++, ?: is called the conditional operator. It is a ternary operator, that is, it takes three arguments. The syntax of using the conditional operator is: expression1 ? expression2 : expression3 This is called a conditional expression.  The conditional expression evaluates as follows: If expression1 evaluates to a nonzero integer (that is, true ), then the result of the conditional expression is expression2, otherwise the result of the conditional expression is expression3. if (a >= b) max = a; else max = b; max = (a >= b) ? a : b;

switch STRUCTURES The general form (syntax) of a switch statement is: switch(expression) { case value1: statements1; break; case value2: statements2; break;. case valuen: statementsn; break; default: statements; }

#include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “ grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; switch( toupper(FeedGrade) ) { case 'A': cout << "30 cents per pound.\n"; break; case 'B': cout << "20 cents per pound.\n"; break; case 'C': cout << "15 cents per pound.\n"; break; default: cout << "That is an invalid”<< “choice.\n"; } #include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; if ( toupper(FeedGrade) == ‘A’ ) cout << "30 cents per pound.\n"; else if ( touuper(FeedGrade) == ‘B’ ) cout << "20 cents per pound.\n"; else if ( toupper(FeedGrade) == ‘C’) cout << "15 cents per pound.\n"; else cout << "That is an invalid”<< “choice.\n"; }

#include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “ grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; switch(FeedGrade) { case 'a': case 'A': cout << "30 cents per pound.\n"; break; case 'b': case 'B': cout << "20 cents per pound.\n"; break; case 'c': case 'C': cout << "15 cents per pound.\n"; break; default: cout << "That is an invalid”<< “choice.\n"; } #include void main(void) { char FeedGrade; cout << "Our dog food is available in three” << “grades:\n"; cout << "A, B, and C. Which do you want” << “ pricing for? "; cin >> FeedGrade; if (FeedGrade==‘a’ || FeedGrade == ‘A’) cout << "30 cents per pound.\n"; else if (FeedGrade==‘b’ || FeedGrade == ‘B’) cout << "20 cents per pound.\n"; else if (FeedGrade==‘c’ || FeedGrade == ‘C’) cout << "15 cents per pound.\n"; else cout << "That is an invalid”<< “choice.\n"; }

TERMINATING A PROGRAM WITH THE assert FUNCTION Certain types of errors that are very difficult to catch can occur in a program. For example, division by zero can be difficult to catch using any of the programming techniques you have examined so far. C++ includes a predefined function, assert, that is useful in stopping program execution when certain elusive errors occur.

int numerator; int denominator; int quotient; double hours; double rate; double wages; char ch; 1. quotient = numerator / denominator; 2. if(hours > 0 && ( 0 < rate && rate <= 15.50)) wages = rate * hours; 3. if('A' <= ch && ch <= 'B')

The syntax to use the assert function is assert(expression); Here expression is any logical expression. If expression evaluates to true, the next statement executes. If the expression evaluates to false, the program terminates and indicates where in the program the error occurred. The specification of the assert function is found in the header file cassert. Therefore, for a program to use the assert function, it must include the following statement: #include

assert(denominator); quotient = numerator / denominator; If denominator is 0, the assert statement halts the execution of the program with an error message similar to the following: Assertion failed: denominator, file c:\temp\assert function\assertfunction.cpp, line 20

During program development and testing, the assert statement is very useful for enforcing programming constraints. Although assert statements are useful during program development, after a program has been developed and put into use, if an assert statement fails for some reason, an end user would have no idea what the error means. After you have developed and tested a program, you should remove or disable assert statements. In a very large program, it could be tedious, and perhaps impossible, to remove all of the assert statements. If you plan to modify a program in the future, you might like to keep the assert statements.

You can disable assert statements by using the following preprocessor directive: #define NDEBUG This preprocessor directive #define NDEBUG must be placed before the directive #include.