This article includes some example programs of functions, which may be helpful if you are a beginner in programming.
1. Create a function void check (int n) that checks whether given number is odd or even.
#include<stdio.h>
void check(int n);
int main()
{
int n;
printf("Enter any number :");
scanf("%d",&n);
check(n);
getch();
}
void check(int n)
{
if(n%2==0)
printf("Even");
else
printf("Odd");
}
Enter any number : 5
Odd
2. Create a function int small (int a , int b) that finds the smaller numbers between two numbers.
#include<stdio.h>
#include<conio.h>
int small(int a , int b);
void main()
{
int a,b;
printf("Enter two numbers:");
scanf("%d%d",&a,&b);
printf("Smaller number is : %d",small(a,b));
getch();
}
int small(int a , int b)
{
if(a<b)
return a;
else
return b;
}
Enter two numbers: 2 5
Smaller number is : 2
3. Create a function that takes one integer argument and finds the sum of its digits.
#include<stdio.h>
void sum(int n);
void main()
{
int n;
printf("Enter any number:");
scanf("%d",&n);
sum(n);
}
void sum(n)
{
int r,sum=0;
while(n>0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("Sum is : %d",sum);
}
Enter any number: 1234
Sum is : 10
4. Create a function that takes an int array as argument and returns the smallest value in the array.
#include<stdio.h>
int small(int a[]);
void main()
{
int a[5],i;
printf("Enter any 5 numbers:");
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
printf("Smallest Number : %d",small(a));
}
int small(int a[])
{
int sm=a[0],i;
for(i=0;i<5;i++)
{
if(a[i]<sm)
sm=a[i];
}
return sm;
}
Enter any 5 numbers:5 7 2 6 3
Smallest Number : 2
5. WAP to find the factorial of a number using recursive function.
#include<stdio.h>
int fact(int n);
void main()
{
int n;
printf("Enter a number:");
scanf("%d",&n);
printf("Factorial is: %d",fact(n));
}
int fact(n)
{
if(n==1)
return 1;
else
return n*fact(n-1);
}
Enter a number:5
Factorial is: 120
6. WAP to display the first 10 numbers in a Fibonacci series using recursive function.
#include<stdio.h>
int fibo(int n);
void main()
{
int i;
for(i=1;i<10;i++)
{
int r=fibo(i);
printf("%d\t",r);
}
}
int fibo(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return fibo(n-1)+fibo(n-2);
}
1 1 2 3 5 8 13 21 34