You are on page 1of 41

ARRAYS

Objectives
Introduction
One Dimensional Array
Declaring Array
Array Initialization
Array Referencing
Sorting an Array
Searching an Array
Two Dimensional Array
Two Dimensional Array Declaration
Two Dimensional Array Initialization
Two Dimensional Array Referencing
String
String Initialization
String Referencing
1
Objectives

• To understand the concept of array as


a data structure

• To be able to declare, initialize, and


use 1- and 2-dimensional array

• To introduce repetition structures to


navigate the contents of arrays.
2
Introduction Array is a group of memory
locations, all have the same
name & the same type.

What is an Array?
It is a collection of two or more adjacent
memory cells, called array elements that
associated with particular symbolic name.

Example: This array w contains 10 elements


double w[10];
Name of array (all elements of this
Position number of the element array have the same name, w)
within array w
Memory
Allocatio
n
w[0] w[1] w[2] w[3] w[4] w[5] w[6] w[7] w[8] w[9]

70.3 48.4 52.67 56.1 54.12 50.78 63.26 68.65 74.37 73.61
3
Introduction(Cont..)
Example 1 :

To compute the average of exam score for 5 students, we need to


come up with 5 identifiers.

Declaration:

int exam_score1, exam_score2, exam_score3, exam_score4,


exam_score5;

Memory allocation :

exam_score1 exam_score2

exam_score3 exam_score4

exam_score5
4
Introduction(Cont..)
By using an array..
Declaration :
int exam_score[5];
array index /
Memory allocation : subscript
array name
Address
exam_score[0] 0x2000

exam_score[1] 0x2004

exam_score[2] 0x2008

exam_score[3] 0x200C

0x2014
exam_score[4]

• The array index/subscript always start with 0 not 1.


• If the array has N elements, the last element is in position N-1.
• array size. Example sizeof(exam_score)=20bytes 5
One Dimensional Array
• A single dimensional array

Terms :
1. Array
a collection of data items of the same name & data type.
2. Array name
name of array is an identifier.
3. Number of array element
maximum number that can be stored in array / size of array
4. Array subscript/Index
a value/expression enclosed in [ ] brackets after the array
name, specifying which array element to access. Must start with
0.
5. Size of array
number of bytes used to store the total number of elements of 6
the array.
Declaring Array
When declaring arrays, we have to specify :
1. Array data type
2. Array Name
3. Number of elements

Format :

data_type array_name[ number_Of_Elements ];

Example :
int exam_score[28];

Array data type Array size / number of


Array name elements
7
Declaring Array (Cont..)
Another Examples :

i) int c[10];

ii) float myArray[ 3284 ];

iii) int a[5]; /* use a[0], a[1], .., a[4] */

iv) char b[3]; /* use b[0], b[1], b[2] */

v) float c[2] = { 0.1, 0.2};


/*initialization at declaration; c[0] = 0.1 , c[1]=0.2 */

vi) double c[3][5]; /* two dimensional array */

Declaring multiple arrays of same type :


Example:
int b[100], x[27];
char car[23], lorry[45];
float duck[3], ant[9]; 8
Array can be initialized at :
Array Initialization 1. compile time (while declaring)
2. run time

1. Compile-Time Initialization of Arrays (while declaring)

• An initializer must be a constant value.


Example :
initializer array elements

int exam_score[4] = { 88, 85, 76, 91 };


4 initializers, therefore 4 array elements
• We also can declare the number of element implicitly.
Example :

first element is refer as exam_score[0]

int exam_score[ ] = {88,85,76,91}

9
third element is refer as exam_score[2]
Array Initialization (cont..)
2. Run-Time Initialization of Arrays
• An array can be initialized at run time explicitly.

Example :

a) for (int i = 0; i <= 27; i++)


exam_score[i] = 0.0;

b) for( int b = 0; b < 27; b++)


scanf(“%d”, &exam_score[b]);
• In addition, if we leave some values of initialization,
rightmost elements will become 0.

Example :

int exam_score[4] = {88,85}; --> the 3rd & 4th element are 0
10
int exam_score[5] = {0}; All elements are 0
Array Referencing
• Each individual element is referred by specifying array name & index

Format:
arrayname[ position number ]
//output for the fragment code :
Example : //output
element for index 0 = 4.05
89
element for index 1 = 3.45
(i) exam_score[0] = 89;
element for index 2 = 3.21
printf( "%d", exam_score[ 0 ] ); element for index 3 = 6.55
element for index 4 = 10.23

(ii) float x[ ] = { 4.05,3.45,3.21,6.55,10.23}

for( int a = 0; a <= 4; a++)


printf( “ element for index %d = %f\n”, a, x[a]);

11
Array Referencing (cont..)

index  0 1 2 3 4

x 4.05 3.45 3.21 6.55 10.23

x[0] x[1] x[2] x[3] x[4]

Position number of the element within array x


“array subscript”

Name of array ( all elements of this array,


have the same name, x)

12
Array Referencing (cont..)
• Manipulation Statement using array :
 Perform operations in subscript (index)
Example :

double Mark [8]={16.0,12.0,6.0,8.0,2.5,12.0,14.0,10.5};


printf (“ %.f ”, Mark[0]);
Mark[3] =25.0;
sum= Mark[0] + Mark[1];
sum += Mark[2];
Mark[3] += 1.0;
Mark[2] = Mark [0] + Mark [1];
for(i=0;i<=7;i++)
printf(“Mark[%d]=%.f”,i,Mark[i]);

Output ?
13
Array Referencing (cont..)
• Manipulation Statement using array :
 Perform operations in subscript (index)
Example :
double Mark [8]={16.0,12.0,6.0,8.0,2.5,12.0,14.0,10.5};

Mark[0] Mark[1] Mark[2] Mark[3] Mark[4] Mark[5] Mark[6] Mark[7]

16.0 12.0 6.0 8.0 2.5 12.0 14.0 10.5

Mark[3] =25.0;//Mark[3]=25.0
Mark[0]=16
sum= Mark[0] + Mark[1];//sum=16.0+12.0=28.0 Mark[1]=12
sum += Mark[2];//sum=sum+Mark[2]=28.0+6.0=34.0 Mark[2]=28

Mark[3] += 1.0;//Mark[3]=Mark[3]+1.0=25.0+1.0=26.0 Mark[3]=26


Mark[4]=3
Mark[2] = Mark [0] + Mark [1];//Mark[2]=16.0+12.0=28.0
for(i=0;i<=7;i++) Mark[5]=12
printf(“Mark[%d]=%.f\n”,i,Mark[i]); Mark[6]=14
Mark[7]=11 14
Two Dimensional Array
• Array of array.
• 2-D array have 2 subscripts showing the number of
rows & the number of column.

Two Dimensional Array Declaration


• Similar with 1-D declaration except it have 2 subscripts.
• Format :

data_type array_name [no_of_element1][no_of_element2]

 data_type : either int, float, double, char.


 array_name : name of array that is an identifier.
 no_of_element1 : size of row.
 no_of_element2 : size of column.
15
Two Dimensional Array Declaration (cont..)
• Example :

(i) int x[10][5]; /*allocate 50 spaces (row:0-9,column:0-4)*/

(ii) float a[3][20]; /*allocate 60 spaces (row:0-2,column:0-19)*/

(iii) int exam_score[3][4]; /*allocate 12 spaces


(row:0-2,column:0-3)*/

16
Two Dimensional Array Declaration (cont..)
Example :
int exam_score[3][4];

row [0] to row[2] column [0] to column[3]

column1 column2 column3 column4


[0] [1] [2] [3]
row1 [0] exam_score[0][0] exam_score[0][1] exam_score[0][2] exam_score[0][3]
row2 [1] exam_score[1][0] exam_score[1][1] exam_score[1][2] exam_score[1][3]

row3 [2] exam_score[2][0] exam_score[2][1] exam_score[2][2] exam_score[2][3]

array name row subscript column subscript

17
Two Dimensional Array Declaration (cont..)
• The right index of an array is increased first before the left
index.
• Example :
int exam_score[3][4]={70,80,90,72,82,92,71,81,91,67,78,98 };

exam_score[0][0] 70
exam_score[0][1] 80
exam_score[0][2] 90
exam_score[0][3] 72
exam_score[1][0] 82
exam_score[1][1] 92
exam_score[1][2] 71
exam_score[1][3] 81
exam_score[2][0] 91
exam_score[2][1] 67
exam_score[2][2] 78
exam_score[2][3] 98 18
Two Dimensional Array Initialization
2-D array can be initialized at :
1. compile time (while declaring)
2. run time

1. Compile-Time Initialization of Arrays (while declaring)

Example :

(i) int exam_score[3][4]={70,80,90,72,82,92,71,81,91,67,78,98};

• The best way : nest the data in braces to show the exact nature
of the array.

Example :

(ii) int exam_score[3][4]={{70,80,90,72},{82,92,71,81},{91,67,78,98}};

19
Two Dimensional Array Initialization (cont..)
• We also can declare the far left dimension size
implicitly.
Example :
(iii) int exam_score[ ][4] =
{{70,80,90,72},{82,92,71,81},{91,67,78,98}};

• If we leave some values out of each row, compiler


initialize them to 0.
Example :
(iv) int exam_score[3][4]={{70,80},{82,92,71},{91,67,78,98}};

[0][0] 70 [0][1] 80 [0][2] 0 [0][3] 0


[1][0] 82 [1][1] 92 [1][2] 71 [1][3] 0

[2][0] 91 [2][1] 67 [2][2] 78 [2][3] 98


20
Two Dimensional Array Initialization (cont..)
2. Run-Time Initialization of Arrays
Example :
int exam_score[3][4]; //array 3x4

• can be initialized by nested for loops.


• The 1st loop varies the row from 0 - 2.
• The 2nd loop varies the column from 0 - 3.

for (row=0;row<3;row++)
for(column=0; column<4; column++)
scanf(“%d”,&exam_score[row][column]);
//end of inner for
//end of outer for row column value
0 0
• TRY: Trace the source code flow using trace table.. 1
2
3
1 0
1
: 21
Two Dimensional Array Referencing

• by specifying array name, its row and column index

• Can access elements in array, using nested for .

• Example:
exam_score[0][2] = 99;
exam_score[1][4] = exam_score[0][3] + 10;

22
Two Dimensional Array Referencing (cont..)
Example Program

#include<stdio.h>
void main( ) {
int exam_score[3][4]={{70,80,90,72},{82,92,71,81},{91,67,78,98}};
for(int row=0; row<3; row++)
{
for(int column=0; column<4; column++){
exam_score[row][column]= exam_score[row][column]+1;
printf("[%d][%d] = %d\n",
row,column,exam_score[row][column]);
}
}
}
//Program Output
[0][0] = 71
[0][1] = 81
[0][2] = 91
[0][3] = 73
[1][0] = 83
[1][1] = 93
[1][2] = 72
[1][3] = 82
[2][0] = 92
[2][1] = 68
[2][2] = 79 23
[2][3] = 99
String

• String is a grouping of characters.

• C implements the string data structure using arrays


of char type.

• include letters, digits and special characters (*, /, $).

• A string constant is a sequence of characters which is


enclosed by double quotation marks (“ ”).

24
String (cont..)
• We can declare a string variable as a 1-D character
array.

• Example :
char college[15];
character array college can store a string from 0 to
14.

• A string always ended by a null character (‘\0’)

• Example :
char college[11]=“UTHM JOHOR”;

U T H M J O H O R \0

25
String Initialization
• can initialize string variables at compile-time.

• many type of expressions:

(a) a string
char college[11]={‘U’,‘T’,‘H’,‘M’,‘ ’,‘J’,‘O’,‘H’,‘O’,‘R’,‘\0’};

(b) a string with a size of array


char college[11]=“UTHM JOHOR”;

(c) a string without a size of array


char college[]=“UTHM JOHOR”;
or
char college[]={‘U’,‘T’,‘H’,‘M’,‘ ’,‘J’,‘O’,‘H’,‘O’,‘R’,‘\0’};

26
String Referencing
• can use scanf and %s, for input of a string variables.
Example :
scanf(“%s”,string_var);

• use fscanf and %s for file-oriented input of string


variables.

• If the string to be input has embedded whitespace


characters, we can resort to the standard gets function.
Example :
gets(string_var);

• use printf and %s and function fprintf for file-oriented


output of string variables.

• puts function also can be used to display string.

27
String Referencing (cont..)
Example :
char string1[ ] = "first";

• string1 actually has 6 elements.

• equivalent to

char string1[ ] = {'f','i','r','s','t','\0' };

• Can access individual characters


string1[3] is character ‘s’.

• Array name is address of array, so ‘&’ sign is not needed for scanf.
scanf( "%s", string2 );

• reads characters until whitespace encountered

28
String Referencing (cont..)
Example Program
/* Treating character arrays as strings using scanf*/
#include <stdio.h>
int main() {
char string1[20], string2[] = "string literal";
int i;
printf("Enter a string: ");
scanf( "%s", string1 );
printf("string1 is: %s\nstring2 is:
%s\n",string1,string2);
printf("string1 with spaces between characters is:\n");

for ( i = 0; string1[ i ] != '\0'; i++ )


printf( "%c ", string1[ i ] );
printf( "\n" );
return 0;
}
//Program Output

29
String Referencing (cont..)
Example Program
/* Treating character arrays as strings using gets*/
#include <stdio.h>
int main() {
char string1[20], string2[] = "string literal";
int i;
printf("Enter a string: ");
gets(string1);
printf("string1 is: %s\nstring2 is:
%s\n",string1,string2);
printf("string1 with spaces between characters is:\n");

for ( i = 0; string1[ i ] != '\0'; i++ )


printf( "%c ", string1[ i ] );
printf( "\n" );
return 0;
}
//Program Output

30
Exercise
1. What will be the values of array k after execution
of the code segment below. The data input is 2,0
and 1.
int k[6] = {0, 0, 0, 0, 0, 0};
int i, n;
for (i = 3; i < 6; ++i)
{
scanf("%d", &n);
k[n] = i;
}
1.1 What is C code segment to access/ display the
elements for array k?

31
Exercise
2. Answer the following questions regarding an array called fractions
a) Define a symbolic constant SIZE to be replaced with the replacement text 10.

b) Define an array with SIZE elements of type float and initialize the elements to 0.

c) Name the fourth element from the beginning of the array.

d) Refer to array element index 4.

e) Assign the value 1.6 to array element nine.

f) Assign the value 3.3 to the seventh element of the array.

g) Print array elements 6 and 9 with two digits of precision to the right of the decimal point, and show the output that
is displayed on the screen.

h) Print all the elements of the array, using a for repetition statement. Assume the integer variable x has been
defined as a control variable for the loop. Show the output.

32
Exercise
3. mean (average)
• The mean or average value is defined as the sum
of all elements divided by the number of
elements.

• Find mean for dataset 3, 21, 0, -3, 34, -14,


45, 18. Using array variable to hold the data.

33
Exercise
4. Find minimum and maximum for
dataset. Using array variable to
hold the data.

• 3, 21, 0, -3, 34, -14, 45, 18

34
Exercise
5. Sort the values in the elements of
an array into ascending order using
the bubble sort algorithm.
The original data:
3 21 0 -3 34 -14 45 18
The sorted data in each iteration:
-14 21 3 0 34 -3 45 18
-14 -3 21 3 34 0 45 18
-14 -3 0 21 34 3 45 18
-14 -3 0 3 34 21 45 18
-14 -3 0 3 18 34 45 21
-14 -3 0 3 18 21 45 34
-14 -3 0 3 18 21 34 45
35
The bubble sort algorithm

36
// Pseudocode for bubble sort

delcare array a[N] with index from 0 to N-1

// find the smallest value in the remaining part of


// the array in each iteration starting with a[i]
for i = 0, 1, ..., N-2
// compare a[i] with a[j] for j from i+1 to N-1
for j = i+1, ..., N-1
// when a[i] > a[j], swap their values
if(a[i] > a[j])
temp = a[i]
a[i] = a[j]
a[j] = temp
endif
endfor
endfor

37
/* File: sort.cpp */
#include <stdio.h>
#define N 8

int main() {
double a[N] = {3, 21, 0, -3, 34, -14, 45, 18};
double temp;
int i, j;

printf("The original data:\n");


for(i = 0; i < N; i++) {
printf("%g ", a[i]);
}
printf("\nThe sorted data in each iteration:\n");
for(i = 0; i < N-1; i++) {
for(j = i+1; j < N; j++) {
if(a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
for(j = 0; j < N; j++) {
printf("%g ", a[j]);
}
printf("\n");
}
return 0;
} 38
Execution and Output

> sort.cpp
The original data:
3 21 0 -3 34 -14 45 18
The sorted data in each iteration:
-14 21 3 0 34 -3 45 18
-14 -3 21 3 34 0 45 18
-14 -3 0 21 34 3 45 18
-14 -3 0 3 34 21 45 18
-14 -3 0 3 18 34 45 21
-14 -3 0 3 18 21 45 34
-14 -3 0 3 18 21 34 45

39
Pass Arrays of Fixed Length to Function
• Pass one dimensional array
– When an array is passed to a function, what is actually passed is
the address of the first element of the array.
– In calling function, specify array name without brackets
type name[10];
……
function(10, name);
The number of elements of the array is usually passed to
function.
– The definition of called function
return_type function(int n, type array_name[]){
/* … */
}
The array_name in the function definition is not necessary the
40
same as in the function call.
Example 1:

/* File: passarray.cpp */
#include <stdio.h>

/** Add ‘dd1’ and ‘dd2’; store the


result in array ‘dd1’ element-wise. **/
Output: void oneDadd(int n, double dd1[], double dd2[]) {
int i;

for(i = 0; i <= n-1; i++) {


dd1[i] += dd2[i];
}
}

int main() {
double d1[5] = {1.0, 2.0, 3.0, 4.0, 5.0};
double d2[5] = {1, 2, 3, 4, 5};
int i;

oneDadd(5, d1, d2);


for(i = 0; i < 5; i++) {
printf("%.2lf \n", d1[i]);
}
printf(“\n");
return 0;
}
41

You might also like