Lesson # 4. Enumerations

Theory

Enumerations

The enum type declaration can be in the .cpp file at the top of the code (that is, outside of the functions), as well as in the header files.

int main()
{
  enum MyType { A, B, C }; // A=0 B=1 C=2
  enum YourType { D = 2, E, F = 0 }; // E=3
  MyType m = A;
}
Each enumerator is associated with a value of the underlying type. When initializers are provided in the enumerator-list, the values of enumerators are defined by those initializers. If the first enumerator does not have an initializer, the associated value is zero. For any other enumerator whose definition does not have an initializer, the associated value is the value of the previous enumerator plus one.
Enumerations in style of C++11:
int main()
{
  enum class Color { Red, Green, Blue };
  Color c = Color::Blue;
}

One more example:

enum Color { red, green, blue };
Color r = red;
switch(r)
{
    case red  : std::cout << "red\n";   break;
    case green: std::cout << "green\n"; break;
    case blue : std::cout << "blue\n";  break;
}
// int n = r; // error: no scoped enum to int conversion
int n = static_cast<int>(r); // OK, n = 0

Type conversion by static_cast

Sample 1:

char c = 97;
std::cout << static_cast<int>(c) << std::endl; // output 97, but not 'a'

Sample 2:

int i1 = 11;
int i2 = 3;
std::cout << i1/i2; // 3
float x = static_cast<float>(i1) / i2;  // output x = 3.66667

Labs and tasks

All the tasks that you did not have time to complete in class automatically become your homework. The homework must be completed before the next lesson.

Follow the rules:

  • To do the tasks, you must create a Visual Studio project: Lesson_4. When the tasks are done, it is necessary to upload the Lesson_4 project files (e.g. L4Task1Imp.cpp, L4Task1header.h and L4Task1main.cpp).
  • To do the tasks, you should use such C ++ structures as enumerations and switch statement.
  • All tasks must be done using functions, the results should be checked by assert statement from the header file , calling them from main with different arguments.
  • All functions and files must be accompanied by comments that describe the task.
Lab 1:

To do: Create a function (named printDay) that gets the number
— the day of the week (from 1 to 7) and returns the full name of the corresponding day (if 1 is entered, so function must print «Monday», if 2«Tuesday», etc.)

Note: Add a header file to your project. Type there a declaration of the enumeration and the signature of your method:

// enum type for representing a day: MON for Monday, etc.
enum Day {MON=1, TUE, WED, THE, FRI, SAT, SAN };
 
// prints given day to the standard output
void printDay(Day d);

Expected output:

please enter the number of a day of a week:
>> 2
Tuesday

[Solution and Project name: Lesson_4, file name L4Lab1Imp.cpp, L4Lab1main.cpp, L4Lab1header.h]

✍ Algorithm:

  1. Open Microsoft Visual Studio. Create a new console project, name your project Lesson_4. Among the Additional options mark Empty project and nothing more. Click Finish button.
  2. In the Solution Explorer window find a Source files folder, click the right mouse button on it and select Add -> New Item. We’re going to create two .cpp files. Call them as it is written in this lab description.
  3. In the Solution Explorer window find a Header files folder, click the right mouse button on it and select Add -> New Item. We’re going to create .h file. Give it a name as it is written in this lab description.
  4. First, let’s define an enumeration to store the names of the week days. The definition must be placed inside the header file. So, open header file and add the code:
  5. #ifndef L4LAB1HEADER_H
    #define L4LAB1HEADER_H
    // type for representing a day of a week
    enum Day { MON = 1, TUE, WED, THE, FRI, SAT, SAN };
    
    #endif L4LAB1HEADER_H
    
  6. Add the definition of our function printDay(). It must accept one parameter – the number of the day of a week (the type of parameter is Dayenum). The function definition must be placed inside the header file too:
  7. // prints given day to the standard output
    void printDay(Day);
    
  8. Open the code of L4Lab1Imp.cpp, we’re going to create an implementation of our function. Include the header file and std namespace:
  9. #include <iostream>
    #include <cassert>
    #include "L4Lab1header.h"
    using namespace std;
    
  10. Add a signature of your function:
  11. // prints given day to the standard output
    void print_month(Day d) {
      // ...
    }
    
  12. To check the day number we need to use Switch statement. Add the code inside the function scope:
  13. switch (d)
    	{
    	case 1:
    		std::cout << "Monday" << std::endl;
    		break;
    	case 2:
    		std::cout << "Tuesday" << std::endl;
    		break;
    	case 3:
    		std::cout << "Wednesday" << std::endl;
    		break;
    	case 4:
    		std::cout << "Thursday" << std::endl;
    		break;
    	case 5:
    		std::cout << "Friday" << std::endl;
    		break;
    	case 6:
    		std::cout << "Saturday" << std::endl;
    		break;
    	case 7:
    		std::cout << "Sunday" << std::endl;
    		break;
    	}
    
  14. Open the L4Lab1main.cpp. Include the header file and needed libraries:
  15. #include <iostream>
    #include <cassert>
    #include "L4Lab1header.h"
    using namespace std;
    
  16. Inside the main function ask user to enter an integer and assign the value to dayNumb variable.
  17. int dayNumb;
    cout << "please enter the number of a day of a week:";
    cin >> dayNumb;
    
  18. To call the function we need to pass it one parameter of our enumeration type (Day type). But all we have is dayNumb variable of integer type. We can use static_cast to convert the variable to Day type:
  19. Day d;
    d = static_cast<Day>(dayNumb);
    
  20. Now we can call a function:
  21. printDay(d);
    
  22. Run the program and check the output.
Task 1:

To do: Define a Month enumeration data type to represent the month.
Create a function (named printMonth()) that will display the full month name for the passed short month name. Use a switch statement.

Note 1: Create another function (named inc()) that displays the next month for the passed short month name.

Note 2: add the header file. Inside the file add the enum and your function declaration:

// type for representing a month: JAN for January, etc.
enum Month {JAN=1, FEB, MAR, /* TODO: ... */ DEC};
// prints given month to the standard output
void printMonth(Month m);
// return next month
Month inc(Month m);

Note 2: Look at the code below and puzzle it out (using static_cast):

(m == DEC)? JAN: static_cast<Month>(m + 1);
// Test this function from the main:
 assert (JAN == inc (DEC));

Expected output:

Full name for JUN is: June
The next month for DEC is: 1

[Solution and Project name: Lesson_4, file name L4Task1Imp.cpp, L4Task1main.cpp, L4Task1header.h]

Task 2:

To do: Within the previous task create a function (named dec()) that, for the entered month, displays the preceding month.

Note 1: Test this function from main:

assert (JAN == dec (FEB));

Note 2: Add the declaration into the header file:

// return previous month
Month dec(Month m);

Expected output:

Full name for JUN is: June
The previous month for JUN is: 5

[Solution and Project name: Lesson_4, file name L4Task2Imp.cpp, L4Task2main.cpp, L4Task2header.h]

Task 3:

To do: {2 points} Create function of Boolean type that returns True (or 1) if the year (positive integer) is a leap year, and False (or 0) otherwise.

Note 1: A leap year is a year that is divisible by 4, except for those years that are divisible by 100 and not divisible by 400.
Note 2: Add some tests to the main function. 2000 and 2012 are leap years, 2100 is a common year.

Note 3: Add the declaration into the header file:

// check if given year is leap
bool is_leap(int);

Expected output:

please enter the year:2000
year is leap - 1

[Solution and Project name: Lesson_4, file name L4Task3Imp.cpp, L4Task3main.cpp, L4Task3header.h]