Selection Structures (if & switch statements) (CS1123)

Slides:



Advertisements
Similar presentations
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
Advertisements

If Statements & Relational Operators Programming.
True or false A variable of type char can hold the value 301. ( F )
1 Engineering Problem Solving With C++ An Object Based Approach Chapter 3 Control Structures.
Slide 1 Summary Two basic concepts: variables and assignments Some C++ practical issues: division rule, operator precedence  Sequential structure of a.
Week 4 Selections This week shows how to use selection statements for more flexible programs. It also describes the various integral types that are available.
1 9/26/08CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
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)
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
The If/Else Statement, Boolean Flags, and Menus Page 180
Chapter 4: Control Structures: Selection
1 9/28/07CS150 Introduction to Computer Science 1 Logical Operators and if/else statement.
1 CS 105 Lecture 5 Logical Operators; Switch Statement Wed, Feb 16, 2011, 5:11 pm.
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.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
Week 3 – Selection Structures UniMAP SemPGT C PROGRAMMING1.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
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)
Computer Science Department Relational Operators And Decisions.
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.
UniMAP Sem II-09/10EKT120: Computer Programming1 Week 3 – Selection Structures.
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT3: Conditional Statements CS2311 Computer Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 4 Selection Structures: Making Decisions.
2 Objectives You should be able to describe: Relational Expressions Relational Expressions The if-else Statement The if-else Statement Nested if Statements.
Basic Of Computer Science
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Rational Expressions and selection structures Relational operators Logical operators Selection structures.
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
PROBLEM SOLVING & ALGORITHMS CHAPTER 5: CONTROL STRUCTURES - SELECTION.
CHAPTER 8 CONTROL STRUCTURES Prepared by: Lec. Ghader R. Kurdi.
Previously Repetition Structures While, Do-While, For.
Chapter 3. Outline Relational Operators Loops Decisions Logical Operators Precedence Summary.
1 COMS 261 Computer Science I Title: C++ Fundamentals Date: September 21, 2005 Lecture Number: 10.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
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.
CHAPTER#3 PART1 STRUCTURED PROGRAM DEVELOPMENT IN C++ 2 nd semester King Saud University College of Applied studies and Community Service Csc.
Chapter 4 Selection: the if-else and switch-case instructions.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Chapter#3 Part1 Structured Program Development in C++
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
Week 4 Program Control Structure
A First Book of C++ Chapter 4 Selection. Objectives In this chapter, you will learn about: –Relational Expressions –The if-else Statement –Nested if Statements.
CPS120: Introduction to Computer Science Decision Making in Programs.
Control Statements: Part1  if, if…else, switch 1.
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,
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
A First Book of C++ Chapter 4 Selection.
Branching statements.
Chapter 3 Selection Statements
The if…else Selection Statement
Chapter 3 Control Statements
Relational Operators A relational operator compares two values. The values can be any built-in C++ data type, such as Character Integer Floating point.
CSC113: Computer Programming (Theory = 03, Lab = 01)
DKT121: Fundamental of Computer Programming
Compound Assignment Operators in C++
Chapter 7 Conditional Statements
Summary Two basic concepts: variables and assignments Basic types:
Week 3 – Program Control Structure
Structured Program Development in C++
Branching statements Kingdom of Saudi Arabia
Presentation transcript:

Selection Structures (if & switch statements) (CS1123)

Selection Structures Condition True False Do Step A Do Step B

In C++, there are three types of selection statements: one-way two-way multi-way

One-Way Decisions One-way decisions either do some particular thing or do nothing at all. The decision is based on a logical expression which either evaluates to true or false, a value of 1 or a value of 0, respectively. Recall that a logical expression always evaluate to a value of true or false; in C++, a nonzero value is always true, and a value of zero is always false. If the logical expression is evaluated to true, then the corresponding statement is executed; if the logical expression evaluates to false, control goes to the next executable statement.

If statement (One Way) - Syntax of if with single-statement body

If statement (One Way) - Syntax of if with multiple-statements body

Examples…. (if, one-way) Write a program to calculate tax collection according to the following formula: 5% Tax, if salary is above 50000 3% Tax , if salary is between 30000 and 50000 2% Tax, is salary is between less than 30000 In the end the program should print the calculated tax.

Two way decisions Two-way decisions either do one particular thing or do another. Similar to one-way decisions, the decision is based on a logical expression.

If statement (Two-Way) - Syntax of if with single-statement body Executed when condition is true Executed when condition is false

If statement (Two-Way) - Syntax of if with single-statement body Executed when condition is true Executed when condition is false

Example 1: int c = 10;   if (c >= 0) { cout << "c is a positive or neutral integer" << endl; } else cout << "c is a negative integer" << endl;

Example 2: int num = 100;   if (num % 2 == 0) { cout << "num is an even integer" << endl; } else cout << "num is an odd integer" << endl; Practical

Examples…. (if, Two-way) Write a program that squares a number (entered by user), if it is between 10 and 100. For all other numbers, an Error message is shown and program terminates.

Examples…. (if, Two-way) Write a payroll program using following rules: Hourly rate: 100 (rupees) If an employee works 40 hours or fewer, he is paid regular pay (hourly rate * number of hours worked). If employees work more than 40 hours, then he WILL receive two times his hourly rate for those hours over 40, in addition to his regular pay for the first 40.

if (weeklyHours <= 40) { earnings = hourlyRate * weeklyHours; } else offHours = weeklyHours - 40; regpay = 40 * hourlyRate; earnings = regpay + offHours * hourlyRate * 2;

