Sunday, May 19, 2019

Enumerations


An enum is a keyword, it is an user defined data type. All properties of integer are applied on Enumeration data type so size of the enumerator data type is 2 byte. It work like the Integer.
It is used for creating an user defined data type of integer. Using enum we can create sequence of integer constant value.

Syntax

enum tagname {value1, value2, value3,....};
  • In above syntax enum is a keyword. It is a user defiend data type.
  • In above syntax tagname is our own variable. tagname is any variable name.
  • value1, value2, value3,.... are create set of enum values.
enumeration in c
It is start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list. If constant one value is not initialized then by default sequence will be start from zero and next to generated value should be previous constant value one.

Read carefully

Example of Enumeration in C

enum week {sun, mon, tue, wed, thu, fri, sat};
enum week today;
  • In above code first line is create user defined data type called week.
  • week variable have 7 value which is inside { } braces.
  • today variable is declare as week type which can be initialize any data or value among 7 (sun, mon,....).

Example of Enumeration in C

#include<stdio.h>
#include<conio.h>

enum ABC {x,y,z};
void main()
{
int a;
clrscr();
a=x+y+z; //0+1+2
printf("Sum: %d",a);
getch();
}

Output

Sum: 3

Example of Enumeration in C

#include<stdio.h>
#include<conio.h>

enum week {sun, mon, tue, wed, thu, fri, sat};
void main()
{
 enum week today;
 today=tue;
 printf("%d day",today+1); 
 getch();
}

Output

3 day
Here "enum week" is user defined data type and today is integer type variable which initialize Tuesday. In above code we add "today+1" because enum is start from 0, so to get proper answer we add "1". Other wise it give "2nd day".

Example of Enumeration in C

#include<stdio.h>
#include<conio.h>

enum week {sun, mon, tue, wed, thu, fri, sat};
void main()
{
for(i=sun; i<=sat; i++)
{
 printf("%d ",i); 
} 
getch();
}

Output

1 2 3 4 5 6 7
In above code replace sun, mon, tue,.... with Equivalent numeric value 0, 1, 2,...

No comments:

Post a Comment

Why learning C Programming is a must?

C is a procedural programming language. It was initially developed by Dennis Ritchie between 1969 and 1973. It was mainly developed as...