Programming in C++ Lecture Notes 2 – Choice Statements Andreas Savva.

Slides:



Advertisements
Similar presentations
Fundamental of C programming
Advertisements

Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
1 Programming in C++ Lecture Notes 9 Functions (Returning Values) Andreas Savva.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
If Statements & Relational Operators Programming.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Conditional Operator (?:) Conditional operator (?:) takes three arguments (ternary) Syntax for using the conditional operator:
1 Objectives You should be able to describe: Relational Expressions The if-else Statement Nested if Statements The switch Statement Common Programming.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
CS 1400 Chapter 4, sections Relational operators Less than< Greater than> Less than or equal= Equal== Not equal!=
Switch structure Switch structure selects one from several alternatives depending on the value of the controlling expression. The controlling expression.
Chapter 6 Control Structures.
1 CS 105 Lecture 4 Selection Statements Wed, Jan 26, 2011, 6:05 pm.
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
CS 1400 Jan 2007 Chapter 4, sections Relational operators Less than< Greater than> Less than or equal= Equal== Not equal!=
Administrative MUST GO TO CORRECT LAB SECTION! Homework due 11:59pm on Tuesday. 25 points off if late (up to 24 hours) Cannot submit after 11:59pm on Wednesday.
Quiz 1 Exam 1 Next Week. Nested if Statements if (myGrade >= 80) if (myGrade >= 90) cout
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
C++ Operators CS242 COMPUTER PROGRAMMING T.Banan Al-Hadlaq.
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.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Chapter 4: Control Structures I (Selection). Objectives In this chapter, you will: – Learn about control structures – Examine relational and logical operators.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
CS102 Introduction to Computer Programming Chapter 4 Making Decisions.
CSE1222: Lecture 6The Ohio State University1. Common Mistakes with Conditions (1)  Consider the following code: int age(26); if (age = 18) { cout
CHAPTER 8 CONTROL STRUCTURES Prepared by: Lec. Ghader R. Kurdi.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Selection. Flow Chart If selection If/else selection Compound statement Switch.
Chapter 5 Logic; Got Any?. Flow of Control The order in which the computer executes statements in a program Control Structure A statement used to alter.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
PROGRAM FLOW CHAPTER3 PART1. Objectives By the end of this section you should be able to: Differentiate between sequence, selection, and repetition structure.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
1 Compound Assignment C++ has a large set of operators for applying an operation to an object and then storing the result back into the object Examples.
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.
CSC1201: Programming Language 2 Lecture 1 Level 2 Course Nouf Aljaffan (C) CSC 1201 Course at KSU1.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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,
Selection Executing Statements Selectively. Review We’ve seen that the C++ if statement permits a Statement to be executed selectively: if (Expression)
Fundamental Programming Fundamental Programming More Expressions and Data Types.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
STRUCTURED PROGRAMMING C++ Operators. Content 2  C++ operators  Assignment operators  Arithmetic operators  Increment and decrement operators  Decision.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
STRUCTURED PROGRAMMING Selection Statements. Content 2  Control structures  Types of selection statements  if single-selection statement  if..else.
LECTURE # 6 : STRUCTURED PROGRAMMING C++ OPERATORS By Mr. Ali Edan.
CSE202: Lecture 5The Ohio State University1 Selection Structures.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Chapter 2: Control Structures (Selection & Repetition)
 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.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
משפטי תנאי ( לוגיקה ) קרן כליף. 2 © Keren Kalif ביחידה זו נלמד :  משפטי תנאי  משפט switch  משפט if מקוצר.
The Ohio State University
Branching statements.
Chapter 3 Selection Statements
Chapter 3 Control Statements
Selection (also known as Branching) Jumail Bin Taliba by
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.
A mechanism for deciding whether an action should be taken
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
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.
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.
Compound Assignment Operators in C++
Summary Two basic concepts: variables and assignments Basic types:
Chapter 4: Control Structures I (Selection)
Decisions, decisions, decisions
Branching statements Kingdom of Saudi Arabia
Presentation transcript:

Programming in C++ Lecture Notes 2 – Choice Statements Andreas Savva

2 If Statements if (the sun is shining) go to the beach; else go to class; If the sun is shining End If ClassBeach TrueFalse

3 Boolean Data Type (false, true) i.e. bool bFlag; bFlag = true; bFlag = 5 > 12; bFlag = 4 == 3 + 1; bFlag true false true Assignment Statement Boolean Operator

4 Boolean Data-Type The type bool is also described as being an integer: false = 0 true = 1 int x = 42; cout << x + true; bool b = false; cout << b; bool b = 1; cout << b; int x = 42; bool b = true; cout << x + b; Output: 0 Output: 1 Output: 43 bool b = true; cout << b; Output: 1

5 Boolean Operators Binary Operators – Compare two values MathematicsC++ === ≠!=> ≥>=< ≤<=

6 Order of Operations 1.Brackets 2.Prefix operators ( ++var, --var, -exp, +exp ) 3.Multiplication ( * ) and Division ( / ) and Remainder ( % ) 4.Addition ( + ) and Subtraction ( – ) 5.Comparison ( >, >=, <, <= ) 6.Equality ( ==, != ) 7.Assignment Statement ( = ) 8.Postfix operators ( var++, var-- )

7 Exercises 4 == != 7 – * 4 / 5 >= % 7 / 2 * 3 != 11 What is wrong with the followings? 1 + [6 + 3 * (6 - 2)] true false (((5 + 1 * 2) + 3) * 2

8 Operators ( Or, And, Not ) Age = 30; 10 < Age < 20  true (10 < Age) && (Age < 20)  false 1 false = 0 true = 1

9 Logical Conditions ( Or, And, Not ) true || true = true true || false = true false || true = true false || false = false true && true = true true && false = false false && true = false false && false = false ! true = false ! false = true OR AND NOT

10 Order of Operations 1.Brackets 2.Prefix operators ( ++var, --var, -exp, +exp ) 3.Multiplication ( * ) and Division ( / ) and Remainder ( % ) 4.Addition ( + ) and Subtraction ( – ) 5.Comparison ( >, >=, <, <= ) 6.Equality ( ==, != ) 7.Logical AND ( && ) 8.Logical OR ( || ) 9.Assignment Statement ( = ) 10.Postfix operators ( var++, var-- )

11 Exercises Note: false = 0 true = not zero Exercises:Statement cout << true || false && false; cout << (true || false) && false; cout << true && 7; cout << 12 && 0; cout 5; cout 5);Output Error - needs () 1

12 if-then-else statement if ( ) ; else ; else if c end if then truefalse

13 if-then-else Example #include using namespace std; main() { int Num1; int Num2; cin >> Num1 >> Num2; if (Num1 > Num2) cout << Num1; else cout << Num2; } Num1Num2Output

14 Another example #include using namespace std; void main() { int grade; cout << ”Enter your grade: ”; cin >> grade; if (grade >= 60) cout << ”You passed”; else cout << ”You failed”; }

15 if-then Statement if ( ) ; if c end if then truefalse

16 if-then Example #include using namespace std; int main() { int grade; cout << ”Enter your grade: ”; cin >> grade; if (grade >= 60) cout << ”You passed”; return 0; }

17 Compound Statements #include using namespace std; void main() { int grade = 30; if (grade >= 60) { cout << ”You passed” << endl; cout << ”Congratulations”; } #include using namespace std; void main() { int grade = 30; if (grade >= 60) cout << ”You passed” << endl; cout << ”Congratulations”; } Congratulations

18 Compound Statements #include using namespace std; int main() { int grade; cout << ”Enter your Grade: ”; cin >> grade; if (grade >= 60) { cout << ”You passed” << endl; cout << ”Congratulations\n”; } else { cout << ”You failed” << endl; cout << ”SORRY\n”; } return 0; } Enter your grade: 46 You failed SORRY Enter your grade: 82 You passed Congratulations

19 Error. Why? #include using namespace std; int main() { int grade; cout << ”Enter your Grade: ”; cin >> grade; if (grade >= 60) cout << ”You passed” << endl; cout << ”Congratulations\n”; else cout << ”You failed” << endl; cout << ”SORRY\n”; return 0; }

20 Correct but... #include using namespace std; int main() { int grade; cout << ”Enter your Grade: ”; cin >> grade; if (grade >= 60) { cout << ”You passed” << endl; cout << ”Congratulations\n”; } else cout << ”You failed” << endl; cout << ”SORRY\n”; return 0; } Enter your grade: 46 You failed SORRY Enter your grade: 82 You passed Congratulations SORRY

21 int main() { int Num1, Num2; cin >> Num1 >> Num2; if (Num1 > Num2) if (Num1 + Num2 > 20) cout << Num1; else cout << Num2; return 0; } Nested if-Statements Num1Num Output 3 12

22 int main() { int Num1, Num2; cin >> Num1 >> Num2; if (Num1 > Num2) { if (Num1 + Num2 > 20) cout << Num1; } else cout << Num2; return 0; } Same as previous example ? Num1Num Output 10 12

23 int main() { int grade; cout << ”Enter your grade: ”; cin >> grade; if (grade > 100 || grade < 0) cout << ”Not a valid grade”; else { cout << ”You got ”; if (grade >= 90) cout << ”an A”; else if (grade >= 80) cout << ”a B”; else if (grade >= 70) cout << ”a C”; else if (grade >= 60) cout << ”a D”; else cout << ”an F”; } return 0; } Example

24 Programming Exercise Enter three numbers: Max = 12

25 Solution 1 void main() { int a, b, c; cout << ”Enter three numbers: ”; cin >> a >> b >> c; if (a > b) if (a > c) cout << ”Max = ” << a; else cout << ”Max = ” << c; else if (b > c) cout << ”Max = ” << b; else cout << ”Max = ” << c; } Enter three numbers: Max = 8

26 Solution 2 void main() { int a, b, c, max; cout << ”Enter three numbers: ”; cin >> a >> b >> c; if (a > b) max = a; else max = b; if (c > max) max = c; cout << ”Max = ” << max; } Enter three numbers: Max = 4

27 Solution 3 void main() { int a, b, c; cout << ”Enter three numbers: ”; cin >> a >> b >> c; if (a >= b && a >= c) cout << ”Max = ” << a; else if (b >= a && b >= c) cout << ”Max = ” << b; else cout << ”Max = ” << c; } Enter three numbers: Max = 45

28 Programming Exercise Age 0 – 4Baby 5 – 14Child 15 – 19Teenager 20 – 64Adult above 64Old How old are you? 18 You are a teenager

29 #include using namespace std; void main() { int Age; cout << ”How old are you? ”; cin >> Age; cout << ”You are ”; if (Age < 0) cout << ”not born yet”; else if (Age < 5) cout << ”a baby”; else if (Age < 15) cout << ”a child”; else if (Age < 20) cout << ”a teenager”; else if (Age < 65) cout << ”an adult”; else cout << ”old”; } Solution How old are you? 32 You are an adult

30 #include using namespace std; void main() { int Digit; cout << ”Enter a digit: ”; cin >> Digit; if (Digit == 0) cout << ”Zero”; else if (Digit == 1) cout << ”One”; else if (Digit == 2) cout << ”Two”; else if (Digit == 3) cout << ”Three”; else if (Digit == 4) cout << ”Four”; else if (Digit == 5) cout << ”Five”; else if (Digit == 6) cout << ”Six”; else if (Digit == 7) cout << ”Seven”; else if (Digit == 8) cout << ”Eight”; else if (Digit == 9) cout << ”Nine”; else cout << ”Not a digit”; } Exercise Enter a digit: 3 Three

31 Day = 4; if (Day = 0) cout << ”Sunday”; else if (Day = 1) cout << ”Monday”; else if (Day = 2) cout << ”Tuesday”; else if (Day = 3) cout << ”Wednesday”; else if (Day = 4) cout << ”Thursday”; else if (Day = 5) cout << ”Friday”; else if (Day = 6) cout << ”Saturday”; What’s wrong with this? Monday if (Day == 0) cout << ”Sunday”; if (0 == Day) cout << ”Sunday”; same as if (0 = Day) cout << ”Sunday”; but the following will give a syntax error

32 Note: false = 0 true ≠ 0 bool Flag; if (Flag == true)... bool Flag; if (Flag)... int num = 10 if (num)... true if (true)... Same if (1)... if (3-2-1)... true false if (2.344)... true

33 Nesting The Condition is the most right if (x = Grade/100, x >= 0.6) { cout << ”You passed” << endl; cout << ”Congratulations”; } if (3,5-1,7,8,9+2) cout << ”This is true”; if (3,4-6,5,3-2-1) cout << ”This is false”;

34 Be Careful Grade = 30; if (Grade >= 60) ; { cout << ”You passed\n”; cout << ”Congratulations\n”; } You passed Congratulations Grade = 74; if (Grade >= 60) { cout << ”You passed” << endl; cout << ”Congratulations\n”; } else ; { cout << ”You failed\n”; cout << ”SORRY\n”; } You passed Congratulations You failed SORRY

35 Switch (Case) Statement switch ( ) { case V 1 : ; case V 2 : ; case V 3 : ;... default : ; } switch expresion end switch V1V1 V2V2 V3V3 otherwise

36 Switch Statement with break switch ( ) { case V 1 : ; break; case V 2 : ; break; case V 3 : ; break;... default : ; break; } switch expresion... end switch V1V1 V2V2 V3V3 otherwise

37 Break Statement switch (Grade) { case ’A’ : case ’B’ : case ’C’ : case ’D’ : cout << ”You passed”; break; case ’F’ : cout << ”You failed”; break; default : cout << ”Invalid grade”; break; } The break statement causes execution to exit the switch statement. Otherwise, the flow of control “falls through” the next case.

38 Switch Statement Example void main() { int Digit; cout << ”Enter a digit: ”; cin >> Digit; switch (Digit) { case 0: cout << ”Zero”; break; case 1: cout << ”One”; break; case 2: cout << ”Two”; break; case 3: cout << ”Three”; break; case 4: cout << ”Four”; break; case 5: cout << ”Five”; break; case 6: cout << ”Six”; break; case 7: cout << ”Seven”; break; case 8: cout << ”Eight”; break; case 9: cout << ”Nine”; break; default: cout << ”Not a digit”; break; } Enter a digit: 3 Three

39 Programming Exercise Age 0 – 4Baby 5 – 14Child 15 – 19Teenager 20 – 64Adult above 64Old How old are you? 18 You are a teenager

40 #include using namespace std; void main() { int Age; cout << ”How old are you? ”; cin >> Age; cout << ”You are ”; if (Age < 0) cout << ”not born yet”; else switch (Age / 5) { case 0 : cout << ”a baby”; break; case 1 : case 2 : cout << ”a child”; break; case 3 : cout << ”a teenager”; break; case 4 : case 5 : case 6 : case 7 : case 8 : case 9 : case 10 : case 11 : case 12 : cout << ”an adult”; break; default : cout << ”old”; break; } Solution How old are you? 32 You are an adult

41 The Conditional Statement A shortcut to a simple if-then-else statement used normally to assign different values to a variable depending on a condition. ?: condition ? stment_if_true : stment_if_false if(year%4 == 0) FebDays = 29; else FebDays = 28; FebDays = year%4 == 0 ? 29 : 28; year%4 == 0 ? FebDays = 29 : FebDays = 28; same as