C++ Programming Control Structures I (Selection).

Slides:



Advertisements
Similar presentations
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Advertisements

CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Logic & program control part 3: Compound selection structures.
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.
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)
Chapter 4: Control Structures I (Selection)
Use Precedence Chart int number ; float x ; number ! = 0 && x < 1 / number / has highest priority < next priority != next priority && next priority What.
1 Lecture 7:Control Structures I (Selection) Introduction to Computer Science Spring 2006.
Multi-alternative Selection Both the if clause and the else clause of an if...else statement can contain any kind of statement, including another selection.
Single selection syntax if ( expression ) { statements; } TRUE FALSE expression if clause 1. Statemens are executed when expression is true 2. { } can.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 4 Control Structures I: Selection.
Chapter 5 Conditions, Logical Expressions, and Selection Control Structures Dale/Weems/Headington.
Control Structures I (Selection)
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 Logical Expressions & If-Else. 2 Overview  More on Data Type bool u Using Relational & Logical Operators to Construct & Evaluate Logical Expressions.
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.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
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,
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.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 4: Control Structures I (Selection)
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
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)
 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.
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)
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.
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.
CONTROL STRUCTURE. 2 CHAPTER OBJECTIVES  Learn about control structures.  Examine relational and logical operators.  Explore how to form and evaluate.
CONTROL STRUCTURE Chapter 3. CONTROL STRUCTURES ONE-WAY SELECTION Syntax: if (expression) statement Expression referred to as decision maker. Statement.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
1 Advanced Programming IF. 2 Control Structures Program of control –Program performs one statement then goes to next line Sequential execution –Different.
Selection in C++ If statements. Control Structures Sequence Selection Repetition Module.
C++ Programming: Program Design Including Data Structures, Fifth Edition Chapter 4: Control Structures I (Selection)
1 Advanced Programming Windows Applications. Create a new Project Select a C# Windows Application.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
Java Fundamentals 4. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
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)
The if…else Selection Statement
Chapter 4: Control Structures I
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 4: Control Structures I
Chapter 4: Control Structures I (Selection)
3 Control Statements:.
Chapter 4 Selection.
Chapter 4: Control Structures I (Selection)
Control Structure Chapter 3.
Control Structure.
Presentation transcript:

C++ Programming Control Structures I (Selection)

Control Structures A computer can proceed: −In sequence −Selectively (branch) - making a choice −Repetitively (iteratively) - looping Some statements are executed only if certain conditions are met A condition is met if it evaluates to true

Control Structures (continued)

Relational Operators A condition is represented by a logical (Boolean) expression that can be true or false Relational operators: −Allow comparisons −Require two operands (binary) −Evaluate to true or false

Relational Operators (continued)

Relational Operators and Simple Data Types You can use the relational operators with all three simple data types: − 8 < 15 evaluates to true − 6 != 6 evaluates to false − 2.5 > 5.8 evaluates to false − 5.9 <= 7.5 evaluates to true

Comparing Characters

Relational Operators and the string Type Relational operators can be applied to strings Strings are compared character by character, starting with the first character Comparison continues until either a mismatch is found or all characters are found equal If two strings of different lengths are compared and the comparison is equal to the last character of the shorter string −The shorter string is less than the larger string

Relational Operators and the string Type (continued) Suppose we have the following declarations: string str1 = "Hello"; string str2 = "Hi"; string str3 = "Air"; string str4 = "Bill"; string str4 = "Big";

Relational Operators and the string Type (continued)

Logical (Boolean) Operators and Logical Expressions (NOT)

Order of Precedence (continued)

Short-Circuit Evaluation Short-circuit evaluation: evaluation of a logical expression stops as soon as the value of the expression is known Example: (age >= 21) || ( x == 5)//Line 1 (grade == 'A') && (x >= 7)//Line 2

Selection: if and if...else One-Way Selection Two-Way Selection Compound (Block of) Statements Multiple Selections: Nested if Comparing if...else Statements with a Series of if Statements

One-Way Selection The syntax of one-way selection is: The statement is executed if the value of the expression is true The statement is bypassed if the value is false ; program goes to the next statement if is a reserved word

One-Way Selection (continued)

Two-Way Selection Two-way selection takes the form: If expression is true, statement1 is executed; otherwise, statement2 is executed − statement1 and statement2 are any C++ statements else is a reserved word

Two-Way Selection (continued)

Compound (Block of) Statement 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; }

25 int carDoors, driverAge ; double premium, monthlyPayment ;... if ( (carDoors == 4 ) && (driverAge > 24) ) { premium = ; cout<<“ LOW RISK “ ; } else { premium = ; cout <<“HIGH RISK ” ; } monthlyPayment = premium / ;

