0% found this document useful (0 votes)
5 views

Functions

c language
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Functions

c language
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Compiled and Executed by Mahesh Reddy Challa (Asst.

prof, CSE Dept)

UNIT –III

 ARRAYS:-
Definition:-
 Array is a derived data type which is used for handling a large volume of data for
reading, Processing and printing.
 Array is a fixed-size sequenced collection of elements of the same data type.
(OR)
 Collection of similar types of data elements that share a common name.
(OR)
 A Homogenous collection of data items that share a common name.

 TYPES OF ARRAYS:-
 Arrays are categorized into three types they are:-
1) ONE-DIMENSIONAL ARRAYS:-
 A linear list of items that can be given a single name using one Subscript is called a
Single subscripted array or a One-Dimensional Array.
 An Array consists of a Subscript which specifies a size for array. Size is nothing but
the number of elements to store in array.
 DECLARATION OF ARRAY:-
In order to declare one dimensional array we use the following syntax:-

Syntax: - Data-type Arrayname [size];

In the above syntax:-


Data-type ------  specifies what type of data you are going to collect (data type can be
int, float, double, char).
Arrayname----- is a name for an array.
[Size] ----------  One subscript which is used to specify the size for array.
Example for declaring an array:-
int array1[10];

1
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

/* this statement tell the compiler that to create an array with name
array1 with a size of 10 elements. I.e. this array can hold 10 integer
elements in contiguous memory locations */
 INITIALIZATION OF ONE-DIMENSIONAL ARRAY:-
 After we declare an array, we can store the elements into it.
 Initialization of array is a process where we assign elements to an Array.
 Initialization of array can be done in two ways:-
1) At compile time: -
 Assigning or initializing elements of an array can be done when an array is
declared.
 Assigning values/elements for an array will be done before we compile the
program i.e. in source program itself we will initialize the elements of array. So,
we call this method as Initialization of array at compile time.
 The following is the syntax for initialization of array at Compile time:-

data-type arrayname[size] = {list of values};

Example 1:- Initialization with size and values:-


int array1[6] = {1,2,3,4,5,6};
 In the above statement we are assigning 6 elements for array1. In this case all the
locations of the array are filled with data.
 Six memory locations are allocated by compiler to array1 and size of each
memory location will be 2 bytes and the total size of memory allocated for array1
is (Number of elements in array * size of data type) i.e. 6*2 = 12 bytes of memory
will be allocated under the name of array1.
Example 2:- Initialization without Size:-
int array1[] = {1,2,3,4,5};
This is another way for initializing an array.
In this example we have declared an array without specifying the size for array. The array
size will be determined by compiler automatically. The size will be the total number of
elements you have assigned.
Example 3:- Partially initialization:-
int array1[6] = {1,2,3};
In this case we have initialized an array with elements which are less than the size of an
array.
The elements will be initialized from 0th position and so on and the remaining positions
will be filled with Zero(s) automatically.
Example 4:- filling initial data with zero.
int array1[6] = {0};
in this case we have initialized array with 0. So, all the array locations will be filled with
zero(s).
If we declare int array[4] = {6}; in this way then first location will be filled with 6 and
remaining locations are filled with zero(s).

2
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

2) Initialization at RUN TIME:-


 Assigning value for an array at run time means providing the data of array after
running the program is known as RUN TIME Initialization.
 Run-time initialization of an array can be done in the following way:-
