If statement The "if statement" is used to break the sequential flow of execution. Enforces branching in execution according to the result of an expression.

Slides:



Advertisements
Similar presentations
CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
Advertisements

1 Conditional Statement. 2 Conditional Statements Allow different sets of instructions to be executed depending on truth or falsity of a logical condition.
Selection Statements Selects statements to execute based on the value of an expression The expression is sometimes called the controlling expression Selection.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 4: Control Structures I (Selection)
Introduction to Java Programming, 4E Y. Daniel Liang.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 3 Selections.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Lecture 03 if-?-switch. loops METU Dept. of Computer Eng. Summer 2002 Ceng230 - Section 01 Introduction To C Programming by Ahmet Sacan Mon July 7, 2002.
Logical Operators and Conditional statements
Chapter 4 Making Decisions
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 4 Making.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Control Statements.
Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End.
1 Lecture 5  More flow control structures  for  do  continue  break  switch  Structured programming  Common programming errors and tips  Readings:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Selection Statements Primitive Type boolean.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
Algorithms and Computing Lecture 3 Control Statements By Dr. M. Tahir Khaleeq.
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Chapter 4 Program Control Statements
Spring 2005, Gülcihan Özdemir Dağ Lecture 3, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 3 Outline 3.1 Introduction.
Conditional Statement
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
CP104 Introduction to Programming Selection Structures_3 Lecture 11 __ 1 The Switch Statement The switch statement provides another means to select one.
Lecture 5 Selection Control Structures Selection Control Structures Dr. Hebbat Allah A. Elwishy Computer & IS Assistant Professor
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
Chapter 3 Selections Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Introduction to Control Statements JavaScript – Part 3 George Mason University June 3, 2010.
Decision making statements. Decision making statements are used to skip or to execute a group of statements based on the result of some condition. The.
Programming C for Engineers An exercise is posted on the web site! Due in one week Single submission.
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.
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
Chapter Making Decisions 4. Relational Operators 4.1.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 4 Making Decisions.
Message: "You are mature"
Control of flow We learned that default flow of instructions is sequential. Then, we learned how to control the flow using "if" and "switch." Now, we will.
Programming Fundamentals1 Chapter 4 SELECTION STRUCTURES.
1 Agenda If Statement True/False Logical Operators Nested If / Switch Exercises & Misc.
EGR 115 Introduction to Computing for Engineers Branching & Program Design – Part 3 Friday 03 Oct 2014 EGR 115 Introduction to Computing for Engineers.
Chapter 7 Conditional Statements. 7.1 Conditional Expressions Conditions - compare the values of variables, constants and literals using one or more relational.
1 Lecture03: Control Flow 9/24/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
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.
 Real numbers representation - Floating Point Notation  First C Program  Variables Declaration  Data Types in C ◦ char, short, int, long, float, double,
BY ILTAF MEHDI(MCS,MCSE, CCNA) 1. INSTRUCTOR: ILTAF MEHDI (MCS, MCSE, CCNA, Web Developer) BY ILTAF MEHDI(MCS,MCSE, CCNA) 2 Programming Fundamentals Chapter.
The if…else Selection Statement
Selections Java.
EKT150 INTRODUCTION TO COMPUTER PROGRAMMING
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Chapter 4 (Conditional Statements)
Flow of Control.
Chapter 3 Branching Statements
Condition Statements.
Chapter 3 Control Statements Lecturer: Mrs Rohani Hassan
Chapter 3 Selections Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Decision Making.
C Programming Variables.
CSC215 Lecture Flow Control.
CSC215 Lecture Control Flow.
Chapter 7 Conditional Statements
Topics 4.1 Relational Operators 4.2 The if Statement
CSC215 Lecture Control Flow.
Chapter 13 Control Structures
Presentation transcript:

If and Switch statements

If statement The "if statement" is used to break the sequential flow of execution. Enforces branching in execution according to the result of an expression. There are two possible paths to take. The expression determines which path should be taken. Read age Rest of the program Message: "You are young" Message: "You are mature" age<=25 ? T F CMPE 150 – Introduction to Computing

