Download presentation
Presentation is loading. Please wait.
1
Programming Control Flow
2
Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; … StatementN; } Start End
3
Absolute Value Given a user input we would like to calculate its absolute value. Something along the lines If the number is negative “make it positive” Notice that we only execute “make it positive” in case the number is negative!
4
Conditional Statements Selects statements to execute based on the value of an expression The expression is sometimes called the guard Conditional statements: if statement switch statement
5
if Statement Used to conditionally execute a statement or block of statements. if (expression) statement; if (grade > 60) printf("Congratulations! You passed"); printf("Your grade is %d", grade); Expr Statement Rest of Program True False
6
Operators In C, every expression has a numeric value When using arithmetic operators (+, -, *, /) this is straightforward The value of A+B is the sum of A and B And so on…
7
More About Operators Expressions with relational operators (, >=, etc.) have values as well (intuitively, we are used to thinking about them as ‘true’ or ‘false’) A < B evaluates to zero if A is larger than or equal to B, and some non-zero value if A is smaller than B The exact non-zero value varies (and is not important for that matter)
8
Relational operators They are: A == B (Note the difference from A = B) A != B A < B A > B A <= B A >= B The expression is “false” if it’s value is zero and “true” otherwise
9
True or False In C, every expression has a numeric value An expression is ‘true’ when its value is non- zero it is false it evaluates to zero. Therefore, in the following – if (expression) statement statement is executed if expression evaluates to non-zero.
10
Block A sequence of statements enclosed within curly braces {} if (grade > 60) { printf("Congratulations! You passed"); printf("Hip Hip Hooray!"); } printf("Your grade is %d", grade);
11
Example - Absolute Value void main() { double num; printf("Please enter a real number: "); scanf("%lf", &num); if (num < 0) num = -num; printf("The absolute value is %g\n", num); }
12
if-else Statement if (expression) statement 1 else statement 2 if expression is true, statement 1 is executed. if expression is false, statement 2 is executed both statements can be (and very often are) replaced by blocks of statements (“compound statements”) Expr Statement1 Rest of Program True False Statement2
13
Example - min int first, second, min;... if (first < second) { min = first; printf ("The first number is smaller than the second.\n"); } else { min = second; printf ("The second number is smaller than the first\n"); } printf("The smaller number is %d\n", min);
14
Nested if The statement in the if statement’s body can be an if statement if (expression) statement if (expression) statement1 else statement2
15
Example – Nested if-else if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");
16
Indentation if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0"); Misleading indentation else is associated with the closest if use {} for clarity and to change the meaning
17
Indenting if Statements if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");
18
Indenting if Statements if (x == y) { if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0"); }
19
Indenting if Statements if (x == y) { if (y == 0) { printf("x == y == 0"); } else { printf("x == y; x,y != 0"); } }
20
if-else Statement (cont.) if (x == y) { if (y == 0) printf("x == y == 0"); } else printf("x == y; x,y != 0");
21
else if if statements distinguish between exactly 2 cases and execute different code in each case The else-if construction allows for a multi-way selection
22
Indenting else if if (expression 1 ) statement 1 else if (expression 2 ) statement 2 else if (expression 3 ) statement 3 else statement 4
23
Example if (grade >= 90) { printf ("A\n"); } else if (grade >= 80) { printf ("B\n"); } else if (grade >= 70) { printf ("C\n"); } else if (grade >= 60) { printf ("D\n"); } else { printf ("F\n"); }
24
Example – Different Indentation if (grade >= 90) { printf ("A\n"); } else { if (grade >= 80) { printf ("B\n"); } else { if (grade >= 70) { printf ("C\n"); } else { if (grade >= 60) { printf ("D\n"); } else { printf ("F\n"); } } } }
25
Example int a, b; printf("Enter two numbers\n"); scanf("%d%d", &a, &b); if (a == b) { printf("The numbers equal %d\n", a); printf("The expression a == b is %d\n", a == b); } else { printf("The numbers are not equal\n"); printf("The expression a == b is %d\n", a == b); } some non-zero value 0
26
Assignment Expression = Assignment expressions have a value. It is the value of the right-hand-side expression For example: (x = 4) evaluates to 4 x = y = z = 0 ( )
27
A Common Error Confusing between the equality and assignment operators we wanted if (x == 4) … we wrote if (x = 4) …
28
Example void main() { int i = 2; printf("i = %d\n", i); printf("(i==4) = %d\n", i==4); printf("i = %d\n", i); printf("(i=4) = %d\n", i=4); printf("i = %d\n", i); } i = 2 (i==4) = 0 i = 2 (i=4) = 4 i = 4
29
Rule of Thumb When comparing to a constant it is better to write the constant first how does this help us? (4 == i) is the same as (i == 4) BUT (4 = i) is a compilation error
30
Logical Operators !A – ‘not’ - True when A is false, and vice versa. A && B – ‘and’ - True when both A and B are true A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true
31
Logical Operators !- not !, negate the value of the expression. &&- and &&, True when both expressions are true ||- or ||, True when at least one of the expressions is true
32
Truth Tables X && YYX False TrueFalse True X ||YYX False True False TrueFalseTrue !XX TrueFalse True NOT ORAND
33
Compound Expressions Expressions can be combined using logical operators If we want to check that a value is within a range Instead of : Write: if (grade >= 55) if (grade < 60) { /* recheck the exam */ } if (grade >= 55 && grade < 60) { /* recheck the exam */ }
34
Compound Expressions Do something if a char is A, C, G or T Instead of: You can write: if (c == 'A' || c == 'C' || c == 'G' || c == 'T') { /* do something */ } if (c == 'A') { /* do something */ } else if (c == 'C') { /* it’s the same thing as before */ } else if (c == 'G') { /* write it again? */ } else if (c == 'T') { /* not again!!! */ }
35
Revisiting main Programs are executed in an environment Upon termination a termination status should be passed to the environment void main() {... } int main() {... return 0; }
36
return Statement return Terminates the program (for now) Return the value of to the environment For now: 1 – an error occurred 0 – program terminated without errors.
37
Validating Input When getting input from the user, it is highly recommended to check whether it is valid. If it’s not, you should display an appropriate message and return a non-zero value. For example – if (grade 100) { printf(“Invalid grade!\n”); return 1; }
38
A silly example int main(void) { int grade; printf("Please enter your grade: "); scanf("%d", &grade); if (grade 100) { printf("This is not a valid grade!\n"); return 1; } printf("This is indeed a grade.\n"); return 0; } Error!! All is well
39
Exercise Read a single letter from the user Make sure the input is valid In case the letter is lowercase convert to uppercase. In case the letter is uppercase convert to lowercase.
40
Solution int main() { char c; printf("Please enter a letter: "); scanf("%c", &c); if (c >= 'a' && c <= 'z') printf("%c in uppercase is %c\n", c, c-'a'+'A'); else if (c >= 'A' && c <= 'Z') printf("%c in lowercase is %c\n", c, c-'A'+'a'); else{ printf("%c is not a letter!\n", c); return 1; } return 0; }
41
Exercise Input Two integers, A and B Output Their relation (i.e. displays A==B, A B)
42
Solution int main() { int m, n; printf("Enter two numbers\n"); scanf("%d%d", &m, &n); if (m == n) printf("%d == %d\n", m, n); else if (m > n) printf("%d > %d\n", m, n); else printf("%d < %d\n", m, n); return 0; }
43
The conditional operator expr 1 ? expr 2 : expr 3 This is an expression. It has a value! If expr 1 is True (non-zero), expr 2 is evaluated; otherwise expr 3 is evaluated
44
The conditional operator int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); min = (i < j) ? i : j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }
45
?: vs. if int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); if (i < j) min = i; else min = j; printf("The minimum between %d and %d is %d\n", i, j, min); return 0; }
46
The ?: operator int main() { int i, j, min; printf("Please enter two numbers: "); scanf("%d%d", &i, &j); printf("The minimum between %d and %d is %d\n", i, j, (i < j)? i : j); return 0; }
47
The switch statement A multi-way conditional statement similar to if-else..if-else allows the selection of an arbitrary number of choices based on an integer value switch (expression) { case int-const-expr: statement break; case int-const-expr: statement break; … default: statement }
48
The switch statement expression must have an integer value (char, int) when the switch statement is executed: the expression is evaluated if a case matches the value of the expression, the program jumps to the first statement after that case label otherwise, the default case is selected the default is optional
49
That grade example again switch (grade/10) { case 10: case 9: printf ("A\n"); break; case 8: printf ("B\n"); break; case 7: printf ("C\n"); break; case 6: printf ("D\n"); break; default: printf ("F\n"); }
50
Give me a break when the switch transfers to the chosen case, it starts executing statements at that point it will “fall through” to the next case unless you “break out” break causes the program to immediately jump to the next statement after the switch
51
What will it print? Given your ID return the test score int id, score;... switch (id) { case 1: score = 90; case 2: score = 100; case 3: score = 87; default: score = 0; } printf(“Your test score is %d\n“, score);
52
Without break if (id == 1) jump to a; if (id == 2) jump to b; if (id == 3) jump to c; jump to d; score = 90; score = 100; score = 87; score = 0; a: b: c: d: end: Code executes sequentially
53
With break if (id == 1) jump to a; if (id == 2) jump to b; if (id == 3) jump to c; jump to d; score = 90; jump to end score = 100; jump to end score = 87; jump to end score = 0; a: b: c: d: end:
54
A more interesting example int main( ) { double n1, n2, res; char op; printf("Please enter two numbers: "); scanf("%lf%lf", &n1, &n2); printf("Please enter an arithmetical operator (+, -, * or /): "); scanf(" %c", &op); Continued on the next slide
55
Another example switch(op) { case '+': res = n1 + n2; break; case '-': res = n1 - n2; break; case '*': res = n1 * n2; break; case '/': /* We're not checking for division by zero for clarity... */ res = n1 / n2; break; default: printf("%c is an invalid arithmetical operator!\n", op); return 1; } /* Display the expression and its result */ printf("%g %c %g = %g\n", n1, op, n2, res); return 0; }
56
Exercise Write a program that accepts a number between 1 and 100 from the user. If there is a coin of that value in cents, it should display its name. Otherwise, it should report that there is no such coin 1 = cent, 5 = nickel, 10 = dime, 25 = quarter, 100 = dollar Remember to check for the validity of the input!
57
Solution int main() { int num; printf("Please enter a number from 1 to 100: "); scanf("%d", &num); /* Make sure the input is valid */ if (num 100) { printf("Invalid input!\n"); return 1; } /* Display the correct coin name, or a default message if there's no such coin */ switch (num) { case 1: printf("It's a cent!\n"); break; case 5: printf("It's a nickel!\n"); break; case 10: printf("It's a dime!\n"); break; case 25: printf("It's a quarter!\n"); break; case 100: printf("It's a whole dollar!\n"); break; default: printf("It's not a coin!\n"); } return 0; }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.