0 ratings0% found this document useful (0 votes) 53 views49 pagesModule 3 - Compressed
BPOPS103 arrays and functions
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
BPOPS103/203 Prof. Thameeza
MODULE - 3
ARRAYS
3.1 INTRODUCTION
+ Anarray is a collection of similar data elements. These data elements have the same data
type. The elements of the array are stored in consecutive memory locations and are
referenced by an index (also known as the subscript)
¢ The subscript is an ordinal number which is used to identify an element of the array.
3.2 DECLARATION OF ARRAYS
* Anarray must be declared before being used.
+ Arrays are declared using the following syntax: type name|size|;
* Declaring an array means specifying the following:
+ Data type—the kind of values it can store, for example, int, char, float, double, or any
other valid data type..
+ Name—to identify the array.
+ Size—the maximum number of values that the array can hold. i.e., the maximum
number of elements that can be stored in the array. For example, if we write, int
marks[10];
then the statement declares marks to be an array containing 10 elements. In C, the array
index starts from zero. The first element will be stored in marks[{0], second element in
marks[1], and so on. Therefore, the last element, that is the 10th element, will be stored in
marks[9]. Note that 0, 1, 2, 3 written within square brackets are the subscripts. In the
memory, the array will be stored as shown in Fig. 3.2.
| a | st |e
Seer
=
element
oe |] om | 108
= ri an
‘marks[0] marks{1] marks[2] marks[3] marks[4] marks{5] marks[6] marks{7] marks[8] marks{9]
Figure 3.2 Memory representation of an array of 10 elements
V Figure 3.3 shows how different types of arrays are declared.
[Link]BPOPS103/203 Prof. Thameeza
data type
1
Ant marks [10]; 1
‘array name I l
1
char nase [15] A} 2) £3) U4) 5) 06) C7) (8) (9) (109114912113) (14}
array size
|
flo airy [5]; 1 ft) 2 Bl
Figure 8.3. Declaring arays of citferent datatypes and sizes
3.3 Accessing The Elements Of An Array
© To access all the elements, we must use a loop. That is, we can access all the
elements of an array by varying the value of the subscript into the array.
But note that the subscript must be an integral value or an expression that evaluates
to an integral value.
* As shown in Fig. 3.2, the first element of the array marks[10] can be accessed by
writing marks[0]. Now to process all the elements of the array, we use a loop as shown
in Fig. 3.4.
U1 Set each element of the array to -2
int 1, marks[10];
For (i=03i<10; i++)
marks (1] =
Figure 3.4 Code to initialize each element of the
array to 1
+ Figure 3.5 shows the result of the code shown in Fig. 3.4. The code accesses every
individual element of the array and sets its value to —1. In the for loop, first the value of
marks[0] is set to —1, then the value of the index (i) is incremented and the next value,
that is, marks[1] is set to -1. The procedure continues until all the 10 elements of the
array are set to —1.
=4[-41[-1]-1[-7]-1]-1]-4[-1]-1
om wae ws ge mM B
Figure 3.5 Array marks after executing the code given in Fig. 3.4
Calculating the Address of Array Elements
+ The array name is a symbolic reference to the address of the first byte of the arr:
[Link]BPOPS103/203 Prof. Thameeza
«When we use the array name, we are actually referring to the first byte of the array.
+ The subscript or the index represents the offset from the beginning of the array to
the element being referenced.
+ That is, with just the array name and the index, C can calculate the address of any
element in the array.
* Since an array stores all its data elements in consecutive memory locations, storing just
the base address, that is the address of the first element in the array, is sufficient.
+ The address of other data elements can simply be calculated using the base address. The
formula to perform this calculation is,
Address of data element, A[k] = BA(A) + w(k — lower_bound)
Here, A is the array,
k is the index of the element of which we have to calculate
the address, BA is the base address of the array A, and
wis the size of one element in memory, for example, size of int is 2.
Example 3.1. Given an array int narks{} -(99,67,78,50,88,90, 4,85), calculate the address of
marks[4] if the base address - 1000.
Solution
Cae le se a]
marks{0] marks{1] marks{2] marks[3] marks[4] marks{5] marks{6] marks{7]
1000 1002 1004-1006. 1008-1010 1012-1014
‘We know that storing an integer value requires 2 bytes, therefore, its size is 2 bytes,
mmarks[4] = 1000 + 2(4 — 0)
= 1000 + 2(4) ~ 1008
Calculating The Length Of An Array
+ The length of an array is given by the number of elements stored in it.
+ The general formula to calculate the length of an array is
Length = upper_bound — lower_bound + 1
where, upper_bound is the index of the last element and lower_bound is the index of the
first element in the array.
Example 3.2 Let ages} be an egets such that
10 Agel] = 5, A 3, Agel?] = 1, Agela] = 7
Show the memory representation of the array and calculate its length
Solution
‘The memory representation of the array age[s} is given as below.
2 Eva seal]
AgefO] Age[1] Age[2] Age[3] Agel 4]
Lang = pn = wane ea
Here, Lover 2, upper bound = a
Therefore, 4-ovies
[Link]BPOPS103/203 Prof. Thameeza
4 Storing Values in Arrays
© When we declare an array, we are just allocating space for its elements; no values are
stored in the array.
+ There are three ways to store values in an array. First, to initialize the array elements
during declaration; second, to input values for individual elements from the
keyboard; third, to assign values to individual elements. © This is shown in Fig. 3.6.
Initialize the olements during declaration
Storing values in an array < Input values for the elements from the keyboard
“Siieme Values 10 individual elements
Figure 8.8 Storing values in an array
1. Initializing Arrays during Declaration
© The elements of an array can be initialized at the time of declaration, just as any
other variable.
© When an array is initialized, we need to provide a value for every element in the
array. () Arrays are initialized by writing,
type array_name[size|=f{list of values};
Note that the values are written within curly brackets and every value is separated by
acomma. It is a compiler error to specify more values than there are elements in the
array. When we write,
«int marks[5]={90, 82, 78, 95, 88}:
© Anarray with the name marks is declared that has enough space to store five elements.
The first element, that is, marks[0] is assigned value 90. Similarly, the second element
of the array, that is marks[1], is assigned 82, and so on. This is shown in Fig. 3.7.
marks{0] [90
marks(1] | 82
marks[2] | 78
marks[3] | 95
marks[4] | 88
Figure 3.7 Initialization of
array marks [5]
[Link]BPOPS103/203 Prof. Thameeza
While initializing the array at the time of declaration, the programmer may omit the size
of the array. For example, int marks[ J {98, 97, 90};
The above statement is absolutely legal. Here, the compiler will allocate enough space
for all the initialized elements. Note that if the number of values provided is less than the
number of elements in the array, the un-assigned elements are filled with zeros. Figure
3.8 shows the initialization of arrays.
int nas (31 (00, 45,67, 85,78; [Da eS
ome 8
sme marts (51 =(00,45; [SOLS
int mets (] «20, 45,72, 81,6,59; [So pas pe per
int marks [5] = (0);
Figure 3.8 niialization of array elements
In the code, we start at the index i at 0 and input the value for the first element of the
array. Since the array has 10 elements, we must input values for elements whose index
varies from 0 to 9.
3. Assigning Values to Individual Elements
© The third way is to assign values to individual elements of the array by using the
assignment operator.
© Any value that evaluates to the data type as that of the array can be assigned to the
individual array element.
© Assimple assignment statement can be written as marks[3] = 100;
© Here, 100 is assigned to the fourth element of the array which is specified as
marks[3]
© To copy an array, you must copy the value of every element of the first array into the
elements of the second array. Figure 3.10 illustrates the code to copy an array. In Fig.
3.10, the loop accesses each element of the first array and simultaneously assigns its
value to the corresponding clement of the second array. The index value i is
incremented to access the next element in succession. Therefore, when this code is
executed, arr2[0] = arrl[0}, arr2[1] = arrl[1], arr2{2] = arrl[2], and so on.
[Link]BPOPS103/203 Prof. Thameeza
int i, arri[io], arr2[10];
arri[10] = {0,1,2,3,4,5,6,7,8,9};
for(i=03icl0;i++)
arr2[i] = arra[i];
Figure 3.10 Code to copy an array at the
. individual element level
« For example, if we want to fill an array with even integers (starting from 0), then we
will write the code as shown in Fig. 3.11. In the code, we assign to each element a
value equal to twice of its index, where the index starts from 0, So after executing this
code, we will have arr{0] = 0, arr{1] = 2, arr{2] = 4, and so on.
// Fill an array with even numbers
int 4,arr[10];
For(i=0;i<10; i++)
arr[i] = i*25
Figure 3.11 Code for filling an array with
even numbers
5 Operations on Arrays
+ There are a number of operations that can be performed on arrays. ( These operations
include:
+ Traversing an array
+ Inserting an element in an array
+ Searching an element in an array
+ Deleting an element from an array
+ Merging two arrays
+ Sorting an array in ascending or descending order
Traversing an Array
Traversing an array means accessing each and every element of the array for a specific
purpose. Traversing the data elements of an array A can include printing every element,
counting the total number of elements, or performing any process on these elements.
* The algorithm for array traversal is given in Fig. 3.12.
[Link]: [INITIALIZATION] SET I = lower_bound
Repeat Steps 3 to 4 while I <= upper_bound
Apply Process to A[I]
set T=I+1
[END OF LOOP]
EXIT
Figure 3.12 Algorithm for array traversal
+ In Step 1, we initialize the index to the lower bound of the array. In Step 2, a while loop is
executed. Step 3 processes the individual array element as specified by the array name and
index value. Step 4 increments the index value so that the next array element could be
processed. The while loop in Step 2 is executed until all the elements in the array are
processed, i.e., until I is less than or equal to the upper bound of the array.
Example:
Write a program to read and display n numbers using an array.
#include
void main()
t
inti, n, a[10];
printf("Enter the number of elements in the array :"); scanf("%d",
&n);
printf(“Enter the array elements:\n”);
for(i=0;i} Setaa] Oxta[s] Sntalé] Oatal7] ote
(@) Since the elements of the array red in ascend:
will be stored after 67. j...at the
position will be moved one position towards the right 0 accommodate the new value
©
als] |e] 6| | | 7 | | 0 | 10
ata[0) Osta(1) Datal2} oate[3) ata[4) oata{s} Date(s] Data[7) Datale) Oate(>] Osta(ze)
Algorithm to Insert an Element in the Middle of an Array
+ The algorithm INSERT will be declared as INSERT (A, N, POS, VAL). The arguments
are
i A, the array in which the element has to be inserted
ii N, the number of elements in the array
iii POS, the position at which the element has to be inserted
iv VAL, the value that has to be inserted
* In the algorithm given in Fig, 3.14, in Step 1, we first initialize I with the total number
of elements in the array. In Step 2, a while loop is executed which will move all the
elements having an index greater than POS one position towards right to create space
for the new element. In Step 5, we increment the total number of elements in the array
by | and finally in Step 6, the new value is inserted at the desired position.
[Link][INITIALIZATION] SET T= 6
Ropest Steps 3 and 4 unite T >= POS.
Ser ars 2] = A(T)
setr=1-a
END oF Loop)
SET N= Ned
SET A[POS] = VAL
ext
Figure 3.14 Algorithm to insort an eloment in the middle
of an array,
Initia aseaqy given as below
Doral
Calling 1wsexr (outs, 6, 3, 100) will lead to the following processing in the array
a
Deta(o] Oat=Ia]
2] 6 |» | 2
Detaz] vata[3] oatals] ostals] oat2[6)
2 ]3f]s™if]«2]« |= | ~»
Data[O] Oveafa] boeofa] otal] Ootala] Owtafs] Oveale]
«os ||] 2 pw) «| ~
Datefo] Ovve[s] betel] ote(3] Sotals] Oates] oatalel
«= [2 ]™ >)m] 2] «|»
Oata(O} Oaea[a] baeal2] Oets[>] Geta[s] Osta(s] Oatal6)
3.5.3 Deleting an Element from an Array
+ Deleting an element from an array means removing a data element from an already
existing array.
+ If the element has to be deleted from the end of the existing array, then we just
have to subtract 1 from the upper_bound.
+ Figure 3.15 shows an algorithm to delete an element from the end of an array.
Step 1: SET upper_bound = upper_bound
Step 2: EXIT
Figure 3.15 Algorithm to delete the last element of
an array
+ For example, if we have an array that is declared as
int marks[60];
The array is declared to store the marks of all the students in the class. Now, suppose there
are 54 students and the student with roll number 54 leaves the course. The score of this
student was stored in marks[54]. We just have to decrement the upper_bound. Subtracting
1 from the upper_bound will indicate that there are 53 valid data in the array.
* Consider an array whose elements are arranged in ascending order. Now, suppose an
element has to be deleted, probably from somewhere in the middle of the array. To do
[Link]this, we must first find the location from where the element has to be deleted and then
move all the elements (having a value greater than that of the element) one position
towards left so that the space vacated by the deleted element can be occupied by rest of
the elements.
Example 3.4 osta() is an array that is declared as int oata(i0}; and contains the following
values:
Datal] = (12, 23, 34, 45, 56, 67, 78, 89, 90, 100);
(@) Ifa data element with value 56 has to be deleted, find its position.
(b) Delete the data element 56 and show the memory representation after the deletion.
Solution
(@) Since the elements of the array are stored in ascending order, we will compare the
value that has to be deleted with the value of every element in the array. As soon as vat
Data[I], Where is the index or subscript of the array, we will get the position from
which the element has to be deleted. For example, if we see this array, hete vat = 56.
Data{o] = 12 which is not equal to 56. We will continue to compare and finally get the
value of pos = 4.
&) (12 7 23 [ 34 [45 [ 67 78 89, 90 | 100
Data[o] Data[1] Data[2] Data[3] Data[4] Data[s] Data[6] Data[7] Data[s)
Algorithm to delete an element from the middle of an array
* The algorithm DELETE will be declared as DELETE(A, N, POS). The arguments are:
i A, the array from which the element has to be deleted
ii N, the number of elements in the array
iii POS, the position from which the element has to be deleted
Figure 3.16 shows the algorithm in which we first initialize I with the position from
which the element has to be deleted. In Step 2, a while loop is executed which will move
all the elements having an index greater than POS one space towards left to occupy the
space vacated by the deleted element. In Step 5, we decrement the total number of
elements in the array by 1.
[INITIALIZATION] SET T= POs
Repeat Steps 3 and 4 while T
void main()
{
int array[100], key, i, n;
printf("Enter number of elements in array:\n");
seanfi"%d", &n); Output
Enter number of elements in
; array
printf("Enter elements of array:\n"); | 5
for (i= 0;i A[MID], then KEY will be present in the right segment of the array. So, the value
of BEG will be changed as LOW = MID + |
iii Finally, if KEY is not present in the array, then eventually, HIGH will be less than LOW.
When this happens, the algorithm will terminate and the search will be unsuccessful. Figure 14.2
shows the algorithm for binary search.
BINARY_SEARCH(A, lower_bound, upper_bound, KEY)
Step 1: [INITIALIZE] SET LOW = lower_bound
HIGH = upper_bound, POS = - 1
Step 2: Repeat Steps 3 and 4 while LOW <= HIGH
Step 3: SET MID = (LOW + HIGH)/2
Step 4: IF KEY = A[MID]
SET POS = MID
PRINT POS
Go to Step 6
ELSE IF KEY > A[MID]
SETLOW= MID + 1
ELSE
SET HIGH = MID - 1
[END OF IF]
[END OF LOOP]
Step 5: IF POS = -1
PRINT “VALUE IS NOT PRESENT IN THE ARRAY”
[END OF IF]
Step 6: EXIT
How Binary Search Works?
[Link]v Fora binary search to work, it is mandatory for the target array to be sorted. The following is
our sorted array and let us assume that we need to search the location of key value 31 using
binary search, Here n=10, key=31
(0
EGER ae
6 8
low high
First, we shall determine middle position of the array by using this formula —
mid = (low + high) /2
Here it is, mid=(0 + 9) / 2 =4 (integer value of 4.5). So, 4 is the mid of the array.
rt
lower part of array pri Upper part pf array
10 14 || 19 || 26 | 31
a 7 2 3 4 5 6 7 8 3
v Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. Since the key element is greater
than the middle element, we should search the key element in the upper part of the array
[ot |[ se [ss 42 || 44
a: = © & oe £ 8 8
low high
We change our low to mid + 1 and find the new mid value again,
low = mid + 1=4+1=5 mid =
(low + high) /2= (5+9)/2 =7
¥ Our new mid is 7 now. We compare the value stored at location 7 with our key value 31.
mid
EA eee ee ec
[Link]v The value stored at location 7 is not a match; rather it is more than what we are looking for.
Since the key element is less than the middle element, we should search the key element in
the lower part of the array.
We change our high to mid - | and find the new mid value again.
high=mid-1 = mid -1=7-1=6
a 7 os 8
mid = (low + high) / 2 = (5+6)/2=5
v Hence, we calculate the mid again. This time it is 5.
mid
| a1 | 33
Pree pe gre.
low high
v We compare the value stored at location 5 with our key value. We find that it is a match.
| 31
0 ¥ 2 = 4 6 & 7 8 3
¥ We conclude that the key value 31 is stored at position mid+1= 5+1=6.
¥ Binary search halves the searchable items and thus reduces the count of comparisons to be
made to very less numbers.
Example: C Program to search key elements in array using binary search algorithms:
#include
#include
void main)
{ int i, low, high, mid, n, key, a[100];
printf("Enter number of elements in
array:\n"); scanf("%d",&n);
[Link]printf("Enter integer numbers in ascending
ie meer Wot eanie (Output:
order:\n"); for (i= 0; i a[mid] )
low = mid + 1;
if (key < a{mid])
high = mid - 1;
}
printf(" %d is Not found! \n", key);
3.6 Passing Arrays to Functions
«Like variables of other data types, we can also pass an array to a function.
+ In some situations, you may want to pass individual elements of the array; while in other
situations, you may want to pass the entire array as shown in Fig. 3.20.
1D arrays for inter-|
function communication
1
Passing individual Passing the entire
ments array
[ |
Passing data values Passing addresses
Figure 3.20 One dimensional arays for inter-function communication
Individual Elements
© The individual elements of an array can be passed to a function by passing either their
data values or addresses.
[Link]. Passing Data Values
Individual elements can be passed in the same manner as we pass variables of any other
data type.
The condition is just that the data type of the array element must match with the type of
the function parameter.
Look at Fig. 3.21(a) which shows the code to pass an individual array element by passing the
data value.
Calling function Called function
main() void func(int mum)
€ 4
int arr[5] =(1, 2, 3, 4, 5}5 print#("xd", num);
; func(arr[3]); y
Figure 3.21(a) Passing values of individual array elements to a function
In the above example, only one element of the array is passed to the called function. This is
done by using the index expression, Here, arr[3] evaluates to a single integer value.
. Passing Addresses
Like ordinary variables, we can pass the address of an individual array element by
preceding the indexed array element with the address operator.
Therefore, to pass the address of the fourth element of the array to the called function, we
will write &arr[3].
However, in the called function, the value of the array element must be accessed using the
indirection (*) operator. Look at the code shown in Fig. 3.21(b).
Calling function
rain()
{
int are(S] =(2, 2, 3, 4, 5)s
Func (arr{3]);
Called function
void func(int *nun)
i
)
printf("%d", num);
)
Figure 3.21(b) Passing addresses of inci
3.6.2 Passing the Entire Arra
array elements to function
© InC the array name refers to the first byte of the array in the memory.
© The address of the remaining elements in the array can be calculated using the array
name and the index value of the element.
+ Therefore, when we need to pass an entire array to a function, we can simply pass the name
of the array.
Figure 3.22 illustrates the code which passes the entire array to the called function.
[Link]Calling function Called function
main) void func(int arr(5})
{ «
int are{3] =(t, 2, 3, 4, 5)5 int 4;
fune(are) for(i; 4055444)
} printfCad", ori);
Figure 8.22 Passing enti array to «function
3.7 Two-Dimensional Arrays
+ A two-dimensional array is specified using two subscripts where the first subscript
denotes the row and the second denotes the column.
+ The C compiler treats a two-dimensional array as an array of one-dimensional arrays.
«+ Figure 3.26 shows a two-dimensional array which can be viewed as an array of arrays.
First
dimension
Second dimension
Figure 3.26 Two-dimensional array
3.7.1 Declaring Two-dimensional Arrays
+ Any array must be declared before being used. The declaration statement tells the compiler
the name of the array, the data type of each element in the array, and the size of each
dimension.
© A two-dimensional array is declared as:
data_type array_name[row_size|[column_size];
+ For example, if we want to store the marks obtained by three students in five different
subjects, we can declare a two dimensional array as: int marks[3][5];
+ Inthe above statement, a two-dimensional array called marks has been declared that has m(3)
rows and n(5) columns. The first element of the array is denoted by marks[0][0], the second
element as marks[0][1], and so on. Here, marks[0][0] stores the marks obtained by the first
student in the first subject, marks[1 [0] stores the marks obtained by the second student in the
first subject. 1 The pictorial form of a two-dimensional array is shown in Fig. 3.27.
[Link]Rows
‘Columns|
Row | sarks[0}fo] | marks(o}{a] | marksfo]{2] | marks(o[3] | narks(0][4]
Row t | warks{1}fo] | marks(t]ti] | marks(2}(2] | warks(2]{3] | marts{1]E4]
Row 2 | marks{2](0] | marks(2}(a] | marks(2](2] | marks[2]{3] | marks{2)/4]
Col | Colt | Col2 Cold Col4
Figure 3.27 Two-dimensional aay
Hence, we see that a 2D array is treated as a collection of ID arrays. Each row of a 2D array
corresponds to a 1D array consisting of n elements, where n is the number of columns. To
understand this, we can also see the representation of a two-dimensional array as shown in
Fig. 3.28.
marks(o] - [ marks{o] | marks[i] | marks(2] | marks[(3] | marks[4]
marks(1] - [marks[o] | marks[i] | marks(2] | marks[3] | marks[4]
marks[2] - [marks[0] | marks{i] | marks[2] | marks(3] | marks[4]
Figure 3.28 Representation of two-dimensional array marks[3][5]
There are two ways of storing a two-dimensional array in the memory. The first way is the
row major order and the second is the column major order.
In a row major order, the elements of the first row are stored before the elements of the
second and third rows. That is, the elements of the array are stored row by row where n
elements of the first row will occupy the first n locations. This is illustrated in Fig. 3.29.
(0,0) (0,1) (0,2) (0,3) (1,0) (1,1) (1,2) (1,3) (2.0) (2,1) (22) (2.3)
Figure 3.29 Elements of a 3 4 2D array in row major order
However, when we store the elements in a column major order, the elements of the first
column are stored before the elements of the second and third column. That is, the
elements of the array are stored column by column where m elements of the first column will
occupy the first m locations. This is illustrated in Fig. 3.30.
l J
(0,0) (1,0) (2,0) (3,0) (0,1) (1,1) (2.1) (3.1) (0.2) (1,2) (2,2) (3.2)
Figure 3.30 Elements of a4 3 20 array in column major order
If the array elements are stored in column major order,
Address(A[I][J]) = Base_Address + w{M (J- 1) + (I= )}
And if the array elements are stored in row major order,
[Link]Address(A[I][J]) = Base_Address + w{N (1-1) + (J — 1)} where w is the number
of bytes required to store one element, N is the number of columns, M is the number of
rows, and I and J are the subscripts of the array element.
Example 8.5 Consider a 20x 5 two-dimensional array marks which has its base addess= 1000
and the size of an element = 2. Now compute the address of the element, sarks(18)(4) assuming
that the elements are stored in row major order.
Solution
Address(A[I][3]) = Base Address + w(W (I ~ 1) + (3 - 1)}
Address(marks[18][4]) = 1000 + 2 {5(18 - 1) + (4 - 1)}
1000 + 2 {5(17) + 3}
1000 + 2 (88)
1000 + 176 = 1176
3.7.2 Initializing Two-Dimensional Arrays
* A two-dimensional array is initialized in the same way as a one-dimensional array is
initialized.
For example, int marks[2][3]={90, 87, 78, 68,
62,71);
+ Note that the initialization of a two-dimensional array is done row by row. The above
statement can also be written as:
int marks[2J[3]={ {90,87,78}.{68, 62. 71}};
* The above two-dimensional array has two rows and three columns. First, the elements in the
first row are initialized and then the elements of the second row are initialized. Therefore,
marks[0][0] = 90 marks[0][1] = 87 marks[0][2] = 78 marks[1][0] = 68 marks[1][1] = 62
marks{1][2] =71
+ In case of one-dimensional arrays, we have discussed that if the array is completely
initialized, we may omit the size of the array. The same concept can be applied to a two-
dimensional array, except that only the size of the first dimension can be omitted.
Therefore, the declaration statement given below is valid.
int marks[][3]={{90,87,78},{68, 62, 71}};
+ Inorder to initialize the entire two-dimensional array to zeros, simply specify the first value
as zero. That is,
int marks[2][3] = {0};
¢ The individual elements of a two-dimensional array can be initialized using the assignment
operator as shown here.
marks[1][2] = 79;
or
marks[1][2] = marks[1][1] + 10;
[Link]3.7.3 Accessing the Elements of Two-dimensional Arrays
+ The elements of a 2D array are stored in contiguous memory locations.
+ Since the two-dimensional array contains two subscripts, we will use two for loops to scan
the elements.
+ The first for loop will sean each row in the 2D array and the second for loop will scan
individual columns for every row in the array.
Example:
Write a C program to read and print the elements of a 2D array.
#include
void main()
f
int arr{2][2], i, j, m,n; printf(“Enter the
size of the array:”);
scanf(“%d%d",&m,&n);
printf(‘“Enter the elements of the array:\n);
for(i=0;i
void main()
{
int i, j, mat[3][3], transposed_mat(3][3];_ printf("\n
Enter the elements of the matrix ");
for(i-0:i<3:i++)
t
for(j=0;j<3;j++)
t
[Link]scanf("%d", &mat[il[i]);
}
}
}
printi("\n The elements of the matrix are ");
for(i=0;i<3si++)
{
353: itt)
printf("%ad\t", mat{il{j));
}
printf("\n");
}
for(i=0;i<3;i++)
t
for(j=0;j<3;j++)
transposed_mat{i][j] = mat{j][i];
printf("\n The elements of the transposed matrix are ");
for(i=0;i<35i++)
{
for(O 535+)
{
printf("%d\t" transposed_ mat[i][j]);
}
printf("\n");
}
}
Output
Enter the elements of the matrix
123456789
The elements of the matrix are
123
456
789
The elements of the transposed matrix are
147
[Link]258
369
2. Write a program to input two m x n matrices and then calculate the sum of their
corresponding elements and store it in a third m x n matrix.
#include
#include
void main()
‘
{
inti,j,m,n, p,q, a[5][5], b[5][5], e[5][5];
printf("\n Enter the number of rows and columns in the first matrix : ");
scanf("%d%d",&m,&n);
printf("\n Enter the number of rows and columns in the second matrix : ");
scanf("%d%d",&p,&q);
if(m !=p || n !=q)
t
printf("\n Number of rows and columns of both matrices must be equal");
exit(0);
}
printf("\n Enter the elements of the first matrix");
for(i=0si
t
for(j=0;j
void main()
t
int array(2][2I[2], i,j, ks
printf("\n Enter the elements of the matrix");
for(i=0;i<2;i++)
{
for(j=0;j<2;)++)
[Link]for(k=0;k<2;k++)
{
seanf"%d", &array[i}[j][k]);
}
}
printf("\n. The matrix is : ");
for(i=0;i<2:i++)
t
printf("\n");
for(j=0;j<2;j++)
{
printi("\n");
for(k=0;k<2;k++)
printf("\t array[%d][%d][%d] = %d", ij.
, arrayLi][i]Ik);
Output
Enter the elements of the matrix
12345678 The matrix is
arr[0][0][0] = 1 arr{0][O][1] =
2 arr[O}[1][0] = 3 arr{O}(1][1]
=4 arr{1J[0][0] = 5
arr[1][0][1] = 6 arr{1][1][0] =
Tar{ JEU =8
3.11 Applications of Arrays
‘Arrays are frequently used in C, as they have a number of useful applications. These applications
are
+ Arrays are widely used to implement mathematical vectors, matrices, and other kinds of
rectangular tables.
+ Many databases include one-dimensional arrays whose elements are records.
+ Arrays are also used to implement other data structures such as strings, stacks, queues,
heaps, and hash tables.
+ Arrays can be used for sorting elements in ascending or descending order.
[Link]Functions
* C enables its programmers to break up a program into segments commonly known as
functions, each of which can be written more or less independently of the others.
+ Every function in the program is supposed to perform a well-defined task.
* Therefore, the program code of one function is completely insulated from the other
functions.
Definition
+ “The set of instructions that performs some specific, well-defined task is called as a
Function.” Or
“Function is a small program or program segment that carryout some specific well-
defined tasks”.
+ Fig. 1.9 explains how the main() function calls another function to perform a well-defined
task.
«In the figure, we can see that main() calls a function named fune1(). Therefore, main() is
known as the calling function and func! () is known as the called function.
+ The moment the compiler encounters a function call, the control jumps to the statements.
that are a part of the called function.
[Link]+ After the called function is executed, the control is returned to the calling program.
yfunci()
statement block;
funei();
return 0;
}
Figure 1.9 main() calls funca()
3.12.1 Why are Functions Needed?
* Dividing the program into separate well-defined functions facilitates each function to
be written and tested separately. This simplifies the process of getting the total
program to work.
© Understanding, coding, and testing multiple separate functions is easier than doing the
same for one big function.
© Ifa big program has to be developed without using any function other than main(), then
there will be countless lines in the main() function and maintaining that program will
be a difficult task.
© All the libraries in C contain a set of functions, which have been pre-written and pre-
tested, so the programmers can use them without worrying about their code details.
This speeds up program development, by allowing the programmer to concentrate only
on the code that he has to write.
© Like C libraries, programmers can also write their own functions and use them from
different points in the main program or any other program that needs its functionalities.
When a big program is broken into comparatively smaller functions, then different
programmers working on that project can divide the workload by writing different
functions.
3.13 Using Functions
While using functions, we will be using the following terminologies:
+ A function f that uses another function g is known as the calling function, and g is
known as the called function.
+ The inputs that a function takes are known as arguments.
[Link]© When a called function returns some result back to the calling function, it is said to
return that result.
+ The calling function may or may not pass parameters to the called function. If the
called function accepts arguments, the calling function will pass parameters, else not.
+ Function declaration is a declaration statement that identifies a funetion’s name, a list
of arguments that it accepts, and the type of data it returns.
+ Function definition consists of a function header that identifies the function, followed
by the body of the function containing the executable code for that function.
3.14 Types of Functions
i, Library Functions/Pre-Defined/ Built-in Functions
* C Library of C Compiler has a collection of various functions which perform some standard
and predefined tasks.
+ These functions written by designers of C Compilers are called as Library functions/Pre-
Defined/Built-in functions.
Ex:sqri(n)- computes square root of n
pow(x,y)- computes x7
printf{)- used to print the data on the screen.
seani{)- used to read the data from the keyboard.
abs(x)- computes absolute value of x
ii. User-Defined/ Programmer Defined Functions
+ The functions written by the programmer/user to do the
specific tasks is called User-Defined’ Programmer Defined
Functions.
+ main( ) is the user defined function.
3.15 Elements of User-Defined Functions
The three elements of user-defined functions are shown below
1) Function Prototype/Declaration
2) Function Definition
3) Function Call
3.15.1 Function Declaration/Function Prototype
+ Before using a function, the compiler must know the number of parameters and the
type of parameters that the function expects to receive and the data type of value that
it will return to the calling program.
[Link]* Placing the function declaration statement prior to its use enables the compiler to make
a check on the arguments used while calling that function.
© The general format for declaring a function that accepts arguments and returns a value as
result can be given as:
return_data_type function_name(data_type variablel, data_type variable2,..);
Here, function_name is a valid name for the function. A function should have a
meaningful name that must specify the task that the function will perform.
return_data_type specifies the data type of the value that will be returned to the
calling function as a result of the processing performed by the called function.
(data_type variable1, data_type variable2, ...) is a list of variables of specified data types.
These variables are passed from the calling function to the called function. They are also
known as arguments or parameters that the called function accepts to perform its task. Ex:
int add(int a,int b);
¢ Things to remember about function declaration
+ After the declaration of every function, there should be a semicolon. If the semicolon
is missing, the compiler will generate an error message.
+ The function declaration is global.
+ Use of argument name in the function declaration is optional.
int func(int, char, floa t);
or
int fune(int num, char ch, float fnum);
+ A function cannot be declared within the body of another function.
+ A function having void as its return type cannot return any value.
+ A function having void as its parameter list cannot accept any value. So the function
declared as void print(); does not accept any input/arguments from the calling
function .
+ If the function declaration does not specify any return type, then by default, the
function returns an integer value. Therefore, when a function is declared as
sum(int a, int b);
Then the function sum accepts two integer values from the calling function and in sum
returns an integer value to the caller,
+ Some compilers make it compulsory to declare the function before its usage while
other compilers make it optional.
Function Definiti
ion
+ When a function is defined, space is allocated for that function in the memory,
+ A function definition comprises of two parts:
[Link]+ Function header
+ Function body
The syntax of a function definition can be given as:
return_data_type function_name(data_type variablel, data_type variable2,..)
{
statements
return(variable);
* The number of arguments and the order of arguments in the function header must be the
same as that given in the function declaration statement.
© While return_data_type function_name(data_type variablel, data_type variable?,...) is
known as the function header, the rest of the portion comprising of program statements
within the curly brackets { } is the function body which contains the code to perform the
specific task
« Note that the function header is same as the function declaration. The only difference
between the two is that a function header is not followed by a semi-colon.
Ex: int add(int a,int b)
{
int sum;
sum=a+b; return
sum;
}
3.15.3 Function Call
+ The function call statement invokes the function.
+ When a function is invoked, the compiler jumps to the called function to execute the
statements that are a part of that function.
* Once the called function is executed, the program control passes back to the calling
function, A function call statement has the following syntax:
function_name(variable1, variable2, ...);
* The following points are to be noted while calling a function:
+ Function name and the number and the type of arguments in the function call
must be same as that given in the function declaration and the function header of
the function definition
+ Names (and not the types) of variables in function declaration, function call, and
header of function definition may vary.
[Link]+ Arguments may be passed in the form of expressions to the called function. In such
acase, arguments are first evaluated and converted to the type of formal parameter
and then the body of the function gets executed.
+ Ifthe return type of the function is not void, then the value returned by the called
function may be assigned to some variable as given below.
variable_name = function_name(variable1, variable2, ...);
Ex: add(a.b);
3.16 return Statement
+ The return statement terminates the execution of the called function and returns control
to the calling function.
+ When the return statement is encountered, the program execution resumes in the calling
function at the point immediately following the function call
« Arreturn statement may or may not return a value to the calling function.
© The syntax of return state can be given as
return ;
Here expression is placed in between angular brackets because specifying an expression is
optional.
+ A function that has void return type cannot return any value to the calling function.
3.17 Passing Parameters to Functions
There are two ways in which arguments or parameters can be passed to the called function.
Call by value: The values of the variables are passed by the calling function to the called
function. Call by reference The addresses of the variables are passed by the calling
function to the called function.
1, Call by Value
+ In this method, the called function creates new variables to store the value of the
arguments passed to it. Therefore, the called function uses a copy of the actual arguments
to perform its intended task.
* Ifthe called function is supposed to modify the value of the parameters passed to it, then
the change will be reflected only in the called function. In the calling function, no change
will be made to the value of the variables. This is because all the changes are made to the
copy of the variables and not to the actual variables.
Example: Write a C program to add two numbers using call by value.
[Link]