540 likes | 608 Vues
Programming. Control Flow. Sequential Program. Start. int main() { Statement1; Statement2; … StatementN; }. S1. S2. S3. S4. S5. End. Absolute Value. Given a user input we would like to calculate its absolute value. Something along the lines
E N D
Programming Control Flow
Sequential Program Start int main() { Statement1; Statement2; … StatementN; } S1 S2 S3 S4 S5 End
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!
if Statement • Used to conditionally execute a statement or block of statements. if(expression) statement; Expr True False Statement Rest of Program if (grade > 60) printf("Congratulations! You passed"); printf("Your grade is %d", grade);
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…
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)
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
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.
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);
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); }
if-else Statement False True Expr if(expression) statement1 else statement2 • if expression is true, statement1 is executed. • if expression is false, statement2 is executed • both statements can be (and very often are) replaced by blocks of statements (“compound statements”) Statement2 Statement1 Rest of Program
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);
Nested if • The statement in the if statement’s body can be an if statement if(expression)statement if(expression) statement1 else statement2
Example – Nested if-else if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");
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
Indenting if Statements if (x == y) if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0");
Indenting if Statements if (x == y){ if (y == 0) printf("x == y == 0"); else printf("x == y; x,y != 0"); }
Indenting if Statements if (x == y){ if (y == 0) { printf("x == y == 0"); } else { printf("x == y; x,y != 0"); } }
if-else Statement (cont.) if (x == y) { if (y == 0) printf("x == y == 0"); } else printf("x == y; x,y != 0");
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
Indenting else if if (expression1) statement1 else if(expression2) statement2 elseif(expression3) statement3 else statement4
Example if (grade >= 90) { printf ("A\n"); } elseif (grade >= 80) { printf ("B\n"); } elseif (grade >= 70) { printf ("C\n"); } elseif (grade >= 60) { printf ("D\n"); } else { printf ("F\n"); }
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"); } } }}
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
Assignment Expression <variable> = <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 ( ) ( )
A Common Error • Confusing between the equality and assignment operators • we wanted if (x == 4) … • we wrote if (x = 4) …
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
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
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
Logical Operators • ! - not • !<expr>, negate the value of the expression. • && - and • <expr1> && <expr2>, True when both expressions are true • || - or • <expr1> || <expr2>, True when at least one of the expressions is true
Truth Tables OR AND NOT
Compound Expressions • Expressions can be combined using logical operators • If we want to check that a value is within a rangeInstead of :Write: if (grade >= 55)if (grade < 60) {/* recheck the exam */} if (grade >= 55 && grade < 60){/* recheck the exam */}
Compound Expressions • Do something if a char is A, C, G or TInstead of:You can write: if (c == 'A') {/* do something */ } elseif (c == 'C') {/* it’s the same thing as before */ } elseif (c == 'G') {/* write it again? */ } elseif (c == 'T') { /* not again!!! */ } if (c == 'A' || c == 'C' || c == 'G' || c == 'T') { /* do something */ }
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; }
return Statement return <expression> • Terminates the program (for now) • Return the value of <expression> to the environment • For now: • 1 – an error occurred • 0 – program terminated without errors.
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 < 0 || grade > 100) { printf(“Invalid grade!\n”); return 1; }
Error!! All is well A silly example int main(void) { int grade; printf("Please enter your grade: "); scanf("%d", &grade); if (grade < 0 || grade > 100) { printf("This is not a valid grade!\n");return 1; } printf("This is indeed a grade.\n"); return 0; }
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.
Solution int main() { char c; printf("Please enter aletter: "); 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 aletter!\n", c); return 1; } return 0; }
The conditional operator expr1 ? expr2 : expr3 • This is an expression. It has a value! • If expr1 is True (non-zero), expr2 is evaluated; otherwise expr3 is evaluated
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; }
?: 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; }
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; }
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 }
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
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"); }
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
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);
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
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 endscore = 100;jump to endscore = 87;jump to endscore = 0; a:b:c:d:end: