Sei sulla pagina 1di 8

FUNCTIONS IN C

Muhammad Suffian
WHY FUNCTIONS???
 To reduce the size of the main program
 To make the program easier to understand and
even easier to write
 Program divided in modules
 The main logic of the program (Main function) is neat
for visualization
 Reusability
 Modules (functions) can be reused multiple times, by
simply making a call to a function. (Instead of writing
the function again and again, just call the name to
use the function.
 If reused with different variables/values, the variable
names/values are to be provided at the time of calling
a function.
EXAMPLE
#include <stdio.h>

void add(); // function declaration

int main()
{
add(); // function call
return 0;
}

/* function definition */
void add()
{
int num1, num2;
int sum = 0;
num1=0;
num2=0;

printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);

sum = num1 + num2;


printf("\nsum is : %d\n", sum);
}
STRUCTURE OF THE PROGRAM
HOW FUNCTION WORKS???...
 Function Declaration
 Compiler intimated, that a function will be called
from main().
 A link or handle of the function is provided to the
compiler

 Function Definition
 AFTER main(), the definition of the function is
provided

 Function Call
 In main the function is called where ever required
HOW FUNCTION WORKS???...
#include <stdio.h>

void add(); // function declaration

int main()
{
add();

return 0;
}

void add()
{
int num1 =0 , num2 =0 , sum = 0;

printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);

sum = num1 + num2;


printf("\nsum is : %d\n", sum);
}
EXAMPLE-2
#include<stdio.h>

int add(int n1,int n2);

int main()
{
int num1=0,num2=0;
int result;

printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);
result = add(num1,num2);
printf("\nResult : %d",result);
return(0);
}

int add(int n1,int n2)


{ int sum;
sum = n1+ n2;
return(sum);
}
EXAMPLE-3
#include<stdio.h>

int add(int n1,int n2);


int sub(int x1, int x2);

int main()
{
int num1=0,num2=0;
int sum, diff;

printf("\nEnter num1:");
scanf("%d", &num1);
printf("\nEnter num2:");
scanf("%d", &num2);
sum = add(num1,num2);
diff = sub(num1, num2);
printf("\nsum : %d",sum);
printf("\ndifference : %d",diff);
return(0);
}

int add(int n1,int n2)


{
return(n1+n2);
}
int sub(int x1,int x2)
{
return(x1-x2);
}

Potrebbero piacerti anche