DA Unit 4 Functions

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 45

FUNCTIONS

CLASS : CSE-A & B


Presented by : Dr. S. Arvind
Date : 18-04-2020
The approach to design a given problem can be in the form of top-down or
bottom up approach.

• “Top down design” is a problem solving method in which a complex problem is


solved by breaking up into sub problems.
• In this design a program is divided into main module and it related modules.
Each module is in turn divided into sub modules until resulting modules are
understood without further division.
• It proceeds from the original problem at the top level to the sub problems at each
lower level.
• Top down design is usually done using a visual representation of modules known as
"structured chart".
• “Structure chart” is a documentation tool that shows the relationships among the
sub problems of a problem.
• The structured chart is read from top-down and left-right.
Structure Chart
Functions in 'C'
Definition:

A function is an independent module that will be called to do a specific


task.
(or)
A function is a self contained block that carries out a specific well defined
task.

In 'C', a program is made of one or more functions, out of which


mandatorily one of the function must be a main function.

The execution of the program always starts with main. It can call other
functions to do some part of the job.

The called function receive control from the calling function. The called
function may or may-not retain a value.

The main function is called by the "Operating System."


Advantages of functions
Problem can be factored into understandable and manageable sub problems
 
• Re usability i.e. a function may be used by many other programs or more than
one place in a program.
  • The length of the source program can be reduced.
  • It is easy to locate and isolate a faulty function.
  • It facilitates top-down modular programming.

• Functions protect the data. ie. local data contains the data that is describes
with in a function and won't be available outside of a function.
Types of functions
 
Functions are broadly classified into 2 types

They are :
 
1. Predefined functions
 
2. User defined functions
1) Predefined (or) Library functions

✓ These functions are already defined in the system libraries


✓ Programmer can reuse the existing code in the system libraries to write error
free code.
✓ But to use the library functions, user must be aware of syntax of the
function.

Ex: 1) sqrt() function is available in math.h library and its usage is :

y= sqrt (x)

Ex: y = sqrt (25)


then ‘y’ = 5
number must be positive

2 ) printf ( ) function is available in stdio.h library

3) clrscr ( ) function is available in conio.h library


Program

#include<stdio.h>
#include<conio.h>
#include<math.h>

main ( )
{
int x,y;

clrscr ( );
printf (“enter a positive number”);
scanf (“ %d”, &x)
y = sqrt(x);
printf(“squareroot = %d”, y);
getch();

}
User defined Functions
 
✓ These functions must be defined by the programmer (or) user.
✓ Programmer has to write the coding for such functions and test
them properly before using them.
✓ The syntax of the function is also given by the user and
therefore need not include any header files.
In order to make a user-defined functions,
we need to do following 3 steps
i) Function Declaration or Function prototype
ii) Function Call
iii) Function Definition or Function
Implementation.
 
1. Function Declaration or Function prototype
Proto type declaration can be done in two places of the program namely

a) Global prototype---declared above all functions and available/accessible for all functions in
program.
b) Local prototype---declared with in main function defination.

General format:
return_type function_name(parameter_list);

NOTE: Parameters that are used in the function declaration are called as "Formal Parameters".
If no formal parameters are needed the list is written as void.

✓ A function must follow the same rules of formation as other variables name in ‘C’
✓ A function name must not duplicate library routine names (or) predefined function names.

Example1: int sum(int m,int n);


In the above example use of parameters names is optional i.e we can declare the same function as:
int sum( int , int);
 
Example2: void function_name( void);
The prototype of function does not take any parameters and does not return any value.
2. Function Call:
General format: function_name(parameter_list);
Note: The parameters in the function call are called as "Actual Parameters".
 
The actual parameters must match with formal parameters in function declaration
in type, order and number.

The function call which returns some value can be used in expression,
whereas a function call which does not return any value can't be used in the
expression.

The function call is a postfix expression with function name as operand and ( )
with actual parameters as operators.

Example :
sum(10,5);
multi(m,n);
multi(expression1,expression2);  
3. Function Definition or Function Implementation:-

It contains the code for the function.


It has two parts,namely function header and function body.
 
❖ The first line in the function definition is called function header.
General format:
return_type function_name(parameter_list)
{
local variable declaration;
statements;
return statement;
}

Note: parameter_list in function definition is called as " formal


parameters". 
return statement can be of two type namely,

return;

// if function is not returning any values return(expression);

// if function is returning a values.

A called function can only return one value per call


 
The return types are void, int, float, char and double.
 
If a function is not returning any value then its return type is
‘void’.
Important point to be remembered regarding parameter_list:

 
1. Parameters present in the function declaration and function
definition are called as "formal parameters."
 
2. Parameters present in the function calling are called as "actual
parameters".
 
3. If the actual parameters are more than formal parameters,
extra actual parameters will be discarded.
 
4. In case of vice-versa , the unmatched formal parameters are
initialized with garbage values.
 
5. In case of mismatch of data type result is garbage value.
01/07/2023 MRM
 
Program
#include<stdio.h>
 

void display()
//global prototype void main()
 