Multi-Way Decisions Multi-way decisions are used to evaluate a logical expression that could have several possible values. “if / else if” statements are often used to choose between ranges of values if ( logical expression ) { stmtT1; } else if ( logical expression ) stmtT2; stmtT3; stmtTN; else

\01 else if statement

The form of a multi-way decision using “nested if” : Purpose: To test more than one factors before we write our executable code By nesting if structures, we write ONE COMPLETE if structure inside a SINGLE BRANCH of a parent if structure

Nested “if...else” Statements if (marks>90) { cout<<“\nYou got A grade”; if(nAvailable_scholorships>0) cout<<“\nYou got scholorship too”; tution_fee_due = 0; } else if (marks>=50) cout<<“\nYou passed the course”; cout<<“\nYou failed the course”;

Matching the else

Matching the “else” #include <iostream> using namespace std; int main() { int a, b, c; cout<<“Enter three numbers, a, b, and c:\n”; cin >> a >> b >> c; if( a==b ) if( b==c ) cout << “a, b, and c are the same\n”; else cout << “a and b are different\n”; return 0; } if( a==b ) { if( b==c ) cout << “a, b, and c are the same\n”; } else cout<< “a and b are different\n”; else cout << “b and c are different\n”;

The else...if Construction if (marks>80) { cout<<“\n You got A grade”; cout<<“\n You won scholarship too”; } else if (marks>70) cout<<“\n You got B grade”; else if (marks>60) cout<<“\n You got C grade”; else if (marks>50) cout<<“\n You got D grade”; else cout<<“\n You are fail”;

The Conditional Operator This operator consists of two symbols, which operate on three operands. Is same as we write:

The Conditional Operator The part of this statement to the right of the equal sign is called the conditional expression: The question mark and the colon make up the conditional operator. The expression before the question mark is the test expression.

The Conditional Operator If the test expression is true, the entire conditional expression takes on the value of the operand following the question mark: alpha in this example. If the test expression is false, the conditional expression takes on the value of the operand following the colon: beta.

Conditional Operator (Ternary operator) if (x > 0) y = 1; else y = -1; is equivalent to y = (x > 0) ? 1 : -1; Syntax: result = (condition) ? Expression1 : Expression2;

Conditional Operator, examples cout << ((num % 2 == 0) ? "num is even" : "num is odd"); int min_value = (num1<num2) ? num1 : num2; unsigned int absvalue = (n< 0) ? -n : n;

switch statement Provides a series of alternatives (selections) based on the value of a SINGLE variable Replaces a series of chained if-else statements Makes code easier to read

Switch - Syntax { } switch (Variable) case <value_1> : statement1; statement2; statement3; break; case <value_2> : statement1; case <value_3> : statement1; default: statement1; } Optional

switch statement (without break) Suppose ch is 'a’ switch (ch) { case 'a': cout <<“ ch contains a”; case 'b': cout <<“ ch contains b”; case 'c': cout <<“ ch contains c”; }

switch statement (with break) Suppose ch is ‘b’ switch (ch) { case 'a': cout <<“ ch contains a”; break; case 'b': cout <<“ ch contains b”; break; case 'c': cout <<“ ch contains c”; break; } cout<<“\n End of program…”;

Switch – Example-1 { } char grade; cin>>grade; switch (grade) case ‘A’: tution_fees *= 0.20; break; case ‘B’: tution_fees *= 0.40; break; case ‘C’: tution_fees *= 0.60; break; default: tution_fees *= 1; }

Switch – Example-3 cout<<“\nEnter numbers: “; int a, b; char key; cout<<“\nEnter numbers: “; cin>>a>>b; cout<<“Enter an arithmetic operator”; cin>> key; switch (key) { case ‘+’ : cout<<(a+b); break; case ‘-’ : cout<<(a-b); break; case ‘*’ : cout<<(a*b); break; case ‘/’ : cout<<(a/b); break; default: cout<<“Error: Invalid key…"; }

Logical Operators These operators allow you to logically combine Boolean variables (that is, variables of type bool, with true or false values). For example, If today is Sunday and its not raining then I will play cricket. The logical connection here is the word and, which provides a true or false value to the combination of the two phrases. Only if they are both true then I will play cricket.

Logical Operators

Example

Example If input is ‘n’ then ?? If input is ‘Y’ then ??

Operator Precedence

Operator Precedence

Class Exercise-1 What will be the output of the following code? int marks = 60; switch(marks) { case 50 : cout<<”Passed”; case 60 : cout<<”Got C”; case 70 : cout<<”Got B”; case 80 : cout<<”Got A”; }

Class Exercise-2 What will be the output of the following code? int n = -29; int temp = (n<0)?-n:n; cout<<temp;

Class Exercise-3 What will be the output of the following code? int x=21, y=31, z=44; if( ( x>16) && (y>x) || (z%2==0) ) cout<<“Hello“; else cout<<“World!“;

Class Exercise-4 What will be the output of the following code? int x = 5, y = 30; if(y/x > 2) if(y % x !=2) x = x + 2;   cout<<x<<”\n“<<y;

homework Write a program that ask the user to enter a number in the range of 1—10. Use a switch statement and display corresponding Roman Number against each entered decimal value. E.g., 1  I 2  II 3  III 4  IV

homework Write a program that ask to input value in seconds. Then the program converts the number of seconds into days, hours, minutes, and seconds value. In the end, the program shows the output in the following format: Days:2 Hours:13 Minuts:32 Seconds:11