Functions (1)
Functions (1)
Types of function
Syntax:
returnType functionName(type1 argument1, type 2 argument2,...);
Calling a function
• Control of the program is transferred to the user-defined function
by calling it.
Syntax :
functionName(argument1, argument2, ...);
#include<stdio.h>
void sum(int, int);
main()
{
int a,b,result;
printf("Calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}
Functions with arguments and return
value
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nCalculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Functions with no arguments and return value
• A function which does not take any argument but only returns
values to the calling function.
• The best example of this type of function is “getchar()” library
function which is declared in the header file “stdio.h”.
Functions with no arguments but returns value
Functions with no arguments but returns value
#include<stdio.h>
int sum();
main()
{
int result;
printf("\n Calculate the sum of two numbers:");
result = sum();
printf(" The sum of two numbers is = %d\
n",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Recursion
• A function calling itself repetitively to compute a value
• Functions are called by main function or by some other function
• But in recursion the same function is called by itself repeatedly
Use of Recursive Function