1) Take a for loop and in the loop write a statement that reads the values that are entered
from keyboard i.e. using scanf () function.
Sample code Snippet:-
for(i=0;i<n;i++)
{
scanf(“formatspecifier”,&arrayname[i]);
}
Example:-
void main()
{
int a[5];
printf(“Enter the elements of array:\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
/* initialization of an array at Runtime */

 Accessing the elements of an Array:-


 In order to access the elements of an array we have to use the Index numbers.
Memory locations of elements are referred by these Index Numbers.
 Suppose if array consists of 6 elements then the position/ index numbers
begins with 0th position and so on.. .
 The following syntax is used to access the elements by their index numbers:-
Arrayname[index number];
Example:-
int a[5] = {1,2,3,4,5};
Here a[0] indicates first element a[1] indicates second element etc..
So if you want to access third element we have to write the code in
the following way
printf(“%d”,a[2]); /* the printf() function print the 3rd
element from the array */
If you want to access all the elements from array put the above
printf() statement in a loop in the following way:

for(i=0;i<5;i++)
{
printf(“%d\t”,a[i]
}

3
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Example: /* W.A.P in C to declare, initialize, and access the elements of one-dimensional array */
void main()
{
int a[6] = {1,2,3,4,5,6};
int i;
printf(“The elements of array
are:\n”);
for(i=0;i<6;i++)
{
printf(“%d\t”,a[i]);
}
}

In the above program code we have initialized array at compile time.

To initialize array at runtime we have to use a loop and read the


elements that are given from runtime. The following is the code to
initialize array elements at runtime.

void main()
{
int a[5],i;

printf(“Enter 5 elements of array:\n”);


for(i=0;i<5;i++)
{
Scanf(“%d”,a[i]);
}
printf(“The elements of array are:\n”);
for(i=0;i<5;i++)
{
printf(“%d\t”,a[i]);
}
}

2) Two-Dimensional Arrays:-
 In this array we collect the data and organize it in the form of TABLE.
 Table format means data will be organized in rows and columns.
 So, this array is declared with two subscripts. One subscript will specify Row
Size and second subscript will specify Column Size.
 A two-Dimensional array is called as Array of Arrays.
 DECLARATION OF TWO-DIMENSIONAL ARRAYS:-
The following syntax is used to declare a two-dimensional array:-

Data-type arrayname [RowSIZE] [ColumnSIZE];

4
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

In the above syntax:


Data-type--- indicates what type of elements/data you are going to collect.
Arrayname- name for an array.
[RowSIZE]- first subscript to specify how many rows you require.
[ColumnSIZE]-- second subscript to specify how many columns you require.
Example:-
int a[2][3];
This declaration tells the compiler that a is array which requires 2 columns and 3 columns.
 INITIALIZATION OF TWO-DIMENSIONAL ARRAY:-
 Initialization and Accessing elements of Two-dimensional array at compile
time:-
1) Declare and initialize the elements:-
int a[Row-Size][Column-Size] = { list of values};
Example: int [2][3] = {{1,2,3},{4,5,6}};
In the above example the array consists of 2 rows and 3 columns so, we have to fill 2
rows of data where each row consists of 3 columns of data.
If you initialize in the following way
int [2][3] = {0};
Then all the elements are initialized with Zeros.
2) Accessing the elements of two dimensional arrays:-
To access the elements of two-dimensional arrays we have to specify row and
column.
Example:-
In the above array if I want to access 1st row 3rd column element i.e. (3) we have to
write the following statement code
printf(“%d”, a[0][2]);
here oth index indicates 1st row and 2 indicates 3rd element.
So, we are accessing 1st row 3rd column data.
Syntax:- printf(“ format specifier”,arrayname[row-index][column-index]);
If we have to access all the elements at a time from two-dimensional array we have to
use a loop in the following way:-

for(i=0;i<ROWSIZE;i++)
{
for(j=0;j<COLOUMNSIZE;j++)
{
printf(“%d\t”,arrayname[i][j]);
}
printf(“\n”);
}

5
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 Initialization and accessing the elements of two-dimensional array at


RUNTIME:-

 To initialize two-dimensional array at runtime use a loop and read elements


from keyboard using scanf () function.
 The following code snippet is used to read elements that are provided at
runtime.

for(i=0;i<ROWSIZE;i++)
{
for(j=0;j<COLOUMNSIZE;j++)
{

scanf(“%d”,arrayname[i][j]);
}
printf(“\n”);
}

 To access the elements from two-dimensional array we use the following code
snippet:-

for(i=0;i<ROWSIZE;i++)
{
for(j=0;j<COLOUMNSIZE;j++)
{
printf(“%d\t”,arrayname[i][j]);
}
printf(“\n”);
}

Note:-
 First for loop is used to access ROWS and second for loop is used to access column
data.
 In first loop i is a variable which will indicate a row and j variable in the second loop
will indicate a column.

6
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Example:-
/* W.A.P in C to Declare, initialize and Access the elements of a Two-
Dimensional Array */

void main()
{
int a[2][3];
int i,j;
printf(“Enter the elements of an array:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,a[i][j]);
}
}
printf(“ Displaying the array elements:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(“%d”,a[i][j]);
}
}
}

3) MULTI-DIMENSIONAL ARRAYS:-
 Multidimensional arrays can be described as "arrays of arrays".
 It’s very difficult to handle these arrays. Because this array holds huge amount of
data. So, it’s difficult to handle and understand these arrays.
 We can simply say that an array which consists more than 2 subscripts is considered
as multi-dimensional arrays.
 DECLARING A MULTI-DIMENSIONAL ARRAY:-
To declare a multi-dimensional array we use the following syntax.

Data-type array_name[d1][d2][d3][d4]………[dn];

In the above syntax:-


Data-type ----  type of data you are collecting.
array_name --  name of the array.
[][][]……[]----------  multiple subscripts.
Where each d is a dimension, and dn is the size of final dimension.
Example: - int table [5][5][20];
 int designates the array type integer.
 table is the name of our 3D array. 
 Our array can hold 500 integer-type elements. This number is reached by multiplying
