Download presentation
Presentation is loading. Please wait.
1
16.216 ECE Application Programming
Instructor: Dr. Michael Geiger Summer 2012 Lecture 4 Conditional statements: if and switch Exam 1 Preview
2
ECE Application Programming: Lecture 4
Lecture outline Announcements/reminders Program 2 graded; regrades due Monday, 7/23 Program 3 due Friday, 7/20 Program 4 due Thursday, 7/26 Exam 1 next Tuesday, 7/24 Allowed one 8.5” x 11” sheet of notes No electronic devices Review Operators Output formatting Today’s lecture Conditional statements Exam 1 Preview Note: will not go through PE2 (conditionals/formatting), but will post last semester’s slides/code on web 5/6/2018 ECE Application Programming: Lecture 4
3
ECE Application Programming: Lecture 4
Review: C operators Operator Associativity Innermost ( ) Left to right Unary -, unary ~ Right to left * / % << >> NOTE: shift amt < 32 & ^ | 5/6/2018 ECE Application Programming: Lecture 4
4
ECE Application Programming: Lecture 4
Review: field width Format specifier for printf() takes form: %[flags][width][.precision] Field width: minimum # chars to be printed Never truncates—if more chars than width, prints all Default behavior—right justify value, print spaces printf(“%10d”, n); (8 spaces, then number 12) Flags allow you to add sign (+), left justify (-), and add leading zeroes (0) printf(“%+-10d”, n); +12_______ (Number 12 with sign, then 7 spaces) printf(“%010d”, n); To use a variable to specify field width, use * as the width printf(“%*d”, n, n); (Field width = 12 10 spaces, then the number 12) 5/6/2018 ECE Application Programming: Lecture 4
5
ECE Application Programming: Lecture 4
Review: precision Format specifier for printf() takes form: %[flags][width][.precision] Specifying precision: # chars after decimal point for FP (%f, %lf) Rounds last digit printf(“%.1lf”, x); 3.8 printf(“%.0lf”, x); 4 Minimum # chars for integer (%d, %i, %u, %x) Does not truncate; will pad with leading 0s printf(“%.3d”, n); 012 Max # chars for string (%s) printf(“%.5s”, “one two”); one t No effect for char (%c) As with field width, can use * to specify that field width is a variable 5/6/2018 ECE Application Programming: Lecture 4
6
Formatted output: hexadecimal
To print a number in hex, use %x or %X %x prints characters a-f in lowercase %X prints characters A-F in uppercase To show leading 0x, use the # flag To show leading 0s, use precision with total # chars Field width + 0 flag also works unless value = 0 Examples (assume var1 = 0x1A2B) printf(“%x”, var1) 1a2b printf(“%X”, var1) 1A2B printf(“%#x”, var1) 0x1a2b printf(“%.6x”, var1) 001a2b printf(“%#.6x”, var1) 0x1a2b 5/6/2018 ECE Application Programming: Lecture 4
7
ECE Application Programming: Lecture 4
Decisions Recall that flowcharts can include decisions Conditionally execute some path May want to: Only perform operation if condition is true: A = 0? TRUE FALSE A = 0? TRUE X = x + 1 FALSE 5/6/2018 ECE Application Programming: Lecture 4
8
ECE Application Programming: Lecture 4
Decisions (cont.) May want to: Perform one operation if condition is true, another if false: A = 0? TRUE X = x + 1 FALSE X = x - 1 5/6/2018 ECE Application Programming: Lecture 4
9
ECE Application Programming: Lecture 4
Decisions (cont.) May want to: Check multiple conditions, in order A = 0? TRUE X = x + 1 FALSE B=1? TRUE X = x - 1 FALSE X = 0 5/6/2018 ECE Application Programming: Lecture 4
10
ECE Application Programming: Lecture 4
if statements Frequently want to conditionally execute code Range checking Error checking Different decisions based on input, or result of operation Basic conditional execution: if statement Form: if (<expression>) <statement> [ else brackets show <statement> ] else is optional 5/6/2018 ECE Application Programming: Lecture 4
11
ECE Application Programming: Lecture 4
if statements (cont.) <expression> can be any valid expression Considered “false” if 0, “true” if nonzero Can use comparisons: Greater than/less than: > < e.g. if (a < b) Greater than or equal/less than or equal: >= <= e.g. if (x <= 20) Equal/not equal: == != e.g. if (var == 10) 5/6/2018 ECE Application Programming: Lecture 4
12
ECE Application Programming: Lecture 4
if statements (cont.) <expression> can be any valid expression Can combine multiple conditions using Logical AND: && Logical OR: || e.g. if ((x < 3) && (y > 5)) Always put each condition in parentheses Can test inverse of condition using logical NOT: ! e.g. if (!(x < 3)) equivalent to if (x >= 3) These operators: not bitwise operators! A & B is a bitwise operation A && B has only 2 possible results: 0 or “non-zero” 5/6/2018 ECE Application Programming: Lecture 4
13
ECE Application Programming: Lecture 4
if statements (cont.) <statement> can be one or more lines If just one line, no additional formatting needed if (x < 3) printf(“x = %d\n”, x); If multiple lines, statement is block enclosed by { } { x = x + 3; } else part is optional—covers cases if condition is not true 5/6/2018 ECE Application Programming: Lecture 4
14
ECE Application Programming: Lecture 4
if if (a > b) big = a; else big = b; if (a+6*3-43) printf("wow is this not cool"); else printf("this is not cool"); 5/6/2018 ECE Application Programming: Lecture 4
15
ECE Application Programming: Lecture 4
if (common pitfalls) a single equals means ASSIGN. a double equal must be used to check for equality. x=12345; if (x=3) { printf("x is 3\n"); } else { printf("x is not 3\n"); } This code will ALWAYS print: x is 3 5/6/2018 ECE Application Programming: Lecture 4
16
ECE Application Programming: Lecture 4
if (example) void main(void) { float a,b,c,disc; : scanf("%f %f %f",&a,&b,&c); if (a==0) { // statements } else { disc = b*b-4*a*c; if ( disc < 0 ) { // statements } else { // statements } } } 5/6/2018 ECE Application Programming: Lecture 4
17
Example: if statements
What does the following code print? int main() { int x = 3; int y = 7; if (x > 2) x = x - 2; else x = x + 2; if ((y % 2) == 1) { y = -x; if ((x != 0) && (y != -1)) y = 0; } printf("x = %d, y = %d\n", x, y); return 0; 5/6/2018 ECE Application Programming: Lecture 4
18
ECE Application Programming: Lecture 4
Example solution int main() { int x = 3; int y = 7; if (x > 2) Condition is true, since 3 > 2 x = x - 2; x set to 1 else x = x + 2; if ((y % 2) == 1) Tests if y is an odd number--true condition { y = -x; y set to -1 if ((x != 0) && (y != -1)) First part of condition is true, second part is false--overall false y = 0; } printf("x = %d, y = %d\n", x, y); Prints: x = 1, y = -1 return 0; 5/6/2018 ECE Application Programming: Lecture 4
19
if (range checking - take 1)
int n; printf("Enter a number 1 to 10: "); scanf("%d",&n); if (n > 10) { printf(“That’s not in range!"); } else if (n < 1) { printf(“That’s not in range!"); } else { printf("Good job!"); } 5/6/2018 ECE Application Programming: Lecture 4
20
if (range checking - take 2)
If there is only one statement needed for the true and/or false condition, the {} are not needed int n; printf("Enter a number 1 to 10: "); scanf("%d",&n); if (n > 10) printf(“That’s not in range!"); else if (n < 1) printf(“That’s not in range!"); else printf("Good job!"); 5/6/2018 ECE Application Programming: Lecture 4
21
if (range checking - take 3)
Use the && or || as needed to check for multiple conditions int n; printf("Enter a number 1 to 10: "); scanf("%d",&n); Note these ( ) are needed if ( (n > 10) || (n < 1) ) printf(“That’s not in range!"); else printf("Good job!"); 5/6/2018 ECE Application Programming: Lecture 4
22
if (range checking - take 4)
Use the && or || as needed to check for multiple conditions int n; printf("Enter a number 1 to 10: "); scanf("%d",&n); Note these ( ) are needed if ( (1 <= n) && (n <= 10) ) printf(“Good job!"); else printf(“That’s not in range!"); 5/6/2018 ECE Application Programming: Lecture 4
23
if (range checking) (The WRONG WAY)
int n; printf("Enter a number 1 to 10: "); scanf("%d",&n); if (1 <= n <= 10 ) // THIS WILL NOT COMPILE printf("Good job!"); else printf(“That’s not in range!"); 5/6/2018 ECE Application Programming: Lecture 4
24
Example: if statements
Write a short code sequence to do each of the following: Given int x, check its value If x is greater than 5 and less than or equal to 10, print x Prompt for and read temperature as input (type double) If temp is 90 or higher, print “It’s too hot!” If temp is 32 or lower, print “It’s freezing!” In all other cases, print “It’s okay” Read 3 int values and print error if input problem Values are separated by a comma If fewer than 3 values read, print error message with number of values Example: Error: only 2 inputs read correctly 5/6/2018 ECE Application Programming: Lecture 4
25
ECE Application Programming: Lecture 4
Example solution Given int x, check its value If x is greater than 5 and less than or equal to 10, print x if ((x > 5) && (x <= 10)) printf(“%d\n”, x); 5/6/2018 ECE Application Programming: Lecture 4
26
Example solution (cont.)
Prompt for and read temperature as input (type double) If temp is 90 or higher, print “It’s too hot!” If temp is 32 or lower, print “It’s freezing!” In all other cases, print “It’s okay” int main() { double temp; printf(“Enter temperature: “); scanf(“%lf”, &temp); if (temp >= 90) printf(“It’s too hot!\n”); else if (temp <= 32) printf(“It’s too cold!\n”); else printf(“It’s okay\n”); return 0; } 5/6/2018 ECE Application Programming: Lecture 4
27
Example solution (cont.)
Read 3 int values and print error if input problem Values are separated by a comma If fewer than 3 values read, print error message with number of values Example: Error: only 2 inputs read correctly int main() { int x, y, z; // Input values int num; // # values read num = scanf(“%d,%d,%d”, &x, &y, &z); if (num < 3) printf(“Error: only %d inputs read correctly”, num); return 0; } 5/6/2018 ECE Application Programming: Lecture 4
28
ECE Application Programming: Lecture 4
switch statements Nesting several if/else if statements can get tedious If each condition is simply checking equality of same variable or expression, can use switch 5/6/2018 ECE Application Programming: Lecture 4
29
switch/case statement - General form
switch ( <expression> ) { case <value1> : <statements> [ break; ] case <value2> : <statements> [ break; ] . . [ default: <statements> [ break; ] ] } 5/6/2018 ECE Application Programming: Lecture 4
30
switch/case statement
Check if <expression> matches any value in case statements If <expression> == <value1>, execute <statements> in that case If <expression> == <value2>, execute <statements> in that case If <expression> does not equal any of the values, go to default case (if present) 5/6/2018 ECE Application Programming: Lecture 4
31
Switch statements and break
Each case is just a starting point—switch does not automatically skip other cases! Example: switch (x) { case 0: x = 3; case 1: x = x * 4; default: x = x – 1; } If x == 0: Start at case 0 x = 3; Then, go to case 1 x = x * 4 = 3 * 4 = 12 Then, go to default: x = x – 1 = 12 – 1 = 11 5/6/2018 ECE Application Programming: Lecture 4
32
Switch statements and break
Use break to exit at end of case You may not always want to use break—will see examples later Rewriting previous example: switch (x) { case 0: x = 3; break; case 1: x = x * 4; default: x = x – 1; } 5/6/2018 ECE Application Programming: Lecture 4
33
switch/case statement - example
#include <stdio.h> int main() { char grd; printf("Enter Letter Grade: "); scanf("%c",&grd); printf(“You are "); // continued next slide 5/6/2018 ECE Application Programming: Lecture 4
34
switch/case statement - example
switch (grd) { case 'A' : printf("excellent"); break; case 'B' : printf("good"); break; case 'C' : printf("average"); break; case 'D' : printf("poor"); break; case 'F' : printf("failing"); break; default : printf(“incapable of reading directions"); break; } return 0; } 5/6/2018 ECE Application Programming: Lecture 4
35
Example: switch statement
What does the program on the previous slides print if the user enters: A B+ c X Recognize, of course, that it always prints: Enter Letter Grade: 5/6/2018 ECE Application Programming: Lecture 4
36
ECE Application Programming: Lecture 4
Example solution What does the program on the previous slides print if the user enters: A You are excellent B+ Only first character is read—’B’ You are good c This program is case-sensitive—’C’ and ‘c’ are two different characters! Will go to default case You are incapable of reading directions X No case for ‘X’—goes to default case 5/6/2018 ECE Application Programming: Lecture 4
37
switch/case statement - Alt example
switch (grd) { case 'A' : case 'a': case 'B' : case 'b': printf("doing very well"); break; case 'C' : case 'c': case 'D' : case 'd': printf("not doing too well"); break; case 'F' : case ‘f': printf("failing"); break; default : printf("incapable of reading directions"); break; } return 0; } 5/6/2018 ECE Application Programming: Lecture 4
38
ECE Application Programming: Lecture 4
Exam 1 notes Allowed one 8.5” x 11” double-sided sheet of notes No other notes No electronic devices (calculator, phone, etc.) Exam will last 50 minutes Covers all lectures through today You will not be tested on design process, IDEs Material starts with basic C program structure 5/6/2018 ECE Application Programming: Lecture 4
39
Review: Basic C program structure
Preprocessor directives #include: typically used to specify library files #define: generally used to define macros We’ll use to define constants Main program Starts with: int main() Enclosed in block: specified by { } Ends with return 0; Indicates successful completion Basic output Call printf(<string>); <string> can be replaced by characters enclosed in double quotes May include escape sequence, e.g. \n (new line) 5/6/2018 ECE Application Programming: Lecture 4
40
Review: Data types, variables, constants
Four basic data types int, float, double, char Constants Discussed viable ranges for all types #define to give symbolic name to constant Variables Have name, type, value, memory location Variable declarations: examples int x; float a, b; double m = 2.35; 5/6/2018 ECE Application Programming: Lecture 4
41
ECE Application Programming: Lecture 4
Review: C operators Operator Associativity Innermost ( ) Left to right Unary -, unary ~ Right to left * / % << >> & ^ | 5/6/2018 ECE Application Programming: Lecture 4
42
Review: Operators and statements
Operators can be used either with constants or variables More complex statements are allowed e.g. x = ; Parentheses help you prioritize parts of statement Makes difference with order of operations x = * 3 is different than x = (1 + 2) * 3 5/6/2018 ECE Application Programming: Lecture 4
43
Review: bit manipulation
Bitwise operators: | & ^ ~ Used for desired logical operations Used to set/clear bits Bit shifts: << >> Used to shift bits into position Used for multiplication/division by powers of 2 Common operations Setting/clearing/flipping individual bit Setting/clearing/flipping multiple bits 5/6/2018 ECE Application Programming: Lecture 4
44
Review: printf() and scanf() basics
To print variables (or constants), insert %<type> in your printf() format string %c: single character %d or %i: signed decimal integer %u: unsigned decimal integer %x or %X: unsigned hexadecimal integer %f: float %lf: double %s: string Each %<type> must correspond to a variable or constant that follows printf("a=%f, b=%f",a,b); To read input, use same format specifiers in scanf() format string, followed by addresses of variables scanf("%d %f",&hours,&rate); 5/6/2018 ECE Application Programming: Lecture 4
45
ECE Application Programming: Lecture 4
Review: field width Format specifier for printf() takes form: %[flags][width][.precision] Field width: minimum # chars to be printed Never truncates—if more chars than width, prints all Default behavior—right justify value, print spaces printf(“%10d”, n); (8 spaces, then number 12) Flags allow you to add sign (+), left justify (-), and add leading zeroes (0) printf(“%+-10d”, n); +12_______ (Number 12 with sign, then 7 spaces) printf(“%010d”, n); To use a variable to specify field width, use * as the width printf(“%*d”, n, n); (Field width = 12 10 spaces, then the number 12) 5/6/2018 ECE Application Programming: Lecture 4
46
ECE Application Programming: Lecture 4
Review: precision Format specifier for printf() takes form: %[flags][width][.precision] Specifying precision: # chars after decimal point for FP (%f, %lf) Rounds last digit printf(“%.1lf”, x); 3.8 printf(“%.0lf”, x); 4 Minimum # chars for integer (%d, %i, %u, %x) Does not truncate; will pad with leading 0s printf(“%.3d”, n); 012 Max # chars for string (%s) printf(“%.5s”, “one two”); one t No effect for char (%c) As with field width, can use * to specify that field width is a variable 5/6/2018 ECE Application Programming: Lecture 4
47
Review: hexadecimal output
To print a number in hex, use %x or %X %x prints characters a-f in lowercase %X prints characters A-F in uppercase To show leading 0x, use the # flag To show leading 0s, use precision with total # chars Field width + 0 flag also works unless value = 0 Examples (assume var1 = 0x1A2B) printf(“%x”, var1) 1a2b printf(“%X”, var1) 1A2B printf(“%#x”, var1) 0x1a2b printf(“%.6x”, var1) 001a2b printf(“%#.6x”, var1) 0x001a2b 5/6/2018 ECE Application Programming: Lecture 4
48
ECE Application Programming: Lecture 4
Review: if statements Conditional execution using if statements: Form: if (<expression>) <statement> [ else brackets show <statement> ] else is optional Expression frequently uses relational operators to test equality/inequality < > <= >= == != e.g., if (x <= 5) Can combine conditions using logical operators AND : && OR: || e.g., if ((x <= 5) && (x > 0)) Can test if condition is false using logical NOT: ! e.g., if (!(x < 5)) 5/6/2018 ECE Application Programming: Lecture 4
49
Review: switch statements
When checking multiple exact values for expression, more sense to use switch statement switch (<expr>) { case <val1> : ... break; case <val2> : default: } break allows you to exit switch statement after completing code Otherwise, program will continue to run through cases until finding break default covers any values without specific case 5/6/2018 ECE Application Programming: Lecture 4
50
ECE Application Programming: Lecture 4
Next time Exam 1 Allowed only one 8.5” x 11” note sheet Please arrive as close to on time as possible! Reminders Program 3 due Friday Program 4 due Thursday, 7/26 5/6/2018 ECE Application Programming: Lecture 4
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.