CS 1023 Intro to Engineering Computing 3 Computer





- Slides: 5
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
Conditions n n Generally used to control what to do next? Expressions that evaluate to True or False In C Programs conditions … Important! = does not compare o Follow keyword if it assigns o Follow keyword while = = compares o Contained within ( and ) Relational Operations: >=, >, = =, != , <, <= => and =< and =! are not legal o Compare numeric expressions o n Compare characters and character strings Boolean (Logical) Operations: ! (not), && (and), | | (or) o o Only used with logical expressions, i. e. , those whose values are True or False Never used with numeric or character expressions
Selection Statements if and if-else Decision Statements n n Flow Control Statements – Making Decisions What statement(s) to perform next? Two basic instructions – if… and if…else… o o if-statement F if (condition) { statement(s) to execute if condition is true ; } if-else-statements F if (condition) { statement(s) to execute if condition is true ; } else { statement(s) to execute if condition is false ; } ; ; ; 1. { and } needed to surround multiple statements. Does no harm to use them for single statements. 2. 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.
Examples of if-statement Count Even Numbers if ((nbr % 2) == 0 ) even. Count++; total. Nbrs = total. Nbrs + 1; Count Even & Odd Numbers if ((nbr % 2) == 0 ) even. Count++; else odd. Count++; total. Nbrs = total. Nbrs + 1; Multiple Instructions in Then-part if ( (side 1 > 0) && (side 2 > 0) ) { area = side 1 * side 2; perimiter = 2*(side 1 + side 2); } else { printf(“Cannot compute area or perimeter. n”); }
Examples of if-statement Nested if-else-statements if ((s 1<s 2+s 3) && (s 2<s 1+s 3) && (s 3<s 1+s 2)) { printf(“legal trianglen”) ; if ( (s 1==s 2) && (s 2==s 3) ) { printf(“equilateral trianglen”) ; } else if (((s 1==s 2)&&(s 1!=s 3)) || (((s 1==s 3)&&(s 1!=s 2) || ((s 2==s 3)&&(s 1!=s 2))) printf(“isosceles trianglen”) ; else printf(“scalene trianglen”) ; } else printf(“not a trianglen”) ;