the value of each dimension. In this case: 5x5x20=500.

7
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Explanation of a 3D Array:-
Let's take a closer look at a 3D array. A 3D array is essentially an array of arrays of arrays:
it's an array or collection of 2D arrays and a 2D array is an array of 1D array.The diagram
below may help you understand:

#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, k;
int arr[3][3][3];
clrscr();
printf(":::Enter 3D Array Elements:::\n\n");

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
scanf("%d",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}
printf(":::Displaying 3D Array Elements:::\n\n");

for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
for(k=0;k<3;k++)
{
printf("%d\t",arr[i][j][k]);
}
printf("\n");
}
printf("\n");
}

getch();
}

8
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 ARRAYS IN FUNCTIONS (or) INTER FUNCTION COMMUNICATION


WITH ARRAYS:-
 In this concept we see how can we pass an Array to function for inter function
communication.
 Array can be passed to functions in different ways they are:-
1) Passing entire array to a function:-
In this method we will pass entire array as argument to a function.
We shall see how to do this step by step:-
1) Declare a function which accepts an Array as a Parameter i.e. the function will
be declared with one parameter which is of type Array.
2) Then call this function by passing the name of array as parameter so, that the
entire elements of array are passed to function.
/* Simple Program that demonstrate how to pass array as parameter
to a function. The function accepts an array as parameter and then
it displays the elements of that array.*/

void display(int a[]);


void main()
{
int a[5] = {1,2,3,4,5};
display(a);
}
Void display(int a[5])
{
printf(“ The elements of array are:\n”);
for(i=0;i<5;i++)
{
printf(“%d\t”,a[i]);
}
}

 In the above code we have declared a function which accepts one


parameter of array type.
 In the main function we have one array of 5 elements to display
the elements of this array main function calls display function
by passing the name of the array to function.
 Then the control gets transferred to the definition of the
function. The array elements are assigned to the array which is
declared inside function header then the elements are displayed
by this function.
/* We shall see another C program which displays the maximum element from
the list of integers using function.*/

9
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

#include <stdio.h>
int maximum( int [] );
int maximum( int values[5] )
{
int max_value, i;

max_value = values[0];
for( i = 0; i < 5; ++i )
{
if( values[i] > max_value )
max_value = values[i];
}
return max_value;
}

main()
{
int values[5], i, max;
printf("Enter 5 numbers\n");
for( i = 0; i < 5; ++i )
{
scanf("%d", &values[i] );
}

max = maximum( values );


printf("\nMaximum value is %d\n", max );
}

Sample Program Output


Enter 5 numbers
7 23 45 9 121
Maximum value is 121
Note: -

 Same procedure is used to pass a two-dimensional array to a function.


 Function should be declared with a parameter of type two-dimensional array.
 Call this function by passing two-dimensional array name.
2) Passing individual elements of array as parameter to Function:-
 This is same as passing data values. Here we are passing an individual array element
at a time to the function.
 The called function cannot tell whether the value it receives comes from an array, or a
variable.
void display(int)
void main()
{
int a[5] = {1,2,3,4,5};
int i;
for(i=0;i<5;i++)
{
display(a[i]);
}
}
void display(int x)
{
printf(“\n element = %d”,x);
}

10
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 ARRAY APPLICATIONS:-
Applications of Arrays:-
 Store elements of same data type.
 Used for manipulating multiple variable names using single name.
 Used for sorting elements.
 Used for performing matrix operation.
 Used in CPU Scheduling.
 Used in recursive functions.
 LIMITATIONS OF ARRAYS:-
1) Static Data:-
Array is static data structure. Memory allocated during compile time cannot be
changed during run time.
2) Cannot hold Different Data types:-
Array cannot hold data of different data type.
3) Inserting data in array is difficult:-
Inserting data into array is difficult because before inserting the data in array
we have to crate empty space by shifting other elements one position a head.
This operation is faster if the size of array is smaller, but same operation will
be more and more time consuming and non-efficient in case of array with
large size.
4) Deletion operation is difficult:-
Deletion is not easy because the elements are stored in contiguous memory
location. After deletion of element from the array empty space will be
created that should be filled by moving elements up in the array.
5) Wastage of Memory: - waste of memory if array is defined with large size.

 Compare and contrast Call by value with Call by reference:-

Call by Value Call by Reference

When Function is called the values of When a function is called address


variables are passed. of variables is passed.

Formal parameters contain the value of Formal parameters contain the


actual parameters. address of actual parameters.
The actual parameters are
Change of formal parameters in the
changed since the formal
function will not affect the actual
parameters indirectly manipulate
parameters in the calling function
the actual parameters
Execution is slower since all the values
Execution is faster since only
have to be copied into formal
addresses are copied.
parameters.

