About Lesson
What is function?
- It is a set of instructions under a name.It is part of program known as sub program.
- It is used to devide a big problem into small small solutions.
- It has agreement that is “Just call me and use me” and with this agreement if function
- required some arguments( data ) then during call data must be passed to function.
- Function provides reusability of code
C
/*
1st Type - Function Does Not Return and Does Not Accept.
*/
#include<stdio.h>
void msg(); // does not accept and does not return
void sum();
int main() // a name which is given to set of instructions
{
msg(); // calling
msg();
return 0;
}
void msg() // definition
{
printf("\nHello User");
printf("\nWelcome to function");
sum(); // calling
}
void sum()
{
int n1,n2,t;
printf("\nenter 2 nos");
scanf("%d%d",&n1,&n2);
t=n1+n2;
printf("\nSum=%d",t);
}
C
/*
Type 2 - Function does not return and accept a value
Syntax:
void funname(datatype);
void main()
{
}
//Definition:
void funname(DT varname)
{
}
*/
#include<stdio.h>
void table(int);
int main()
{
int num;
printf("\nenter the number to print a table");
scanf("%d",&num);
table(num);
return 0;
}
void table(int num)
{
int i;
for(i=1;i<=10;i++)
{
printf("\n%d x %d = %d", num, i, num*i);
}
}
C
/*
Type 3- Function Accept and Return Both
Factorial of given number using function
Syntax:
RT funname(DT,DT...);
void main()
{
}
RT funname(DT var, DT var)
{
....
...
return value;
}
*/
#include<stdio.h>
int fact(int); // Fact is a function accept an int value and return an int also.
int main()
{
int x, y;
printf("\nenter a number to get its factorial");
scanf("%d",&x);
y=fact(x);
printf("\n Factorial of %d is %d",x,y);
return 0;
}
int fact(int num)
{
int i,f=1;
for(i=1;i<=num;i++)
{
f=f*i;
}
return f;
}
C
/*
Type 4 - Does Not Accept but Return
Area of a circle
syntax:
RT funname();
int main()
{
}
RT funname()
{
.....
return value;
}
*/
#include<stdio.h>
float getpi(); // getpi does not accept but return a float value
int main()
{
float r, a;
printf("\n enter Radius of a circle");
scanf("%f",&r);
a=getpi()*r*r;
printf("\nArea of a circle is %.2f",a);
return 0;
}
float getpi()
{
return 3.14;
}