Press "Enter" to skip to content

C++ : Input a Number and Display Corresponding Word using Switch

In this tutorial we accept a number between 0 and 9 and the C++ program converts the input number into its corresponding English word. For example, if you enter ‘3’, then program will print ‘three’ and if you type ‘7’, then shows ‘seven’ and so on.
If you type a number other than these limits, then program will display the error message of invalid number input.

#include <iostream>
using namespace std;
int main()
{
    int num;
    cout << "Enter a number between 0 and 9:";
    cin>>num;
    switch(num)
    {
        case 0:
            cout<<"Zero";
            break;
        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:
            cout<<"Six";
            break;
        case 7:
            cout<<"Seven";
            break;
        case 8:
            cout<<"Eight";
            break;
        case 9:
            cout<<"Nine";
            break;
        default :
            cout<<"Invalid number, please type between 0 and 9";
    }

    return 0;
}

Code Explanation:

Here variable ‘num’ accepts an integer number between 0 and 9, and it will have passed into a switch case. The switch case contains all the case for input of 0,1,2… up to 9.
If user type number 1, then print the word ‘one’ using code cout<<“one” and so on.

If the entered number match any one of switch cases, then no need to check the remaining parts of switch cases, that is why ‘break’ statement is used.

At last ‘default’ part manages the case that the user enter a number rather than given limit (between 0 and 9), then shows the error message of invalid input.

Sample output:

Input a number and display Corresponding word in C++

One Comment

  1. erjilopterin erjilopterin 23rd May 2020

    Dead indited subject material, Really enjoyed examining.

Leave a Reply

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