Unit III - Arrays and Functions (1)
Unit III - Arrays and Functions (1)
STRUCTURE
3.3 Introduction
3.4 Arrays
3.6 Functions
3.6.2 Recursion
3.7 Summary
3.8 Keywords
3.11 References
3.1 INTRODUCTION
An array is a group of elements (data items) that have common characteristics (Ex: Numeric
data, Character data etc.,) and share a common name. The elements of an array are
differentiated from one another by their positions within an array.
88
Each array element (i.e., each individual data item) is referred as specifying the array name
followed by its subscript enclosed in square brackets. The subscript indicates the position of
the particular element with respect to the rest of the element. The subscript must be a non-
negative number.
For example, in the n element array, x, the array elements are x [1], x [2], x [3], x [4] ….x[n]
and 1,2,3…n are the subscripts x[i] refers to the ith element in a list of n elements.
Depending on the number of subscripts used, arrays are classified into one-dimensional
arrays, two-dimensional arrays and so on.
3.2 ARRAY
Definition of Array
An array is defined to be a group of logically related data items of similar type stored in
contiguous memory location is called array.
Arrays whose elements are specified by a single subscript are called one-dimensional or
single dimensional array. It is used to store a list of values, all of which share a common
name and disguisable by subscripts values.
SYNTAX
type array-name[n];
Where,
array name->is the name of an array of n elements of the type specified. The size of an array
must be an integer constant.
89
Example
The integer array declaration int x[100] creates an array that is 100 elements long with the
first element being 0 and the last being 99.
The subscript used to declare an array is sometimes called a dimension and the declaration
for the array is often referred to as dimensioning. The dimension used to declare an array
must always be a positive integer constant, or an expression that can be evaluated to be
constant when the program is compiled. It is sometimes convenient to define an array size in
terms of the symbolic constant. For example i[20]=124.
An individual element in an array can be referred to by means of the subscript, the number
In brackets following the array name. A subscript is the number that specifies the elements
position in an array. In the C language, subscript begins with zero. Thus, the valid subscript
value can from 0 to n-1, if n is the dimension of array. The subscript value used to access an
array element could a binary expression etc. Thus, i[2] is not the second element of the array
I but the third.
Properties of an array
4. The size of the array is the length of the array times the size of the elements, but the
size of the array is usually referred as the product of subscript used.
Once the array is declared, how individual elements in the array are accessed. This is done
with the help of subscripts (i.e., number specified in the square brackets following the array
90
name). The subscript specifies the elements position in the array. The array elements are
numbered, starting from zero. The first item stored at the address pointed by the array name
itself. This can also be referred as position 0. Thus, the first element of the array age is
referred as age. The fourth element of the array is reoffered as age.
An array can be initialized when declared by specifying the values of some or all of its
elements. Array can be initialized at the time of declaration when their initial values are
known in advance. The values to initialize an array must be constants never variables or
function calls. The array can be initialized as follows:
int array[5]={4,6,5,7,2};
float x[6]={0,0.25,-0.50,0,0};
when an integer array is declared as int array [5] = {4,6,5,7,2}; the compiler will reserve ten
contiguous bytes in hold the five integer elements as shown in the diagram.
4 6 5 7 2
array [0] array [1] array [2] array [3] array [4]
The array size need not be specified explicitly. When initial values are included as a part of
an array declaration. With a numerical array, the array size will automatically be set equal to
the number initial values included within the declaration.
91
Thus, digits will be a six-element integer array, and x will be a four-element floating-point
array. The individual elements will be assigned the following values. The example given
below,
digits [0] =1; digits [1] =2; digits [2] =3; digits [3] =4; digits [4] =5; digits [5] =6;
in the above array initialization, although the array size is 10, values were defined only for
the first six elements. If fewer then all numbers have values specified, then the rest will have
undefined values.
Example 1
Write a program to get five person ages to calculate average of person age.
else
for(i=0;i<n;i++)
92
printf(“Age:”);
scanf(“%d”,&age[i]); sum=sum+age[i];
EXAMPLE 2
Write a program to get 10 elements, to display any one of the element in the given list.
int array[10]={10,20,30,40,50,60,70,80,90,100};
if(getchar()=‟Y‟);
}}
93
Arrays whose elements are specified by two subscripts are referred as two-dimensional arrays
or double dimensional arrays. A two-dimensional arrays of size m rows by n columns are
declared as follows:
type array-name[m][n];
A two-dimensional array two dimension of type int, 3 rows and 4 columns are declared as
follows:
EXAMPLE
Arrays can be stored in the memory in two orders. Row major order and column major order.
Multi-dimensional arrays are stored in memory using the row major order. Organization of
the array named two dims with 3 rows and 4 columns in the row major order is shown here:
Elements in a two-dimensional array can be accessed by means of a row and a column. The
row subscript generally is specified before the column subscript.
For example, two dim [1][3] will access the elements in two number 1(the second row) and in
a column number (fourth) of the array. In array notation, two dim [1] represents a row and
two dim [1][3] represents a column within that row. When initializing a two-dimensional
94
array at the time of array declaration, the elements will be assigned by rows, that are the
elements of the first row will be assigned, then the elements of the second and so on.
int values[3][4]={1,2,3,4,5,6,7,8,9,10,11,12}
values [2][0] =9 values [2][1] =10 values [2][2] =11 values [2][3] =12
The values can also be initialized by forming groups of initial values enclosed within braces.
The value within an integer pair of braces will be assigned to the elements of a row.
For Example,
};{1,2,3,4}
{5,6,7,8}
{9,10,11,12}
NOTE
1. If there are too few values within a pair of braces the reaming elements of that row will be
assigned zero.
2. If the number of values in each inner pair of braces exceeds the defined row size, it will
result a compilation error.
95
Like single-dimensional array, a double dimensional array can also be initialized. Arrays can
be initialized by the following ways,
Similar to single dimensional arrays, a double dimensional array can also be initialized with
one or more values during its declaration.
Where the storage type, may be either auto or register or static or extern. The storage type
while declaring an array is optional. The datatype specifies the type of elements that will be
stored in the array. The array name is the name used to identify the array. The rules for
naming array names are same as identifiers. Note that an array should not have the same
name as an ordinary variable in the same block or a function.
For Example
int marks[4][2];
marks[4][2]={82,44},
{92,65},
{73,64},
{65,100}.
The first subscript ranges from 0 to 3 and the second subscript ranges from 0 to 1. In the first
case, the first inner pair of braces are assigned to the array elements in the first row, the value
of second inner pair of braces are assigned to the array elements in the row and so on.
marks[0][0]=82 marks[0][1]=44
96
marks[1][0]=92 marks[1][1]=65
marks[2][0]=73 marks[2][1]=64
marks[3][1]=65 marks[3][2]=100
float amount[2][3]={70.50,90.74,50.75,75.10}
In the example, the size of the array is 6(3*2) and the values 1,2,3,4,5,6 are assigned to the
variable amount [0][0], amount [0][1] …. amount [2][1], amount [3][1] respectively. In the
second example’s row size is missing. While initializing an array, the second dimension (i.e.,
Col size) is missing, but the first dimension (i.e., row size) is optional.
An array can be initialized by using for loop, a while loop or do-while loop. The given
example illustrates the use of initializing an array using for loops.
Examples for initializing an array using a for loop, int i, j, mark [5][5]
In the example, the for loop initializes all the program elements of the array to zero.
Similarly, array elements of the index to zero. Similarly, array can also be initialized while
loop and do- while loops.
data-type variable-name[row-size][col-size];
where,
97
data-type->refers to any valid c data-type.
row-size->indicates the number of rows and column size indicates the number of elements in
each row
Row size and column size should be integer consists or convertible into integer values. Total
number of locations allocated will be equal to row size* column size. Each element in a 2D
array is identified by the array name followed by a pair of square brackets enclosing its row-
number, followed by a pair of square brackets enclosing its column-number. Row number
ranges from 0 to row-size-1 and column number ranges from 0 to column size-1.
Example
int a[3][3];
Where, a declared to be an array of two dimensions and of data type int. Row size and
column size of a 3 and e respectively. Memory gets allocated to accommodate the array are
as follows. It is important to note that a is the column name shared by all the elements of the
array.
column numbers
0 1 2
Each data item in the array a is identifiable by specifying the array name a followed by a pair
of square brackets enclosing row number, followed by a pair of square brackets enclosing
98
row number followed by a pair of square brackets enclosing column number. Row-number
ranges from 0 to 2 that are first row is identified by row-number 0, second row is identified
by row- number 1 and so on. Similarly, column-number ranges from 0 to 2. First column is
identified by column-number 0, second column is identified by column-number 1 and so on.
a [0][0] refers to data item in the first row and first column a [0[1] refers to data item in the
first row and second column
a [3][3] refers to data item in the fourth row and fourth column a [3][4] refers to data item in
the fourth row and fifth column
Example 1
for(j=4;j<4;j++)
scanf(“%d”,&a[i][j]);
printf(“Matrix a \n”);
for(i=0;i<3;i++)
for(j=0;j<4;j++)
printf(“%4d”,a[i][j]); printf(“\n”);
99
getch();
Example 2
#include<stdio.h>
void main()
int num[5][5],i,j,m,n,sum=0;
scanf(“%d %d”,&m,&n);
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf(“%d”,&num[i][j]);
for(i=0;i<n;i++)
for(j=0;j<n;j++)
sum=sum+num[i][j];
Example 3
#include<stdio.h>
100
#include<conio.h>
void main()
int a[3][3],b[3][3],c[3][3],I,j,m,n,p,q;
scanf(“%d %d”,&p,&q);
for(i=0;i<n;++i)
for(j=0;j<m;++j)
scanf(“%d”,&a[i][j]);
for(i=0;i<n++i)
for(j=0;j<m;++j)
scanf(“%d”,&b[i][j]);
for(i=0;i<n;++i)
for(j=0;j<m;++j)
c[i][j]=a[i][j]+b[i][j];
for(i=0;i<n;++i)
101
}
elsefor(j=0;j<m;++j)
printf(“%5d”,c[i][j]);
printf(“\n”);
String is a sequence of characters that is treated as a single data item and terminated by null
character'\0'. Remember that C language does not support strings as a data type. A string is
actually one-dimensional array of characters in C language. These are often used to create
meaningful and readable programs.
For example : The string "hello world" contains 12 characters including '\0' character which
is automatically added by the compiler at the end of the string.
char name[12]={ 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 'i', 'n', 'k', '\0' }; //valid initialization
Remember that when you initialize a character array by listings all its characters separately
then you must supply the '\0' character explicitly.
3.4 FUNCTIONS
In this unit, you study about user has chosen the function name, return data type and
arguments (numbers and type), are called user-defined functions.
102
In C functions can be classified into two categories,
1. Library functions
2. User-defined functions
This is greatest features in C is that there is no conceptual difference between the user-
defined functions and library functions. For example, we can write a series of function to
process matrices (such as square of given number, finding cos value, finding sine value, etc.).
These are user-defined functions they are written by user. After user, they can be compiled
into libraries and distributed. To the users of the library, these functions will act as library
functions. That is these functions are predefined and precompiled; the users need not worry
about the functions work internally
A function depending upon the arguments present or not and whether a value is returned or
not, may be classified as
103
The use of functions in C has many advantages:
2. The length of a source program can be reduced by using functions at an appropriate Places.
They are three elements that are related to user defined functions are:
1. Function definition
2. Function call
3. Function declaration
Function Definition
1. Function name
2. Function type
3. List of parameters
5. Function statements
6. A return statements
104
All the six elements are grouped into two parts, namely,
Function header
Function body
SYNTAX
return-type function-name(parameters)
{
Declarations;
Statements;
return value;
}
where,
parameters comma->separated list of types and names of parameters value-> value returned
upon termination (not needed if return-type void)
And represents external values needed by the function. The list of parameters can be empty.
All declarations and statements that are valid in the main program can be used in the Function
definition, where they make up the function body.
Function Header
The function header consists of three parts: The function type (also known as return type, the
function name and the formal parameters list. Note that a semicolon is not used at the end of
the function header.
105
Function Body
The function body contains the declarations and statements necessary for performing the
required task. The body enclosed in braces, contains three parts, and is given below:
return (x+y)/2;
The return statement forces the function to return immediately, possibly before reaching the
end of the function body.
Function Call
A function can be called by simply using the function name followed by a list of actual
parameters (or arguments), if any, enclosed in parentheses.
SYNTAX
Variable=function-name (arguments);
The arguments are values with types corresponding to the function parameters.
EXAMPLE
106
int main(int argc, char **argv)
Implicit type conversion is used when the types of the arguments and parameters do not
agree.
When a function is called the value of the argument is copied to the corresponding parameter.
Changes made to the parameter inside the function will not affect the argument (call by
value).
EXAMPLE
i--;
void main()
107
Function Declaration
Like variables all function in a C program must be declared, before they are invoked. A
function declaration (also known as function prototype) consists of four parts.
SYNTAX
1. Function name
2. Parameter list
3. Terminating semicolon
Declaration is not necessary if the function definition precedes the first call.
Definition of functions
1. Argument declaration
108
2. Body of the function
The first part of the function specification consists of type specification of the value returned
by the function followed by the function name, a set of arguments (may or may not be
present) separated by commas and enclosed in parenthesis. If the function definition does not
include any arguments, an empty pair of parentheses must follow the function name.
SYNTAX
where
return type->specifies the data type value to be returned by the function. The return type is
assumed to be of type int by default if it is not specified.
function name-> used to identify the function. The rules for naming a function are Same as
identifiers.
argument list->specified inside the parenthesis after the function name is optional.
Most functions have list of parameters and a return value that provides means for
communication between functions. The arguments in the function reference, which defines
the data items that are actually transferred, are referred as actual arguments or actual
parameters. All variables declared in function definitions are local variables. Their scope is
visible known only in the function in which they are defined. Functions arguments are als0
local variables.
109
EXAMPLE
Write a program for sum of two numbers and return the sum to the main function.
int addnum(int,int);
int sum,a,b;
scanf(“%d %d”,&a,&b);
sum=addnum(a,b);
int addnum(num1,num2)
The above program consists of two functions, The required main function
The programmer defined function addnum, which sums the two values.
The function main reads in two integer values, and assigns them to a and b. Then, main calls
addnum, transferring the integer values a and b receiving their sum. The sum is then
displayed and the program terminates.
The integer values are transferred via the arguments num1 and num2,and their sum tot is
returned to the calling portion of the program via the return statement.
110
Return values and their types
The return statement is used to return the control from the calling function to the next
statement of the called portion of the program. The return statement also causes program
logically to return to the point from where the function is accessed (called).The return
statement returns one value per call.
The return statement can be any one of the types as shown below, return;
The first and second return() statements, does not return any value, and are just equal to the
closing brace of the function. If the function reaches the end without using a return statement,
the control is simply transferred back to the calling portion of the program without returning
any value. The return() statement returns a value 1 to the calling function. The third return()
statements return a value 1 to the calling function.
The exit() is build-in function available as part of C library. The common thing shared by
both the return statement and the exit() is that both are used to exit the function in which they
are used.
EXAMPLE 1
if(fact<=1) return(1);
This return() statement returns a constant q when the condition specified inside the if
statement evaluates to true.
EXAMPLE 2
return(num1+num2+num3);
111
This return() statement returns a value depending upon the result of the conditional
expression specified inside the parenthesis.
EXAMPLE 3
return(power(5,2));
This return() statement calls the function specified inside the parenthesis and collects the
result obtained from that function, and returns it to the calling function.
NOTE
1 The limitation of a return statement is that it can return only one value from the
called function to the calling function.
2 The return statement can be present anywhere in the function, not necessarily at the
end of the function.
3 Number of return statements used in a function is not restricted, since the return
statement which executes first will return the value from the called function to the
calling function and the other return statements are left unexpected.
4 If the called function does not return any value, then the keyword void must be used
as the return specifier.
5 Parenthesis used around the expression in a return statement is optional.
Function Prototypes
A C function returns an integer value by default. Whenever a call is made to a function the
compiler assumes that this function would return a value of type int.If you decide that a
function should return a value other that int, then it is necessary to mention the first line of
the function in the program, before it is used, which is called the function prototype also
referred as the function declaration.
112
Function prototypes are usually written at the beginning of the program explicitly before all
user-defined functions including the main() function.
SYNTAX
where,
return type->represents the data type of the value that is returned by the function dt 1,dt 2…dt
n->represents the data types of the arguments
EXAMPLE
where sum is the name of the function, int before the function name sum() indicates that the
function returns a value of type int. The variable num inside the parenthesis is the parameter
passed to the called function. The data type int before the parameter num indicates that is
type integer.
3.4.2 Recursion
The process of calling a function by itself is called recursion and the function which calls
itself is called recursive function. Recursion is used to solve various mathematical problems
by dividing it into smaller problems. This method of solving a problem is called Divide and
Conquer.
113
In programming, it is used to divide complex problem into simpler ones and solving them
individually.
statements;
Flowchart of Recursion
114
Note: In order to prevent infinite recursive call, we need to define proper exit condition in a
recursive function.
#include<stdio.h>
int main()
printf("Hello world");
main();
return 0;
In this program, we are calling main() from main() which is recursion. But we haven’t
defined any condition for the program to exit. Hence this code will print “Hello world”
infinitely in the output screen.
Types of recursions
Direct Recursion
Indirect Recursion
Direct Recursion
if (n==1 || n==2)
return 1;
else
return (fibo(n-1)+fibo(n-2));
115
}
In this program, fibo() is a direct recursive function. This is because, inside fibo() function,
there is a statement which calls fibo() function again directly.
Indirect Recursion
A function is said to be indirect recursive if it calls another function and this new function
calls the first calling function again.
int func1(int n)
if (n<=1)
return 1;
else
return func2(n);
int func2(int n)
return func1(n);
In this program, func1() calls func2(), which is a new function. But this new
function func2() calls the first calling function, func1(), again. This makes the above function
an indirect recursive function.
3.5 SUMMARY
116
Three steps in using a function are declaring a function, defining a function and
calling the function.
A function is called by specifying its name, followed by a pair of parentheses, which
contains parameters if needed.
The argument that represents the names of data items that are transformed into the
function from the calling portion of the program are called as formal arguments or
formal parameters.
The corresponding arguments in the function reference which define the data items
that are actually transferred are called as actual arguments or actual parameters.
The return statement is used to return the information from the function to the calling
function of the program
A function may be declared anywhere as long as its declaration is above all reference
to the function. So, a function should be declared before it is called.
The execution of a function is terminated when it executes the return statement or
when the last statement of the function is executed or when it encounters the closing
brace of the function.
3.6 KEYWORDS
Main (): main () is a specifically recognized function in C. Every Program must have
a main () function to indicate where the program has to begin its execution.
Function Definition: function definition is an independent program module that is
specially written to implement the requirements of the function.
Function Call: The program or a function that calls the function is referred to as the
calling program or calling function.
Function Definition or Function Prototype: The calling program should declare any
function (like declaration of variable) that is to be used later in the program. This is
known as the function declaration or function prototype.
Function Body: The function body contains the declarations and statements
necessary for performing the required task. The body enclosed in braces, contains
three parts.
Return (): A return () statement that returns the value evaluated by the function.
117
Function parameters: Function parameters are the means of communication between
the calling and the called functions.
Formal parameters: The formal parameters (commonly called parameters) are the
parameters given the function declaration and function definition.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
A. Descriptive Questions
Short Questions
2. What is a function?
Long Questions
118
4. What is calling function?
4. The keyword used to transfer control from a function back to the calling function is
int **a;
a. switch
b. goto
c. go back
d. return
119
5. How many times the program will print "Algbly"?
int main() {
printf("Algbly");
main();
return 0;
}
a. Infinite times
b. 32767 times
c. 65535 times
d. Till stack overflows
Answer
3.9 REFERENCES
References Book
120