FUNC1
FUNC1
FUNC1
Lecture 7
Functions
Structured Programming
Keep the flow of control in a
program as simple as
possible.
Use top-down design.
• Keep decomposing (also known as
factoring) a problem into
smaller problems until you have
a collection of small problems
that you can easily solve.
Top-Down Design Using Functions
C programs normally consist
of a collection of user-
defined functions.
• Each function solves one of the
small problems obtained using
top-down design.
• Functions call or invoke other
functions as needed.
Function Definitions,
Prototypes, and Calls
#include <stdio.h>
void prn_message(void); /* fct prototype */
/* tells the compiler that this */
/* function takes no arguments */
int main(void) /* and returns no value. */
{
prn_message(); /* fct invocation */
}
void prn_message(void) /* fct definition */
{
printf(“A message for you: “);
printf(“Have a nice day!\n”);
}
Form of a Function Definition
type function_name ( parameter type list )
{
declarations
statements
}
Some Terminology
Header: Everything before the first brace.
Body: Everything between the braces.
Type: Type of the value returned by the function.
Parameter List: A list of identifiers that provide information
for use within the body of the function.
Also called formal parameters.
The return Statement
When a return statement is
executed, program control is
immediately passed back to the
calling environment.
• If an expression follows the keyword
return, the value of the expression
is returned to the calling
environment as well.
return;
return expression;
If There is No return
Control is passed back to the
calling environment when the
closing brace of the body is
encountered.
• Known as “falling of the end.”
Exit Status and return Verus exit( )
In main() either
return expr;
or
exit(expr);
will return an integer value to the
operating system.
In functions other than main(),
the effects of return and exit
are different.
return expr Versus exit(expr)
return expr returns the value
of expr to the calling
function.
exit(expr) always causes the
program to terminate and
returns an exit status to the
operating system. The value
in expr is the exit status.
Demo Program – Using a Function
to Calculate the Minimum of 2 Values
#include <stdio.h>
int min(int a, int b);
int main(void)
{
int j, k, m;
printf(“Input two integers: “);
scanf(“%d%d”, &j, &k);
m = min(j, k);
printf(“\nOf the two values %d and %d, “
“the minimum is %d.\n\n”, j, k, m);
return 0;
}