Download presentation
Presentation is loading. Please wait.
1
Relational, Logical, and Equality Operators
Think of these as returning true/false (logical) values, represented by integer values 0 (false) and 1 (true) Relational operators: >, <=, <, <= Equalify operators: ==, != These binary operators can be applied to built-in data types such as int, float, etc. (will discuss strings in future) Examples: (3 != 4) evaluates to 0. Hence, printf( “%d”, (3 != 4)); (in a program) would print out 0. IMPORTANT! == (two equals) vs. = (one equal) common source of programmer errors in C. Logical operators: &&, ||, !
2
Example: Logical Operators
#include <stdio.h> void main() { int i, j; for( i = 0; i < 2; i++ ) for( j = 0; j < 2; j++ ) printf( “%d AND %d = %d, %d OR %d = %d\n”, i, j, i && j, i, j, i || j ); }
3
If-else Syntax: if( expression ) statement1 [else statement2]
Recall that statements are either single commands terminated by semicolons, or blocks of commands delimited by braces {}. if( expression ) same as if( expression != 0 ) Q: What’s better, if( expression ) … else … Or if( !expression) … else … if(( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 ) printf( “%d is a leap year\n”, year );
4
If-else-if-else… Syntax: if( expression ) statement1
else if( expression2 ) statement2 else if( expression3 ) statement3 … else statement Temptation: Continually indent. What’s the equivalent series of if statements (no elses)? Beware “dangling else problem” – if if else
5
Example: If-else #include <stdio.h> void main() {
int low, high, i; scanf( “%d”, &low ); scanf( “%d”, &high ); for( i = low; i <= high; i++ ) if( i % 3 == 0 ) printf( “%d is divisible by 3\n”, i ); else if( i % 2 == 0 ) printf( “%d is divisible by 2, but not 3\n”, i ); }
6
Switch & Case / for, while
Syntax: switch( int-valued-exp ) { case const-expr: statements [break;] … default: } For( exp1; exp2; exp3 ) { statement(s) } Equivalent to: exp1; While( exp2 ) exp3 Can include break; How to go other way? do { statement(s) } while( exp );
7
Switch example switch( month ) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: printf( “31 days.\n” ); break; case 2: printf( “28 days.\n” ); default; printf( “30 days.\n” ); }
8
Finding maximum values
#include <stdio.h> void main() { int num, max = -1, i, user_input; printf( “How many positive ints you gonna enter?” ); scanf( “%d”, &num ); for( i = 0; i < num; i++ ) scanf( “%d”, &user_input ); if( user_input > max ) max = user_input; } printf( “Your maximum value was: %d\n”, max );
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.