Lecture 6 Function
Lecture 6 Function
What is function?
v A large program in C is divided into many
subprogram. Each subprogram is called a
function.
Function
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 */
a = x * x * x;
return a;
}
Example 2
#include <stdio.h>
void main(){
int x;
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);
va_end(valist);
/* 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).