Skip to main content

Control Flow : Practice

if...else and else if ladder

Just doing the theory in a practical course is not a good idea. It's recommended to practice questions on these basic concepts when we are starting our programming journey to understand the concepts properly and build intuition for advanced concepts. Trust me this will help you in the long run.

Suggestion : First try to do the questions on your own. Give yourself some time and resist the temptation to look at the solution quickly. After giving your best shot, you can definitely go through the solution.โœŒ๏ธ

We will start with a basic problem. It will help you in understanding how to approach a question.

Problem 1

Write a C++ program to find maximum between three numbers.

Input

Input num1 : 10
Input num2 : 20
Input num3 : 15

Output

Maximum among all three numbers is 20

We as human beings are intelligent and just by looking at the numbers we can tell the largest one. When I was starting to code and I came across this question my first thought was when I know which is largest why should I write such a long code for this basic stuff. Too smart Right??๐Ÿ˜…But What if there are 1000 numbers or may be lakhs of numbers. Your program does the magic of finding that out very quickly. For your program to find out the largest number, you will have to think in a step wise manner.

Approach 1

Intuition

Consider three friends Raju, Farhan and Aamir. How will you find the tallest among them. Compare the height of Raju and Farhan.

If Raju >Farhan , surely Farhan is not the tallest. Then you will do one more comparison between Raju and Aamir to find the tallest one. Similarly think of the case where Raju >Farhan is not true. I hope , if ..else conditions are coming to your mind.

Try it out yourself here!

Explanation/Steps

  1. Input three numbers from user. Store it in some variable say num1, num2 and num3.
  2. Compare first two numbers i.e. num1 > num2. If the statement is true then num2 is surely not max value. Perform one more comparison between num1 with num3 i.e. if(num1 > num3), then num1 is max otherwise num3.
  3. If the statement num1 > num2 is false. Which indicates that num1 is not max. Hence, this time compare num2 with num3. If the statement num2 > num3 is true then num2 is max otherwise num3.
Solution
#include <iostream>
using namespace std;

int main(){
    int num1, num2, num3, max;

    /* Input three numbers from user */
    cout<<"Enter three numbers: "<<endl;
    cin>>num1>>num2>>num3;
    
    if(num1 > num2){
    
        if(num1 > num3){
            max = num1;  /* If num1 > num2 and num1 > num3 */
        }
        else{
            max = num3;   /* If num1 > num2 but num1 > num3 is not true */
        }
    }
    else{
    
        if(num2 > num3){
            max = num2;   /* If num1 is not > num2 and num2 > num3 */
        }
        else{
            max = num3;   /* If num1 is not > num2 and num2 > num3 */
        }
    }
    
    /* Print maximum value */
    cout<<"Maximum among all three numbers is "<< max;

    return 0;
}

Don't you think the above approach is lengthy? Hence we will see one more solution with a concise code !!

Approach 2

Alternate Solution
#include <iostream>
using namespace std;
int main(){
    int num1, num2, num3, max;

    /* Input three numbers from user */
    cout<<"Enter three numbers: "<<endl;
    cin>>num1>>num2>>num3;

    if((num1 > num2) && (num1 > num3)){
        max = num1; /* If num1 > num2 and num1 > num3 */
    }
    else if(num2 > num3){
        max = num2; /* If num1 is not > num2 and num2 > num3 */
    }
    else{
        max = num3; /* If num1 is not > num2 and num2 is also not > num3 */
    }

    /* Print maximum number */
    cout<<"Maximum among all three numbers is "<< max;

    return 0;
}

Problem 2

Write a C++ program to input a character from user and check whether given character is alphabet, digit or special character.

Input

Input any character: 3

Output

Character is Digit

We will see two approaches for this question. Just think for a while how will you approach this question.

Approach 1

Intuition

We just need to know the conditions when a character will be a alphabet, digit or special character. If a character is neither a digit nor a alphabet, What it will be?? A special character right. Now frame your thoughts into conditions using if else and elseif.

  • A character is alphabet if it in between a-z or A-Z.
  • A character is digit if it is in between 0-9.
  • A character is special symbol character if it neither alphabet nor digit.

Try it out yourself here!

Explanation/Steps

  1. Input a character from user. Store it in some variable say ch.
  2. First check if character is alphabet or not. A character is alphabet if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')).
  3. Next, check condition for digits. A character is digit if(ch >= '0' && ch <= '9').
  4. Finally, if a character is neither alphabet nor digit, then character is a special character.
Solution
#include <iostream>
using namespace std;
int main(){

    char ch;

    /* Input character from user */
    cout<<"Enter any character: "<<endl;
    cin>>ch;

    /* Alphabet check */
    if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
        cout<<"Character is Alphabet";
    }
    else if(ch >= '0' && ch <= '9'){
        cout<<"Character is Digit";
    }
    else {
        cout<<"Character is Special Charater";
    }

    return 0;
}

Have you heard about ASCII values??If yes, please try to solve this question using that. If no then also its fine. You can refer to the hint and then proceed to try.

Approach 2

Hint

Every character, like letters, numbers, or special symbols, has a unique number assigned to it, called the ASCII value. When you input a character, we can figure out if it's a letter, number, or special character based on its ASCII value.

Here are the ranges:

For big letters (A to Z): ASCII values are between 65 and 90.
For small letters (a to z): ASCII values are between 97 and 122.
For numbers (0 to 9): ASCII values are between 48 and 57.

So, by checking the ASCII value, we can tell what kind of character you entered!

Try it out yourself here!

Explanation/Steps

  1. Input a character from user. Store it in some variable say ch.
  2. First check if character is alphabet or not. A character is alphabet if((ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90)).
  3. Next, check condition for digits. A character is digit if(ch >= 48 && ch <= 57).
  4. Finally, if a character is neither alphabet nor digit, then character is a special character.
Alternate Solution
#include <iostream>
using namespace std;
int main(){
    char ch;

    /* Input a character from user */
    cout<<"Enter any character: "<<endl;
    cin>>ch;


    if((ch >= 97 && ch <= 122) || (ch >= 65 && ch <= 90)){
        cout<<"Character is Alphabet";
    }
    else if(ch >= 48 && ch <= 57){
        cout<<"Character is Digit";
    }
    else{
        cout<<"Character is Special Character";
    }

    return 0;
}

Problem 3

Write a C++ program to input amount from user and print minimum number of notes (Rs. 500, 100, 50, 20, 10, 5, 2, 1) required for the amount.

Input

567890

Output

Total Number of Notes
500 = 1135
100 = 3
50 = 1
20 = 2
10 = 0
5 = 0
2 = 0
1 = 0

Approach

Forget about coding for a moment and then think about this problem. What is coming to you mind?? The greed for 500 notes is too difficult to resist. I would want maximum number of 500 notes. It's not about greed guys. This is hint for your approach. XD

Intuition

For getting the minimum number of notes , we should have maximum number of 500 notes, then 100, then 50 and so on. One more thing if the entered amount is less than 500,obviously we will not have a 500 note. I guess now you should try the question !!

Try it out yourself here!

Explanation/Steps

  1. Input amount from user. Store it in some variable say amount.
  2. If amount is greater than 500 then, divide amount by 500 to get maximum 500 notes required. Store the division result in some variable say note500 = amount / 500;.After division, subtract the resultant amount of 500 notes from original amount. Perform amount = amount - (note500 * 500).
  3. Repeat above step, for each note 200, 100, 50, 20, 10, 5, 2 and 1.
Solution
#include <iostream>
using namespace std;
int main(){
    int amount;
    int note500, note100, note50, note20, note10, note5, note2, note1;
    
    /* Initialize all notes to 0 */
    note500 = note100 = note50 = note20 = note10 = note5 = note2 = note1 = 0;


    /* Input amount from user */
    cout<<"Enter amount: "<<endl;
    cin>>amount;


    if(amount >= 500){
        note500 = amount/500;
        amount -= note500 * 500;
    }
    if(amount >= 100){
        note100 = amount/100;
        amount -= note100 * 100;
    }
    if(amount >= 50){
        note50 = amount/50;
        amount -= note50 * 50;
    }
    if(amount >= 20){
        note20 = amount/20;
        amount -= note20 * 20;
    }
    if(amount >= 10){
        note10 = amount/10;
        amount -= note10 * 10;
    }
    if(amount >= 5){
        note5 = amount/5;
        amount -= note5 * 5;
    }
    if(amount >= 2){
        note2 = amount /2;
        amount -= note2 * 2;
    }
    if(amount >= 1){
        note1 = amount;
    }

    /* Print required notes */
    cout<<"Total number of notes "<<endl;
    cout<<"500 ="<< note500<<endl;
    cout<<"100 ="<< note100<<endl;
    cout<<"50 ="<< note50<<endl;
    cout<<"20 ="<< note20<<endl;
    cout<<"10 ="<< note10<<endl;
    cout<<"5 ="<< note5<<endl;
    cout<<"2 ="<< note2<<endl;
    cout<<"1 ="<< note1<<endl;

    return 0;
}

Problem 4

Write a C++ program to input sides of a triangle and check whether a triangle is equilateral, scalene or isosceles triangle.

Input

Input first side: 30
Input second side: 30
Input third side: 30

Output

Triangle is equilateral triangle

Approach

I hope you are not bored till now. If yes please bear with me for some more time. ๐Ÿ˜…When we come out of our comfort zone then the real progress starts.๐Ÿ™Œ Now coming back to the question, to solve this question we first need to know the basic conditions for a triangle to be equilateral, scalene or isosceles triangle. Sometimes ,I mention the basic stuff, if you are well versed with that you can skip that portion.

Properties of triangle

  • A triangle is said Equilateral Triangle, if all its sides are equal. If a, b, c are three sides of triangle. Then, the triangle is equilateral only if a == b == c.
  • A triangle is said Isosceles Triangle, if its two sides are equal. If a, b, c are three sides of triangle. Then, the triangle is isosceles if either a == b or a == c or b == c.
  • A triangle is said Scalene Triangle, if none of its sides are equal.

Try it out yourself here!

Explanation/Steps

  1. Input sides of a triangle from user. Store it in some variables say side1, side2 and side3.
  2. Check if(side1 == side2 && side2 == side3), then the triangle is equilateral.
  3. If it is not an equilateral triangle then it may be isosceles. Check if(side1 == side2 || side1 == side3 || side2 == side3), then triangle is isosceles.
  4. If it is neither equilateral nor isosceles then it scalene triangle.
Solution
#include <iostream>
using namespace std;
int main(){
    int side1, side2, side3;
    
    /* Input sides of a triangle */
    cout<<"Enter three sides of triangle: "<<endl;
    cin>>side1>>side2>>side3;

    if(side1==side2 && side2==side3) {
        cout<<"Equilateral triangle"; /* If all sides are equal */
    }
    else if(side1==side2 || side1==side3 || side2==side3) {
        cout<<"Isosceles triangle"; /* If any two sides are equal */
    }
    else {
        cout<<"Scalene triangle"; /* If none sides are equal */
    }

    return 0;
}

Problem 5

Write a C++ program to input electricity unit charge and calculate the total electricity bill according to the given condition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill.

Approach

This will be our last question for this exercise. Happy or Sad or No Reaction ?? I am confident you will be able to do this question if you have gone through the above questions. Please don't say I am overconfident. You just need to follow what the question says. There are instances where we just need to follow the steps given in the question. Sounds easy right??

Try it out yourself here!

Explanation/Steps

  1. Input unit consumed by customer in some variable say unit.
  2. If unit consumed less or equal to 50 units. Then amt = unit * 0.50.
  3. If unit consumed more than 50 units but less than 100 units. Then add the first 50 units amount i.e. 25 to final amount and compute the rest 50 units amount. Which is given by amt = 25 + (unit-50) * 0.75. I have used units-50, since I already calculated first 50 units which is 25.
  4. Similarly check rest of the conditions and calculate total amount.
  5. After calculating total amount. Calculate the surcharge amount i.e. sur_charge = total_amt * 0.20. Add surcharge amount to net amount. Which is given by net_amt = total_amt + sur_charge.
Solution
#include <iostream>
using namespace std;
int main()
{
    int unit;
    float amt, total_amt, sur_charge;

    /* Input unit consumed from user */
    cout<<"Enter total units consumed: "<<endl;
    cin>>unit;


    /* Calculate electricity bill according to given conditions */
    if(unit <= 50)
    {
        amt = unit * 0.50;
    }
    else if(unit <= 150)
    {
        amt = 25 + ((unit-50) * 0.75);
    }
    else if(unit <= 250)
    {
        amt = 100 + ((unit-150) * 1.20);
    }
    else
    {
        amt = 220 + ((unit-250) * 1.50);
    }

    /*
     * Calculate total electricity bill
     * after adding surcharge
     */
    sur_charge = amt * 0.20;
    total_amt  = amt + sur_charge;

    cout<<"Electricity Bill = Rs."<<total_amt;

    return 0;
}

This exercise ends here. Hope you enjoyed and learned. In this article, different questions covered different concepts such as nesting of if else statements, using multiple if statements, use of elseif.

Remember Practice leads to Perfection.

Happy Learning !! ๐Ÿ˜€See you in the next article with even more energy.