Department of CSE 1 1.4 Control Structures: Selection.

Slides:



Advertisements
Similar presentations
ICS103: Programming in C 4: Selection Structures Muhamed F. Mudawar.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
Chapter 4 Selection Structures: if and switch Statements Instructor: Alkar / Demirer.
Control Structures 4 Control structures control the flow of execution of a program 4 The categories of control structures are: –Sequence –Selection –Repetition.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 3 - Structured Program Development Outline.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
1 CS 201 Selection Structures (1) Debzani Deb. 2 Error in slide: scanf Function scanf(“%lf”, &miles); function name function arguments format string variable.
Control Structures Control structures control the flow of program execution. 3 types of control structures: sequence, selection.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Chapter 4 Selection Structures: if and switch Statements Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
19/5/2015CS150 Introduction to Computer Science 1 Announcements  1st Assignment due next Monday, Sep 15, 2003  1st Exam next Friday, Sep 19, 2003  1st.
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Structural Program Development: If, If-Else Outline.
CPS 125: Digital Computation and Programming Selection Structures: if and switch Statements.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Lecture 4 C Program Control Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc.
Selection Structures (if & switch statements) (CS1123)
Conditional Statements For computer to make decisions, must be able to test CONDITIONS IF it is raining THEN I will not go outside IF Count is not zero.
1 CSC 1401 S1 Computer Programming I Hamid Harroud School of Science and Engineering, Akhawayn University
A. Abhari CPS1251 Topic 4: Control structures Control Structures Overview Conditions if Statement Nested if Statements switch Statement Common Programming.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Flow Control (Switch, do-while, break) Outline 4.7The.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Decision II. CSCE 1062 Outline  Boolean expressions  switch statement (section 4.8)
Flow of Control Part 1: Selection
Lecture 2: Logical Problems with Choices. Problem Solving Before writing a program Have a thorough understanding of the problem Carefully plan an approach.
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
Chapter 6: Control Structures Computer Programming Skills Second Term Department of Computer Science Foundation Year Program Umm Alqura.
Selection. Flow Chart If selection If/else selection Compound statement Switch.
A First Book of ANSI C Fourth Edition Chapter 4 Selection.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Selection Relational Expressions A condition or logical expression is an expression that can only take the values true or false. A.
Conditional Structures UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) ADNAN BABAR MT14028 CR
Lecture 2 Control Structure. Relational Operators -- From the previous lecture Relational Operator Meaning == is equal to < is less than > is greater.
Control Statements in C 1.Decision making statements 2.Looping statements 3.Branching statements
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 3 (2) & 4 September 8 & 10, 2009.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Lecture 4: C/C++ Control Structures Computer Programming Control Structures Lecture No. 4.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X1 Chapter 3 Control Statements.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 4 - Program Control Outline 4.1Introduction 4.2The Essentials of Repetition 4.3Counter-Controlled.
Introduction to C Programming CE Lecture 3 Control Structures in C.
Control statements Mostafa Abdallah
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 4: Making Decisions 1.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Control structures in C by Dr P.Padmanabham Professor (CSE)&Director Bharat Institute of Engineering &Technology Hyderabad Mobile
Control Statements: Part1  if, if…else, switch 1.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
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,
Chapter 4 : Selection Structures: if and switch statement By Suraya Alias.
Lesson #4 Logical Operators and Selection Statements.
Lesson #4 Logical Operators and Selection Statements.
Decision making If.. else statement.
The if…else Selection Statement
Decisions Chapter 4.
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
Chapter 2.1 Control Structures (Selection)
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Control Structures.
Structured Program
Chapter 7 Conditional Statements
Decision making If statement.
2.6 The if/else Selection Structure
CprE 185: Intro to Problem Solving (using C)
Selection Control Structure
ICS103: Programming in C 4: Selection Structures
Presentation transcript:

Department of CSE Control Structures: Selection

Objectives To understand how decisions are made in a computer To understand the relational operators To understand the logical operators and,or and not To write programs using relational and logical operators To write programs that uses two way selection. if …else statements To write programs that uses multi way selection if …else if ladder and switch case To understand classification of characters 2 Department of CSE

Agenda Relational and Logical operators Ternary operator Simple if if …else if else if ladder Nested if switch case 3 Department of CSE

