Functions
Functions
Introduction
Man is an intelligent species, but still cannot perform all of
life’s tasks all alone.
You may
– call a mechanic to fix up your bike,
– hire a gardener to mow your lawn,
– rely on a store to supply you groceries every month.
is called or invoked.
Contd.
Function
self-contained block of statements that perform some specific,
well-defined task.
using a function is something like hiring a person to do a
specific job for you. Sometimes the interaction with this
person is very simple; sometimes it’s complex.
Modularity-
Process broken down to three parts - making the dough, rolling
and roasting.
Re-Use-
Flour, Rolling-pin and gas stove are not made by us but re-used.
Any brand flour can be used.
Abstraction-
While writing recipe for roti, we are not concerned with details of
each small process - as long as the roti is edible, nutritious and
soft enough.
Type of Function
There are two type of function in C Language.
Library function or pre-defined or built-in function.
• These functions are provided by the system and stored in
library, therefore it is also called ‘Library Functions‘.
e.g. scanf(), printf(), sqrt(), pow(), strcmp(), strlen() etc.
• To use these functions, you just need to include the appropriate
C header files.
Example:
int sum(int a, int b);
void display(float c, int d, int e);
Note: At the time of function declaration function must be terminated with ;
Function prototypes are usually written at the beginning of a program, ahead
of any functions (including main()).
Function Prototype/ Declaration
Return Type − A function may return a value. The return_type is the
data type of the value the function returns. Some functions perform
the desired operations without returning a value. In this case, the
return_type is the keyword void. (default is int).
Not Accepting
Type 3 Returning Value
Parameter
Not Accepting
Type 4 Not Returning Value
Parameter
Type 1 : Accepting Parameter and Returning Value
Above type of method is written like this –
sum(2,3);
Type 3 : Not Accepting Parameter but Returning Value
int add()
{
int i, int j;
i = 10;
j = 20;
return i + j;
}
result = add();
Type 4 : Not Accepting Parameter and Not Returning Value
void add()
{
int i, int j;
i = 10;
j = 20;
printf("Result : %d",i+j);;
}
add();
Rules of Writing Function in C Programming
Rule 1. C program is a collection of one or more functions
main()
{
pune();
mumbai();
maharashtra();
}
Rule 2. A function gets called when the function name is
followed by a semicolon.
main( )
{
display( ) ;
}
Rule 3 : A function is defined when function name is followed by a
pair of braces in which one or more statements may be present.
Rules of Writing Function in C Programming
display( )
{
statement 1 ;
statement 2 ;
statement 3 ;
}
Rule 4. Any function can be called from any other function.
( main also ) main( )
{
message( ) ;
}
message( )
{
printf ( "\nWe are going to call main" ) ;
main( ) ;
}
Rules of Writing Function in C Programming
Rule 5. A function can be called any number of times.
main()
{
message( );
message( );
}
message()
{
printf("\nLearning C is very Easy");
}
Rule 6. The order in which the functions are defined in a
program and the order in which they get called need not
necessarily be same
Rules of Writing Function in C Programming
main( )
{
message1( ) ;
message2( ) ;
}
message2( )
{
printf ( "\n I am First Defined But Called Later " ) ;
}
message1( )
{
printf ( "\n I am Defined Later But Called First ") ;
}
Rule 7. A function can call itself ( Process of Recursion )
Rules of Writing Function in C Programming
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}
Any update made inside function will not affect the original
value of variable in calling function.
In the below given example num1 and num2 are the original
values and xerox copy of these values is passed to the function
and these values are copied into number1,number2 variable of
sum function respectively.
int num1=50,num2=70;
interchange(&num1,&num2);
/* calling a function to swap the values.
printf("\nNumber 1 : %d",num1);&a indicates pointer to a ie. address of variable a
printf("\nNumber 2 : %d",num2);&b indicates pointer to b ie. address of variable b
return 0;
}
Summary of Call By Value and Call By Reference
}
void avg_per(float*avg,float*per)
{
float m1,m2,m3,sum;
scanf("%f%f%f",&m1,&m2,&m3);
sum=m1+m2+m3;
*avg=sum/3;
*per=(sum*100)/150;
}
Call by Value- Class Exercise
Write a program to find out the maximum value between two integer numbers
using function.
#include <stdio.h>
int max(int num1, int num2); //function declaration
int main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
ret = max(a, b); //calling a function to get max value
printf( "Max value is : %d\n", ret );
return 0;
}
Call by Value- Class Exercise
/* function returning the max between two numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
Function Example : Max amoung 3 Numbers
void max(int,int,int);
void main()
{
int a,b,c;
printf(“Enter Three Numers”);
scanf(“%d%d%d”,&a,&b,&c);
max(a,b,c);
}
void max(int x, int y, int z)
{
int max = x;
if(y>max)
max=y;
if(z>max)
max=z;
printf(“Largest Number is %d”, max);
}
What is the evaluation order of function parameters in C?
Function parameters are not evaluated in a defined order.
According to the draft C99 standard in C the order of
evaluation of function arguments and the order in which side
effects take place are both unspecified. (from C99 §6.5.2.2p10:)
Compiler of C as it is traditionally build to maximize the speed
and optimization can evaluate the function arguments in any
way.
Argument evaluation and argument passing are related but
different problems.
Consider the following function call:
fun (a, b, c, d ) ;
In this call it doesn’t matter whether the arguments are
evaluated from left to right or from right to left.
What is the evaluation order of function parameters in C?
However, in some function call the order of evaluation of
arguments becomes an important consideration.
For example:
int a = 1 ;
printf ( "%d %d %d", a, ++a, a++ ) ;
int main ()
{
int g = 10; // local variable declaration and initialization
printf ("value of g = %d\n", g);
return 0;
}
Output- value of g = 10
Formal Parameters
Formal parameters, are treated as local variables with-in a
function and they take precedence over global variables.
#include <stdio.h>
int a = 20; //global variable definition
int sum(int, int);
int main ()
{
/* local variable definition in main function */
int a = 10;
int b = 20;
int c = 0;
printf ("value of a in main() = %d\n", a);
c = sum( a, b);
printf ("value of c in main() = %d\n", c);
return 0;
}
Formal Parameters
/* function to add two integers */
int sum(int a, int b) // a & b are formal parameters of sum()
{
printf ("value of a in sum() = %d\n", a);
printf ("value of b in sum() = %d\n", b);
return a + b;
}
Output-
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
Initializing Local and Global Variables
When a local variable is declared, it is not initialized by the
system, you must initialize it yourself. Global variables are
initialized automatically by the system when you declare them
as follows −
Data Type Initial Default Value
int 0
char '\0'
float 0
double 0
Pointer NULL
#include <stdio.h>
void display(int a[ ][2]); /*declaring a function which takes a two dimensional integer
array as an argument*/
int main()
{
int num[2][2],i,j;
printf("Enter 2x2 numbers:\n");
for(i=0 ;i<2 ;i++)
{
for(j=0 ;j<2 ;j++){
scanf("%d",&num[i][j]);
}
}
display(num); //the whole 2D array gets passed to the function display()
return 0;
}
C Passing Multi-Dimensional Array
Instead you should use fgets(), which allows you to limit the
number of characters read, so that the buffer does not
overflow.:
char s[10];
fgets( s, 10, stdin );