What happens if you omit braces? if ( (carDoors == 4 ) && (driverAge > 24) ) premium = ; cout<< “ LOW RISK “ ; else premium = ; cout<< “ HIGH RISK ” ; monthlyPayment = premium / ; COMPILE ERROR OCCURS. The “if clause” is the single statement following the if.

Braces can only be omitted when each clause is a single statement if ( lastInitial <= ‘K’ ) volume = 1; else volume = 2; Cout<< “Look it up in volume # %d of the phone book”; cout<< volume ;

If--Else for a mail order Write a program to calculate the total price of a certain purchase. There is a discount and shipping cost:  The discount rate is 25% and the shipping is if purchase is over  Otherwise, The discount rate is 15% and the shipping is 5.00 pounds.

What output? and Why? int age; age = 20; if ( age == 16 ) { cout<< “Did you get driver’s license?” ; }

What output? and Why? int age; age = 30; if ( age < 18 ) cout<< “Do you drive?”; cout<< “Too young to vote”;

What output? and Why? int code; code = 0; if ( ! code ) cout<< “Yesterday”; else cout<<“Tomorrow”;

Example Write a program to ask a student for his grades in 3 exams ( each out of 50 ), get their total and inform the student whether he passed or failed the course.

Multiple Selections: Nested if Nesting: one control statement in another An else is associated with the most recent if that has not been paired with an else

Multiple Selections: Nested if (continued)

Comparing if…else Statements with a Series of if Statements

37 Example The Air Force has asked you to write a program to label aircrafts as military or civilian. Your program input is the plane’s speed and its estimated length. For planes traveling faster than 1100 km/hr, you will label those shorter than 52 m “military”, and longer as “Civilian”. For planes traveling less than 1100, you will issue an “aircraft unknown” statement.

38 Example Write a program to get the roots of a quadratic equation, given the 3 coefficients a, b, and c, a x 2 + b x + c = 0

Writing Nested if Statements Display one word to describe the int value of number as “Positive”, “Negative”, or “Zero” Your city classifies a pollution index −less than 35 as “Pleasant”, −35 through 60 as “Unpleasant”, − and above 60 as “Health Hazard.” −Display the correct description of the −pollution index value.

Conditional Operator (?:) Conditional operator ( ?: ) takes three arguments −Ternary operator Syntax for using the conditional operator: expression1 ? expression2 : expression3 If expression1 is true, the result of the conditional expression is expression2 −Otherwise, the result is expression3

switch Structures switch structure: alternate to if-else switch (integral) expression is evaluated first Value of the expression determines which corresponding action is taken Expression is sometimes called the selector

Light bulbs Write a program to ask the user for the brightness of a light bulb (in Watts), and print out the expected lifetime: BrightnessLifetime in hours , , otherwise0

Program Write a C program to calculate the average of three test grades and print out a report with the student’s ID number, average, and how well is the student progress. “Very Good” is a 70-point average or better, “Good” is an average between 60 and 70, and “Failing” is 50 point average or less.

Write a C program that calculates bills for the Electricity company. There are 3 types of customers: residential (code R), commercial (code C), and Industrial (code I). - For a code R customer, the bill is $10 plus $0.05 for each kilowatt used. - For a code C customer, the bill is $1000 for the first 2000 kilowatt, and $0.005 for each additional kilowatt used. - For a code I customer, the bill is $1000 if he used less than 4000 kilowatt, $2000 if he used between 4000 and kilowatt, or $3000 if he used more than kilowatt. The inputs of the program should be the type of customer ( R C or I) and the kilowatts used. The output should be the amount of money the customer has to pay.

Find The output int x = / 3 * ; switch ( x ) { case 21: printf ( “ Eeny “ ) ; break; case 24: printf ( “ Meeny “ ) ;break; case 25 : printf ( “ Miny “ ) ; break; case 28 : printf ( “ Mo “ ) ; break; default : printf(“ None of them “); }

Write a program that reports the content of a compressed-air cylinder based upon the first letter of the cylinder’s color. The program input is a character representing the observed color of the cylinder: ‘Y’ or ‘y’ for yellow, ‘G’ or ‘g’ for green and so on. Given: ColorContent OrangeAmmonia BrownCarbon Monoxide YellowHydrogen GreenOxygen

Using selection Every Sunday through Thursday you go to class. −When it is raining you take an umbrella. But on the weekend, what you do depends on the weather. −If it is raining you read in bed. Otherwise, you have fun outdoors.