1 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the min of 3 numbers Forming Complex relational expressions.

Slides:



Advertisements
Similar presentations
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Advertisements

BBS514 Structured Programming (Yapısal Programlama)1 Selective Structures.
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
If Statements & Relational Operators Programming.
true (any other value but zero) false (zero) expression Statement 2
If Statements. COMP104 If / Slide 2 Three Program Structures * Sequence - executable statements which the computer processes in the given order * Choice.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Chapter 4 Making Decisions
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
12-2 Know how if and switch C statements control the sequence of execution of statements. Be able to use relational and logical operators in the conditional.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
Section 3 - Selection and Repetition Constructs. Control Structures 1. Sequence 2. Selection 3. Repetition.
1 Chapter Four Boolean Expressions and Control Statements.
Lecture 4 Introduction to Programming in C Prof. Dr. Arne Kutzner Hanyang University / Seoul Korea.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
Conditional Statement
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
Programming Fundamentals. Today’s lecture Decisions If else …… Switch Conditional Operators Logical Operators.
Principles of Programming - NI July Chapter 5: Structured Programming In this chapter you will learn about: Sequential structure Selection structure.
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.
CSEB 114: PRINCIPLE OF PROGRAMMING Chapter 5: Structured Programming.
CPS120: Introduction to Computer Science Decision Making in Programs.
Copyright © 2012 Pearson Education, Inc. Chapter 4: Making Decisions.
Flow of Control Part 1: Selection
Chapter 6: Control Structures Computer Programming Skills Second Term Department of Computer Science Foundation Year Program Umm Alqura.
Making Decisions. 4.1 Relational Operators Used to compare numbers to determine relative order Operators: > Greater than < Less than >= Greater than.
Gator Engineering Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 5 Selection Statements.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
Chapter 5: Structured Programming
1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4: Making Decisions.
Lecture 3 – Selection. Outline Recall selection control structure Types of selection One-way selection Two-way selection Multi-selection Compound statement.
Chapter 5: Structured Programming
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Lecture 4: C/C++ Control Structures Computer Programming Control Structures Lecture No. 4.
Chapter 5: Control Structures I (Selection). Objectives In this chapter you will: Learn about control structures Examine relational and logical operators.
Week 4 Program Control Structure
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,
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
CPS120: Introduction to Computer Science Decision Making in Programs.
Chapter 5: Selection Statements Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Chapter 5 Selection Statements.
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.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CC213 Programming Applications Week #2 2 Control Structures Control structures –control the flow of execution in a program or function. Three basic control.
Lecture 3.1 Operators and Expressions Structured Programming Instructor: Prof. K. T. Tsang 1.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
Selection Statements Chapter 5
Chapter 5: Structured Programming
Chapter 4: Making Decisions.
Week 3 C Program Structures (Selection Structures)
EGR 2261 Unit 4 Control Structures I: Selection
Week 3 – Selection Structures
Chapter 4: Making Decisions.
Selection Statements Chapter 5
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Week 3 – Program Control Structure
Structured Program Development in C++
PROGRAM FLOWCHART Selection Statements.
CprE 185: Intro to Problem Solving (using C)
Lecture 4: Selection Control Structure
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

1 If statement and relational operators –, >=, ==, != Finding min/max of 2 numbers Finding the min of 3 numbers Forming Complex relational expressions –Logical Operators (!, &&, ||) Cascaded if statement Conditional Operator switch statement Today’s Material

2 Generic C Program Structure #include /* main designates the starting place of our program */ main() { /* Variables hold Data Items Needed in the Program */ Variable Declarations; /* Steps of our program: I/O, computation (expressions) */ Statement1; Statement2; … StatementN; } /* end-of-the program */

