Chapter 5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

CHAPTER 5: BASIC DATA STRUCTURES

5.1. Arrays and Strings

What is an Array?
So far, we have been using variables of different types for our data. A single variable was
capable of storing only one value at a time. We would probably have used the code shown
below if we were required to work with the ages of 4 students. Example:
age1

int age1; int age2; 4 bytes


int age3; int age4;
age2
cout<<"Enter ages of five students: ";
cin>>age1>>age2>>age3>>age4; ... age3

Each

of the variable declarations in the above example cause only age4

enough memory to be reserved to hold one value of type int, as shown

in the figure.

An array allows us to group a number of values of the same type into


one large unit. The individual values are stored together in consecutive memory locations
and are referred to as elements of the array.
4 bytes 1st element

2nd element
age
3rd element
4th element

In the figure shown, the name of the array is age, it can store 4 elements, and each one is
an integer.

Defining and Using Arrays


In C++, the array shown in the figure above is defined as follows:
int age [4];

where the type of the array is followed by the name which is followed by the size of the
array within square brackets. The size specifies the maximum number of elements that the

Introduction to Computing Handout Compiled by: Mohammed A. 40


array can hold. Each element will be of the type specified in the declaration. When the
compiler sees this statement, it reserves enough memory (contiguous) to hold 4 values of
type int. Arrays of any data type can be defined. All of the following are valid array
declarations.
long populations [210]; //210 elements of type long float salaries [15]; //15
elements of type float char name [30]; //30 elements of type char

Note:
• The number in brackets specifying the size of the array must be a constant or an
expression that evaluates to a constant, and should also be an integer.
• The size of the array is fixed. There is no way to change the size after the array is
defined.

Example:
const int SIZE = 110; int
num_people = 100;
char letters [26]; //OK: 26 is a literal constant
double atomic weights[SIZE]; //OK: SIZE is a const variable float heights[num_people]; //ERROR:
num_people is a non const variable
Subscripts
Even though an entire array has only one name, the
elements may be accessed and used as individual 0
variables. Each element is assigned a number known as age1 a
subscript or an array index. 2

3
To access a specific element, we use the name of the array followed by the
subscript of the element in square brackets. An element, when accessed by its
subscript, behaves exactly like a variable of the array's type. Example:
5. int age[4]; //an array to hold 4 integers
6. age[0] = 23; //age[0] is a variable of type int
7. age[1] = 15;
8. age[2] = 12;
9. age[3] = age[1] + age[2];
10. cout<<"Age of first student = "<<age[0];
11. cout<<"\nTwo times age of third student = "<<age[2]*2;

Note:
• Subscript numbering in C++ always starts at zero. The subscript of the last element in
an array is one less than the total number of elements in the array. Therefore, in the
above example, there is no such element as age[4].

Introduction to Computing Handout Compiled by: Mohammed A. 41


• Make sure you understand the differences between array definition and element
access. An array definition begins with a type specifier and the number inside the
brackets (the size specifier) specifies how many elements the array holds. When
working with an element of the array, there is no type specifier and the number inside
the brackets (the subscript) indicates which element is being accessed. Also note that
the size specifier must be a constant whereas any variable can be used as a subscript.

Individual elements of different arrays maybe used as normal variables. However, it is not
possible to assign one array to another or use an array in an expression hoping to affect all
its elements. Examples:
5. int age[4];
6. int student_age[4];
7. age[0] = 23;
8. age[1] = 15;
9. age[2] = 12;
10. age[3] = 27;
11. for (int i=0; i<4; i++)
12. student_age[i] = age[i]; //OK
13. student_age = age; //ILLEGAL
14. cout<<age*2; //ILLEGAL