{
printf("\n welcome");
 

display();
//function call printf("\n have a
nice day");
 
}
void display() //function definition
 

 
{

 
printf("to function concepts");

 
return;
}
 
Categories of functions based on arguments
Categories of functions:
 

Depending on whether arguments are present (or) not and whether a value is
returned (or) not, functions are categorized into:
➢ functions without arguments and without return values
➢ functions without arguments and with return values
➢ Functions with arguments and without return values
➢ Functions with arguments and with return values.
functions without arguments and without return values
 
Example:

 
main ( )
{
 

void sum ( ); //local


prototype clrscr ( );
sum ( );
//function call
getch ( );
}
 

// function definition void sum ( )


 
{

 
int a,b,c; // local variables

printf(“Enter 2 numbers”); scanf (“%d%d”, &a, &b); c = a+b;


printf(“sum = %d”,c);
functions without arguments and with return values
 
Example:
main ( )
 

 
{

 
int sum ( ); //local prototype

int ans; //local declaration clrscr ( );


 
ans= sum ( ); //calling function

 
printf(“sum = %d”,ans);

 
}
int sum ( ) //function defination
 

 
{

 
int a,b;

 
static int c;

printf(“enter 2 numbers”); scanf (“%d%d”, &a, &b); c =


a+b;
 
return c;
}
Functions with arguments and without return values
main ( )
 
{
 

void sum (int, int ); //local prototype and formal


parameters int a,b; //local declarations
clrscr ( );
 

 
printf(“enter 2 numbers”);
scanf(“%d%d”, &a,&b);
sum (a,b); //function calling and actual parameters
}
//function definition and formal parameters void sum ( int x , int y)
{
 
int c;
c= x+y;
printf (“sum=%d”, c);
}
NOTE : variable names in the actual parameters and formal parameters
need not be the same.
Functions with arguments and with return values.
Example:
 

#include <stdio.h>
 

int sum ( int , int ); // global declaration and


formal parameters main ( )
{
 

 
int a, b, ans;
clrscr ( );
 

 
printf(“enter 2 numbers”);

 
scanf(“%d%d”, &a,&b);

 
ans= sum (a,b); //calling a function and actual parameters
printf (“sum=%d”, ans);
 

 
getch ( );
}
 

//definition of a function and formal parameters


int sum ( int a, int b )
 {
 static int c;
 c= a+b;
 return c;
}
Parameters Passing Techniques To Functions
(OR) Inter function communications:
The data flow between calling and called function can be divided into
3 strategies namely
i) Downward flow or Call by value
ii) Upward flow or Call by address
iii) Bi- directional flow
Figure 4.2: Parameters Passing Techniques To Functions
Downward flow:

Figure 4.2: Parameters Passing Techniques To Functions


 

➢ The calling function sends data to the called function.


➢ No data flows in opposite direction.
➢ The called function may change the values passed, but the original
values in calling function remain untouched i,e don't change values
➢ The Pass-by-value mechanism in 'C' is an example for this downward
communication;
➢ In pass-by-value mechanism ,the calling function sends a copy of each
value to the called function
 
Example on the Downward communication or CALL BY VLAUE
#include <stdio.h>
 

void dowfun( int ,int); // function


declaration int main(void)
{
int a=5; //local declarations
dowfun(a,15); printf("%d",a); return 0;
}
  void dowfun(int x, int y)
 {
 x = x + y;
 return;
 }
Explanation: In the above example 'a' value i.e 5 and 15 are copied
to ' x 'and 'y ' respectively during the function call. In function
implementation 'x' value is assigned with sum of 5 and 15.ie with
20. ,but these changes in 'x' are not going to reflect the original value of
'a' .
UPWARD FLOW (OR) UPWARD
 
COMMUNICATION.
• This communication occurs when the called function sends data back to the calling
function.
 

• "Pass -by -reference "concept is implemented in "c" by means of UPWARD


FLOW
 

• 'C' provides return statement to return one data item to the calling function.
 

• To pass multiple data items up to the calling function,we need to pass the
address of the variables to the called function.
• To get the address of a variable we use address operator (&). Eg: If the variable
in the calling function is x ,its address operator is (&x).
EXAMPLE FOR PASS BY ADDRESS OR CALL BY REFERENCE OR CALL BY
 
ADDRESS OR UPWARD COMMUNICATION
# include <stdio.h>
  void upfun(int* a,int* b); //global prototype int main(void)
{
 
int x,y; //local declarations
upfun( &x,&y); //function calling
printf("%d %d", x,y);
return 0;
}
 void upfun( int* a,int* b) //function definit ion and parameters are address or pointer
variables
 {
 
*a=23; //here a is address variable and * is called indirection operator
 *b=26;
 return;
 }
BI -DIRECTIONAL FLOW:
 

It occur when the calling function sends data down to the called function
during or at the end of its processing,the called function then send s data upto the
calling function. In this flow ,we use the indirect reference on both sides of the
assignment statement.
Example:
 

 
#include<stdio.h>

 
void bifun(int* a, int* b);

 
int main(void)
{
 

 
int x=2;

 
int y=6;

bifun(&x,&y); //function call with addresses of the


parameters printf("%d%d",x,y);
return 0;
 

 
}

 
void bifun(int* a,int* b) //function definition with address variables a and b

 
{
*a=*a+2; // //here a is address variable and * is called indirection operator
 

 
*b=*b/2;

 
return;
}
 
