Question: To increase program readability, C++ provides for enumerated data types. Such types allow descriptive names to be assigned an order and used in place of

To increase program readability, C++ provides for enumerated data types. Such types allow descriptive names to be assigned an order and used in place of a sequence of integers. An enumerated data type is declared by a statement beginning with the keyword enum, followed by an identifier and then by a list of descriptive names enclosed in braces. Thus,

enum week_days {Monday, Tuesday, Wednesday, Thursday, Friday};

establishes an order among the workdays of the week. A variable of this type can then be declared by using week_days as the type within a variable declaration statement. Thus,

week_days day;

declares day to be a variable of type week_days.

Variables of enumerated data types can be used as array indices. For example, if hours_worked is declared by the statement

float hours_worked[5];

then the expression hours_worked[Tuesday] provides a more descriptive reference to the second entry in the array than hours_worked[1].

Execute the following program and explain the results.

#include

using namespace std;

enum coin_type {nickel, dime, quarter};

int main()

{

coin_type coin;

int holdings[3] = {3, 6, 2};

int total = 0;

for (coin = nickel; coin <= quarter; coin++)

{

switch (coin)

{

case nickel: total = total + (5 * holdings[coin]); break;

case dime: total = total + (10 * holdings[coin]); break;

case quarter: total = total + (25 * holdings[coin]); break;

}

}

cout << "Total holdings are " << total << " cents. ";

return 0;

}

Although enumerators are stored in memory as integers and you can use them as array subscripts, expressions like coin++ do not work the same as for integers. Instead you must convert coin++ to an equivalent expression

coin = static_cast(coin + 1)

Replace coin++ with coin = static_cast(coin + 1)in the for loop.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!