Techtopz

(@techtopz)

Techtopz is a blog on programming and tech stuff.
Techtopz is now on UpHub.
Follow us for more updates.

    


C++ | Switch statements introduction

This post will give introduction to switch statements (how to use them in c++ ). The first program will show the number in words. The next program will show the word starting by given alphabet. You can extend the program by using more number and alphabets in the program. So enjoy the program. Lets begin...


Program to show number in words.

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type int
int a;
//Input the number save it in 'a'.
cout<<"Enter the no."<<endl;
cin>>a;
//conditional switch statement.
switch (a)
{
case 1:
cout<<"One";
break;
case 2:
cout<<"Two";
break;
case 3:
cout<<"Three";
break;
case 4:
cout<<"four";
break;
case 5:
cout<<"five";
break;
case 6:
case 7:
cout<<"six or seven";
break;
case 8:
case 9:
case 10:
case 11:
case 12:
cout<<"Number from 8 to 12";
break;
default:
cout<<"Error";
}
//get character
getch();
}


Output

Enter the number
4
four

or

Enter the number
6
six or seven

or

Enter the number
10
number from 8 to 12.

Program to show word starting from given alphabet

#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type cahr
char a;
//Input the alphabet save it in 'a'.
cout<<"Enter the alphabet"<<endl;
cin>>a;
//conditional switch statement.
switch (a)
{
case 'a':
cout<<"Apple";
break;
case 'b':
cout<<"Ball";
break;
case 'c':
cout<<"Cat";
break;
case 'd':
cout<<"Dog";
break;
case 'e':
cout<<"Elephant";
break;
case 'f':
case 'g':
cout<<"Fan or Goat";
break;
case 'h':
cout<<"Hat";
break;
default:
cout<<"Error";
}
//get character
getch();
}


Output

Enter the number
h
Hat

How does it work
1. You number or alphabet
2. The conditional statement decides the word.
3. The word is printed.

Extending it
The program can be extended. You can use more numbers or alphabets to expand it. Go ahead…..

Explanation.
1. Include ‘iostream.h’ and ‘conio.h’ files.
2. Add void main.
3. Start program by first clearing the screen.
4. Declare the variables as int or char. (name them as you want.)
5. Add cout and cin of variable of input of number or alphabet.(as shown in program)
6. Decide the word by using switch conditional statement.
7. Print the word.

At the end
You learnt creating the c++ program of Switch statements (showing numbers in words) and( showing word starting by given alphabet). So now enjoy the program.


Login to like the post