0% found this document useful (0 votes)
4 views52 pages

Chapter_6_Array_-_add_notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views52 pages

Chapter_6_Array_-_add_notes

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 52

CCP203 - Computer Programming

- Module 6 -
ARRAY
CCP203 - Computer Programming

Objectives
• To understand the definition and concepts of array in
manipulating data structures
• To understand how to declare an array, initialize an
array, and identify individual elements of an array
• To be able to pass arrays to functions
• To understand the use of arrays to store, sort and search
data via several techniques.
• To be able to declare and manipulate multi-dimensional
arrays
CCP203 - Computer Programming

Definition of Arrays
• An array – a group of memory locations
related by the fact that they all have the same
name and the same type.

20 100 585 1250


memory
locations

int semester[4];
CCP203 - Computer Programming

Why we use Arrays?


• To make a program efficiently developed
• Example: to store the number of students in every
semester.
– You might store the numbers in variable
semester. If there are four semesters, you can
write the variables like these:
semester1, semester2, semester3, semester4
– If the number of semesters is increased, you are
required to add more variables.
• When we add another variables, the program
becomes complex and difficult to invoke some
operations such as passing value, do arithmetic
operations and etc.
CCP203 - Computer Programming

General form of Array Declaration


typeOfData nameOfArray[sizeOfArray];
e.g:
int
int semester[4];
semester[4];
/*semester has 4 elements and every element is
an integer value.*/

• sizeOfArray indicates how many elements


should be stored in memory
• nameOfArray is any suitable names be given to
be a variable. The name must follow the
identifier’s rules. The name of array is also the
address of the first element of array.
• typeOfData indicates that every elements in
array has a same type of data.
CCP203 - Computer Programming

Examples of Array Declaration


• char code[4]; /* an array of four character codes */

code ‘R’ ‘o’ ‘a’ ‘r’


[0] [1] [2] [3]

• int grade[100]; /* an array of 100 integer grades */

grade 10 5 28 -95 …… 43
[0] [1] [2] [3] ……… [99]

• float amount[11]; /*an array of 11 floating points*/

amount 1.2 5.9 2.8 -34.5 …… 98.4

[0] [1] [2] [3] ……… [10]


CCP203 - Computer Programming

Indexing in Array
• Indexing begins with 0 until i th
element.
e.g: int semester[4];
start with 0

semester[0] 20

semester[1] 100

semester[2] 585
semester[3] 1250

[i-1]
CCP203 - Computer Programming

name of array
semester[0] 20

semester[1] 100

semester[2] 585

semester[3] 1250

subscript
- must be an integer
- can consists of an expression
and the expression is evaluated
to determine the subscript
CCP203 - Computer Programming

Declaration and Initialization of Array

• An array can be declared by given the initial value


first.
e.g:

int grade[6] = { 79, 80, 75, 50, 40, 55};

The values of the above array are:

grade[0] = 79 grade[1] = 80
grade[2] = 75 grade[3] = 50
grade[4] = 40 grade[5] = 55

cont’d…
CCP203 - Computer Programming

Declaration and Initialization of Array

If there are fewer initializers than elements in the


array, the remaining elements are automatically
initialized to zero.
e.g:
int grade[6] = { 79, 80, 75};

The values of the above array are:


grade[0] = 79 grade[1] = 80
grade[2] = 75 grade[3] = 0
grade[4] = 0 grade[5] = 0

cont’d…
CCP203 - Computer Programming

Declaration and Initialization of


Array

If the array size is omitted from a declaration, the


number of elements in the array will be the
number of elements in the initializer list.
e.g:
int grade[] = { 79, 80, 75, 50};

The size of array grade is 4.

cont’d…
CCP203 - Computer Programming

Declaration and Initialization of


Array

Providing more initializers in an array than the


actual number of elements in the array will cause
a syntax errror.

e.g:

int grade[3] = { 79, 80, 75, 50,35, 85};


CCP203 - Computer Programming

Subscripted Variables
• Let say, if array declaration as below:

int value[4]; /* an array of 4 integer values */

Examples of valid subscripted variables:

value[1] = value[0] – 11;