11
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Functions:-

Designing Structured Programs:-

Structured Programming: - is a method of writing a computer program that uses

 Top-Down analysis for problem solving


 Modularization for program structure and organization
 Structured code for the individual modules.

Top-Down Analysis: -

A program is written to tell the computer what to do. But what do you want it to do?
What is the job you want it to perform for you? This job is more formally called the
PROBLEM. However, before you can tell the computer what to do, you have to solve the
problem yourself. In other words, we have to state every step necessary in order to accomplish
the job. This activity is called Problem solving or Problem Analysis. For big problems,
developing a solution can be very complicated. So, Top-Down analysis is a method of problem
solving. It tells you how to start and guides you through the entire process. The idea is to
subdivide a large problem into several smaller tasks or parts. Top-Down analysis, therefore,
simplifies or reduces the complexity of the process of problem solving.

Modular Programming:-

Programs generally require many instructions for the computer. Modular programming is a
method of organizing these instructions. Large programs are broke down into separate,smaller
sections called modules, subroutines, or subprograms. Each module has a specific job to do and
is relatively easy to write. Thus, modular programming simplifies the task of programming by
making use of a highly structured organizational plan. There is, of course, a direct correlation
between the subdivisions of the problem obtained through a top-down analysis and the
modules: each subdivision will correspond to a module in the program.

Structured Coding:-

In structured programming instructions are organized within various structures. A control


structure represents a unique pattern of execution for a specific set of instructions. It determines
the precise order in which the set of instructions is executed.

Each control structure represents a different pattern of execution, but each of these patterns in
turn represents one of three basic types of execution. The component statements within a
specific control structure are executed either sequentially, conditionally, repetitively.

1
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

The order in which the instructions in a module are executed is determined exclusively by the
use of control structures, the module is said to be structured and the code is described as
structured code.

Function:-

 Function is block or part of program.


 We use functions when we need to reduce a long code into smaller code
(or) when we need to execute same code “n” number of times.

Definition:-

Function is a self-contained block of statements which performs a coherent (means Logical)


task of same kind.

(Or)

A function is a self-contained block of code that carries out some specific and well-defined
task.

Functions in C:-

C functions are classified into two types:

1) Library functions: - these are built in functions available in standard library of C. The
standard C library is collection of various types of functions which perform some standard
and predefined tasks.

Examples:-

 printf() and scanf() of C performs I/O operations which are defined in standard library
of C i.e. <stdio.h>
 pow(), sqrt(), ceil(),floor() etc… Mathematical calculations functions are defined in
standard library <math.h>
 clrscr(), getch(), etc…. performs console operations which are defined in <conio.h>
standard library.
 malloc(), calloc(), free() etc… performs Memory allocation which are defined in
<stdlib.h> standard library.

Note:- whenever we require to use these library functions in our programs we have to
include the standard library otherwise we can’t use them in our programs. To include
the standard library files to our program we use the instruction #include <library
filename>.

2
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Ex:- to use pow( ) function defined in math.h library we write the following
instruction

#include <math.h>

2) User-defined functions: - A function which is declared and defined by the programmer to


perform a specific task in a program is user-defined function.

The main aim of function is to divide and conquer by which a complicated task will be
successively divided into smaller and more manageable task which can be handled easily.
This function is a complete and independent program which can be used by any other
subprograms.

Advantages of Using Functions:-

 We can handle the programs easily.


 Debugging is more suitable for programs.
 Reduces the size of program.
 Easy to understand the actual Logic of a program.
 It is possible to construct Modular and Structured programs.

Function:-
Is a self-contained block of statements which performs a coherent task of a same kind.

Functionality of a C Function:-

 C program doesn’t execute the functions directly.


 In order to execute a function it is required to invoke (i.e. call) that function.
 When we call any function in a C program then the program control goes to the body
of a function. Then the statement of body-of –the function gets executed.
 So, in order to execute the statements in the body of a function we have to call that
function.
Steps to perform before calling a Function:-
1) Declare the function.
2) Define that function.
3) Call the function.

3
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

1) Declaration of functions:-

To declare a function in C we have to follow the following syntax:


<return-type><function-name>(<parameter1>,<parameter2>… ...... <parameter>);

In the above syntax


return-type -------  is the type of data the function returns.
function-name -------------name of a function.
( ) ---------------------------  parentheses are used to pass arguments/parameters.
Function can accept any N number of parameters or may not accept any parameters it
depends on how you are going to declare and define it.

Example: - int Sum (int x, int y);