Control Structures Control structures Control structures control the flow of execution in a program or function. There are three kinds of execution flow: Sequence Sequence: the execution of the program is sequential. Selection Selection: A control structure which chooses alternative to execute. Repetition Repetition: A control structure which repeats a group of statements. selection We will focus on the selection control structure. 4 Department of CSE

Conditions A program may choose among alternative statements by testing the value of key variables. e.g., if mark is greater than 50 print “Pass” Condition Condition is an expression that is either false (represented by 0) or true (represented by 1). e.g., “mark is greater than 50” is a condition. relationalequality operators Conditions may contain relational or equality operators, and have the following forms. relational-operator variable relational-operator variable (or constant) equality-operator variable equality-operator variable (or constant) 5 Department of CSE

Courtesy: Pearson Addison-Wesley.4-6 Operators Used in Conditions OperatorMeaningType <Less thanRelational >Greater thanRelational <=Less than or equal toRelational >=Greater than or equal toRelational ==Equal toEquality !=Not equal toEquality

4-7 Examples of Conditions OperatorConditionMeaning <=x <= 0x less than or equal to 0 < Power < MAX_POWPower less than MAX_POW == mom_or_dad == ‘M’ mom_or_dad equal to ‘M’ != num != SETINELnum not equal to SETINEL

Logical Operators logical operators. There are three kinds of logical operators. && : and || : or ! : not Logical expression Logical expression is an expression which uses one or more logical operators, e.g., (temperature > 90.0 && humidity > 0.90) ! (n = 100).

The Truth Table of Logical Operators Op 1Op 2 Op 1 && Op2Op 1 || Op2 nonzero Op 1 ! Op 1 nonzero0 01

Operator Precedence precedence An operator’s precedence determines its order of evaluation. Unary operator Unary operator is an operator that has only one operand. !, + (plus sign), - (minus sign), and & (address of) They are evaluated second only after function calls. OperatorPrecedence function callshighest ! + - & * / % + - = > == != && || = lowest

Copyright ©2004 Pearson Addison-Wesley. All rights reserved Evaluation for !flag || (y + z >= x - z) Evaluation tree The result of this expression is true

Comparing Characters relational equality operators We can also compare characters in C using the relational and equality operators. ExpressionValue ‘9’ >= ‘0’1 (true) ‘a’ < ‘e’1 (true) ‘Z’ == ‘z’0 (false) ‘a’ <= ‘A’system dependent

DeMorgan’s Theorem DeMorgan’s theorem DeMorgan’s theorem gives us a way of transforming a logical expression into its complement. The complement of expr 1 && expr 2 is comp 1 || comp 2, where comp 1 and comp 2 are the complement of expr 1 and expr 2, respectively. The complement of expr 1 || expr 2 is comp 1 && comp 2. e.g., age > 25 && (status == ‘S’ || status ==‘D’) is equal to !(age <=25 ||(status != ‘S’)&& status!=‘D’)

4-14 Conditional Statements Pseudocode example: If student’s mark is greater than or equal to 60 Print “Passed” If the condition is true Print statement executed, program continues to next statement If the condition is false Print statement ignored, program continues

Flowchart of if statement 15 Department of CSE true false mark >= 50 print “Passed” A decision can be made on any expression. zero - false nonzero - true Example: Mark=60 is true

Translation into C If student’s mark is greater than or equal to 50 Print “ You have passed in examination ” if ( mark >= 50 ) printf(“You have passed in examination!\n”); if structure Single-entry/single-exit 16 Department of CSE

4-17 Single way selection if Statement selection The if statement is the primary selection control structure. It has a null else statement. Syntax: if (condition) statement; e.g. 1 If student’s mark is greater than or equal to 50 Print “ You have passed in examination ” if ( mark > 50 ) printf(“You have passed in examination!\n”); e.g. 2 If quantity is not equal to 0 calulate price as price * quantity print price if (quantity!= 0.0 ){ price = price * quantity; printf(“Price=Rs. %8.2f!\n”,price); } Mark > 60 Print “Passed” False True

Two way selection if else Statement two way selection control structure. The if else statement is the primary two way selection control structure. Syntax: if (condition) statement; else statement; e.g. 1 if ( mark > 50 ) printf(“You have passed in examination!\n”); else printf(“Sorry Try again!\n”);

e.g. 2 if (quantity!= 0.0 ){ price = price * quantity; printf(“Price=Rs. %8.2f!\n”,price); } else printf(“Quantity is less than 0.0\n”); 19 Department of CSE

