-->

Learn to code the on-demand coding Languages in an easy way. We help you understand programming concepts and coding Techniques Better.

Tuesday, February 9, 2021

What is enumeration in C | Example of enum..

Enumerations in C:

Enum: The Enum in C is the Enumerated type. An Enumeration is the set of named constants. It is also a user-defined data type like structure and union, consists of integer values associated with name constants. The Enumeration type is defined using the enum keyword.

The syntax for Declaring the Enum Type:

    enum enum_name{name1,name2,name3,..........};

                            (or)

    enum enum_name

    {

        name1,

        name2,

        name3,

        .

        .

    };

enum: The enum is a keyword used to define enumeration type.

enum_name: Like structure, and union we can give any name to the enum.

name1,name2,name3....: These names are the named constants associated with specific integer values. By default, the values for these names start from 0,1,2,.....etc.

Don't forget to put the semicolon at the end of the enum.

Declaring the Enum type:

   Ex1:  enum days{sun,mon,tue,wed,thu,fri};

    The above declaration specifies that the names in the enum are associated with sun=0, mon=1, tue=2, wed=3, thu=4, fri=5,  sat=6. 

    Ex2:  enum days{sun=5,mon,tue,thu,sat};

        The above declaration specifies that the names in the enum are associated with the values  sun=5, mon=6, tue=7, wed=8, thu=9, fri=10.

Declaring the Enum variable: The enum variable is used to access the value of the name. 

    enum  days d;

    Here d is the enum variable.

The Declaration of Enum and variable both can be represented as:

    enum days{sun,mon,tue,wed,thu,fri} d;

Example: Let's create a simple program of an enum.

              Program:

          

             Output:

          

            Explanation: In the above code we have created a type of enum named as days which consists of all the names of days. We have assigned a value 1 to the initial name and the value gets incremented for the following names. Inside the main method, we have defined a for loop in which we initialize the i variable by sun and this loop will iterate till sat. The enum values start iterating from 1 to 7. 


In this tutorial, we have learned how to create the enum user-defined type with the enum keyword. And also a simple example of how enum works.


prev <---Unions in C                                                        next Topic--->typedef in C





No comments:

Post a Comment