Arrays provide a convenient method for working with groups of related values. The
same name can be used to refer to the group and loops can be used to access each
element in turn (see lines 11 and 12 above). The following example program
demonstrates this convenience. The program accepts the scores of students, calculates
the average, and displays the difference from the average for each student. Example:
1. #include <iostream.h>
2. using namespace std;
3.
4. int main() {
5. const int TOTAL = 5;
6. float scores[TOTAL], sum=0, avg;
7. cout<<"Score Averager\n";
8. //Read the scores
9. for (int i=0; i<TOTAL; i++) {
10. cout<<"Enter score for Student "<<i+1<<":> ";
11. cin>>scores[i];
12. }
13. //Caculate the average
14. for (int j=0; j<TOTAL; j++)
15. sum+=scores[j];
16. avg = sum/TOTAL;
17. cout<<"\nAverage = "<<avg<<endl;
18. //Display the difference
19. for (int k=0; k<TOTAL; k++) {
20. cout<<"\tThe difference from average for Student "

Introduction to Computing Handout Compiled by: Mohammed A. 42


21. <<k+1<<" is "<<scores[k]avg<<endl;
22. }
23. return 0;
24. }
Note the use of the constant TOTAL in the above example. Modifying the program to
accept 50 students is as simple as changing the definition on line 5 to
5. const int TOTAL = 50;

Initializing Arrays
From what we have seen so far, if we want to initialize the elements of an array, we have
to write separate assignment statements for each element.
int age[4]; age[0]=25;
age[1]=12; //and so on

Fortunately, C++ allows us to initialize array elements when they are defined.
int age[4] = {25, 12, 15, 27};

This statement is made up of an array definition followed by an assignment operator and


an initializer list. The initializer list contains a set of comma separated values within a pair
of curly braces. These values are stored in the array elements in the order they appear in
the list. (The first value, 25, is stored in age [0], the second value, 12, is stored in age [1],
and so forth).

It is possible to define an array without specifying its size, as long as you provide an
initialization list that includes a value for every element. C++ automatically makes the
array large enough to hold all the initialization values. For example, the following
definition creates an array with five elements:
double factors [] = {1.0, 1.5, 2.0, 2.5, 3.0};

What happens if you use an explicit array size, but it doesn’t agree with the number of
initializers? If there are too few initializers, the missing elements will be set to 0. If there
are too many, an error is signaled.
int age [4] = {25, 12}; //age [2] and age [3] will be set to 0 double factors [4] = {1.0, 1.5, 2.0, 2.5,
3.0}; //ERROR!

Exercises:
1. What are the output of the following pieces of code? a)
5. double balance [5] = {100.0, 250.0, 325.0, 500.0, 1100.0};
6. const double INT_RATE = 0.1;
7. cout <<setprecision (2);
8. for (int count = 0; count < 5; count++)
9. cout << (balance[count] * INT_RATE) << endl;

b)
5. const int SIZE 5;
6. int count;

Introduction to Computing Handout Compiled by: Mohammed A. 43


7. int time[SIZE] = {1, 2, 3, 4, 5},
8. speed[SIZE] = {18, 4, 27, 52, 100},
9. dist[SIZE];
10. for (count = 0; count < SIZE; count++)
11. dist[count] = time[count] * speed[count];
12. for (count = 0; count < SIZE; count++)
13. {
14. cout << time[count] << " ";
15. cout << speed[count] << " ";
16. cout << dist[count] << endl;17. }
2. Develop a program that finds the maximum and minimum values in an integer array.
The values are to be entered by the user.
3. Develop a program that sorts an array of integers in increasing order.
4. Develop a program that calculates the mean, median, mode, and standard deviation of
an array of floating point numbers.

Character Arrays and Strings


A string is a special array of characters. The strings we have seen until now have been
unnamed string constants used in cout statements, such as
cout<<"Hello World!\n";

