Function
What is function?
v A large program in C is divided into many
subprogram. Each subprogram is called a
function.
Function
User defined Library function
function printf()
main() scanf()
pow()
ceil()
Example 1
#include <stdio.h>
Argument/formal parameter
int CubeArea(int x); /* function prototype */
main(){
Return data type Ø The variable to be passed from
int x, area; calling function to called
function is called argument.
printf(“Enter a value: “); Ø void print(int x);
scantf(“%d”, &x); No return of data
Return data type
area = CubeArea(x); /* calling function */
printf(“The area of cube is %d.”, area);
return 0; Output
} Enter a value: 4
The area of cube is 64.
int CubeArea(int x){ /* function definition */
int a;
a = x * x * x;
return a;
}
Example 2
#include <stdio.h>
int input(); /* function prototype */
void main(){
int x;
x = input(); /* calling function */
printf(“The inputted is %d.”, x);
}
int input(){ /* function definition */
int a;
printf(“Enter a value: “);
scanf(“%d”, &a);
return a;
}
Variable Length Arguments
int main()
{
printf("Average of {2, 3, 4} = %d\n", average(2, 3, 4));
printf("Average of {3, 5, 10, 15} = %d\n",average(3, 5, 10, 15));
return 0;
}
int average(int num, ...){
va_list valist;
int sum = 0, i; Header file: stdarg.h
va_start(valist, num);
for (i = 0; i < num; i++)
sum += va_arg(valist, int);
va_end(valist);
return sum / num;
}
Practice
#include <stdio.h>
/* function prototype */
/* power function */
double power(double x, int n);
double power(double x, int n){
long fact(int n);
double p;
………………………………………
/* main function */
return p;
void main(){
}
double x, term = 1, sum = 0;
int n = 1;
……………………………………
/* fact function */
while ( term > 0.001){
long fact(int n){
……………………….
long f;
term = power(x, n)/fact(n);
………………………………………
n++;
return f;
}
}
printf(“The result is %.2f.”, sum);
}
Write down functions for calculating values of sin(x), cos(x) and log(1 + x).