Function's • Function is a piece of a code to accomplish certain operation. • It has a name for identification. • They are of tw...

What is function & use of function in C Programming language

Function's

• Function is a piece of a code to accomplish certain operation.
• It has a name for identification.
• They are of two types

1. Predefined function.


2. User-defined function.


Example

add() /* function */
{
int a,b,c;
Printed("Enter two numbers");
Scanf("%d %d",&a,&b);
c=a+b;
Printf("sum is %d",c);
} isEven()
{ int a;
printf ("Enter a number");
scanf("%d",&a);
if (a%2==0)
printf ("Even");
else
printf("add");
}
main()
{
clrscr();
add();
isEven();
add();
add();
}

Technical Terms
• Function Call
• Function Declaration (Functional prototype)
• Function Call

Function Definition

  add()
{
printf("Enter two numbers");
scanf ("%d %d",&a,&b);
c=a+b;
printf("sum is %d",c);
}

Function Call

main()
{
clrscr();
add();


Remember


• Program must have at least one function.
• Function name must be unique.
• Function is an operation once defined can be used many times.
• One function is the program must be main.
• Function consumes memory only when it is invoked and released from RAM as soon as it finished it's job.


Benefits Of Function


Modularization
• Easy to read
• Easy to Debug
• Easy to modify
• Avoids rewriting of same code over and over
• Better memory utilisation


Ways To Define A Function

• Takes nothing return something.
• Take something return nothing.
• Takes nothing return somthsome.
• Takes somthsome return something.

/*Takes nothing return something*/

#include<studio.h>
#include<conio.h>

  void main ()
{
     void add(void);
     clrscr();
    getch();
}
  void add()
{
    int a,b,c;
printf("Enter two numbers");
scanf ("%d %d",&a,&b);
c=a+b;
printf("sum is %d",c);
}

/* Take somtsomet returns nothing*/

There is no use of function ( printf() and scanf()) because there is no need to take data from the user whereas already data is stored is variable.

Example

#include<conio.h>
#include<studio.h>

 void add (int,int);
 void main()
{
    int x,y;
   clrscr ();
printf("Enter two numbers");
scanf("%d %d",&X,&y);

add(x,y); /* actual argument (call by value)*/

getch();

}
void add (int x,int y) /* formal argument*/
{
 int c;
c= x+y;
printf("sum is %d" , c);
}

/*Takes Nothing Returns Nothing */

Example

 #include<conio.h>
 #include<studio.h>
   main()
{
     int s;
  clrscr ();
 s = add();
printf("sum is %d", s);
  getch ();
}
  int add()
{
int a,b,c;
printf("Enter two numbers");
scanf("%d %d", &a,&b);

return (a+b);
}


/*Takes something returns nothing */
  
#include<conio.h>
#include<studio.h>

    int add (int,int);
     void main()
{
    int s,x,y;
  clrscr ();
printf ("Enter two numbers");
   s= add (x,y);
printf("sum is %d",s);
    getch();
}
   int c;
c = a+b;
return (c);
}



0 Comments: