C Program classroom exercise on decisions and loops

This program is here mainly because it demonstrates how a switch statement with its fall through can be easily used to implement a seemingly complicated algorithm.

Last Reviewed and Updated on May 17, 2017
Posted by Parveen(Hoven),
Aptitude Trainer and Software Developer

Advertisement

C Program classroom exercise on decisions and loops

Write a program that implements this algorithm.

  1. Ask the user to enter a character.
  2. If he enters a vowel in lowercase display it in uppercase. For example if the user enters 'e' your output should be 'E'.
  3. If he enters a vowel in uppercase display: "Already uppercase vowel".
  4. If he enters 'Q' or 'q' the program should exit, otherwise it should again keep asking the user to enter a character and repeat the above algorithm.

A switch with fall-through can be used to easily implement the above requirement. The solution below should ideally use a loop, but just for a change, and more importantly, a student may not have been taught loops at this stage, so I have instead used statement labels. Some developers are of the view that labels should be avoided. Personally, I don't think so.

int main()
{

    char c;

lblX:
    cout << "Enter a lowercase vowel['Q' to quit]:";

    cin >> c;

    switch(c)
    {

    case 'a':
    case 'e':
    case 'i':
    case 'o':
    case 'u':
        {

            cout << "In Uppercase: ";

            cout << (char)(c + ('A' - 'a'));

            cout << endl;

            goto lblX;

        }

    case 'A':
    case 'E':
    case 'I':
    case 'O':
    case 'U':
        {

            cout << "Already Uppercase vowel." << endl;

        }

    default:
        goto lblX;

    case 'Q':
    case 'q':
        {

            cout << "Quitting..." << endl;

        }

        break;

    }

    return 0;

}


My C/C++ Videos on Youtube

Here is the complete playlist for video lectures and tutorials for the absolute beginners. The language has been kept simple so that anybody can easily understand them. I have avoided complex jargon in these videos.



Creative Commons License
This Blog Post/Article "C Program classroom exercise on decisions and loops" by Parveen (Hoven) is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Updated on 2017-05-17.


Advertisement