Sei sulla pagina 1di 11

CHAPTER 7 ARRAY

Objectives

To introduce the concept of array One-dimensional array Two-dimensional array

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

7.1

Introduction

An array is a group of variables with the same data type and name. Many applications require the processing of multiple data items that have common characteristics. Example: A set of numerical data, represented by x1, x2, ., xn

You can have integer arrays, long-integer arrays, and double floating arrays, short integer arrays and so on.

Each array element (individual data item) is referred to by specifying the array name followed by one or more subscripts/index. Example: If a char name[10] = NorAzlina; name[5] = l; That is because element of location in array started with 0.

C++ recognizes that you have defined an array when you put bracket [ ] , after the array name. Syntax: DataType array variable [element-size];

If x is an n-element array, the array element are x[0], x[1], .., x[n-1]

Example: char nama [10];

When you define an array with a subscript or index, you instruct C++ to reserve a specific number of memory location for that array.

Lecturer: Wannoraini Abdul Latif

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

char name[10] = NorAzlina name


Element-size

in memory : name[0] name[1] o r A z l i n a \0 name[2] name[3] name[4] name[5] name[6] name[7] name[8] name[9] N

Element location

7.2

Each element in an array occupies the same amount of storage as non-array of variable of the same data type. Your program may refer elements using formulas for subscripts.

One-dimensional array One-dimensional array is an array with one subscript. Example: char name [7]; Declaration

Array can be defined as any type in C++ 1. 2. 3. 4. Syntax: Lecturer: Wannoraini Abdul Latif 3 Integer array Floating-point arrays Character arrays String arrays ..

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

DataType arrayVariable[element-size]; Computer Memory char name[5] = ADAM;

A In computer memory

An element of an array (first element)

Memory location (element location) Aname[0] D name[1]Aname[2]Mname[3] \0name[4]

Location subscript/index

Initialisation

o o
1. 2. 1.

You must assign a value to array elements before using them. Here are two ways to initialise elements in an array: Initialise the elements of definition time. Initialise the elements in the program. Initialise the elements at definition time. o You can initialise character array as a string or a single character. Example: char weather[5] = Rain; or char weather[4] = {R, a, i, n}; single character string

C++ automatically initialises global arrays to null zeros. Therefore, global


character array elements are null, and numeric array elements all contain zero. You should limit the use of global arrays, explicitly initialise them to zero, even though C++ does this for you, to clarify your attentions. You cannot initialise an array, using the assignment statement operator and braces, after you define it. Example: 4

Lecturer: Wannoraini Abdul Latif

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

char name[10]; name = Ali; You can initialise arrays in this manner only when you define them. Example: char name[10] = Ali; If you want to fill an array with data after you define the array, you must do so element-by-element or by using function. Example: name [0] = A; 2. Initialise the elements in the program.

We do not know the contents of arrays when you define them. The for loop is a perfect tool for looping through arrays when you fill them with values. You cannot assign one array to another. You have to copy the arrays one element at a time, using a loop. Example:
for (ctr = 0; ctr<ARRAYSIZE; ctr++) { savedSales [ctr] = totalSales[ctr]; }

Memory location Empty list When values are assigned, memory automatically located the spaces int list [5];

list [0] list [1] list [2] list [3] list [4]

/*assigning value to selected elements*/ list [0] = 23; /*first element*/ list [3] = 15; /*fourth element*/

23

list [0] list [1] list [2]

/*inputting value to fifth element */ cin >> list[4]); Lecturer: Wannoraini Abdul Latif

15

list [3] list [4] 5

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

Passing Array to function Example:


/*this program show passing array #include <iostream.h> #define STUDENT 5 int avgAll (int [ ]); main() { int marks [STUDENT]; int i = 0, total = 0, avg; cout << Please enter all marks :; for (i = 0; i < STUDENT; i++) { cin >> marks[i]; } avg = avgAll(marks); } int avgAll(int marks [ ]) { int i, total = 0; for (i = 0; i < STUDENT; i++) { total += marks[i]; } return (total / STUDENT); } /*passing array to function*/ to function*/

cout << Average = << avg;

7.3

Array processing Searching a Value in a List

o o

If and for loop is a command used to search an array. To search an array for a specific value, look at each element in that array, comparing with the if statement to see whether they match.

Lecturer: Wannoraini Abdul Latif

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

Example:
/*this program shows how to search value in array*/ #include <iostream.h> #define SIZE 15 main () {

int List[SIZE] = {99, 55, 18, 29, 23, 56, 78, 23, 45, 60, 221, 34, 65, 76, 85}; int highValue, ctr; highValue = List[0]; /*initialises with first array element*/

for (ctr = 0; ctr < SIZE; ctr++) { if (List[ctr] > highValue) /*stores current value if it is*/ highValue = List[ctr]; /*higher than the highest so far*/ } cout << The highest number in the list is << highValue; }

Sorting o o A method for putting arrays in a specific order (such as alphabetical order or numerical order in ascending order or descending order) There are several ways to sort arrays. 1. 2. 3. o Bubble sort Quick sort Shell sort The basic goal of each method is to compare each array element to another array element and swap them if the higher one is less than the other. Bubble Sort

Easy to understand. Easy to program, but slower compared to many other method. Values in the array are compared to each other, a pair at a time and swapped, if they are not in back-to-back order. The lowest value eventually floats to the top of the array, like a bubble in a glass of ice cream soda.

Lecturer: Wannoraini Abdul Latif

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

Example:
/*Example using bubble sort*/ #include <iostream.h> #define SIZE 15 void sortArray (int [ ]); main () { int List[SIZE] = {99,55,18,29,23,56,78,23,45,60,221,34,65,76,85}; } sortArray (List);

void sortArray (int List [ ]) { int temp; /*temporary variable to swap with*/ int index1, index2; /*need two loop counters to swap pairs of numbers*/ /*sort the array*/ for (index1 = 0; index1 <=(SIZE - 1); index1++) { for (index2 = (index1 + 1); index2 < SIZE; index2++) { if (List[index1] > List[index2]) /*swap if this pair*/ { temp = List[index1]; /*is not in order*/ List[index1] = List[index2]; /*cause the ascending order*/ List[index2] = temp; } } cout << List[index1]; } }

7.4

Two dimensional Array

It is actually an array of arrays. Sometimes called tables or matrices, having at least two dimensions rows and columns, and sometimes they have even more dimensions. Syntax: dataType variablearray[rowcount] [columncount];

Example: int a[2][5]; Array elements are stored row by row. 8

Lecturer: Wannoraini Abdul Latif

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

Data in the two-dimensional array, always in the same type of data. The number of dimensions corresponds to the dimensions in the physical world.

7.4.1

Declaration

When you define a multidimensional array, you must let C++ know that the array has more than one dimension. Put more than one subscript in brackets after the arrays name. Example: int teams [15] [10]; /*reserve a two-dimensional table */

C++ passes all arrays, including multidimensional arrays, by address. When dimensioning a two-dimensional table, always put the maximum number of rows first, and the maximum number of columns second. Example:

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

1 1 5 9

3 4 8 12

Rows

0 1 2

Multidimensional arrays are stored in row order. Despite the two-dimensional table organization, your memory is still in sequential storage.

C++ has to map multidimensional arrays to single-dimensional memory, does it so in row order. Therefore, the first row (array) completely fills memory before the second row.

7.4.2 Why we use multidimensional array? It is more efficient than one-dimensional array when a program had more than one array, as we have to declare many variables and also had many statements Lecturer: Wannoraini Abdul Latif 9

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

7.5

String Array We cannot store an array of strings, but we can store an array of character pointers, and each character pointer can point to a string in memory.

By defining an array of character pointer, you define a ragged-edge array. It is similar to two-dimensional tables, except that instead of each row being the same length (the same number of elements), each row contains a different number of characters.

Example: G M J M S

All two-dimensional table have been fully justified.

char names [5] [10] = {{George},{Michel},{Joe},{Marcus},{Stephanie}};

e i o a t

o c e r e

r h \0 c p

g e u h

e l s a

\0 \0 \0 n i e \0

But, much of the table is wasted space. The unfilled elements contain null zeros because C++ zeros out all elements you do not initialise in arrays. This uses too much memory.

To fix memory-wasting problem of fully justified tables, you should define a single-dimensional array to character pointers. Each pointer points to a string in memory, and the string do not have to be in the same length. Example:
char *names [5] = {{George}, {Michel}, {Joe}, {Marcus}, {Stephanie}};

The asterisk (*), before names make this an array of pointers. The strings are being pointed to by the array elements. The string wastes no data. Each string takes only as much memory as needed by the string and its terminating zero. This gives data a ragged-right appearance.

Lecturer: Wannoraini Abdul Latif

10

TCS1013 INTRODUCTION TO PROGRAMMING

CHAPTER 7

names

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

G e \0 M i \0 J M \0 S o a t

o c e r e

r h \0 c p

g e

e l

\0 \0

u h

s \0 a n i e \0

Lecturer: Wannoraini Abdul Latif

11

Potrebbero piacerti anche