Single way selection if Statement Write a C program to print the number entered by user only if the number entered is negative. void main(){ int num; printf("Enter a number to check.\n"); scanf("%d",&num); if(num<0) { /* checking whether number is less than 0 or not. */ printf("Number = %d\n",num); } /*If test condition is true, statement above will be executed, otherwise it will not be executed */ printf("The if statement in C programming is easy."); return 0; }

Two way selection if else Statement Write a C program to print the number entered by user only if the number entered is positive or negative. void main(){ int num; printf("Enter a number to check.\n"); scanf("%d",&num); if(num<0) { /* checking whether number is less than 0 or not. */ printf(“Negative Number = %d\n",num); } else{ /*If test condition is false statement */ printf(“Positive Number = %d\n",num); } return 0; }

Two way selection if else Statement Write a C program to print the number entered by user only if the number entered is even or odd. void main(){ int num; printf("Enter a number to check.\n"); scanf("%d",&num); if(num%2==0) { /* checking whether number is odd or even. */ printf(“Even Number = %d\n",num); } else{ /*If test condition is false statement */ printf(“OddNumber = %d\n",num); } return 0; }

23 if/else Selection Structure Ternary conditional operator ( ?: ) Three arguments (condition, value if true, value if false ) Code could be written: ( mark >= 50 ? printf(“Passed”) : printf(“Failed”); truefalse print “Failed”print “Passed” mark >= 60 ConditionValue if trueValue if false

Combining condition with logical operators If both conditions need to be true use logical AND ( && )operator  If first condition is false second condition not evaluate. If only one of the condition true use logical OR (|| ) operator  If first condition is true second condition not evaluated.  Logical AND ( && ) and logical OR (|| ) act as short circuiting operators.

Combining condition with logical operators e.g. 1 /* if condition 1 is true condition 2 will be evaluated*/ if ( (road_status == ‘S’) && (temp>0) ) printf(“Wet roads ahead!\n”); else printf(“Drive carefully!\n”); e.g. 2 /* if condition 1 is true condition 2 will not be evaluated*/ if ( (road_status == ‘S’) || (temp>0) ) printf(“Wet roads ahead!\n”); else printf(“Drive carefully!\n”);

Nested if Statements Nested if statementanother if statement Nested if statement is an if statement with another if statement as its true task or false task. e.g., if (road_status == ‘S’) else printf(“Drive carefully!\n”); if (temp > 0) { printf(“Wet roads ahead!\n”); } else { printf(“Icy roads ahead!\n”); }

An Example for the Flowchart of Nested if Statements Another if statement Main if statement

Multiway Decision Making statements multiway decision If there are many alternatives, it is better to use the syntax of multiway decision. C programming provides two types of multiway control structures. if else if ladder switch case

Multiway Decision Making statements if else if ladder

multiway decision If there are many alternatives, it is better to use the syntax of multiway decision. Syntax: if(condition 1) { statements; / ∗ statements will execute if the condition 1 is true ∗ / } else if(condition 2) { statements; / ∗ statements will execute if the condition 2 is true ∗ / } else if(condition 3) { statements; / ∗ statements will execute if the condition 3 is true ∗ / } else if(condition n) { statements; / ∗ statements will execute if the condition n is true ∗ / } else { statements; / ∗ statements will execute if all conditions are false ∗ / }

Multiway Decision Making statements if else if ladder

e.g. Write a C program to check if a number is positive negative or zero void main() { int num; printf("Enter a number = "); scanf("%d",&num); if(num>0) { printf("Number is Positive"); } else if(a<0) { printf("Number is Negative"); } else { printf("Number is Zero"); } return 0; }

An Example of Multiple-Alternative Decisions

Multiway-Selection Structure switch case Useful when variable or expression is tested for multiple values Consists of a series of case labels and an optional default case break is (almost always) necessary It is used to terminate a case in the switch statement

4-35 The switch Statement a single variable an expression The switch statement is used to select one of several alternatives when the selection is based on the value of a single variable or an expression. switch (controlling expression) { case label 1 : statement 1 break ; case label 2 : statement 2 break ; … case label n : statement n break ; default: statement d ; } If the result of this controlling expression matches label 1, execute staement 1 and then break this switch block. If the result matches none of all labels, execute the default statement d.

switch (expression) { case val1: statement break; case val2: statement break; …. case valn: statement break; default: statement break; } if (expression == val1) statement else if (expression==val2) statement …. else if (expression== valn) statement else statement switch case and if else if ladder

Flowchart switch case true false case a case a action(s)break case b case b action(s)break false case z case z action(s)break true default action(s)

An Example of a switch Statement with Type numeric(int) Case Labels Print the day based on the number entered by the user. If any number other than 1-7 is entered say unknown number.

An Example of a switch Statement with Type numeric(int) Case Labels /* Print the day based on the number entered*/ void main() { int day; printf(“Enter the day of the week(1-7):”); scanf(“%d”,&day); switch(day) { case 1: printf(“Sunday\n”); break; case 2: printf(“Monday\n”); break; case 3: printf(“Tuesday\n”); break; case 4: printf(“Wednesday\n”); break; case 5: printf(“Thursday\n”); break; case 6: printf(“Friday\n”); break; case 7: printf(“Saturday\n”); break; default: printf(“Incorrect entry Try again!\n”); }

An Example of a switch Statement with Type char Case Labels Write a program to enter the ship name based on the character entered. If it is B or b Battleship If it is C or c Cruiser If it is D or d Destroyer If it is F or f Frigate If it is not any of the letter print unknown ship

Copyright ©2004 Pearson Addison-Wesley. All rights reserved An Example of a switch Statement with Type char Case Labels class is a char variable. Two or more cases can execute the same statement.

Department of CSE42 Try it yourself 1.Write a program to enter the temperature and print the following message according to the given temperature by using if else ladder statement. 1. T 30 "Its hot".

Department of CSE43 Try it yourself input the boiling point 2.Write a program that prompts the user to input the boiling point in degree Celsius. Using switch case output the substance The program should output the substance corresponding to the boiling point listed in the table. “substance unknown” The program should output the message “substance unknown” when it does not match any substance. SubstanceBoiling point Water100°C Mercury357°C Copper1187°C Silver2193°C Gold2660°C

Try it yourself Examples of the scenario of your program. within a range of boiling points You can determine the substance within a range of boiling points to get bonus (e.g., +5 degrees). Please input: 357 The substance is Mercury. Please input: 3333 Substance unknown. Please input: 359 The substance is Mercury.

Rules to be followed for switch case Case doesn’t always need to have order 1, 2, 3 and so on. It can have any integer value after case keyword. Also, case doesn’t need to be in an ascending order always, you can specify them in any order as per the need of the program. Character labels can be used in switch case. Valid expressions for switch switch(1+2+23) switch(1*2+3%4) Invalid switch expressions switch(ab+cd) switch(a+b+c) Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable.

Predict the output void main() { int i=2; switch (i) { case 1: printf("Case1 "); case 2: printf("Case2 "); case 3: printf("Case3 "); case 4: printf("Case4 "); default: printf("Default "); } return 0; } 46 Department of CSE

Predict the output What will be the output of the following code fragment? int year; scanf(“%d”,&year); if(year%100==0) { if(year%400==0) printf(“leap year\n“); } else printf(“not leap year\n“); if the input given is (i)2000 (ii)1900 (iii) Department of CSE

Predict the output What will be the output of the following code fragment? int year; scanf(“%d”,&year); if(year%100==0) { if(year%400==0) printf(“leap year\n“); } else printf(“not leap year\n“); if the input given is (i)2000 (ii)1900 (iii) 19 Ans. (i)leap year (ii) No output (iii) not leap year 48 Department of CSE

Predict the output void main() { int i=2; switch (i) { case 1: printf("Case1 "); case 2: printf("Case2 "); case 3: printf("Case3 "); case 4: printf("Case4 "); default: printf("Default "); } return 0; } Output: Case2 Case3 Case4 Default Reason: No break statement.It will execute the first matching case and then all the case statements below it. 49 Department of CSE

Try it Yourself Convert the following if –else loop into switch…case. if ( grade == 'A' || grade == 'a' ) ++aCount; else if ( grade == 'B' || grade == 'b' ) ++bCount; else if ( grade == 'C' || grade == 'c' ) ++cCount; else if ( grade == 'D' || grade == 'd' ) ++dCount; else { printf( "Incorrect letter grade entered." ); printf( " Enter a new grade.\n" ); 50 Department of CSE

Summary In this lecture we have seen how to alter the flow of a program based on condition. The decisions may be two way or multi way. The C constructs used for Single way  if Two way  if else Multiway  Nested if else if else if ladder switch case 51 Department of CSE