0% found this document useful (0 votes)
0 views6 pages

Chapter Two

Uploaded by

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

Chapter Two

Uploaded by

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

Chapter two Data Structures and Algorithm Analysis

Chapter two

2. Arrays

An array is a sequence of objects all of which have the same type. The objects are called
the elements of the array and are numbered consecutively 0, 1, 2, 3, ... . These numbers are called
index values or subscripts of the array. The term “subscript” is used because as a mathematical
sequence, an array would be written with subscripts: a 0, a1, a2, …. The subscripts locate the
element’s position within the array, thereby giving direct access into the array.

If the name of the array is a, then a[0] is the name of the element that is in position 0, a[1]
is the name of the element that is in position 1, etc. In general, the ith element is in position i–1.
So if the array has n elements, their names are a[0], a[1], a[2], …, a[n-1].

We usually visualize an array as a series of adjacent storage


compartments that are numbered by their index values. For example, the
diagram here shows an array named a with5elements: a[0] contains 11.11, a[1]
contains 33.33, a[2] contains 55.55, a[3] contains 77.77, and a[4] contains
99.99.

The diagram actually represents a region of the computer’s memory


because an array is always stored this way with its elements in a contiguous sequence. The
method of numbering the ith element with index i–1 is called zero-based indexing. It guarantees
that the index of each array element is equal to the number of “steps” from the initial element
a[0] to that element. For example, element a[3] is 3 steps from element a[0].

Virtually all useful programs use arrays. If several objects of the same type are to be used
in the same way, it is usually simpler to encapsulate them into an array.

2.1 Processing Arrays

Arrays are usually processed using for loops. Look at the following C++ program.

int main(){
double a[3];
a[0] = 11.11;
a[1] = 33.33;
a[2] = 55.55;
}

The first line declares a to be an array of 3 elements of type double. The next three lines assign
values to those elements. Look how an array is accessed using for loop.

1|Page
Chapter two Data Structures and Algorithm Analysis

int main(){
const int SIZE=5; // defines the size N for 5 elements
double a[SIZE]; // declares the array’s elements as type
double
cout << "Enter " << SIZE << " numbers:\t";
for (int i=0; i<SIZE; i++)
cin >> a[i];
cout << "In reverse order: ";
for (int i=SIZE-1; i>=0; i--)
cout << "\t" << a[i];
}

Enter 5 numbers: 11.11 33.33 55.55 77.77 99.99


In reverse order:99.99 77.77 55.55 33.33 11.11

The first line defines the symbolic constant SIZE to be 5 elements. The second line
declares a to be an array of 5 elements of type double. Then the first for loop reads 5 values into
the array, and the second for loop prints them in reverse order.

The syntax for an array declaration is


type array-name[array-size];
where type is the array’s element type and array-size is its number of elements.

2.2 Initializing an Array

This program initializes the array a and then prints its values:

int main(){
float a[] = { 22.2,44.4,66.6 };
int size = sizeof(a)/sizeof(float);
for (int i=0; i<size; i++)
cout << "\ta[" << i << "]="<< a[i] << endl;
}

a[0] = 22.2
a[1] = 44.4
a[2] = 66.6

The first line declares a to be the array of 3 elements described above.


The second line uses the sizeof() function to compute the actual number of
elements in the array. The value of sizeof(float) is 4 because on this machine a
float value occupies 4 bytes in memory. The value of sizeof(a) is 12 because
2|Page
Chapter two Data Structures and Algorithm Analysis

the complete array occupies 12 bytes in memory. Therefore, the value of size is computed to be
12/4 = 3.

An array can be “zeroed out” by declaring it with an initializer list together with an
explicit size value, like this:

float a[7] = { 55.5,66.6,77.7 };

This array is declared to have 7 elements of type float; then its initializer list initializes
the first 3 elements with the given values and the remaining 4 elements with the value 0.

2.3 Using Arrays with Enumeration Types

In addition to the predefined types such as int and char, C++ allows you to define your
own special data types. This can be done in several ways, the most powerful of which use classes
as described in Chapter 11. We consider here a much simpler kind of user-defined type.

An enumeration type is an integral type that is defined by the user with the syntax

enum typename { enumerator-list };

Here enum is a C++ keyword, typename stands for an identifier that names the type being
defined, and enumerator-list stands for a list of names for integer constants. For example, the
following defines the enumeration type Semester, specifying the three possible values that a
variable of that type can have