value[2] = 2 * (value[0] – 6);
value[3] = amount * val1;
amount = value[3] + value[2];
value[a - b]; /* a = 4, b = 3 */
value[num]; /* num is 2 */

total = value[0] + value[1] + value[2] + value[3];

 total = 0;
for (I = 0; I <= 3; ++i)
total = total + value[i];
CCP203 - Computer Programming

Example – Program 1
/*This program was developed to read 4 integer numbers */

#include <stdio.h>

void main(void)
{
int x[4],i;
for(i = 0; i < 4; i++)
{
printf(“Enter value for %d index :“, i);
scanf(“%d”, &(x[i]));
}
}
CCP203 - Computer Programming

Example – Program 2
/*This program was developed to print 5 integer numbers */

#include <stdio.h>

void main(void)
{
int x[5] = {20, 1, -4, 27, 500};

for(i = 0; i < 5; i++)


printf(“x[%d] = %d\n“, i, x[i]);
}
CCP203 - Computer Programming

Example – Program 3
/*This program was developed to read 3 integer numbers and
print the total of the numbers.*/

#include <stdio.h>
void main(void)
{
int x[3], total, i;
for(i = 0; i < 3; i++)
{
printf(“x[%d] = “, i);
scanf(“%d”, &(x[i]));
total += x[i];
}
printf(“Total = %d\n”, total);
}
CCP203 - Computer Programming

Example – Program 4
/* This program was developed to read 3 integer numbers and
print the average of the numbers.*/

#include <stdio.h>
void main(void)
{
int x[3], total, i;
for(i = 0; i < 3; i++)
{
printf(“x[%d] = “, i);
scanf(“%d”, &(x[i]));
total += x[i];
}
printf(“Average = %d\n”, total/3);
}
CCP203 - Computer Programming

Example – Program 5
What is the output of this program?
Output:
#include <stdio.h> -15
void main(void) 44
{ 162
int x[4] = {199, -15, 44, 37}; 199 -15 44 37
int a = 5; 221 -13 46 39

printf(“%d\n”, x[1]);
printf(“%d\n”, x[7-a]);
printf(“%d\n”, x[0] – x[3]);
for(i = 0; i < 4; i++)
printf(“%d”, x[i]);
for(i = 0; i < 4; i++)
{
x[i] += 2;
printf(“%d”, x[i]);
}
for(i = 0; i < 4; i++)
printf(“%d”, x[i]);
}
CCP203 - Computer Programming

Passing Arrays To Functions

• To pass an array argument to a function, specify the


name of the array without brackets and followed by
the size of the array (optional)
e.g:
modifyHours(WorkingHours, 24);

/*this function call pass array


WorkingHours and its size, 24, to
function modifyHours.*/
CCP203 - Computer Programming

Passing Arrays To Functions


To receive an array through a function call, the
function’s parameter list must specify that an array
will be received with its size (optional).
e.g:
void modifyHours(int b[], int size)

/*this function header indicates


that function modifyHours expects
to receive an array of integers in
parameter b and the number of
array element in parameter size.*/
@ void modifyHours[int b[]);
CCP203 - Computer Programming

Passing Arrays To Functions


To declare a function prototype, the function’s
parameter list must specify the data type of the array
and its size (optional) .
e.g:
void modifyHours(int [], int);

/*this function prototype indicates


that function modifyHours has an
integer parameter of the array and
its size.*/
@ void modifyHours(int []);
CCP203 - Computer Programming

Passing Arrays To Functions


#include <stdio.h>
void modifyHours(int [], int); /* function prototype */

void main()
{
int WorkingHours[24];
:
modifyHours(WorkingHours, 24); /* function call */
}

/* function definition/header */
void modifyHours(int b[], int size)
{
:
}
CCP203 - Computer Programming

Examples of Declarations & Function Calls


Assume that the array nums, keys, units and prices are declared as:

int nums[5]; /* an array of five integers */


char keys[256]; /*an array of 256 characters */
double units[20], prices[20]; /* two arrays of 20 doubles */

For these arrays, the following function calls can be made:


findMax(nums);
findCh(keys);
calcTot(nums, units, prices);

The following are the suitable function headers:


int findMax(int vals[5])
char findCh(char inKeys[256])
void calcTot(int arr1[5], double arr2[20], double
arr3[20])
CCP203 - Computer Programming
Passing Arrays To Functions
• C passes arrays to functions simulated call by
reference
e.g:
modifyHours(WorkingHours, 24);
void modifyHours(int b[], int size)

WorkingHours
b
Name
Nameof ofthe
thearray
arrayisis
When actually
actuallythe
thestarting
starting
Whenthethecalled
calledfunction
functionmodifies
modifies
array address
addressof
ofthe
thearray
arrayinin
arrayelements
elementsin inits
itsfunction
function
body, memory
memorylocations.
locations.
body,ititisismodifying
modifyingthe theactual
actual
elements
elementsof ofthe
thearray
arrayin intheir
their
original
originalmemory
memorylocations.
locations.
CCP203 - Computer Programming
Passing Arrays To Functions

• An individual element in an array can be passed


call by value
• To pass an element of an array to a function, use
the subscripted name of the array element as an
argument in the function call
e.g:
modifyHours(WorkingHours[10]);

Refer to Figure 6.13 (page 221 – C: How To Program)


to learn more details about differences between call by
reference and call by value.
CCP203 - Computer Programming

Example – Program 6
What is the output from this program?
Output:
#include <stdio.h> The value in 0 index is 20
The value in 1 index is 12
void print1(int [4]); The value in 2 index is 7

The value in 3 index is 70


void main(void)
{
int nums[4] = {20, 12, 7, 70};
printNum(nom);

}
void printNum(int nos[4])
{
int i;
for(i = 0; i < 3; ++i)
printf(“The value in %d index is %d\n”, i, nos[i]);
}
CCP203 - Computer Programming

Example – Program 7
What is the output from this program?
Output:
#include <stdio.h> The value in 0 index is 40
The value in 1 index is 24
void print1(int [4]); The value in 2 index is 14

The value in 3 index is 140


void main(void)
{
int nums[4] = {20, 12, 7, 70};
printNum(nom);
}
void printNum(int nos[4])
{
int i;
for(i = 0; i < 3; ++i)
{
nos[i] *= 2;
printf(“The value in %d index is %d\n”, i, nos[i]);
}
}
CCP203 - Computer Programming

Example – Program 8
What is the output from this program?
Output:
#include <stdio.h> The maximum value is 27

void findMax(int [5]);

void main(void)
{
int nums[5] = {2, 18, 1, 27, 16};
findMax(nums);

}
void findMax(int vals[5]) /* find the maximum value */
{
int i, max = vals[0];
for(i = 0; i < 4; ++i)
if (max < vals[i])
max = vals[i];
printf(“The maximum vakue is %d”, max);
}
CCP203 - Computer Programming

Sorting Arrays
• Sorting data:- placing data into some
particular order such as ascending or
descending
e.g:
– AeU sorts all students list by their Student ID.
– Bank sorts all transactions by date.
• Several types of sorting techniques are
bubble sort, selection sort, heap sort,
insertion sort and etc.
CCP203 - Computer Programming

Sorting Arrays

• Bubble sort – among popular sorting


techniques, but run slowly especially for
large arrays.

• Algorithms:
– Involve several passes
– In each pass, successive pair of elements are
compared
– If a pair is in increasing order -> leave the values
– If a pair is in decreasing order -> swap the
values.
CCP203 - Computer Programming

Sorting Arrays
Data in original order (refer Fig 6.15 – page 224):
2 6 4 8 10 12 89 68 45 37

a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]

if(a[i]
if(a[i] >> a[i
a[i ++ 1]){
1]){
temp
temp == a[i];
a[i];
a[i]
a[i] == a[i+1];
a[i+1];
a[i+1]
a[i+1] == temp;
temp;
}}

Data are sorted by bubble sort technique and in


ascending order:
2 4 6 8 10 12 37 45 68 89
CCP203 - Computer Programming

Searching Arrays
• Searching:- process of finding a particular element
of an array.
• Two techniques of searching:-
– Linear search
– Binary search

