Functions
Functions
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:-
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:-
2
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
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]);
}
}
void main()
{
int a[5],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:-
4
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
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)
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];
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)
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] );
}
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.
11
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
Functions:-
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:-
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:-
Definition:-
(Or)
A function is a self-contained block of code that carries out some specific and well-defined
task.
Functions in C:-
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>
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.
Function:-
Is a self-contained block of statements which performs a coherent task of a same kind.
Functionality of a C Function:-
3
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
1) Declaration of functions:-
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) {
Statement1;
Statement2;
Statement 3;
…………….
Statement n;
return [<expression>];
This is called the function body which contains local declarations and function
statements.
Example:-
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.
function-name( );
5
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
function-name(a,b);
/* Sample code which shows how to declare, define and call a function */
p Sum(3, 4);
= --------------------------------- call to function
printf(“%d”,p);
return 0;
}
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.
6
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
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) 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();
}
8
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
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 main()
{
clrscr();
add(30,15);
add(63,49);
add(952,321);
getch();
}
Functionality process:-
9
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
Example:-
#include<stdio.h>
#include<conio.h>
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:-
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 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)
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.
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.
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;
*x = 10;
*y = 20;
return;
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).
13
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
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: -
Storage Classes:-
Scope of variable.
Lifetime of variable.
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.
15
Compiled and Executed by Mahesh Reddy Challa (Asst.prof, CSE Dept)
If we declare any variable with auto storage specifier then this Storage class Tells
about:-
Scope of variable.
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)
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: - ??
Unary operator (&) is not associated with it because value is not stored in RAM
instead it is stored in register.
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);
}
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.
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
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)
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