Function Part 2
Types
of user defined functions:
1. 1. Function with no
arguments and no return value.
2. 2. Function with
arguments and return value.
3. 3. Function with
arguments and no return value.
4. 4. Function with no
arguments and return value.
1. Function with no arguments and no return value:
#include<stdio.h>
int main()
{
printf("\n main start ");
f1();
printf("\n after One ");
f2();
printf("\n after two");
f3();
printf("\n main end");
return 0;
}
f1()
{
printf("\n I am in ONE");
}
f2()
{
printf("\n I am in TWO");
}
f3()
{
printf("\n I am in
Three");
}
eg:
#include<stdio.h>
int main()
{
printf("\n main start");
f1();
printf("\n after one");
f2();
printf("\n
After two");
f3();
printf("\n main end");
return 0;
}
{
printf("\n one start
");
f2();
printf("\n One End");
}
f2()
{
printf("\n Two start");
f3();
printf("\n Two End");
}
f3()
{
printf("\n I am in three");
}
Function with arguments and no return
values:
main()
{
=============;
=============;
function(param1,
param2, param3…..);
=============;
=============;
}
function( type arg1, type arg2, type arg3, ……….)
{
=============;
=============;
=============;
}
Parameters à passing values
Arguments
à receivers
Eg:
main()
{
int a=10;
float b=20.5;
=====;
=====;
function(a,b); -Ã
here a and b are parameters .
======;
======;
}
function(
int x, float y) Ã
x and y are the arguments .
{
============;
============;
============;
}
To call a function, the no of parameters
and type of parameters should be matched with function arguments.
This memory will be deleted automatically,
once control come out of the function.
Program to write function by name roots()
to find roots of quadratic equation ax2
+ bx + c = 0;
Here a , b and c parameters for the roots
function.
#include<stdio.h>
#include<math.h>
int main()
{
int a, b, c;
printf("\n Enter the values of a , b and c");
scanf("%d %d
%d",&a, &b,&c);
roots(a,b,c);
return 0;
}
roots(int
x, int y, int z)
{
int desc;
float r1,r2;
if(x==0)
{
printf("\n not a qudratic equation");
return;
}
desc=y*y - 4 * x * z;
if(desc < 0 )
{
printf("\n
roots are imaginary");
return;
}
r1 = ( -y + sqrt(desc))/(2*x);
r2 = ( - y - sqrt(desc))/(2*x);
printf("\n r1 =%f and r2 =%f",r1,r2);
}
0 Comments