In prestandard C++, a string is an array of type char ending with a null character
('\0'). Character arrays can be defined, used, and initialized just like any other array.
char greeting[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\n', '\0'};

Strings are special because unlike other arrays,


• We have an alternate form of initialization, using double quotes
char greeting[] = "Hello World!\n";
This statements creates the null terminated character array shown above.
• Strings can be used with cin and cout like any other variable.
5. char hi[] = "Hello, ";
6. char name[30];
7. cout<<"Enter your name:> ";
8. cin>>name;
9. cout<<hi<<name<<"!\n";

Note: The Standard C++ Library defines a string type. The strings defined here as "a null
terminated array of characters" are now commonly known as Cstyle strings or CStrings.
From now on, unless specified, the term strings refers to CStrings.

If you try running the above example and enter your full name as input, you will get an
output that looks like the following
Enter your name:> Mohammed Ahmed Hello,
Mohammed!

Introduction to Computing Handout Compiled by: Mohammed A. 44


Where did the father's name go? It turns out that when using cin with the extraction
operator (>>) a space is considered as a terminating character. Thus strings consisting of a
single word are read, but anything typed after a space is thrown away. To read text
containing blanks we use another function, cin. Get (). In the above example, change line
8 to
8. cin.get(name, 30);

The first argument to cin.get() is the array address where the string being input will be
placed. The second argument specifies the maximum size of the array. This program now
works as expected.
Enter your name:> Mohammed Ahmed Hello,
Mohammed!Note:

• Functions of this type are known as member functions and will be discussed later.
• There is a potential problem when you mix cin.get() with cin and the extraction
operator (>>). This problem and the method to avoid it are to be observed in the lab.

Passing Arrays to Functions


Functions can be written to process the data in arrays. Usually, such functions accept
an array as an argument. When a single element of an array is passed to a function, it is
handled like any other variable. Example:
1. #include <iostream>
2. using namespace std;
3.
4. void showValue(int num)
5. {
6. cout<<num<<endl;
7. //just display an int
8. }
9.
10. int main ()
11. {
12. int myArray[]={1, 2, 3, 4, 5};
13. showValue(myArray[3]);
14. return 0;
15. }

If the function were written to accept the entire array as an argument, it would be set up as
follows
4. void showValue(int num[], int N)
5. {
6. for (int i=0; i<N; i++)
7. cout<<num[i];8. }

and the function call would be like

Introduction to Computing Handout Compiled by: Mohammed A. 45


13. showValue(myArray, 5);
Notice that along with the array, the size of the array is also passed to showValues. This is
so that the function knows how many values there are to be processed. Also notice that
there is no size specifier within the brackets following num in the function header.

Note: Unlike the arguments we have seen before, array elements will not be copied to the
array specified in the parameter list. Instead, the original array itself is accessed by the
function with a different name. (In the above example, num simply refers to myArray).
This means that any modification made to the array inside the function will remain even
after the function completes. This will be discussed in detail in chapter 6.

5.2. Multidimensional Arrays

The arrays we have seen so far are said to be one dimensional arrays. Sometimes though we
may want to work with data requiring multidimensional arrays for example, matrices and
data in the form of a table.

[ 1 2 3

A=4 5 6 ]
3 5 7

C++ allows us to have arrays of more than one dimension. Each dimension is represented as a
subscript in the array. Therefore, a two-dimensional array has two subscripts; a three-
dimensional array has three subscripts; and so on. Arrays can have any number of
dimensions, although it is highly unlikely that we will require arrays of more than two
dimensions.

Defining and Using TwoDimensional (2D) Arrays


It is best to think of a 2D array as a table having rows and columns of elements, as shown
in the grade sheet above. To define a 2D array, two size specifiers are required: the first
one is for the number of rows and the second one is for the number of columns.
float scores [3][4];

Each element in a 2D array is accessed with two subscripts: the first one is for its row and
the second for its column. The following figure shows all the elements for the array
defined above.

Introduction to Computing Handout Compiled by: Mohammed A. 46


The elements are used in a program just as a 1D array
score [1][2] = 80.5;

this statement sets value for the third column of the second row to be 80.5.
The following program is fairly complex and demonstrates the usage of arrays. Compile it
and observe the results. Make sure you understand how it works. (You may want to
change the value of STUDENTS to something smaller) Example:
1. #include <iostream.h>
2. #include <iomanip.h>
3. using namespace std;
4.
5. int main () {
6. const int STUDENTS = 80;
7. const int COURSES = 4;
8. float scores[STUDENTS][COURSES];
9. cout<<"Course Average Calculator\n";
10. int i, j;
11. //read the scores
12. for (i=0; i<STUDENTS; i++)
13. {
14. cout<<"Enter scores for student "<<i+1<<endl;
15. for (j=0; j<COURSES; j++)
16. {
17. cout<<"\tFor Course "<<j+1<<":> ";
18. cin>>scores[i][j];
19. }
20. }
21. //calculate the averages
22. float sum=0, avg[STUDENTS];
23. for (i=0; i<STUDENTS; i++) {
24. sum=0;
25. for (j=0; j<COURSES; j++)
26. sum+=scores[i][j];
27. avg[i] = sum/COURSES;
28. }
28.
29. //First display the column headers
30. cout<<setw (4) <<"No.";
31. for (j=0; j<COURSES; j++)

Introduction to Computing Handout Compiled by: Mohammed A. 47


32. cout<<setw (10) <<j+1;
33.
34. cout<<setw(10) <<"Average"<<setprecision(2)<<right<<endl;
35. cout<<setw(4+10*(COURSES+1))<<setfill('~')<<'~'
36. <<setfill(' ')<<endl;
37. //Then display the values
38. for (i=0; i<STUDENTS; i++) {
39. cout<<setw(4)<<i+1;
40. for (j=0; j<COURSES; j++)
41. cout<<setw(10)<<scores[i][j];
42. cout<<setw(10)<<avg[i]<<endl;
43. }
44. cout<<setw(4+10*(COURSES+1))<<setfill('~')<<'~'
45. <<setfill(' ')<<endl;
46. return 0;
47. }
Initializing TwoDimensional Arrays
You can consider a 2D array to be an array of arrays. The initialization statement uses an
initializer list where each element is by itself an initializer list for a single row.
float scores [2][3] = {{1, 2, 3}, {4, 5, 6}};

The elements of the row are assigned the values {1, 2, 3} and those on the second row get
{4, 5, 6};

Exercises:
1. Write a program that accepts a 2D integer array from the user and
a. Sums all the elements
b. Stores the sum of each row in a 1D integer array
c. Stores the sum of each column in a 1D integer array

2. Write a program that accepts two square matrices of identical dimensions from the
user and
a. Transposes the two matrices and displays the results
b. Performs matrix addition and stores the result in a third matrix
c. Performs matrix multiplication and stores the result in a third matrix

5.3. String Manipulations

Working with Whole Strings


The C++ library provides many functions for manipulating and testing strings. The
following functions are defined in the header file string.h (or cstring for standard C++).
All of the examples shown below must include the header file.

strlen: takes a string as an argument and returns its length. The length of a string is the
number of characters up to, but not including, the null terminator. Example:

Introduction to Computing Handout Compiled by: Mohammed A. 48


char name[50] = "Abebe Kebede"; int len1, len2;
len1 = strlen(name); //l1 is now 12 len2 = strlen("Hello
World"); //l2 = 11

Note: Do not confuse the length of the string with the size of the array holding it.

strcat: takes two strings as arguments and concatenates them, giving a single string that
consists of all the characters of the first string followed by all the characters of the second.
The string passed as the first argument will hold the concatenated string.
Example: str1
char str1[13] = "Hello "; char str2[] = H e l l o \0
str2 "World!" cout<<"Before: "<<str1<<endl;
W o r l d \0
strcat(str1, str2); cout<<"After: strcat (str1, str2)
"<<str2<<endl;
H e l l o W o r l d \0

str1
Note:
• strcat will not add a space between the two strings. You have to do that yourself.
• Make sure that the array holding the first string is large enough to hold both strings
together plus a null character.

strcpy: is used to copy one string to another. This is because arrays can't be copied
using the assignment operator (=). Example:
char str1[20];
char str2[] = "Second String"; strcpy (str1, str2); cout<<"str1:
"<<str1<<endl; strcpy (str2, "Another String"); cout<<"str2:
"<<str2<<endl;

Note:
• If there is anything already stored in the first string, it will be overwritten.
• If the length of the second string is larger than the array size of the first string, a
buffer overflow may occur.

strcmp: takes two strings as arguments and returns an integer result which is
• 0 if the two strings are equal
• negative if the first string comes before the second in alphabetical order
• positive if the first string comes after the second in alphabetical order Example:
char password [30]; char quit [] = "exit";
cout<<"Enter your password: ";
cin>>password;
if (strcmp (password, "classpass”) ==0)
cout<<"Logon Successful!\n";

Note:
• strcmp is case sensitive.

Introduction to Computing Handout Compiled by: Mohammed A. 49


• The! operator can be used with strcmp but it is confusing (opposite in meaning)
Example:
char str1[30], str2[30]; cout<<"Enter first string: ";
cin>>str1;
cout<<"Enter second string: "; cin>>str2;
if (! strcmp (str1, str2))
cout<<"The two strings are identical\n"; else if (strcmp (str1, str2) <
0)
cout<<str1<<" comes before "<<str2<<endl; else
cout<<str2<<" comes before "<<str1<<endl;

strncpy and strncat: are alternate versions of strcpy and strcat. These functions take one
extra integer argument. In both cases, this integer specifies how many characters to take
from the second string. strncpy and strncat are safer than strcpy and strcat as they help
minimize buffer overflow errors.

Note: Standard C++ contains another header file, strings, for working with standard
strings. This header file is entirely different from string.h (or cstring)

String/Numeric Conversion
There is a difference between a number stored as a string and one stored as a numeric
value. For example
char strnum[] = “100”; int num = 100; '1' '0' '0' \0

100
C++ provides functions for converting strings to numbers and vice versa.
The following functions are defined in stdlib.h (or cstdlib in standard C++). atoi: accepts a
string as an argument and returns an integer which is the converted value.
int num = atoi("4123"); //num = 4123

Similarly, we have atol(to long) and atof(to float/double);


long lnum = atol ("12345678"); float fnum = atof
("2.34");

itoa (not standard): converts an integer to a string. It accepts three


arguments argument1 the integer to be converted argument2 the string to
hold the converted result argument3 the base (8, 10, or 16)
char strnum[4]; itoa(102, strnum,
10);

Note: make sure that the size of the character array is enough to hold the converted value.

Introduction to Computing Handout Compiled by: Mohammed A. 50


Character Testing
C++ provides functions that allow us to test the value of a character. All of them take a
single character and return either true (non 0 value) or false (0). These functions are
defined in the ctype.h (or cctype) header file.

isalpha: returns true if the character is a letter of the alphabet


isalnum: an alphabet or digit (from 0 9) isdigit: a digit
islower: a lowercase character
isupper: an uppercase character
ispunct: punctuation isspace:
whitespace Example:
char ans[10];
cout<<"Enter a string: "; cin>>ans;
int i, len = strlen(ans); for (i=0; i<len; +
+i)
{
if (!isdigit(ans[i]))
break;
}
if (i == len)
cout<<"You entered a number\n"; else
cout<<ans<<" is not a number\n";

Exercise:
Write a program that checks whether a given password is strong. Requirements for a
strong password are:
• Minimum of 10 characters
• a mixture of uppercase letters, lowercase letters, digits, and punctuation marks.
• Does not contain whitespace

Case Conversion
There are two functions defined in ctype.h (or cctype) that are used for case conversion.
toupper: returns the uppercase of a character
tolower: returns the lowercase of a character

char test = toupper('a'); //test = 'A';

Arrays of Strings
You can consider a two dimensional array of characters as an array of strings. Example:
const int MONTHS = 13; const int
MAX = 10;
char ourMonths[MONTHS][MAX] = {"Meskerem", "Tikimt", "Hidar", "Tahsas",
"Tir", "Yekatit", "Megabit", "Miazya", "Ginbot", "Sene", "Hamle",
"Nehase", "Pagume"}; for (int i=0;
i<MONTHS; ++i)
cout<<ourMonths[i]<<endl;
Exercise:

Introduction to Computing Handout Compiled by: Mohammed A. 51


Modify the day of week program discussed in class to use a string array instead of the
switch statement.
5.4. Introduction to Pointers

Recall that every variable is allocated a section of memory large enough to hold a value of
the variable's data type 1Byte for char, 2Bytes for short and so on. Each byte of memory
has a unique address. A variable's address is the address of the first byte allocated to the
variable. Consider the following declarations

char letter; short number;


float amount;

In this example, 1200 is the address of the char variable, letter, 1201 is the address of the
short variable, number, and 1203 is the address of the float variable, amount.

Pointer variables, which are often just called pointers, are designed to hold memory
addresses. With pointer variables you can indirectly manipulate data stored in other

1200 1201 1203

ptrl ptrn ptra

In the above diagram, ptrl points to letter, ptrn points to number, and ptra points to
amount. A pointer is declared as follows.
int *ptrInt;

The above statement defines a pointer to a variable of type int called ptrInt. The asterisk
(*) in front of the variable name indicates that ptrInt is a pointer variable. The int data
type indicates that ptrInt can be used to hold the address of an integer variable. Getting the
address of a variable is accomplished with the address operator (&) in C++. When this
operator is placed in front of a variable name, it returns the address of that variable.
Example:
int x = 10; int
*ptrInt;
ptrInt = &x; //now ptrInt points to the variable x
Pointers allow us to indirectly access and modify the variable being pointed to. When an
asterisk is placed in front of a pointer variable name, it dereferences the pointer it gives
the value of the variable that the pointer is pointing to.
Example:
int x = 10; int *ptrInt =
&x;
cout<<*ptrInt; //displays 10
In this usage, the asterisk is known as the indirection operator.

Introduction to Computing Handout Compiled by: Mohammed A. 52


Note that the asterisk can be used as a multiplication operator, in the definition of
a pointer, and as the indirection operator. The following example demonstrates the
usage of pointers.
1. #include <iostream.h>
2. using namespace std;
3. int main ()
4. {
5. int x = 20, y = 30;
6. //define pointers to x and y
7. int *p = &x, *q = &y;
8. //print the values and addresses
9. cout<<"Value of x = "<<*p
10. << “, \address of x = "<<p<<endl;
11. cout<<"Value of y = "<<*q
12. << “, \tAddress of y = "<<q<<endl;
13. //Modify x using the pointer
14. *p = 40; //changes the value of x to 40
15. cout<<"After *p = 40\n";
16. cout<< “New value of x = "<<x<<endl;
17. //Assigning the value of x to y using pointers
18. *q = *p; //now the value of y = 40
19. cout<<"After *q = *p\n";
20. cout<<" New value of y = "<<*q<<endl;
21. //changing the value of y using the variable
22. y = 10;
23. cout<<"After y = 10\n";
24. cout<<" Value of y = "<<*q<<endl;
25. //Assigning the pointers themselves
26. q = p; //now q points to x
27. cout<<"After q = p\n";
28. cout<<" Value pointed by q = "<<*q<<endl
29. <<" Value pointed by p = "<<*p<<endl
30. <<" Value in p = "<<p<<endl
31. <<" Value in q = "<<q<<endl;
32. return 0;
33. }

Value of x = 20,Address of x = 0xbfe75378


Value of y = 30,Address of y = 0xbfe75374
After *p = 40
New value of x = 40
After *q = *p
Sample Output New value of y = 40
Arrays and Pointers After y = 10
An array name, without Value of y = 10
brackets and a subscript,After q = p
Value pointed by q = 40
Value pointed by p = 40
Value in p = 0xbfe75378
Introduction to Computing Handout Compiled by: Mohammed A. 53
Value in q = 0xbfe75378
actually represents the starting address of the array. This means that an array name is
really a pointer. Example:
short values[] = {15, 23, 42}; cout<<*values<<endl; //prints 15

In the above example, values points to the first element of the array. Therefore, *values
gives us the value of the first element of the array (values [0]).

5.5. Enumerated Data Types

So far we have been using data types that are built into the C++ language, such as int and
double. However, C++ also allows us to create our own data types. In the remaining
sections of this chapter, we will see the constructs that allow us to define our own data
types.

An enumerated data type is a programmer defined data type that contains a set of named
integer constants.
enum Mood {Depressed, Sad, Happy, Ecstatic};

The declaration shown above creates a data type named Mood. It is called an enumerated
type because the legal set of values that variables of this type can have are enumerated, or
listed, as part of the declaration. A variable of type Mood may only have values that are in
the list inside the braces. These permissible values are called enumerators.

Note that the enum statement above does not actually create any variables it just defines
the data type.

A variable of the Mood type would be defined just like a variable of any other type.
Mood today;

Assignment and comparisons might look like this.


today = Ecstatic; if (today ==
Ecstatic)
{
cout<<"You must be in a really good mood!\n"; }

Note that there are no quotation marks around Happy or Ecstatic. These are named
constants, not string literals.

So what exactly is the value of Happy? By default, the first enumerator is assigned the
value 0. Each subsequent enumerator is assigned a value one greater than the value of the
enumerator. Therefore, the symbol Depressed is stored as the integer 0, Sad is stored as
the integer 1, Happy is stored as 2 and Ecstatic is stored as 3. If you don't like the way the
enumerator values are assigned by default, you can explicitly assign a value to an
enumerator. This value need not be unique. As before, in the absence of an explicit
assignment, the value assigned to an enumerator is one greater than its immediately

Introduction to Computing Handout Compiled by: Mohammed A. 54


preceding element. Remember that if you do assign values to the enumerators, they must
be integers. Example:
enum Coins {And = 1, Amist = 5, Asir = 10, Simuni = 25, Hamsa = 50}; enum Years {Previous = 2000,
Current, Next};
//Here Current = 2001, Next = 2003 enum Constants {Pi = 3.14, e =
2.72 }; //Error!
Even though the values in an enumerated data type are actually stored as integers, you can
not always substitute the integer value for the symbolic name.
Coins oneCent = And; //legal
Coins fiftyCent = 50; //Illegal use Hamsa instead

You can, however, test an enumerated variable by using an integer value instead of a
symbolic name.
Coins b = Asir;
if (b == Asir) //legal cout<<"You have 10
cents"; if (b != 10) //Still legal
cout<<"You don't have 10 cents";

You can in fact use relational operators with enumerators in any way you like. For
example, both usages shown below are legal.
enum Mood {Depressed, Sad, Happy, Ecstatic};
Mood today = Happy, yesterday = Sad; if (today < yesterday)
cout<<"Things are bad, huh? \n";
else
cout<<"Feeling better! \n";

if (today >= 2)
cout<<"You are in a good mood today!\n";

Note: Annoyingly enum types don't behave well with cin and cout statements. cout treats
variables of enum types as integers. A program that attempts to use cin to read a value for
an enumerated type will not compile. Example:
enum cppClasses {Tuesday=2, Saturday=6}; cppClasses
today = Tuesday; cout <<today; //outputs 2

One of the advantages of an enumerated data type is that the symbolic names help make a
program selfdocumenting. The symbolic names may also be used in a switch statement as
they are associated with integer values.
Example:
1. #include <iostream.h>
2. using namespace std;
3.
4. int main ()
5. {
6. enum Mood {Depressed, Sad, Happy, Ecstatic};
7. int ans;
8. cout<<"Mood Companion\n";
9. cout<<"What is your mood today? ";
10. cin>>ans;

Introduction to Computing Handout Compiled by: Mohammed A. 55


11. switch (ans)
12. {
13. case Depressed:
14. cout<<"Bad day, huh? \n";
15. break;
16. case Sad:
17. cout<<"Don't worry, be happy\n";
18. break;
19. case Happy:
20. cout<<"Nice day, huh?\n";
21. break;
22. case Ecstatic:
23. cout<<"Life is beautiful!\n";
24. break;
25. }
26. return 0;
27. }

Introduction to Computing Handout Compiled by: Mohammed A. 56

You might also like