Functions
Functions
1. Objective ..............................................................2
2. Function Definition ..............................................2
3. Function Prototypes .............................................5
4. Calling Functions .................................................5
5. Questions/Practice ...............................................9
2. Function Definition
The length of your program can be reduced.
It becomes easy
Functions can be called several times within your
program.
There are two types of functions in C:
Functions
Library Use-defined
Functions Functions
Where
o function-name: any valid identifier
o Return-value-type:
data type of the result (default int)
void – indicates that the function returns
nothing
o Parameter-list:
Also called formal parameters.
A list of variable, comma separated list,
declares parameters:
A type must be listed explicitly for each
parameter unless, the parameter is of type int
o Declarations and statements: function body
(block)
Abdelghani Bellaachia, CSCI 1121 Page: 3
Variables can be declared inside blocks (can
be nested)
You cannot create functions within inside
other functions.
o Returning control
If nothing returned
return;
or, until reaches right brace
If something returned
return expression;
Example:
int findMax(int a,int b){
if (a <b)
return (b);
else return (a);
}
Example:
4. Calling Functions
Used when invoking functions
If the function returns a value:
o Given the following function:
return-value-type function-name( parameter-list )
{
declarations and statements
}
var = function-name(list-values);
o Example:
printf()
o Call by reference
To pass original values
It changes the original variables
//gcc 5.4.0
#include <stdio.h>
int findMax(int a,int b){
if (a <b)
return (b);
else return (a);
}
int main(void)
{
int x =5;
int y = 10;
printf ("Max of %d and %d is %d\n", x, y, findMax(x,y));
x = 100; y = -1;
printf ("Max of %d and %d is %d\n", x, y, findMax(x,y));
return 0;
}
//gcc 5.4.0
#include <stdio.h>
int sumaray(int myparam[], int limit){
int i;
int sum=0;
for(i=0; i < limit; ++i)
sum += myparam[i];
return (sum);
}
void main(void)
{
int myarr1[5] = {1,2,3,4,5};
int myarr2[8] = {1,2,3,4,5,6};
2
1
𝑉=𝑎 ∗ ℎ
3
𝑉 = 𝑎2 ∗ ℎ
𝑉 = 𝜋𝑟 2 ∗ ℎ