C Programming and Data Structures: Unit II: C Programming – Advanced Features

Enumerated Data Types

Definition, Syntax, Example C programs

• Defintion: The enum is an abbreviation used for enumerated data type. When this keyword is used we can basically initialize the sequence of integer constants.

Enumerated Data Types

• Defintion: The enum is an abbreviation used for enumerated data type. When this keyword is used we can basically initialize the sequence of integer constants.

The syntax is

enum identifier_name{sequence of items};

• For example :

enum fruit {Mango, Orange, Banana, Grapes, Guava};

•  Here fruit is the name given to the set of constants. If there is no value given to the sequence then by default the first value in the list is 0. For instance here Mango = 0, Orange = 1, Banana = 2, Grapes = 3 and Guava = 4. We can reassign these values as well.

• For instance :

Mango = 1, Orange = 2, Banana= 3, Grapes = 4 and Guava = 5.Similarly we can write

enum fruit {Mango = 2, Orange, Banana-8, Grapes, Guava};

then the values get set automatically as

Mango= 2, Orange = 3

Banana= 8, Grapes = 9, Guava = 10

• The main advantage of enum is that even if we do not initialize the constants, each one would have a unique value. The first would be zero and the rest would be one more than the previous one.

• Let us understand the use of enumerated data type with the help of following C program -

C Program

#include<stdio.h>

#include<stdlib.h>

void main( )

{

enum fruit {Mango, Orange, Banana, Grapes, Guava};

printf("\n Mango: %d",Mango);

printf("\n Orange: %d", Orange);

printf("\n Banana: %d", Banana);

printf("\n Grapes: %d", Grapes);

printf("\n Guava: %d", Guava);

getch( );

}

Output

Mango: 0

Orange: 1

Banana: 2

Grapes: 3

Guava: 4

 

We can declare some variable of enum type and assign the integer constants to this variable. Just go through the following program and its output:

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

void main( )

{

enum fruit {Mango=10,Orange, Banana, Grapes,Guava};

enum fruit points;

clrscr( );

points=Mango;

printf("\n If I eat Mango then I will get %d points", points);

points=(Banana+Grapes);/Banana=12 and Grapes=13/

printf("\n But if I eat Banana and Grapes then");

printf(" I will get %d points",points);

getch( );

}

Output

If I eat Mango then I will get 10 points

But if I eat Banana and Grapes then I will get 25 points

Review Questions

1. What is the purpose of enumeration type?

2. Explain the data type enumeration? What are the various operations that can perform on enumeration?

 

C Programming and Data Structures: Unit II: C Programming – Advanced Features : Tag: : Definition, Syntax, Example C programs - Enumerated Data Types