Lecture 3: Statements and Flow of Control
- Last time we learned how to create C expressions using
a variety of operators. Today we are going to look at
how to create statements out of those expressions and
to use C's flow control constructs to write interesting
programs.
C Statements
- A C statement is an expression followed by a semicolon OR
- A series of C statements enclosed in curly braces
(also called a block or compound statement)
- Either:
p = q;
- Or:
| { |
| temp = p; |
| p = q; |
| q = temp; |
| } |
- The empty statement(;) does remarkably little but is very
efficient.
The If Statement
| if (condition) |
| statement1 |
| else |
| statement2 |
- the first branch of the C ``if'' statement is executed
if the condition in parens is true
- the second branch is executed otherwise
- the else clause is optional
- Example:
| if(x < 17) { |
printf(``The if branch n''); |
| } else { |
printf(``The more fascinating else branch n''); |
| } |
More Examples of If
| if(x < 17) |
printf(``The if branch n''); |
| else { |
| printf(``The more fascinating ''); |
printf(``else branch n''); |
| } |
- Remember, a compound statement must be surrounded by curly braces
Else if
- Often you want to perform a series of tests.
- Just follow an else with another if:
| if (condition1) |
| statement1 |
| else if (condition2) |
| statement2 |
| else if (condition3) |
| statement3 |
| else |
| statement |
Whiling Your Time Away
| while (condition) |
| statement |
- The while loop statement executes as follows:
- 1.
- Check the expression in parens.
- 2.
- (a)
- If the condition in parens is true,
execute the loop statement and repeat (ie: goto step 1)
- (b)
- If the condition is false, exit the loop.
- An example, computing factorial:
| int main(void) |
| { |
| int n, fact = 1; |
| |
| scanf(``%d'',&n); |
| while(n > 0){ |
| fact = fact * n; |
| n = n - 1; |
| } |
printf(``fact = %d n'',fact); |
| return 0; |
| } |
For Loops
- The for loop is a very useful, specialized while loop:
| for (init; condition; op) |
| statement |
- The for loop above is equivalent to the following while loop:
| init; |
| while (condition) { |
| statement |
| op; |
| } |
- Factorial again:
| int main(void) |
| { |
| int n, fact; |
| |
| scanf(``%d'',&n); |
| |
| for(fact = 1; n > 0;n-) |
| fact = fact * n; |
| |
printf(``fact = %d n'',fact); |
| return 0; |
| } |
More For Loops
- Using for loops we can write very compact code:
| int main(void) |
| { |
| int n, fact; |
| scanf(``%d'',&n); |
| for(fact = 1; n > 0; fact *= n, n-); |
printf(``fact = %d n'',fact); |
| return 0; |
| } |
- ... but you should always strive for readability.
Writing obfuscated code is very easy in C. Don't do it!
And More For Loops
- Notice the comma operator in the for loop:
| for( ... ; fact *= n, n-); |
- Arguments to the comma operator are evaluated left to
right (here, we multiply and then subtract)
- The result of the comma operator is the result of the
rightmost argument.
- Be careful not to confuse semicolons and commas!
- The comma is used occasionally in for loops and
seldom elsewhere (except by mistake).
- Another interesting loop:
- We can leave out components of the for loop if we choose!
- If we leave out the condition, loop will repeat infinitely.
Functions
| # include <stdio.h> |
| |
print_witticism: |
| Inputs: a witticism number(w_num) |
| Side Effects: Prints witticism given by w_num |
|
| void print_witticism(int w_num) |
| { |
printf(``printing witticism %d n'', w_num); |
return; returning void |
| } |
| |
| int main() |
| { |
| int x = 17, y = 3; |
| |
| print_witticism(x); |
| print_witticism(y); |
| print_witticism(42); |
| |
| return 0; |
| } |
Functions Cont'd ...
- Comment every function precisely!
- C functions are defined as follows:
type function_name( param_list
) { ... }
where param_list is:
type1 var1, ..., typen varn
- The type before the function name is the return type of the
function.
- The param_list is the list of parameters to the function with
their types.
- C functions end with a return statement
- The main function should return an integer.
- Return 0 if your program exits normally.
- Return another number if there is an error.
Casts Revisited
- In the following example, we use a cast to help round:
| int round1(float x) |
| { |
| return (int)(x + .5); |
| } |
- However, C also does automatic type converversion for
function arguments and results. round1 above
is equivalent to round2:
| int round2(float x) |
| { |
| return x + .5; |
| } |
... And More Casts
- If you pass trunc a float, it will cast the argument to an
integer, truncating it, and will convert the result back to a float:
| float trunc(int x) |
| { |
| return x; |
| } |
| |
| int main(void) |
| { |
| float x = 3.5, y; |
| |
y = trunc(x); y == 3.0 |
| return 0; |
| } |
The Switch Statement
| switch (expression) { |
| case const-expr: statements break; |
| case const-expr: statements break; |
| ... |
| default: statements break; |
| } |
- Switch is a multi-way choice statement.
- The expression is an integer or character expression.
- The const-expressions in the cases must all be different and
can be in any order.
- The default is optional.
- Switch is evaluated as follows:
- 1.
- Evaluate the expression
- 2.
- Match the expression against each const-expression.
If there is a match, execute that branch.
- 3.
- If there is no match, execute the default.
- 4.
- If there is no match and no default, do nothing.
An Example - The calculator
| int main(void) |
| { |
| float arg1, arg2, res; |
| char op; |
| |
| while ((scanf(``%f %c %f'', &arg1, &op, &arg2)) == 3) |
| { |
| switch (op) { |
| case '+': |
| res = arg1 + arg2; |
| break; |
| case '-': |
| res = arg1 - arg2; |
| break; |
| ... |
| default: |
printf(``Unknown operator: %c n'', op); |
res = 0.0; default result |
| break; |
| } |
printf(``%f n'',res); |
| } |
printf(``Input error: program terminated! n''); |
| return 1; |
| } |
More on Switch
Watch Out!
- break at the end of the case is not required BUT you should
(almost) always put it in. If you forget it, execution will
fall through to the next case
- Consider:
| switch (op) { |
| case '+': |
| res = arg1 + arg2; |
| case '-': |
| res = arg1 - arg2; |
| break; |
| ... |
| } |
- When the program should execute the same branch for several
different constant expressions, ``fall through'' intentionally:
| int x; |
| ... |
| switch (x) { |
| case 0:
case 1:
case 2: |
printf(``Do the same thing for 0,1,2 n''); |
| break; |
| ... |
| } |
More About the Break Statements
- Another use of the break statement is in loops:
| int main(void) |
| { |
| char stop; |
| |
| while (1) { |
printf(``Do you want to stop now? n''); |
| scanf(``%c'', &stop); |
| if (stop == 'y') |
| break; |
| } |
| |
| return 0; |
| } |
Summary
- A statement: an expression followed by a semi-colon or
a series of statements surrounded by curly braces.
- The If statement: The basic choice statement in C.
- The Switch statement: A multi-choice statement.
- The While statement: A looping construct
- The For statement: A second looping construct with
initialization, and testing the exit condition
``built in''
- We also learned about C functions.