If statement Syntax: where stat_block is one of the following: if (int_expr) stat_block1 else stat_block2 where stat_block is one of the following: a single statement stat; the null statement ; a group of statements enclosed in braces { stat1; ... statn; } Text in green is optional CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing If statement stat0; if (expr) { stat1; stat2; } else stat3; stat4; Notice the indentation. stat0 expr ? T F stat1 stat2 stat3 stat4 CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing If statement stat0; if (expr) { stat1; stat2; } stat4; stat0 expr ? T F stat1 stat2 stat4 CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing If statement Read a number and state whether it is odd or even. int num; scanf("%d", &num); printf("%d is an ", num); if (num%2!=0) printf("odd "); else printf("even "); printf("number.\n"); CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing If statement Read one character as input; check if it is a digit; if so, convert it to an integer and display the number that is two times the input number; o/w display an error message. char ch; int num; scanf("%c", &ch); if ((‘0’<=ch) && (ch<=‘9’)) { num=ch-’0’; printf("Two times the input is %d \n", 2*num); } else printf("Input is not a digit! \n"); CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Nested-if statements Remember the syntax: if (int_expr) stat_block1 else stat_block2 Statement block contains statements. "if" is also a statement. So, you can "nest" one if statement in another. This structure is called nested-if statements. You can nest as much as you want. CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Nested-if statements stat0; if (expr1) if (expr2) { stat1; stat2; } else if (expr3) { stat4; stat5; stat6; stat7; stat8; stat0 expr1 ? T F stat1 stat2 stat8 stat4 stat5 expr2 ? expr3 ? stat6 stat7 CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Nested-if statements stat0; if (expr1) if (expr2) { stat1; stat2; } else if (expr3) { stat4; stat5; stat6; stat7; stat8; stat0 expr1 ? T F stat1 stat2 stat8 stat4 stat5 expr2 ? expr3 ? stat7 IF INDENTATION IS NOT CORRECT, IT IS MISLEADING CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Nested-if statements Remember that the "else" part is optional. Thus, some of the if statements may not have an "else" part. Then, it is a little bit tricky to find to which "if" the "else" belongs. Note that indentation is completely ignored by the compiler, so it does not help. The trick is the following: "else" belongs to the nearest incomplete "if" CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Else-if statements if (age<=1) printf("infant"); if (age<=3) printf("toddler"); if (age<=10) printf("child"); if (age<=18) printf("adolescent"); if (age<=25) printf("young"); if (age<=39) printf("adult"); if (age<=65) printf("middle-aged"); else printf("elderly"); CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Else-if statements Else-if is a variation of nested-if. An inner if statement is executed iff all previous if statements have failed. Thus, executing an inner if statement implies that all previous expressions were false. Syntax: if (int_expr1) stat_block1 else if (int_expr2) stat_block2 ... else stat_blockn CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Else-if statements if (age<=1) printf("infant"); else if (age<=3) printf("toddler"); else if (age<=10) printf("child"); else if (age<=18) printf("adolescent"); else if (age<=25) printf("young"); else if (age<=39) printf("adult"); else if (age<=65) printf("middle-aged"); else printf("elderly"); CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Else-if statements Alternative would be: if (age<=1) printf("infant"); if ((1<age) && (age<=3)) printf("toddler"); if ((3<age) && (age<=10)) printf("child"); if ((10<age) && (age<=18)) printf("adolescent"); if ((18<age) && (age<=25)) printf("young"); if ((25<age) && (age<=39)) printf("adult"); if ((39<age) && (age<=65)) printf("middle-aged"); if (65<age) printf("elderly"); CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Ternary operator Ternary operator is similar to the "if" statement. But it is an operator, not a statement. Syntax: int_expr ? value1 : value2 Eg: a = (b>c) ? b : c; k = (n!=0) ? m/n : 0; CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Ternary operator Note that it is not possible to know at compile time whether value1 or value2 will be used. Therefore, the type of the expression is the type of the larger value. Eg: In the expression below, if the value of b is 9 a = b / (b%2)?2:3.0; the value of a is 4.5 (not 4), because we perform a float division (not integer division) CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 1 Write a code segment that detects whether a number is divisible by 6. if ((num%2==0) && (num%3==0)) printf("%d is divisible by 6 \n",num); CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 2 Write a code segment that detects whether a number is divisible by 3 or 6. if (num%3==0) if (num%2==0) printf("%d is divisible by 6 \n",num); else printf("%d is divisible by 3 \n",num); CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 3 Write a program that reads two real numbers and checks if they are equal. (Assume first number is smaller.) #include <stdio.h> #define EPSILON 0.000000001 float r1, r2; int main() { scanf("%f %f", &r1, &r2); if ((r2-r1)<=EPSILON) printf("The numbers are (almost) equivalent"); return 0; } CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 4 Write a program that reads a 3-digit number from the input char-by-char, and displays its square. #include <stdio.h> char c1, c2, c3; int num; int main() { scanf("%c%c%c",&c1,&c2,&c3); num = (c1-'0')*100; num += (c2-'0')*10; num += c3-'0'; num *= num; printf("%d", num); return 0; } CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Switch statement If you have multiple cases depending on different values of the same integer expression, switch is easier to use. Syntax: switch (int_expr) { case constant_int_value1: stat(s); case constant_int_value2: stat(s); ... default: stat(s); } You may have zero or more statements in each case. CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Break statement Switch statement actually gathers many statements of several cases. The case labels denote the specific statement from which the execution of this group of statements begins. All statements till the end of the group are executed sequentially. To separate the cases, break statement is used. break breaks the sequential execution of the statements and immediately jumps to the end of the switch statement. CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Break statement stat0; switch (expr) { case value1: stat1; stat2; case value2: stat3; stat4; stat5; case value3: stat6; break; case value4: stat7; stat8; } stat9; stat0 stat1 stat2 stat3 stat4 stat5 stat6 stat7 stat8 stat9 If expr happens to be value2 CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 6 Write a program that reads a character ('a', 'p', or 'v') and radius R. It displays the area or perimeter of a circle with radius R, or the volume of a sphere. #include <stdio.h> #define PI 3.14 char ch; float R; int main() { scanf("%c%f",&ch,&R); switch(ch) case 'a': printf("Area of circle = %f\n", PI*R*R); break; case 'p': printf("Perimeter of circle = %f\n", 2*PI*R); case 'v': printf("Volume of sphere = %f\n", (4/3)*(PI*R*R*R)); default: printf("Invalid input\n"); } return 0; 3.141592654 (4.0/3) CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Switch statement Define the days of the week as an enumerated type and display them as strings. enum day_type {MON=1,TUE,WED,THU,FRI,SAT,SUN} day; scanf("%d", &day); switch (day) { case SUN: printf("Sunday\n"); break; case WED: printf("Wednesday\n"); break; case TUE: printf("Tuesday\n"); break; case THU: printf("Thursday\n"); break; case FRI: printf("Friday\n"); break; case SAT: printf("Saturday\n"); break; case MON: printf("Monday\n"); break; default: printf("Incorrect day\n"); break; } CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Switch statement Note that without the "break" statement, execution traverses all cases until the end of the switch statement. This allows implementation of OR (if you use it properly. Eg: switch (number) { case 1: case 3: case 5: printf("Odd number \n"); break; case 0: case 2: case 4: printf("Even number \n"); break; } CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Switch statement As long as the cases are separated with "break"s, their order is not relevant. "default" is optional. If the default case is not specified and none of the cases holds, no statement is executed; this is not an error. It is a good practice to put a break even after the last case. CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 5.1 Write a program that defines a type for letter grades (AA,BB,CC,DD,F as 4,3,2,1,0), reads a grade and displays corresponding letter grade. #include <stdio.h> enum grade_type {F,DD,CC,BB,AA}; int main() { enum grade_type g; scanf("%d", &g); printf("%d", g); return 0; } CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 5.2 But, we don't want to display a number. We want to see the letter grade. #include <stdio.h> enum grade_type {F,DD,CC,BB,AA}; int main() { enum grade_type g; scanf("%d", &g); switch (g) case AA: printf("AA \n"); break; case BB: printf("BB \n"); break; case CC: printf("CC \n"); break; case DD: printf("DD \n"); break; case F: printf("F \n"); break; default: printf("Invalid \n"); break; } return 0; CMPE 150 – Introduction to Computing

CMPE 150 – Introduction to Computing Example 5.3 Could we do it without defining an enumerated type? #include <stdio.h> int main() { int g; scanf("%d", &g); switch (g) case 4: printf("AA \n"); break; case 3: printf("BB \n"); break; case 2: printf("CC \n"); break; case 1: printf("DD \n"); break; case 0: printf("F \n"); break; default: printf("Invalid \n"); break; } return 0; CMPE 150 – Introduction to Computing