3 Example C Program #include /* Convert fahrenheit to celsius */ main() { float fahrenheit, celsius; printf(“Enter a temp in fahrenheit: “); scanf(“%f”, &fahrenheit); celsius = (fahrenheit-32)/1.8; printf(“%f degrees fahrenheit equals %f degrees celsius\n”, fahrenheit, celsius); } Prompt the user and get the fahrenheit temperature to convert celsius = (fahrenheit-32)/1.8 Print the fahrenheit and celsius degrees Start End So far our programs consisted of statements all of which are executed in sequence until the end of the program is reached

4 What about programs which need to select between two alternative set of statements? –You make a comparison and execute a different set of statement depending on the outcome of the comparison –Recall our examples with “if” statements –We will consider the problem of computing min/max of 2 numbers next Programs with If Statements

5 Computing min and max of 2 numbers Prompt the user and get number1 and number2 Print min and max number1 < number2 ? min = number1 yes max = number2 min = number2 max = number1 no Start End 1.Prompt the user and get number1 and number2 2.if (number1 < number2) –2.1. min = number1; –2.2. max = number2; 3.else (i.e., number1 >= number2) –3.1. min = number2; –3.2. max = number1; 4.Print min and max

6 if-else Statement Allows a program to choose between two alternatives by testing the value of an expression Syntax: if (expression) statement1; [else statement2;] If the expression is true (1) statement1 is executed, otherwise statement2 is executed expression Y N statement 1 statement 2

7 if-else Examples int finalGrade; printf(“Please enter the final grade: “); scanf(“%d”, &finalGrade); if (finalGrade >= 45) printf("Pass \n"); int finalGrade; printf(“Please enter the final grade: “); scanf(“%d”, &finalGrade); if (finalGrade >= 45) printf("Pass!\n"); else printf("Fail!\n");

8 What if I need to execute more than one statement? int finalGrade; … if(finalGrade >= 45) { printf("Pass!\n"); printf("Congratulations!\n"); } else { printf("Fail!\n"); printf("Better luck next time.\n"); } /* end-else */ block(compoundstatement)

9 Curly Brace Location int finalGrade; … if(finalGrade >= 45){ printf("Pass!\n"); printf("Congratulations!\n"); } else { printf("Fail!\n"); printf("Better luck next time.\n"); } /* end-else */ The location of curly braces is a matter of style –To the compiler it does not matter

10 Finding the min and max of 2 ints int a, b; int min, max; printf(“Enter 2 ints: “); scanf(“%d%d”, &a, &b); if (a < b) { min = a; max = b; } else { min = b; max = a; } /* end-else */ printf(“min of %d and %d is %d\n”, a, b, min); printf(“max of %d and %d is %d\n”, a, b, max); Prompt the user and get number1 and number2 Print min and max number1 < number2 ? min = number1 yes max = number2 min = number2 max = number1 no Start End

11 Execution of the Program(1) int a, b; int min, max; printf(“Enter 2 ints: “); scanf(“%d%d”, &a, &b); if (a < b) { min = a; max = b; } else { min = b; max = a; } /* end-else */ printf(“min of %d and %d is %d\n”, a, b, min); printf(“max of %d and %d is %d\n”, a, b, max); ? a ? min DATA ? 45 ? b 56 ? max 56 Enter 2 ints: min of 45 and 56 is 45 max of 45 and 56 is

12 Execution of the Program(2) int a, b; int min, max; printf(“Enter 2 ints: “); scanf(“%d%d”, &a, &b); if (a < b) { min = a; max = b; } else { min = b; max = a; } /* end-else */ printf(“min of %d and %d is %d\n”, a, b, min); printf(“max of %d and %d is %d\n”, a, b, max); ? a ? min DATA ? ? b ? max 77 Enter 2 ints: min of 77 and 22 is 22 max of 77 and 22 is

13 Relational Expression in if Statement Expression in if statement compares two values and produces either True (1) or False (0) –Called a relational expression –Formed using relational operators greater than or equal to>= greater than> less than or equal to<= less than< not equal!= equal to== MeaningOperator C does not have an explicit boolean type –So integers are used instead. The general rules is: –“Zero is false, any non-zero value is true” expression Y N statement 1 statement 2

