‘enum’ in C Programming

What is enum?

‘enum’ means enumeration. It is a user-defined data type which defines symbolic names to a set of integer constants. The first name is always assigned to 0.

You can assign values to any elements in the group.

Eg:

enum months { January, February, March, April, May, June, July, August, September, October, November, December };

Here, January  is assigned as 0. But we can assign the value by yourself as January =1;

Syntax:

Declaration statement:

enum Fruit { APPLE, BANANA, GRAPES }

Variable Declaration:

Enum Fruit sample;

Sample = APPLE;

User Value Assignment:

Enum Weekday { SUNDAY =1, MONDAY = 2, TUESDAY = 3, WEDNESDAY=4, THURSDAY = 5,FRIDAY=6,SATURDAY=7};

Let us create a program to display the Weekdays value

C Program for enum:

#include <stdio.h>

void main()

{

int a;

enum Weekday { SUNDAY =1, MONDAY = 2, TUESDAY = 3, WEDNESDAY=4, THURSDAY = 5,FRIDAY=6,SATURDAY=7};

printf(“enter the value for week day”);

scanf("%d",&a);

switch(a)

{

 case 1 : printf("It is Sunday");

                break;

case 2 : printf("It is Monday");

                break;

case 3 : printf("It is Tuesday");

                break;

case 4 : printf("It is wednesday");

                break;

case 5 : printf("It is Thursday");

                break;

case 6 : printf("It is Friday");

                break;

case 7 : printf("It is Saturday");

                break;

default: printf("You have entered wrong value");

               break;

}

}

Output:

Compile and run the program to get the output.

enter the value for week day3

It is Tuesday

That’s all. The C program to display information using enum was written and executed successfully. Hope, this code is useful to you. Keep coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.