enum Semester {FALL,SPRING,SUMMER};

We can then declare variables of this type:

Semester s1, s2;

and we can use those variables and those type values as we would with predefined types:

s1 = SPRING;
s2 = FALL;
if (s1 == s2) cout << "Same semester." << endl;

The actual values defined in the enumerator-list are called enumerators. In fact, they are
ordinary integer constants. For example, the enumerators FALL, SPRING, and SUMMER that
are defined for the Semester type above could have been defined like this:

const int FALL = 0;


const int WINTER = 1;

3|Page
Chapter two Data Structures and Algorithm Analysis

const int SUMMER = 2;

The values 0, 1, … are assigned automatically when the type is defined. These default values can
be overridden in the enumerator-list:

enum Coin {PENNY=1,NICKEL=5,DIME=10,QUARTER=25};

If integer values are assigned to only some of the enumerators, then the ones that follow are
given consecutive values. For example,

enum Month {JAN=1,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC};

will assign the numbers 1 through 12 to the twelve months.

Since enumerators are simply integer constants, it is legal to have several different enumerators
with the same value:

enum Answer {NO = 0,FALSE=0,YES = 1,TRUE=1,OK = 1};

This would allow the code

int answer;
cin >> answer;
:
if (answer == YES) cout << "You said it was o.k." << endl;

to work as expected. If the value of the variable answer is 1, then the condition will be true and
the output will occur. Note that since the integer value 1 always means “true” in a condition, this
selection statement could also be written

if (answer) cout << "You said it was o.k." << endl;

int main()
{ enum Day { SUN,MON,TUE,WED,THU,FRI,SAT };
float high[SAT+1] = {88.3,95.0,91.2,89.9,91.4,92.5,86.7};
for (int day = SUN; day <= SAT; day++)
cout << "The high temperature for day " << day
<< " was " << high[day] << endl;
}

The high temperature for day 0 was 88.3


The high temperature for day 1 was 95.0

4|Page
Chapter two Data Structures and Algorithm Analysis

The high temperature for day 2 was 91.2


The high temperature for day 3 was 89.9
The high temperature for day 4 was 91.4
The high temperature for day 5 was 92.5
The high temperature for day 6 was 86.7

2.4 Type Definitions

Enumeration types are one way for programmers to define their own types. For example,
enum Color { RED,ORANGE,YELLOW,GREEN,BLUE,VIOLET };
defines the type Color which can then be used to declare variables like this:

Color shirt = BLUE;


Color car[] = { GREEN,RED,BLUE,RED };
float wavelength[VIOLET+1] = {420,480,530,570,600,620};

Here, shirt is a variable whose value can be any one of the 6 values of the type Color and is
initialized to have the value BLUE, car is an array of 4 such Color type variables indexed from 0
to 3, and wavelength is an array of 6 float type variables indexed from RED to VIOLET.

Test run

int main(){
enum Color { RED,ORANGE,YELLOW,GREEN,BLUE,VIOLET };
Color shirt = VIOLET;
Color car[] = { GREEN,RED,BLUE,RED };
float wavelength[VIOLET+1] = {420,480,530,570,600,620};
cout<<"\nshirt = "<<shirt;
cout<<"\nwavelength[1] = "<<wavelength[5];
}

Output

Shirt = 5
Wavelength[1] = 620

C++ also provides a way to rename existing types. The keyword typedef declares a new name
(i.e., a synonym or alias) for a specified type. The syntax is typedef type alias; where type is the
given type and alias is the new name. For example, if you are used to programming in Pascal,
you might want to use these type aliases:

typedef long Integer;

5|Page
Chapter two Data Structures and Algorithm Analysis

typedef double Real;

Then you could declare variables like this:


Integer n=22;
const Real PI = 3.141592653589793;

Note the syntax for the typedef of an array type:

typedef element-type alias[];

It shows that the number of elements in an array is not part of its type. Look at the following
example.

void main(){
typedef int IntegerArray[];
IntegerArray a = {1,2,3};

for(int i = 0; i < 3; i++)


cout<<a[i]<<”,”;

Output

1,2,3

In the above example the first line make an alias IntegerArray for int data type. Now this alias
can declare an array of type int just because of the [] after its name.

6|Page

You might also like