return-type is int -------  function returns integer data.
Sum----------------------  is function name.
(int x, int y) ------------- Parentheses consist of two arguments x.y of integer type data.
We can also call function declaration as function prototype.
A function prototype:-
1) Will identify the return type of the function so that the compiler can generate the correct
code for the return data.
2) It also specifies the type and number of arguments used by the function.

2) Defining a function / definition of a function:-


To define a function we have to use the follow syntax:
<return-type><function-name>(<parameter1>,<parameter2>… ..... <parameter>)
{
/* statements may be executable as well as declaration statements */
Statement1;
Statement2;
Statement 3;
…………….
Statement n;
return [<expression>];
}

In the above syntax there are two parts

1) <return-type><function-name>(<parameter1>,<parameter2>… ...... <parameter>)

4
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

This is called function header which consists of the returntype, the function name, and the
formal parameters.

2) {

/* statements may be executable as well as declaration statements */

Statement1;

Statement2;

Statement 3;

…………….

Statement n;

return [<expression>];

This is called the function body which contains local declarations and function
statements.

Example:-

int Sum(int x, int y)


{
int s;
s = x+y;
return s;
}

3) Call the function:-

Calling a function can be done by its name. In our sample example we declared and defined
Sum () function so, if any function wants to use this function it should call this Sum() function
by its name.

The function who calls any function is known as Calling Function.

The function that was called is known as Called Function.

Syntax: - to call a function.

/* call to a function without passing parameters */

function-name( );
5
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

/* call to a function by passing parameters */

function-name(a,b);

/* Sample code which shows how to declare, define and call a function */

int Sum(int a, int b); ----------  declaration of function


int main()
{
int p;

p Sum(3, 4);
= ---------------------------------  call to function

printf(“%d”,p);
return 0;
}

int Sum(int a, int b)


{ function defination
int s;
s = a+b;
return s;
}

 return Keyword:-

return is keyword of c. when the control reaches to the return keyword it immediately
terminates the execution of that function and transfer the control to the calling function.

Syntax:- return [<expression>];

Features of return type of function:-


 Default return type of the function is signed int data type.
 Function can return only one value at a time.
 Storage classes allowed with return type are static, extern, typedef. We cannot use
auto and register storage classes with the return type of any function.
 Default storage class of return type of a function is extern.
 In return type we can use modifier like
short,long,signed,unsigned,extern,const,volatile etc.. .

6
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Types of return statements:-


 return statement is used to return a value from called function to calling function.
 return statements are divided in to two types:-
1) Plain return :- the plain return acts as closed brace of a function i.e it doesn’t
return any value to the calling function.
Syntax:- return;

2) return with expression:- it returns evaluated value of expression to the calling


function.
Syntax: - return <expression>;

7
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 FUNCTION CATEGORY(S):-

Functions can be categorized into 4 based on their return value and parameters/arguments they
are:-

1. Functions with no arguments and no return value.

1) A C function without any arguments means you cannot pass data (values like int, char
etc) to the called function.
2) Similarly, function with no return type does not pass back data to the calling function.
3) It is one of the simplest types of function in C.
4) This type of function which does not return any value cannot be used in an expression it
can be used only as independent statement.
Let’s have an example to illustrate this.
#include<stdio.h>
#include<conio.h>

void printline()
{
int i;
printf("\n");
for(i=0;i<30;i++)
{
printf("-");
}
printf("\n");
}

void main()
{
clrscr();
printf("Welcome to function in C");
printline();
printf("Function easy to learn.");
printline();
getch();
}

Diagrammatical representation of the function functionality.

8
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

2. Functions with arguments and no return value.

1) In our previous example what we have noticed that “main()” function has no control
over the UDF “printfline()”, it cannot control its output. Whenever “main()” calls
“printline()”, it simply prints line every time. So the result remains the same.

A C function with arguments can perform much better than previous function type.
2) This type of function can accept data from calling function. In other words, you send
data to the called function from calling function but you cannot send result data back
to the calling function.
3) Rather, it displays the result on the terminal.
4) But we can control the output of function by providing various values as arguments.
Let’s have an example.

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

void add(int x, int y)


{
int result;
result = x+y;
printf("Sum of %d and %d is %d.\n\n",x,y,result);
}

void main()
{
clrscr();
add(30,15);
add(63,49);
add(952,321);
getch();
}

Functionality process:-

3. Functions with arguments and return value.


1) This type of function can send arguments (data) from the calling function to the called
function and wait for the result to be returned back from the called function back to the
calling function.
2) And this type of function is mostly used in programming world because it can do two way
communications; it can accept data as arguments as well as can send back data as return
value.
3) The data returned by the function can be used later in our program for further calculations.

9
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Example:-

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

int add(int x, int y)


{
int result;
result = x+y;
return(result);
}