14 Relational Expression Examples Assume a = 1, b = 2, and c = 3 1Trueb == 2 0Falsec != 3 0False(b + c) > (a + 5) 1True(a + b) >= c 1Truea < b ValueInterpretationExpression

15 Flowchart for finding the min of 3 ints(1) Prompt the user and get number1, number2 and number3 number1 < number2 ? yes Start number1 < number3 ? number2 < number3 ? min = number2 min = number3 no min = number1 min = number2 yes no Print min End

16 Code for finding the min of 3 ints (1) int a, b, c; int min; printf(“Enter 3 ints: “); scanf(“%d%d%d”, &a, &b, &c); if (a < b){ if (a < c) min = a; else min = c; } else { if (b < c) min = b; else min = c; } /* end-else */ printf(“Min of %d, %d, %d is %d\n”, a, b, c, min); Problem: Find the minimum of 3 integers

17 Flowchart for finding the min of 3 ints(2) Prompt the user and get number1, number2 and number3 number2 < min? Start no min = number1 min = number2 yes number3 < min? no min = number3 yes Print min End

18 Code for finding the min of 3 ints (2) /* Here is a simpler alternative implementation */ int a, b, c; int min; printf(“Enter 3 ints: “); scanf(“%d%d%d”, &a, &b, &c); min = a; /* Assume that a is the minimum */ if (b < min) min = b; /* Is b smaller? */ if (c < min) min = c; /* Is c smaller? */ printf(“Min of %d, %d, %d is %d\n”, a, b, c, min); Problem: Find the minimum of 3 integers

19 The need for Logical Operators In certain cases, you may want to form more complex relational expressions –(x is equal to 5) OR (x is equal to 8) (x == 5) OR (x == 8) –(x is greater than 5) AND (x is less than 10) (x > 5) AND (x < 10) –(x is less than y) AND (y is not equal to 20) (x < y) AND (y != 20) C provides 3 logical operators to form such complex relational expressions –AND (&&), OR (||), NOT (!)

20 Logical Operators Used to combine relational expressions that are either True (1) or False (0) –Using logical operators you can form complex relational expressions and use them inside if statements && (AND) 0 (False) 1 (True) NOT! OR|| AND&& MeaningSymbol || (OR) 0 (False) 1 (True)

21 Expressions using Logical Operators(1) Suppose that a is an integer variable whose value is 7 and ch is a character variable holding the character 'q': ExpressionInterpretationValue (a >= 6) && ( ch == 'q')True1 (a >= 6) || ( ch == 'A')True1 (a >= 6) && ( ch == 'A')False0

22 Expressions using Logical Operators(2) int temp = 75; double rain = 0.35; /* probability */ printf(“warm? %d\n”, temp > 70 && temp 70 && temp < 85); printf(“nice? %d\n”, temp > 70 && rain 70 && rain < 0.4); printf(“hot/cold? %d\n”, temp 85); printf(“cloudy? %d\n”, rain > 0.3 && rain 0.3 && rain < 0.7); warm? 1 nice? 1 hot/cold? 0 cloudy? 1

23 /* If a equals 4 OR a equals 10 */ if (a == 4 || a == 10){... } else {... } /* end-else */ /* x is in between 2 AND 20 */ if (x >= 2 && x <= 20){... } /* end-if */ /* y is greater than 20 AND x is NOT equal to 30 */ if (y > 20 && x != 30){... } /* end-if */ Expressions using Logical Operators(3)

24 Associativity & Precedence Rules left >, >=, <, <=4 left+, -3 left*, /, %2 right-, ++, --1 AssociativityOperatorPrecedence ==, != &&, || =, +=, -=,.. left right Here is the associativity and precedence rules for all operators provided by C Again, the best thing to do is to parenthesize the expression to avoid ambiguity

