Press "Enter" to skip to content

This is a simple c program to print name of color according the given letter from VIBGYOR, the color of rainbow. This program is to learn the working of Switch Case statement.



#include <stdio.h> 
#include <conio.h>
#include <stdlib.h>
void main()
{
char cletter;
printf("Enter a letter from VIBGYOR :");
scanf("%c",&cletter);
switch(cletter)
{
case 'V':
printf("Violet");
break;
case 'I':
printf("Indigo");
break;
case 'B':
printf("Blue");
break;
case 'G':
printf("Green");
break;
case 'Y':
printf("Yellow");
break;
case 'O':
printf("Orange");
break;
case 'R':
printf("Red");
break;
default:
printf("Not a color letter from VIBGYOR");
}
getch();
}

This program accepts a letter into the variable ‘cletter’. Then switch case check the given character. If it marches to a letter from VIBGYOR, then print the corresponding color name. But this program checks only capital letters.
If you want to check both capital and small letters, then you need to convert the letter into a common form or use the method of if-else statement.
So you need to use the function ‘toupper()’ to convert letters into capital letters. First of all you need to import ctype.h library at top.

#include <stdio.h> 
#include <conio.h> 
#include <stdlib.h> 
void main()
{
char cletter;
printf("Enter a letter from VIBGYOR :");
scanf("%c",&cletter);
cletter = toupper(cletter);
switch(cletter)
{
//Remaining codes are same
}

Using IF – Else Statement:

#include <stdio.h> 
#include <conio.h> 
#include <stdlib.h> 
void main()
{
char cletter;
printf("Enter a letter from VIBGYOR :");
scanf("%c",&cletter);
if(cletter =='V' || cletter == 'v')
printf("Violet");
else if(cletter =='I' || cletter == 'i')
printf("Indigo");
else if(cletter =='B' || cletter == 'b')
printf("Blue");
else if(cletter =='G' || cletter == 'g')
printf("Green");
else if(cletter =='Y' || cletter == 'y')
printf("Yellow");
else if(cletter =='O' || cletter == 'o')
printf("Orange");
else if(cletter =='R' || cletter == 'r')
printf("Red");
else
printf("Not a color letter from VIBGYOR");
getch();
}

Here else if statements check the given letter either capital or small and if it match the ‘if condition letters’, then print the corresponding color letter.

Sample Output:

Display Color Name from VIBGYOR Letters using Switch Case and IF Else

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: