Enum-in C++ .

In this session i have discussed enum in C++ .


enum is a user defined data types in C++ . Which is used to assign name to number by default it is start from 0 . But you can change the number according to your requirement .

The use of enum makes the program easy to read and maintain . We use the enum keyword to declare the enum .


Enum declaration

enum enum_name{const1,cont2 .....};
enum week{sunday,monday,tuesday,wednesday,thursday,friday,saturday};
    

In above code by default the const1=0 , const2=1 . sunday=0 , monday=1 and so on

You can change the by default value as .

      enum weekdays
      {
            sunday=0,
            monday=3,
            tuesday=6,
            wednesday=12,
            thursday=13,
            friday=14,
            saturday=15
      };
    

Example : Write a C program that demonstrate the enum .

    #include<iostream>
    using namespace std; 
    enum weekdays
    {
        sunday=1,
        monday=2,
        tuesday=3,
        wednesday=4,
        thursday=5,
        friday=6,
        saturday=7
    };
    int main()
    {
        enum weekdays day;
        int i;
        cout<<"Enter the number of days";
        cin>>i;
        switch(i)
        {
            case sunday:
            {
                cout<<"Sunday";
                break;
            }
            case monday:
            {
                cout<<"Monday";
                break;
            }
            case tuesday:
            {
                cout<<"Tuesday";
                break;
            }
            case wednesday:
            {
                cout<<"Wednesday";
                break;
            }
            case thursday:
            {
                cout<<"Thursday";
                break;
            }
            case friday:
            {
                    cout<<"Friday";
                    break;
            }
            case saturday:
            {
                    cout<<"Saturday";
                    break;
            }
            default:
            {
                cout<<"Wrong entry";
            }
    }
   return (0);
}

    
    OUTPUT : Enter the Number of Day : 3
             Tuesday
    



Welcome to AndroidATPoint.

back image                     next image