Download presentation
Presentation is loading. Please wait.
Published byMaud Walker Modified over 6 years ago
1
Department of Computer Science Western Michigan University
CS 1023 Intro to Engineering Computing 3: Computer Programming Conditions – Asking Questions if- and if-else-statements Mark Kerstetter Department of Computer Science Western Michigan University © Spring 2012
2
Conditions Generally used to control what to do next?
Expressions that evaluate to True or False In C Programs conditions … Follow keyword if Follow keyword while Contained within ( and ) Relational Operations: >=, >, = =, != , <, <= Compare numeric expressions Compare characters and character strings Boolean (Logical) Operations: ! (not), && (and), | | (or) Only used with logical expressions, i.e., those whose values are True or False Never used with numeric or character expressions Important! = does not compare it assigns = = compares => and =< and =! are not legal
3
Selection Statements if and if-else Decision Statements
Flow Control Statements – Making Decisions What statement(s) to perform next? Two basic instructions – if… and if…else… if-statement if (condition) { statement(s) to execute if condition is true ; } if-else-statements if (condition) { statement(s) to execute if condition is true ; } else { statement(s) to execute if condition is false ; } ; { and } needed to surround multiple statements. Does no harm to use them for single statements. Do not place semicolon after a condition. The if and if-else statements include the statements to do next! ; Caution! A common mistake when writing if and if-else statements is to place a semicolon immediately at the end of the first line of the statement thus creating an empty statement.
4
Examples of if-statement
if ((nbr % 2) == 0 ) evenCount++; totalNbrs = totalNbrs + 1; Count Even Numbers if ((nbr % 2) == 0 ) evenCount++; else oddCount++; totalNbrs = totalNbrs + 1; Count Even & Odd Numbers if ( (side1 > 0) && (side2 > 0) ) { area = side1 * side2; perimiter = 2*(side1 + side2); } else { printf(“Cannot compute area or perimeter.\n”); } Multiple Instructions in Then-part
5
Examples of if-statement
Nested if-else-statements if ((s1<s2+s3) && (s2<s1+s3) && (s3<s1+s2)) { printf(“legal triangle\n”) ; if ( (s1==s2) && (s2==s3) ) { printf(“equilateral triangle\n”) ; } else if (((s1==s2)&&(s1!=s3)) || (((s1==s3)&&(s1!=s2) || ((s2==s3)&&(s1!=s2))) printf(“isosceles triangle\n”) ; else printf(“scalene triangle\n”) ; } else printf(“not a triangle\n”) ;
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.