void main()
{
int z;
clrscr();

z = add(952,321);
printf("Result %d.\n\n",add(30,55));
printf("Result %d.\n\n",z);

getch();
}

Functionality process:-

4. Functions with no arguments but returns value.


1) We may need a function which does not take any argument but only returns values to the
calling function then this type of function is useful.
2) The best example of this type of function is “getchar()” library function which is
declared in the header file “stdio.h”.
3) We can declare a similar library function of own.
Example.
#include<stdio.h>
#include<conio.h>

int send()
{
int no1;
printf("Enter a no : ");
scanf("%d",&no1);
return(no1);
}

10
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

void main()
{
int z;
clrscr();
z = send();
printf("\nYou entered : %d.", z);
getch();
}

Functionality process:
5. Functions that return multiple values.
1) So far, we have learned and seen that in a function, return statement was able to
return only single value. That is because; a return statement can return only one
value. But if we want to send back more than one value then how we could do this?
2) We have used arguments to send values to the called function, in the same way we
can also use arguments to send back information to the calling function.
3) The arguments that are used to send back data are called Output Parameters.
Example: Using Pointer concept
#include<stdio.h>
#include<conio.h>

void calc(int x, int y, int *add, int *sub)


{
*add = x+y;
*sub = x-y;
}

void main()
{
int a=20, b=11, p,q;
clrscr();
calc(a,b,&p,&q);
printf("Sum = %d, Sub = %d",p,q);
getch();}

11
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 INTER FUNCTION COMMUNICATION:-


 The communication between the calling function and called function for the exchange
of data is referred as Inter function communication.

 The called function and calling functions exchange the data(i.e) flow of data between
called and calling functions can be done in 3 different ways:-

1) DOWNWARD FLOW:-
1) The data flow will be from calling function to called function i.e. calling function will
pass data to called function. But, the called function doesn’t send any data back to
calling function. So, the downward communication can be referred as One-Way
Communication.

2) In this procedure, copies of data items are passed from calling function to the called
function.

3) The called function may change the values passed, but the original values in the
calling function doesn’t change it remains unchanged.

4) The CALL-BY-VALUE Mechanism is the best solution for the communication in the
downward direction.

Rules for downward communication:-

 When you call any function that function call statement should be by passing
parameters/Data. The parameters should be passed as Values (Call-by-value method).

 Called function parameter list should contain appropriate data values to receive the
data sent by calling function.

 Use the parameter identifiers (names) in the called function to access the local copies
of the data.

2) UPWARD COMMUNICATION:-
1) In this mechanism the called function sends data to the calling function. Calling
function doesn’t send the data to called function when it calls the called function.

2) The called function can send data to calling function by the help of return statement.
But, by using the return statement a function can send only one value.

3) Another thing to say about this mechanism is that if calling function calls the called
function and sends the address of some variables to called function then the original
values in the calling function will be changed.

4) To get the address of a variable, we use the address operator (&).


i. Ex:- fun_name(&a,&b)

12
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

5) The called function needs to declare that the parameter is to receive an address in
other words, it needs to create an address variable.
6) To declare an address variable, we can use an (*) asterisk.

Example:-
void assignValue(int *x, int *y);

int main()

int a,b;

assignValue(&a,&b);

printf(“%d %d\n”,a,b);

return 0;

void assignValue(int *x, int *y)

*x = 10;

*y = 20;

return;

Rules for upward communication:-

 To send data from the called function to calling function:

 We have to use the & symbol in front of the data variable when we call the function.

 We have to use * symbol after the data type when we declare the address variable.

 We have to use the * in front of the variable when we store data indirectly.

3) BI-DIRECTIONAL COMMUNICATION:-
In this procedure/Mechanism the calling sends data to called function (Data flows Down) and
the called function sends data to calling function (Data flows Up).

The rules for bi-directional communication are same as upward communication.

13
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 Parameter Passing Techniques:-


 How to pass parameters to function:-
 we can pass parameters in a function in two different ways:-
1) Pass-By-Value/Call-By-Value:-
In this approach we pass copy of actual variables in function as parameters. Hence
any modifications on these parameters inside the function will not reflect in the actual
variables.
2) Pass-By-Reference/Call-By-Reference: -
In this approach we pass memory address actual variables in function as parameters.
Hence any modifications on parameters inside the function will reflect in the actual variables.
Example:- /* Passing parameters to function using call-by-value technique */
#include <stdio.h>
int main()
{
int a = 5,b = 10;
swap(a,b); /*Here we pass values of a,b as parameters which are
called as Actual parameters */
printf(“%d%d”,a,b);
return 0;
}
/* Here a.b is assigned with values passed by calling function (i.e a
value and b value (Actual parameters) in called function a, b variables are
called Formal Parameters.*/
void swap(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
}
Example: - /* Parameter Passing using call-by-reference Technique */
#include <stdio.h>
int main()
{
int a = 5,b = 10;
swap(&a,&b); /*Here we pass references of a,b as parameters which
are called as Actual parameters */
printf(“%d%d”,a,b);
return 0;
}
/* Here a,b are pointer variables which are assigned with address
values passed by calling function (i.e. a address value and b
address value (Actual parameters) in called function a, b
variables are called Formal Parameters.*/
void swap(int *a, int *b)
{
int *temp;
*temp = *a;
*a = *b;
*b = *temp;
}

14
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

In this Technique a, b values will be modified if called function modifies the data. In this
example swap function is called function which had interchanged values of a and b. so, the
actual parameters are affected.
 SCOPE: - Region or Part of program in which variable is accessible.
 EXTENT: -

 Period of time during which memory is associated with variable.

 Actually every variable in a program has memory associated with it.

 Memory requirement of variables is different for different types of variables.

 In C, Memory is allocated & released at different places.

Storage Classes:-

1) Storage class Tells about:-

 Where the variable is stored.

 Scope of variable.

 Default initial value.

 Lifetime of variable.

Where the variable is stored:-

Storage class determines the location of variable, where it is declared.

Scope of variable: -

It tells the compiler about the visibility of variable in the block. Variable may have
block scope, local scope and external scope.

Default initial value of the variable:-

Whenever we declare a variable in C, garbage value is assigned to the variable.


Garbage value may be considered as initial value of the variable... C programming
have different storage classes which has different initial values such as global variable
have initial value as 0 while local auto variable have default initial garbage value.

Life Time Of variable:-

Lifetime of variable = Time of Declaration - Time of variable Destruction.

15
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 Types of Storage classes in C:-

1) Automatic (auto) storage class:-

 This is default storage class.

 All variables declared are of type auto by default.

 In order to explicit declaration of variable use auto keyword.

If we declare any variable with auto storage specifier then this Storage class Tells
about:-

 Where the variable is stored.

 Scope of variable.

 Default initial value.

 Lifetime of variable.
Every storage class specifier gives the above information. we see what information
does this auto storage specifier tells about variable in Tabular form.

Example:-

void main()
{
auto a = 20 ;
{
auto a= 60 ;
printf("nNum : %d",num);
}
printf("nNum : %d",num);
}

O/P :-?

16
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

2) External (extern) storage class:-

 Variables of this storage class are Global Variables.


 Global Variables are declared outside the function and are accessible to all functions
in the program.
 Generally, External variables are declared again in the function using keyword extern.
 In order to explicit declaration of variable use extern keyword

Example:-
int num = 75 ;

void display();

void main()
{
extern int num ;
printf("nNum : %d",num);
display();
}

void display()
{
extern int num ;
printf("nNum : %d",num);
}
O/P: - ??

3) Register Storage class:-


 Register keyword is used to define local variable.

 Local variable are stored in register instead of RAM.

 As variable is stored in register, the maximum size of variable = maximun size of


register.

 Unary operator (&) is not associated with it because value is not stored in RAM
instead it is stored in register.

 This is generally used for faster access.

 Common use is Counter.

17
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Example:-
#include<stdio.h>
int main()
{
int num1,num2;
register int sum;
printf("\nEnter the Number 1: ");
scanf("%d",&num1);
printf("\nEnter the Number 2 : ");
scanf("%d",&num2);
sum = num1 + num2;
printf("\nSum of Numbers : %d",sum);
return(0);
}

4) Static Storage (static) Class:-

 The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.

18
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 The static modifier may also be applied to global variables. When this is done, it
causes that variable's scope to be restricted to the file in which it is declared.
 In C programming, when static is used on a class data member, it causes only one
copy of that member to be shared by all objects of its class.

Example:-
#include <stdio.h>
/* function declaration */void func(void);
static int count = 5; /* global variable */main()
{
while(count--)
{
func();
}
return 0;
}
/* function definition */
void func( void )
{
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}

19
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 RECURSION:-
Recursive function:-
A function is called “recursive” if a statement within body of that function calls the same
function.
(OR)
A function which is called by it-self is called a recursive function.

Recursion is a repetitive step or Process where the function is called by it-self. This process
is called as circular definition.

Usage of a Recursive Concept:-

 In this concept it uses a Technique called “Divide and Conquer” Technique.


 Divide and Conquer Means it’s a problem solving technique in which we divide a
given problem into Sub problems. These sub problems will be solved which give the
original problem solution.
 Concept of recursive function:

 A recursive function is called to solve a problem.


 A recursive function will solve a simple problem very easily.
 If we give complex problems to solve, then the function divide the problem into 2
pieces: a part that it knows how to solve and another part that it does not know
how to solve.
 The part that it knows how to solve the problem is known as “Base Condition/Base
Case”.
 The part that it doesn’t know how to solve the problem is known as “Recursive (or)
Inductive (or) General Condition.
 So, in a recursive function we use two conditions 1) a base condition and
2) A recursive condition. In recursive condition we will have a statement which will
call the same function again and again until it reaches base condition. Once the base
condition is reached or satisfied then function stops calling by it-self.

20
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Example:-
/* Problem to find out “n” factorial */

Solution:-
Structure of the problem:-
1) A function takes one parameter/argument n.
2) Next we have to use two conditions to solve this problem using recursion they are:
To solve the factorial problem we divide the problem into two pieces as
discussed above One part which a function know how to solve the problem
and other part a function that it doesn’t know how to solve the problem.
i) BASE CONDITION:-
for this problem the base condition is
if (n==1)
return val = 1; /* Base */
ii) Recursive Condition/ Inductive Condition:-
if(n>1): then function gets called by itself by passing (n-1),(n-2).(n-3)….
So on as arguments until value of n is equal to 1. This recursive (a function calling by
it-self) step continues until the base condition is reached.

Program code:-

fact :n
BASE : (n==1) : value =1
INDUCTIVE : (n>1) : x = fact(n-1)
value = n*x

Code Snippet for declaring a recursive program:

int factorial(int n);


int main()
{

int n,fact;
printf(“Enter a value for n:\n”);
scanf(“%d”,&n);
fact = factorial(n);
printf(“The factorial of %d = %d”,n,fact);
}

int factorial(int n)
{
int value,x;
if(n==1) /* Base condition*/
{
value = 1;
return value;
}
else
{
X = factorial(n-1); /*This is Recursive step*/
value = n*x;
}
return (value);
}

21
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

Advantages of Recursion:-
 Avoidance of unnecessary calling of functions.
 A substitute for iteration where the iterative solution is very complex.
 For example to reduce the code size for Tower of Honai
application, a recursive Function is best suited.
 Extremely useful when applying the same solution.
Disadvantages of Recursion:-
 Recursive calling increase the space complexity.
 Recursive solution is always logical and it is very difficult to trace.(debug and
understand).
 Before each recursive calls current values of the variables in the function is stored in
the PCB, i.e. process control block and this PCB is pushed in the OS Stack.
 So sometimes a lot of free memory is required for recursive solutions.
 By too many recursive functions there may be confusion in the code.
 Recursion takes a lot of stack space, usually not considerable when the program is
small and running on a PC.
 It is very hard to debug or extend the functionality in case of recursive logic.
 In recursive we must have an if statement somewhere to force the function to return
without the recursive call being executed, Otherwise the function Will never return.
 Limitations of Recursion:-

 Recursion works best when the algorithm uses a data structure that naturally supports
recursion. For example, Trees are a naturally recursive structure and recursion works
well with them. In other cases, the algorithm is naturally suited to recursion. For
example, the binary search algorithm ends itself to a natural recursive algorithm. On
the other hand, not all looping algorithms can or should be implemented with a
recursion.
 Recursive solutions may involve extensive overhead because they use calls. When a
call is made, it takes time to build a stack frame and push it into the stack. Conversely,
when a return is executed, the stack frame must be popped from the stack and the
local variables reset to their previous values. Again, this takes time. A recursive
algorithm therefore generally runs slower than its non-recursive implementation.
 Each time we make a call we use up some of our memory allocation. If the recursion
is deep – that is, if there are many recursive calls – then we may run out of memory.
Therefore, the algorithms we have discussed so far (factorial) is better developed
iteratively if large numbers are involved. As a general rule, recursive algorithms
should be used only when their efficiency is logarithmic.

(Or) Simply remember that Recursion should not be used if the answer to any of the
following questions is no:

 Is the algorithm or data structure naturally suited to recursion (tree is the first
choice)?
 Is the recursive solution shorter and more understandable?
 Does the recursive solution run within acceptable time and space limits?
 As a general rule, recursive algorithms should be effectively used only when their
efficiency is logarithmic.
22
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)

 Compare and contrast Iteration with Recursion:-

ITERATION RECURSTION
Iteration explicitly uses repetition structure Recursion achieves repetition by calling the
same function repeatedly
Iteration is terminated when the loop condition Recursion is terminated when base case is
fails satisfied
May have infinite loop if the loop condition Recursion is infinite if there is no base case or
never fails if base case never reaches

Iterative functions execute much faster and Recursive functions are slow and takes lot of
occupy less memory space memory space compared to iterative functions

23

You might also like