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.

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

Problem 1

Write a Java 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 humans are smart, and we can easily spot the biggest number just by looking at them. When I started coding, I wondered why I should write a long program for something so simple. I mean, I already know how to pick the biggest number, right? 😅 But imagine dealing with a thousand or even hundreds of thousands of numbers. That's where your program comes in handy. It quickly figures out the biggest number by following step-by-step instructions.

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 striking your mind.

Try it yourself here!

Explanation

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
import java.util.Scanner;

public class FindMaxNumber {
    public static void main(String[] args) {
        int num1, num2, num3, max;

        // Input three numbers from the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter three numbers:");
        num1 = scanner.nextInt();
        num2 = scanner.nextInt();
        num3 = scanner.nextInt();

        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 the maximum value
        System.out.println("Maximum among all three numbers is " + max);
    }
}


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

Approach 2

Alternative solution
import java.util.Scanner;

public class FindMaxNumber {
    public static void main(String[] args) {
        int num1, num2, num3, max;

        // Input three numbers from the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter three numbers:");
        num1 = scanner.nextInt();
        num2 = scanner.nextInt();
        num3 = scanner.nextInt();

        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 the maximum number
        System.out.println("Maximum among all three numbers is " + max);
    }
}

Problem 2

Write a Java 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'll explore two methods to tackle this question. Take a moment to consider how you would approach it.

Approach 1

Try it yourself here!

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.

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
import java.util.Scanner;

public class CharacterTypeCheck {
    public static void main(String[] args) {
        char ch;

        // Input character from the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter any character:");
        ch = scanner.next().charAt(0);

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

Are you familiar with ASCII values? If so, attempt to solve this question using that knowledge. If not, that's okay too. Feel free to refer to the hint and then proceed with your attempt.

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!

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.
Alternative solution
import java.util.Scanner;

public class CharacterTypeCheck {
    public static void main(String[] args) {
        char ch;

        // Input a character from the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter any character:");
        ch = scanner.next().charAt(0);

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

Problem 3

Write a Java 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

Pause thinking about the code for a bit. Consider the problem. What's your first thought? The idea here is to aim for as many 500 notes as possible. It's not about being greedy; it's a helpful hint for how to approach the situation.

Try it yourself here!

Intuition

For getting the minimum number of notes , we should have maximum number of 500 notes, then 100, then 50 and so on. Also if the entered amount is less than 500, we will not have a 500 note.

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
import java.util.Scanner;

public class CountCurrencyNotes {
    public static void main(String[] args) {
        int amount, 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 the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter amount:");
        amount = scanner.nextInt();

        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
        System.out.println("Total number of notes");
        System.out.println("500 =" + note500);
        System.out.println("100 =" + note100);
        System.out.println("50 =" + note50);
        System.out.println("20 =" + note20);
        System.out.println("10 =" + note10);
        System.out.println("5 =" + note5);
        System.out.println("2 =" + note2);
        System.out.println("1 =" + note1);
    }
}

Problem 4

Write a Java 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.

Try it yourself here!

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.

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
import java.util.Scanner;

public class TriangleType {
    public static void main(String[] args) {
        int side1, side2, side3;

        // Input sides of a triangle
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter three sides of the triangle:");
        side1 = scanner.nextInt();
        side2 = scanner.nextInt();
        side3 = scanner.nextInt();

        if (side1 == side2 && side2 == side3) {
            System.out.println("Equilateral triangle"); // If all sides are equal
        } else if (side1 == side2 || side1 == side3 || side2 == side3) {
            System.out.println("Isosceles triangle"); // If any two sides are equal
        } else {
            System.out.println("Scalene triangle"); // If no sides are equal
        }
    }
}

Problem 5

Write a Java 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

You just need to follow what the question says. There are instances where we just need to follow the steps given in the question.

Try it 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
import java.util.Scanner;

public class ElectricityBill {
    public static void main(String[] args) {
        int unit;
        float amt, total_amt, sur_charge;

        // Input unit consumed from the user
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter total units consumed:");
        unit = scanner.nextInt();

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

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

        System.out.println("Electricity Bill = Rs." + total_amt);
    }
}

This exercise ends here. Hope you enjoyed and learned.

In this article, different questions were covered with concepts such as nesting if else statements, using multiple if statements, and else if.

Remember, Practice leads to Perfection.