Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; …...
-
date post
22-Dec-2015 -
Category
Documents
-
view
234 -
download
0
Transcript of Programming Control Flow. Sequential Program S1 S2 S5 S4 S3 int main() { Statement1; Statement2; …...
Absolute Value
Given a user input we would like to calculate its absolute value.
Something along the linesIf 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;
if (grade > 60) printf("Congratulations! You passed");printf("Your grade is %d", grade);
Expr
Statement
Rest of Program
True
False
Operators
In C, every expression has a numeric value
When using arithmetic operators (+, -, *, /) this is straightforwardThe value of A+B is the sum of A and BAnd 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
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”)
Expr
Statement1
Rest of Program
TrueFalse
Statement2
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) statementif (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
else if (expression3)
statement3
else
statement4
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"); }
Example – Different Indentationif (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"); } } }}
Exampleint 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 operatorswe 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) = 0i = 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 trueA || 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
X Y X && Y
False False False
False True False
True False False
True True True
X Y X ||Y
False False False
False True True
True False True
True True True
X !X
False True
True False
NOT
OR AND
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' || 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!!! */}
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;
}
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;}
Error!!
All is well
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.
Solutionint 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;
}
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. ifint 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 againswitch (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 end score = 100;jump to endscore = 87;jump to endscore = 0;
a:
b:
c:
d:
end:
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
Another exampleswitch(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;}
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!
Solutionint main(){ int num;
printf("Please enter a number from 1 to 100: ");
scanf("%d", &num);
/* Make sure the input is valid */ if (num < 1 || 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;}