Lecture 16
Lecture 16
1
Pointer arithmetic - program
*x 564
560
i 3
560 564
*y 790
794
j 1.5
790 794
*z 320
321
k c
320 321
2
Sorting program
• Sorting means arranging element of array in
ascending or descending order
0 1 2 3 4 5
24 34 12 44 56 17
500 504 508 512 516 520
4
Selection sort
5
C program – Selection sort
0 1 2 3 4
44 33 55 22 11
i=0
j=1
if ( 44 > 33) true
0 1 2 3 4
33 44 55 22 11
j=2
if ( 33 > 55) false
j=3
if ( 33 > 22) true
0 1 2 3 4
22 44 55 33 11
j=4
if ( 22 > 11) true
0 1 2 3 4
11 44 55 33 22
6
Cont.
0 1 2 3 4
11 44 55 33 22
i=1
j=2
if ( 44 > 55) false
j=3
if ( 44 > 33) true
0 1 2 3 4
11 33 55 44 22
j=4
if ( 33 > 22) true
0 1 2 3 4
11 22 55 44 33
7
Cont..
0 1 2 3 4
11 22 55 44 33
i=2
j=3
if ( 55> 44) true
0 1 2 3 4
11 22 44 55 33
j=4
if ( 44 > 33) true
0 1 2 3 4
11 22 33 55 44
8
Cont…
0 1 2 3 4
11 22 33 55 44
i=3
j=4
if ( 55 > 44) true
0 1 2 3 4
11 22 33 44 55
9
Bubble sort
10
Insertion sort
11
Passing array to a function
0 1 2 3 4 5
24 34 12 44 56 17
500 504 508 512 516 520
*j 520
504
500
524
512
516
508
Program output i 1534
6
0
2
element = 24
element = 34
element = 12
element = 44
element = 56
12
element = 17
Two Dimensional Arrays
• It is also possible for arrays to have two or more
dimensions
• For example you want to input roll no and mark
of 4 students.
• Since we know 1D array, so for this problem we
can have two 1D array
– One for roll number
– Second for marks
• One 2D array can be used to store these values
13
Example program
row column
0 1
0 10 85
stud[2][0]
1 12 65 stud[3][1]
stud[2][1]
stud[0][1]
stud[1][1]
stud[3][0]
stud[0][0]
stud[1][0]
2 13 89
3 14 92
Roll Number Marks 14
Initializing a 2-Dimensional Array
15
Example program
• Write a program that adds two 4 x 4 matrices.
3 5 6 1 4 2 -7 0 7 7 -1 1
5 3 2 9 5 7 3 1 10 10 5 10
1 0 -3 4 + 6 3 -1 0
= 7 3 -4 4
7 2 3 -9 8 9 -2 3 15 11 1 -6
16