Function in C
Function in C
PROGRAM 1:
#include<stdio.h>
#include<conio.h>
void printmg();
void main()
{
clrscr();
printmsg();
getch();
}
printmsg()
{
printf("This is a user defined function.
\n");
printf("This blockis executed in printmsg()
function body.");
}
FUNCTION WITH NO ARGUMENTS AND NO RETURN
VALUE
#include<stdio.h>
#include<conio.h>
void add();
void main()
{
clrscr();
add();
getch();
}
void add()
{
int a,b,sum;
printf("Enter the value of a :");
scanf("%d",&a);
printf("Enter the value of b :");
scanf("%d",&b);
sum=a+b;
printf("Addition : %d",sum);
}
FUNCTION WITH ARGUMENTS AND NO RETURN VALUE
#include<stdio.h>
#include<conio.h>
void add(int a,int b);
void main()
{
int m,n;
clrscr();
printf("Enter the value of m : ");
scanf("%d",&m);
printf("Enter the value of n : ");
scanf("%d",&n);
add(m,n);
getch();
}
#include<stdio.h>
#include<conio.h>
int add();
void main()
{
int result;
clrscr();
result=add();
printf("Addition : %d",result);
getch();
}
int add()
{
int a,b,sum;
printf("Enter the value of a : ");
scanf("%d",&a);
printf("Enter the value of b : ");
scanf("%d",&b);
sum=a+b;
return sum;
}
FUNCTION WITH ARGUMENTS AND RETURN VALUE
#include<stdio.h>
#include<conio.h>
int add(int a,int b);
void main()
{
int m,n,result;
clrscr();
printf("Enter the value of m : ");
scanf("%d",&m);
printf("Enter the value of n : ");
scanf("%d",&n);
result=add(m,n);
printf("Addition : %d",result);
getch();
}
#include<stdio.h>
#include<conio.h>
void swap(int a,int b);
void main()
{
int m,n;
clrscr();
printf("Enter the value of m : ");
scanf("%d",&m);
printf("Enter the value of n :");
scanf("%d",&n);
printf("\nValues before swapping \nm:%d
\nn:%d",m,n);
swap(m,n);
printf("\nValues after swapping \nm:%d
\nn:%d",m,n);
getch();
}
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
}
CALL BY REFERENCE
#include<stdio.h>
#include<conio.h>
void swap(int *a,int *b);
void main()
{
int m,n;
clrscr();
printf("Enter the value of m : ");
scanf("%d",&m);
printf("Enter the value of n :");
scanf("%d",&n);
printf("\nValues before swapping \nm:%d
\nn:%d",m,n);
swap(&m,&n);
printf("\nValues after swapping \nm:%d
\nn:%d",m,n);
getch();
}
void swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}
RECURSIVE FUNCTION
#include<stdio.h>
#include<conio.h>
int fact(int n);
void main()
{
int num,result;
clrscr();
printf("Enter the value of num : ");
scanf("%d",&num);
result=fact(num);
printf("Factorial of %d = %d",num,result);
getch();
}
int fact(int n)
{
if(n==0)
return 1;
else
return n*fact(n-1);
}