25 Cascaded If Statements We often need to test a series of conditions stopping as soon as one of them is true –E.g. We want to test whether “n” is equal to 0, less than 0 or greater than 0 if (n < 0) printf(“n < 0\n”); else { if (n == 0) printf(“n == 0\n”); else printf(“n > 0\n”); } /* end-else */ Instead of nesting the second if statement inside the else, we often write it as follows, called the cascaded if if (n < 0) printf(“n < 0\n”); else if (n == 0) printf(“n == 0\n”); else printf(“n > 0\n”);

26 Cascaded if Syntax if (expression1) statement1; [else if (expression2) statement2; else if (expression3) statement3; … else statementN;]

27 Cascaded if Example int finalGrade; … if (finalGrade >= 90) printf(“Passed: Your grade is A \n”); else if (finalGrade >= 85) printf(“Passed: Your grade is A- \n”); else if (finalGrade >= 80) printf(“Passed: Your grade is B+ \n”); else if (finalGrade >= 75) printf(“Passed: Your grade is B \n”); else if (finalGrade >= 70) printf(“Passed: Your grade is B- \n”); else if (finalGrade >= 55) printf(“Passed: Your grade is C \n”); else printf(“Failed \n”);

28 Conditional Operator You will encounter statements of the following sort in many place in your code: if (expression) statement1; else statement2; There is a shorter way to write such statements using the tertiary conditional operator –condition ? expr1 : expr2 Examples: a = (b >= 0) ? b : -b; a gets the absolute value of b min = (a < b) ? a : b; min gets the minimum of a & b

29 switch Statement Often we need to compare an expression against a series of values to see which one matches –We can implement such code using cascaded if as follows if (grade == 5) printf(“Excellent\n”); else if (grade == 4) printf(“Good\n”); else if (grade == 3) printf(“Pass\n”); else if (grade == 2) printf(“Poor\n”); else if (grade == 1) printf(“Fail\n”); else printf(“Illegal grade\n”); As an alternative to this kind of cascaded if, C provides the “switch” statement

30 switch Statement Example Here is the re-implementation of the previous cascaded if statements using the switch statement switch(grade){ case 5: printf(“Excellent\n”); break; case 4: printf(“Good); break; case 3: printf(“Pass\n”); break; case 2: printf(“Poor\n”); break; case 1: printf(“Fail\n”); break; default: printf(“Illegal grade\n”); break; } /* end-switch */

31 switch Statement Syntax Selects a sequence of one or more instructions based on the result of comparing the value of an expression to a specific value switch(expression) { case value1: statement1; … [break;] case value2: statement2; … [break;] default: statementN; … [break;] } /* end-switch */

32 Another switch Example int main(){ char operator; int a, b; printf(“Enter an expression: “); scanf(“%d%c%d”, &a, &operator, &c); switch(operator) { case ‘+’: printf(“%d+%d = %d\n”, a, b, a+b); break; case ‘-’: printf(“%d-%d = %d\n”, a, b, a-b); break; case ‘*’: printf(“%d*%d = %d\n”, a, b, a*b); break; case ‘/’: if(value == 0) { printf(“Error: Divide by zero \n”); printf(“ Operation ignored \n”); } else printf(“%d/%d = %d\n”, a, b, a/b); break; default: printf(“Unknown operator \n”); break; } /* end-switch */ return 0; } /* end-main */

33 The role of break inside switch Notice that “break” takes us out of the switch statement If break is omitted after a case, the control continues with the first statement of the next case switch(grade){ case 5: printf(“Excellent\n”); case 4: printf(“Good); case 3: printf(“Pass\n”); case 2: printf(“Poor\n”); case 1: printf(“Fail\n”); default: printf(“Illegal grade\n”); } /* end-switch */ If grade == 3, this will print –Pass Poor Fail Illegal grade

34 The role of break inside switch Falling through the case may be what is really intended in your code. –If that’s the case, put a comment for your own benefit Example: switch(grade){ case 5: case 4: case 3: case 2: num_passing++; /* Fall through */ case 1: num_total++; break; } /* end-switch */