View
223
Download
4
Embed Size (px)
Citation preview
Lecture 3
• Strings• More control statements
• C functions
Announcements
More control statements
K&R: ch. 3
More control statements
• for loops– Much like while loops but more general and sometimes more
convenient
• switch statements– Nice alternative to messy if-else sequences
• do-while loops– Slight variant on while loops
• goto statements– Typically to be avoided
• break and continue statements
Control statements, cont.
• These are all explained nicely with examples in ch. 3 of K&R
• Main points – These additional statements don't allow you to do anything that
you couldn't have done with while and if
– However, they do make it much cleaner and more concise to express certain logic. Often so much so that without them a solution may be too difficult to come up with.
For loops
• General syntax– for ( expr11; ; expr2expr2; ; expr3expr3 ){ ){ statement1; .}This is exactly equivalent to:expr1;while (expr2) { statement1; expr3;}
For loops, cont.
• Expr1– Called the initializer; evaluated once and only once before the
loop executes for the first time.
• Expr2– The termination condition; evaluated at the beginning of each
iteration of the loop. If it evaluates to false, loop ends.
• Expr3– Evaluted at the end of each iteration of the loop.
For loops, cont.
• Simple, most obvious, and most typical usage: for ( j = 0; j < n; j++ ) {…}
(write out the equivalent while statement!)• Infinite loop:
for (; ; ) { … } /* any part may be ommited */
• May also combine expressions:for (j=0, k=m; j < k; j++, k--){ … }
For loops, cont• Arithmetic expressions
– Initialization, loop-continuation, and increment can contain arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y / x ) is equivalent to
for ( j = 2; j <= 80; j += 5 )• Notes about the for structure:
– "Increment" may be negative (decrement)– If the loop continuation condition is initially false
• The body of the for structure is not performed• Control proceeds with the next statement after the for structure
– Control variable
• Often printed or used inside for body, but not necessary
1. Initialize variables
2. for repetition structure
• Program Output
Switch statements
• General syntaxswitch( expr ){
case const-expr: statements
case const-expr: statements
.
.
default: statements
}
Switch, cont.
• Note that cases must be constant expression, not variables!
• If a case is matched, switch falls through to the next statement. A break must be used to avoid evaluating subsequent cases.
• Just a cleaner way of to write a bunch of if-else statements.
Switch flow-chart
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
do/while Repetition Structure
• The do/while repetition structure – Similar to the while structure
– Condition for repetition tested after the body of the loop is performed
• All actions are performed at least once
– Format:do {
statement;
} while ( condition );
1 /* Fig. 4.9: fig04_09.c
2 Using the do/while repetition structure */
3 #include <stdio.h>
4
5 int main()
6 {
7 int counter = 1;
8
9 do {
10 printf( "%d ", counter );
11 } while ( ++counter <= 10 );
12
13 return 0;
14 }
Do-while example
Do-while and goto
• No great advantages to using them.• If you're curious, very well explained in K&R 3.6
& 3.8.
C functions
Breaking a program into smaller, reusable pieces
Functions
• Functions– Enable you to break a program into smaller pieces
(modularization).
– Each function performs a specified task. It may receive input data and return output data.
– Main program is mainly a wiring together of function calls.
– All variables declared inside functions are local variables
• Known only in function defined
– Parameters
• Communicate information between functions
Functions, cont.
• Benefits of functions– Divide and conquer
• Manageable program development
– Software reusability
• Use existing functions as building blocks for new programs
• Abstraction - hide internal details (library functions)
– Avoid code repetition
Start with an example
• Imagine that many different times in a C program you have to find the maximum of two numbers: if ( a > b ){
bigger = a;
}
else{
bigger = b;
}
• While this may not seem like a lot of code, it can get very ugly and make the program difficult to follow. It would be much nicer to say something like: bigger = imax(a,b);
C functions, cont.
• The purpose of a C function is to allow the programmer to accomplish exactly this; that is, to move snippets of code outside of the main program and call them by an intuitive name. These functions can then be reused in any program where they are needed.
Example: Max function
int imax( int, int ) ; /* function "prototype" - listed before main*/ int main(int argc, char* argv[]){ int a, b, c; a = atoi(argv[1]); b = atoi(argv[2]); c = imax(a,b); printf("%s: %d, "The max value is: ", c);}/* our first non-main function */int imax( int val1, int val2 ){ if (val1 > val2){ return(val1); } else{ return(val2); } }
Dissecting the max function
• Our programming world will extend now, from main() { … } within a single file, to:
#include< … >
function prototypes …
main(…) { … }
func1(…) { …}
func2(…) { …}
.
all within a single file!
Components of a function
• Each function is composed of three parts:– Name
• Like variables it's up to you.• Should choose clear, intuitive name
– Return type• Data type that the function will return to user. • For imax function this is an int.
– Parameter list• List of datatypes that will be passed to the function.• For imax functions there are two: int and int.
– Author of function makes all of these decisions!
Components, cont.
• Each of the three mentioned on the previous slide parts goes in a specific place:
return-type function_name( param1, param2, …) { }
Where param1, etc. are composed of two parts:
param1_type param1_name
• Example:
int imax( int x, int y)
Return type: int
Name : imax
Parameter list: an integer x and an integer y
Body of a function
• After the function header comes the body, denoted by braces { … }
• The body is always organized as variable declarations and then executable statements.
• Finally, the function should always end with a return statement, specifying the variable that is to be passed back to the caller.– Example: return(x); /* end the function and hand back the value of the
variable x to the calling function */
Calling a function
• Function calls– The word"call" refers to the process of invoking functions. When
you call a function:
• Provide function name and arguments (data)
• Function performs operations or manipulations
• Function returns results– Function call analogy:
• Boss asks worker to complete task– Worker gets information, does task, returns result
– Information hiding: boss does not know details
Calling a function, cont.
• The formal process of calling a function is as follows:
return_value = func_name( arg1, arg2, …);
return_value: optional variable to store output
func_name : name of the function you wish to invoke.
arg1, … : Data that you are passing to the function.
Known as an argument list. Must match function parameter list in number
and type.
Example: calling a function
• Using our previous imax example: int maxval; /* declare an integer to
store the result */ int a = 8; b = 10; /* create some data */
maxval = imax(a,b); /* function call */
• Example says "call the function imax, passing to it the variables a and b, and store the result in the integer maxval."
More examples
• Write a function which takes no input and gives no output; it's only effect is to print an error message to the screen and abort.
• Write a function called power with the following interface:– double power(double x, int n)which evaluates x to the nth power.
• Write a function which returns the sum of an arbitrary-sized 1d array.
• Write a function that sorts an array• Write a function to find the max value of an array
Writing functions
• For each problem on the previous slide, we should first set up the function before writing any code:– What is the input type and number?
– What is the output (return val)?
– What is a good name for the function?
• Once this is done, we can address go ahead and write the details of the function.
Data visibility
• Extremely important!– Function can only "see" three types of variables:
• Those declared locally within the function
• Those passed into the function through it arg list
• "Global variables" defined outside of any function– We have not yet used global variables
– Any variables defined in other functions (even main) that are not passed into another function are NOT visible to that function, and it can not see or manipulate their values!
• This behavior is crucial to achieving code modularity.
Function nuances
• Just a few more things to know about functions:– Prototype
– Dummy argument names
– Void argument lists and return types
– Calling a function without accepting return value
– "pass by value" vs. "pass by reference"
• Each of these is described in the subsequent slides
Prototyping
• Though not always strictly necessary, I will require that we template all funtions.
• Templating means the following:– For each non-main function in your source file, you should include
function headers just before main().– A "header" is just the return_type, name, and param list of the function,
ie:• int imax(int a, int b)• Note that "dummy arguments" a and b are optional here• Int imax(int, int ) is ok
• Templating helps the compiler know what to expect when it encouters a function call for the first time.
Dummy arguments
• When we setup a function the param names are often referred to as "dummy arguments". For example, for imax:– int imax(int a, int b)
– The variables a and b are the dummy arguments.
– You can choose to name these anything regardless of the specific names passed to the function at calling time.
– Whatever you choose to name them, that will be their name inside the function.
Void arguments
• A function may have zero or one return values, and zero or more paramters. If you create a function with zero return values, you should use void:– void printerr( int errorcode );
• Likewise for zero parameters:– void printerr(void)
• Use void is optional, but it is a good practice since the compiler it will cause the compiler to do some extra checking.
Calling functions
• For a function that does not return void, you may still choose to discard the return argument by simply calling the function with no " = ":– imax(a,b) is legal, though not obviously useful.
– c = imax(a,b) is more typical and useful