• Linear search (refer fig. 6.18, pg 230)


– Works well for small arrays/unsorted arrays
– Not efficient for large arrays – low speed searching

• Binary search (refer fig. 6.19, pg 232)


– Suitable for sorted arrays
– High-speed searching
CCP203 - Computer Programming

Searching Arrays

• Algorithms for linear search:


– Compares each element of an array with the
search key
– If the search key is found -> the array
subscript is returned.
CCP203 - Computer Programming

Searching Arrays
• Algorithms for binary search:
e.g: find the search key, number 8 from these
following elements in an array:
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

2 4 6 8 10 12 14 16 18 20 22

1. Find the search key by eliminating one half of


the elements in the array and locates the
middle element.
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

2 4 6 8 10 12 14 16 18 20 22

middle element
CCP203 - Computer Programming

Searching Arrays
2. Compares the middle element to the search key
3. If the search key is equal to the middle element,
the array subscript is returned.
4. If the search key is not equal to the middle
element, continues searching on another half of
the array (sub-array) depending to these rules:
• If the search key is less than the middle
element -> search on the first half of the
array
• If the search key is more than the middle
element -> search on the second half of the
array
CCP203 - Computer Programming

Searching Arrays

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

2 4 6 8 10 12 14 16 18 20 22

8 < 12

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

2 4 6 8 10 12 14 16 18 20 22

8>6
CCP203 - Computer Programming

