Lecture 5 - Function Part I
Lecture 5 - Function Part I
Lecture 5 - Function Part I
Functions (Part 1)
2
Outline
Introduction
Functions in C
Pre-defined functions
User-defined functions
Number, order and type of parameter
Functions that do not return a value
Functions that return a value
3
Functions in C
Functions can be created to execute small,
frequently-used tasks
All C programs consist of one or more functions.
One function must be called main.
In C, there are two types of function
Predefined functions / standard functions
- main(), printf(), scanf()
User-defined functions
- Your own code
7
User-Defined Functions
1. Function Prototypes
•Function prototype is a declaration; indicates
the function exists
•Should have function name, return type and
parameter
•Argument name is not compulsory
•Function prototype has the following form:
<return_type> <function_name> (arg_type arg_name, ...);
e.g. double product (double x,double y);
double product(double,double); //is also
acceptable
Functions Prototype - Example
#include <stdio.h>
Function prototype /* function prototype */
float product(float x, float y);
Like a variable declaration
Placed before main () int main()
Tells compiler that the {
function will be defined later float var1 = 3.0, var2 = 5.0;
Helps detect program errors float ans;
Note semicolon!! /*function call*/
ans = product(var1, var2);
printf("var1*var2 = %.2f\n",ans);
}
/* function definition */
float product(float x, float y)
{
float result;
result = x * y;
return result;
}
12
2. Function Calls
•Consists of a function name followed by an
argument expression list enclosed in
parentheses
•Function call has the following form:
<function_name> (exp, exp ...)
•exp is an expression – can be variable or
constant
ans = product(x,y);
Functions Call- Example
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
Function call
/*function call*/
main() is the 'calling ans = product(var1, var2);
function' printf("var1 = %.2f\n"
product() is the 'called "var2 = %.2f\n",var1,var2);
function' printf("var1*var2 = %g\n", ans);
Control transferred to the }
function code /* function definition */
Code in function definition is double product(double x, double y)
executed {
double result;
result = x * y;
return result;
}
14
3. Function Definitions
•Function definition includes the body of a function
•Function definition has the following form:
<return_type> <function_name> (arg_type arg_name, ...)
{
… statements …
}
Example: no semicolon
int sum (int num1,int num2){
int add;
add = num1 + num2; argument name in
function definition
return add; must be included
} in function header
Functions Definition - Example
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
/*function call*/
ans = product(var1, var2);
printf("var1 = %.2f\n"
"var2 = %.2f\n",var1,var2);
printf("var1*var2 = %g\n", ans);
}
Function definition /* function definition */
double product(double x, double y)
Note, NO semicolon {
double result;
result = x * y;
return result;
}
Functions Return - Example
#include <stdio.h>
/* function prototype */
double product(double x, double y);
int main()
{
double var1 = 3.0, var2 = 5.0;
double ans;
Function return /*function call*/
ans = product(var1, var2);
return statement terminates printf("var1 = %.2f\n"
execution of the current function "var2 = %.2f\n",var1,var2);
Control returns to the calling printf("var1*var2 = %g\n", ans);
function }
return expression;
then value of expression is /* function definition */
returned as the value of the double product(double x, double y)
function call {
Only one value can be double result;
returned this way result = x * y;
return result;
}
17
int main(){
int x,y, result;
printf( “Enter x and y : ”);
scanf(“%d %d”, &x, &y);
result = sum(x,y); //function call
printf(“Sum is : %d”, result);
return 0;
}
int sum(int num1, int num2) //function definition
{
int add;
add = num1+num2;
return add;
}
18
What about number, order and
type of parameter?
•Number, order and type of parameters in the argument
list of a function call and function definition MUST
match.
•If function prototype and definition have three
parameters then the function call must have three
parameters.
•If the types are int, float and double in the
prototype, the types in the function call should be int,
float and double, respectively.
19
Example :
There are two arguments for function prototype, function
definition and function call;
The first is int and the second is double.
With these three we have met the number, order and
type requirements.
20
Example 2: Number, order and
type of parameter
int sum(int, int);//function prototype
int sum(int num1, int num2)//function
definition
sum(x,y); //function call
int main(){
int x,y;
function1(); //function call
printf(“Enter x and y: ”);
scanf(“%d %d”, &x, &y);
sum_print(x,y); //function call
return 0;
}
void sum_print(int num1, int num2){ //function definition
int add;
add = num1+num2;
printf(“Sum is: %d”,add);
}
void function1(){ //function definition
printf(“Welcome to this program\n”);
}
22
Sample application
•Write a C program that calculates and prints
addition and subtraction of numbers.
•Your program should have functions:
ladd : adds two numbers
lsubtract : subtracts two numbers
lprint_result : prints results from calculation
27
Sample application(cont)
#include <stdio.h>
int add(int,int);
int subtract(int,int);
void print_result(int);
int main()
{ int num1,num2,answer;
char op;
printf(“Enter two numbers and operator:”);
scanf(“%d %d %c”, &num1,&num2,&op);
switch(op)
{ case ‘+’ :answer=add(num1,num2);break;
case ‘-’ :answer=subtract(num1,num2);break;
default: printf(“Invalid operator”);
exit(0);
}
print_result(answer);
return 0;
}
int add(int x,int y)
{
int sum;
sum = x+y;
return(sum);
}
int subtract(int x,int y)
{
int sub;
sub=x-y;
return(sub);
}
void print_result(int ans)
{
printf(“Answer is %d”, ans);
}
1 /* Fig. 5.4: fig05_04.c
UniMAP
EKT
28 150 :Sem
Computer
2
I -10/11Programming
Finding the maximum of three integers */
3 #include <stdio.h>
4 1. FUNCTION PROTOTYPE (3
5 int maximum(int, int, int); /* function prototype PARAMETERS)
*/ 6
7 int main()
8 {
9 int a, b, c;
10
11 printf( "Enter three integers: " );
12 scanf( "%d %d %d", &a, &b, &c );
13 printf( "Maximum is: %d\n", maximum( a, b, c )
); 14 2. FUNCTION CALL
15 return 0;
16 }
17
18 /* Function maximum definition */
19 int maximum(int x, int y, int z)
20 {
21 int max = x; 3. FUNCTION DEFINITION
22
23 if ( y > max )
24 max = y;
25
26 if ( z > max )
27 max = z;
28
29 return max;
30 }
Enter three integers: 22 85 17
Maximum is: 85
PROGRAM OUTPUT
29
Scope and Mechanics of Passing Values to
Functions
•Scope refers to the region in which a declaration is
active
•Two types:
Global Variable/ File Scope
Local Variable/ Function Scope
30
Global and Local Variables /*printf(
} Compute
circle
#include
float
main()
float
scanf(“%f”
if
else
} (pi
*/
{
rad;
float
printf(
rad Area
“Area
area
peri =and
<stdio.h>
= “Enter
3.14159;
, /*
>“Negative
“Area
“Peri
0.0 =)
pi
2 *Perimeter
&rad);
the
Local
*radius
/*
%f\n”
={ */
Global
%f\n”
pi
rad , “ of
);
radius\n”);
*
, *
rad;
area
rad;
area
peri a
*/);
);
•Global variable
These variables are declared
outside all functions at the
top of a source file.
declarations not placed in
any functions
Life time of a global variable
is the entire execution period
of the program.
Can be accessed by any
function defined below the
declaration, in a file.
31
Global and Local Variables /*printf(
} Compute
circle
#include
float
main()
float
scanf(“%f”
if
else
} (pi
*/
{
rad;
float
printf(
rad Area
“Area
area
peri
> =and
<stdio.h>
= “Enter
3.14159;
, /*
&rad);
=the
“Area
“Peri
“Negative
0.0 pi
2 *Perimeter
)Local
*radius
/*
%f\n”
={ */
Global
%f\n”
pi
rad , “ of
);
*/
radius\n”);
*
, *rad;
area
rad;
area
peri a
););
•Local variables
These variables are declared
inside some functions (in a block {
… })
Life time is the entire execution
period of the function in which it
is defined.
Cannot be accessed by any
other function scope is within
its block
In general variables declared
inside a block are accessible only
in that block.
32
void main(void){
printf("%d\n“, global); //Reference to global variable
ChangeGlobal();
printf("%d\n", global);
}
void ChangeGlobal( ){
global = 5; //Reference to global variable
}
void ChangeLocal();
void main(void){
int local = 3; //This is a local variable
printf("%d\n", local); //Reference to local variable
ChangeLocal();
printf("%d\n", local);
return 0;
}
void ChangeLocal(){
int local = 5; //This is another local variable
printf("%d\n", local);
}
The output will be:
3
5
3
34
Sample Application
Write a C program that reads item code and quantity, then
calculates the payment. Use functions:
fnMenu – print item code menu
fnDeterminePrice – determine price based on item
code
fnCalc - calculate payment
fnPrintResult – print payment