Passing arrays to functions (or)Arrays and functions
There are 2 ways of passing arrays as arguments to functions. They are sending entire array
as argument to function
❖ sending individual elements as argument to function.
 
1. sending entire array as argument to function
 
❖ To send entire array as argument, just send the array name in the function call.
❖ To receive the entire array, an array must be declared in the function header..
Example:
main ( )
 

{ void display (int a[5]);


 

int a[5], i;
 

clrscr( );
 

printf (“enter 5 elements”);


 

for (i=0; i<5; i++)


 

scanf(“%d”, &a[i]);
display (a);
getch( );
}
void display (int a[5])
{
int i;
 printf (“elements of the array are”);
 for (i=0; i<5; i++)
 printf(‘%d ”, a[i]);
}
 
sending individual elements as argument to function.
❖ If individual elements are to be passed as arguments then array elements
along with their subscripts must be given in function call
 
❖ To receive the elements, simple variables are used in function definition
main ( )
 

 
{
void display (int, int);
int a[5], i;
 clrscr( );
 printf (“enter 5 elements”);
 for (i=0; i<5; i++)
 scanf(“%d”, &a[i]);
 display (a [0], a[4]);
 getch( );
 }
 void display (int a, int b)
 {
 print f (“first element = %d”,a);
 printf (“last element = %d”,b);
 }
Program to perform addition of two matrix using funtions

 
#include<stdio.h>

 
#define RMAX 10
#define CMAX 10
 

void read(int [RMAX][CMAX],,int,int);//prototype void


display (int [RMAX][CMAX],int,int); //prototype
void add(int [RMAX][CMAX],int [RMAX][CMAX],int,int);
//prototype int main()
 
{

int A[RMAX][CMAX],B[RMAX][CMAX],SUM[RMAX]
[CMAX]; Int row,column;
int r1,c1,r2,c2;
 

 
printf("enter r1,c1 and r2, c2");
scanf("%d%d%d%d",&r1,&c1,&r2,&c2);
 
if(r1==r2 && c1== c2)
{
 

printf("matrix addition is possible");


printf("\nenter A matrix:\n");
read(A,r1,c1);//calling
printf("\nenter B matrix\n");
read(B,r2,c2);//calling
add(A,B,r1,c1);
printf(“A matrix is\n”);
display(A,r1,c1);//calling
printf(“B matrix is \n”);
display(B,r2,c2);//calling
printf(“sum of A and B matrix is:\n”);
display(SUM,r1,c1);//calling
 

 
}

 
else

 
{
printf(“matrix addition is not possible”);
 

 
}

 
return 0;

 
}

 
void read (int X[RMAX][CMAX], int rowsize,int columnsize)
{
 

 
for(row=0;row<rowsize ;row++)

 
{

 
for(column=0;column<columnsize;column++)
{
 

 
scanf("%d",&X[row][column]);

 
}
}
void display (int X[RMAX][CMAX], int rowsize,int columnsize)
 

 
{
for(row=0;row<rowsize ;row++)
{
 for(column=0;column<columnsize;column++)
 {
 scanf("%d",X[row][column]);
 }
 }
 //CODE TO COMPUTE SUM OF A AND B MATRIX
 void add(int A[RMAX][CMAX],int B[RMAX][CMAX],int rowsize,int columnsize)
 {
 for(row=0;row<rowsize; row++)
 {
 for(column=0;column<columnsize; column++)
 { SUM[row][column]=A[row][column]+B[row][column];
}
 }
 return ;
 }
 
Passing pointers to functions (or)Pointers for inter function communication:

a) Passing Address/call by
reference b) Function
returning pointer
a) Passing Address/call by
reference:
 

When the want a called function to have access to a variable in the calling
function,we pass the address of that variable to the called function and
use indirection operator to access them.
Example Program to swap two Values
 

#include<stdio.h>
 

void swap(int*, int*); //prototype void


main()
 
{
int a=5,b=3;
 

 
printf("values of a and b before swapping is %d and %d",a,b);
swap(&a,&b); //calling function
printf("values of a and b after swapping is %d and %d",a,b);
  return;
 }
 void swap(int* x,int* y) //called functio
 {
 int temp;
 temp=*a;
 *a=*b;
 *b=temp;
 return;
 }
 
Function Returning Pointer

When a function return a pointer, it must point to a data in calling


function. A function can't return a pointer to a local variable in
called function.
Example on function returning pointer
 

 
Program to display smallest of two number

#include<stdio.h> int*
small(int *,int *); void main()
{
 

 
int a,b,*s;

printf("enter a and b values");


scanf("%d %d",&a,&b);
s=small(&a,&b);
 
printf("smallest of % d and %d is %d",a,b,*s);

 
getch();
return;
 
int* small(int* x,int* y)
{
if (x<y)
return x;
else
return y;
}

You might also like