Searching Arrays
[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

2 4 6 8 10 12 14 16 18 20 22

8 < 10

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

2 4 6 8 10 12 14 16 18 20 22

search key = middle element


If the search key is found, the subscript array ( [3] ) is
returned.
CCP203 - Computer Programming
Multi Dimensional Arrays
• Arrays in C can have multiple subscripts represented
by tables of values, which is consists of rows and
columns
e.g:
int x[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

column column column column


0 1 2 3
row 0 X[0][0] X[0][1] X[0][2] X[0][3]
row 1 X[1][0] X[1][1] X[1][2] X[1][3]
row 2 X[2][0] X[2][1] X[2][2] X[2][3]

column subscript
row subscript
array name
CCP203 - Computer Programming

Multi Dimensional Arrays

• A multiple-subscripted array can be declared by given the initial value first

int x[3][4] = {1,2,3,4,5,6,7,8,9,10,11,12};

The values of the array are:

X[0][0]
X[0][0] == 1,
1, x[0][1]
x[0][1] == 2,
2, x[0][2]
x[0][2] == 3,
3, x[0][3]
x[0][3] == 44
X[1][0]
X[1][0] == 5,
5, x[1][1]
x[1][1] == 6,
6, x[1][2]
x[1][2] == 7,
7, x[1][3]
x[1][3] == 88
X[2][0]
X[2][0] == 9,
9, x[2][1]
x[2][1] == 10,
10, x[2][2]
x[2][2] == 11,
11, x[2][3]
x[2][3] == 12
12
CCP203 - Computer Programming

Multi Dimensional Arrays

• It also can be initialized like a single subscripted


array
e.g:
int b[2][2] = {{1,2},{3,4}};

b[0][0] b[0][1]
b[1][0] b[1][1]

The values of the array are:


b[0][0] = 1 b[0][1] = 2
b[1][0] = 3 b[1][1] = 4
CCP203 - Computer Programming

Multi Dimensional Arrays

• If there are not enough initializers for a given row,


the remaining elements of that row are initialized
to zero.
e.g:
int b[2][2] = {{1},{3,4}};

b[0][0] = 1 b[0][1] = 0
b[1][0] = 3 b[1][1] = 4
CCP203 - Computer Programming
Multi Dimensional Arrays

To pass a double subscripted array argument to a


function, specify the name of the array without
brackets and followed by the sizes of the array
e.g:
maximum(studentGrades, 3, 4);

/*this function call pass array


studentGrades and its size, 3 and
4, to function maximum.*/
CCP203 - Computer Programming

Multi Dimensional Arrays


To receive a double subscripted array through a
function call, the function’s parameter list must specify
that the array will be received with its sizes.
e.g:
int maximum(int grades[][4], int pupils, int tests)

/*this function definition indicate


that function maximum expects to
receive a double subscripted array
of integers in parameter grades and
the number of array element in
parameter pupils and tests.*/
CCP203 - Computer Programming

Multi Dimensional Arrays


To declare a function prototype, the function’s
parameter list must specify the data type of the
double subscripted array and its sizes .
e.g:
int maximum(int [][4], int, int);

/*this function prototype indicate


that function maximum has an
integer parameters of the double
subscripted array and its sizes.*/
CCP203 - Computer Programming
Multi Dimensional Arrays
#include <stdio.h>

int maximum(int [][4], int, int);/*function prototype*/

main()
{
int studentGrades[3][4];
:
maximum(studentGrades, 3, 4);/*function call*/
}

/*function definition*/
int maximum(int grades[][4], int pupils, int tests)
{
:
}
CCP203 - Computer Programming
Examples of Declarations & Function
Calls..Multidimensional Array
Assume that the array test, code and stocks are declared as:

int test[7][9]; /* an array of 36 integers */


char code[26][10]; /*an array of 260 characters */
float stocks[100][52]; /* an array of 520 floats */

For these arrays, the following function calls can be made:


findMax(test);
obtain(code);
price(stocks);

The following are the suitable function headers:


int findMax(int nums[7][9])
char obtain(chr key[26][10])
void price(float names[100][52])
CCP203 - Computer Programming
Multi Dimensional Arrays
• Take notes: function definition/header
int maximum(int grades[][4], int pupils, int tests)

The 1st subscript is not required, but all subsequent subscripts


are required

• Compiler uses these subscripts to determine


the locations in memory of elements in multi
dimensional arrays
• All array elements are stored consecutively in
memory regardless of the number of subscripts
• In multi dimensional array, the first row is stored
in memory followed by the second row.
CCP203 - Computer Programming

Subscripted Variables

• Let say, if array declaration as below:

int value[4][9]; /* an array of 36 integer values */

Examples of valid subscripted variables:

value[1][0] = value[0][1] – 7;
value[3][2] = 2 * (value[0][4] – 6);
value[0][4] = amount * val1;
amount = value[0][1] + value[2][2];
value[a - b][a + 1]; /* a = 4, b = 3 */
value[num * 4]; /* num is 2 */
CCP203 - Computer Programming

Example – Program 9
What is the output from this program?
Output:
#include <stdio.h> 6
The value is 6
2
void readPrint(int [2][3]); The value is 2
-13
void main(void) Thevalue is -13
{ 0
readPrint(nom); Thevalue is 0
} 589
void readPrint(int nos[2][3]) Thevalue is 589
{ 65
int row, column; Thevalue is 65
for(row = 0; row < 2; ++row)
for (column = 0; column < 3; ++column)
{
scanf(“&d\n”, &nos[row][column]);
printf(“The value is %4d\n”, nos[row][column]);
}
}
CCP203 - Computer Programming

Exercise 1 :
• Define suitable arrays to represent the
following data:
a) An array of 6 floats
b) An array of 5 characters
c) An array of 2 by 3 integers

For each array, determine how many


elements it contains and what its storage
requirements are.
CCP203 - Computer Programming

Exercise 2:
What would be printed by the following program?

#include <stdio.h>

int main(void);
{
/* Local Definitions */
int list [10] = {2, 1, 2, 4, 1, 2, 0, 2, 1, 2};
intline[10];

/* Statements */
for (i=1; i<= 10; i++)
line[i] = list[9 – i];
for (i=1; i<= 10; i++)
printf (”%d %d\n”, list[i], line[i]);
return 0;
} /* main */
CCP203 - Computer Programming

Exercise 3 :
Trace and determine the output that will be generated by
each of the following C programs.

#include <stdio.h>

main(void);
{
int a,b = 0;
int c [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

for (i=1; i<= 10; i++)


line[i] = list[9 – i];
for (a = 0; a < 10; ++a)
if ((c[a] % 2) == 0) b += c[a];
printf (”%d”,b);
}

You might also like