Categories
Class 9

Conditional Statements in Java

Multiple Choice Questions

  1. In a switch case, when the switch value does not respond to any case then the execution transfers to:
    a) a break statement
    b) a default case
    c) a loop
    d) none
  2. Which of the following is a compound statement?
    a) p = Integer.parseInt(in.readLine());
    b) c = ++a;
    c) if(a > b) a++; b–;
    d) a = 4;
  3. Condition is essentially formed by using:
    a) Arithmetic operators
    b) Relational operators
    c) Logical operators
    d) All
  4. if((a > b) & (a > c)), then which of the statement is true?
    a) b is the smallest number
    b) b is the greatest number
    c) a is the greatest number
    d) all of the above
  5. if(a > b)
    c = a;
    else
    c = b;
    It can be written as:
    a) c = (b > a)?a:b;
    b) c = (a != b)?a:b;
    c) c = (a > b)?b:a;
    d) None
  6. If a, b and c are the sides of a triangle, then which of the following statement is true for:
    if(a!=b && a!=c && b!=c)?
    a) Equilateral triangle
    b) Scalene triangle
    c) Isosceles triangle
    d) All of the above
  7. Two arithmetic expressions can be compared with if statement using:
    a) Arithmetic operator
    b) Relational operator
    c) Ternary operator
    d) None
  8. Which of the following is a conditional statement?
    a) if
    b) goto
    c) for
    d) none
  9. Which of the following statements accomplishes ‘fall through’?
    a) for statement
    b) switch statement
    c) if-else
    d) none
  10. A Java program executes but doesn’t give the desired output. It is due to:
    a) the logical error in the program
    b) the syntax error in the program
    c) the run-time error in the program
    d) none

II. Answer the following questions:

1. Name the different ways to manage the flow of control in a program.
Normal flow, Bi-directional flow, Multiple branching.

2. Mention one statement each to achieve:
(a) Bi-directional flow of control
if-else statement
(b) Multiple branching of control
switch case statement

3. Explain the following statements with their constructs:
(a) nested if
One if statement inside the other is termed as nested if statement.

if(condition 1){
if(condition 2){
statement(s)
}
}

(b) if-else
It is used to execute a set of statements when a condition is true, and execute another set of statements when the condition is false.

if(condition){
statement(s)
}
else{
statement(s)
}

(c) if-else-if

if(condition 1){
statement(s)
}
else if(condition 2){
statement(s)
}
else{
statement(s)
}

4. Differentiate between if and switch statement.
The if statement works with all kinds of comparisons using a variety of relational and logical operators. The switch statement on the other hand checks only for equality of two values.

5. What is the purpose of switch statement in a program?
The switch statement is a multi-branching statement where out of several options, any one gets executed and the rest are skipped.

6. Explain with the help of an example, the purpose of default in a switch statement.
The default case is executed when none of the listed cases are matched.

switch(5){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("Other");
}

7. Is it necessary to use break statement in a switch case statement? Explain.
The break statement is optional in a switch statement. If not provided, then it may lead to fall through in switch statement in which the flow of control can move from one case to another.

8. Explain ‘fall through’ with reference to a switch case statement.
When we do not provide the break statement in switch statement, it leads to fall through, in which the flow of control moves from one case to another.

9. What is a compound statement? Give an example.
A statement that includes a set of statements within it under opening and closing curly braces is a compound statement.
Example:

if(a > b){
System.out.println(a + " is greater");
System.out.println(b + " is smaller");
}

10. Explain with an example the if-else-if construct.

if(marks >= 80)
System.out.println("A");
else if(marks >= 60)
System.out.println("B");
else if(marks >= 40)
System.out.println("C");
else
System.out.println("D");

In the above example, the if-else-if construct provides a series of conditions and the one that matches gets executed while the other conditions and statements are skipped.

11. Name two jump statements and their use.
The break statement is used to exit from a loop or switch statement.
The continue statement is used to move to the next iteration of the loop.

12. Give two differences between the switch statement and the if-else statement.
The switch statement only checks for equality, whereas the if-else statement can do all kinds of comparisons. The switch case is a multi-branching statement whereas the if-else statement is a bi-directional statement.

Predict the output of the given snippet, when executed:

Q1.

int a = 1, b = 1, m = 10, n = 5;
if((a == 1) && (b == 0)){
System.out.println((m + n));
System.out.println((m - n));
}
if((a == 1) && (b == 1)){
System.out.println((m * n));
System.out.println((m % n));
}

OUTPUT:
50
0

Q2.

int x = 1, y = 1;
if(n > 0){
x = x + 1;
y = y + 1;
}

What will be the value of x and y if n assumes a value (i) 1 (ii) 0?
OUTPUT when n = 1:
x = 2, y = 2
OUTPUT when n = 0:
x = 1, y = 1

Q3.

int b = 3, k, r;
float a = 15.15F, c = 0;
if(k == 1){
r = (int)a / b;
System.out.println(r);
}
else{
c = a / b;
System.out.println(c);
}

OUTPUT:
variable k might not have been initialized.

Q4.

switch(opn){
case 'a':
System.out.println("Platform Independent");
break;
case 'b':
System.out.println("Object Oriented");
case 'c':
System.out.println("Robust and Secure");
break;
default:
System.out.println("Wrong Input");
}

When (i) opn = ‘b’ (ii) opn = ‘x’ (iii) opn = ‘a’
OUTPUT i:
Object Oriented
Robust and Secure
OUTPUT ii:
Wrong Input
OUTPUT iii:
Platform Independent

Unsolved Java Programs Solved!

Q1. Write a program to input three angles of a triangle and check whether a triangle is possible or not. If possible, then check whether it is an acute-angled triangle, right-angled or an obtuse-angled triangle, otherwise display “Triangle not possible”.
Sample inputs: Enter three angles: 40, 50, 90
Sample output: Right-angled triangle

import java.io.*;
class Triangle{
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.println("Enter three angles:");
        int a = Integer.parseInt(br.readLine());
        int b = Integer.parseInt(br.readLine());
        int c = Integer.parseInt(br.readLine());
        int sum = a + b + c;
        if(sum == 180 && a > 0 && b > 0 && c > 0){
            System.out.println("Triangle possible.");
            if(a < 90 && b < 90 && c < 90)
                System.out.println("Acute-angled triangle.");
            else if(a == 90 || b == 90 || c == 90)
                System.out.println("Right-angled triangle.");
            else
                System.out.println("Obtuse-angled triangle.");
        }
        else
            System.out.println("Triangle not possible.");
    }
}

Q2. Write a program to input the cost price and the selling price of an article. If the selling price is more than the cost price then calculate and display actual profit and profit %. Otherwise calculate and display actual loss and loss %. If the cost price and the selling price are equal, then display the message “Neither profit nor loss”.

import java.io.*;
class Article{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Cost Price = ");
        double cp = Double.parseDouble(br.readLine());
        System.out.print("Selling Price = ");
        double sp = Double.parseDouble(br.readLine());
        if(sp == cp)
            System.out.println("Neither profit nor loss.");
        else if(sp > cp){
            double profit = sp - cp;
            double pp = profit / cp * 100;
            System.out.println("Profit = " + profit);
            System.out.println("Profit % = " + pp);
        }
        else{
            double loss = cp - sp;
            double lp = loss / cp * 100;
            System.out.println("Loss = " + loss);
            System.out.println("Loss % = " + lp);
        }
    }
}

Q3. Write a program to input three numbers and check whether they are equal or not. If they are unequal numbers then display the greatest among them. Otherwise, display the message “All the numbers are equal”.

import java.io.*;
class Check{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("First number: ");
        int a = Integer.parseInt(br.readLine());
        System.out.print("Second number: ");
        int b = Integer.parseInt(br.readLine());
        System.out.print("Third number: ");
        int c = Integer.parseInt(br.readLine());
        if(a == b && b == c)
            System.out.println("All the numbers are equal.");
        else{
            int g = Math.max(a, b);
            g = Math.max(c, g);
            System.out.println("Greatest number: " + g);
        }
    }
}

Q4. Write a program to accept a number and check whether the number is divisible by 3 as well as 5. Otherwise decide:
a) Is the number divisible by 3 and not by 5?
b) Is the number divisible by 5 and not by 3?
c) Is the number neither divisible by 3 nor by 5?
The program displays the message accordingly.

import java.io.*;
class Divisible{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Number: ");
        int num = Integer.parseInt(br.readLine());
        if(num % 3 == 0 && num % 5 == 0)
            System.out.println("Divisible by 3 and 5.");
        else if(num % 3 == 0)
            System.out.println("Divisible by 3 and not by 5.");
        else if(num % 5 == 0)
            System.out.println("Divisible by 5 and not by 3.");
        else
            System.out.println("Neither divisible by 3 nor by 5.");
    }
}

Q5. Write a program to input year and check whether it is:
a) a leap year
b) a century leap year
c) a century year but not a leap year

import java.io.*;
class Leap{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter year: ");
        int year = Integer.parseInt(br.readLine());
        if(year % 4 == 0 && year % 100 != 0)
            System.out.println("Leap year.");
        else if(year % 400 == 0)
            System.out.println("Century leap year.");
        else if(year % 100 == 0)
            System.out.println("Century year but not a leap year.");
        else
            System.out.println("Common year.");
    }
}

Q6. Write a program to input two unequal positive numbers and check whether they are perfect square numbers or not. If the user enters a negative number, then the program displays the message “Square root of a negative number can’t be determined”.

import java.io.*;
class Perfect{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter first number: ");
        int a = Integer.parseInt(br.readLine());
        System.out.print("Enter second number: ");
        int b = Integer.parseInt(br.readLine());
        if(a < 0 || b < 0)
            System.out.println("Square root of negative numbers can't be determined.");
        else{
            double s1 = Math.sqrt(a);
            double s2 = Math.sqrt(b);
            if(s1 == (int)s1)
                System.out.println(a + " is a perfect number.");
            if(s2 == (int)s2)
                System.out.println(b + " is a perfect number.");
            if(s1 != (int)s1 && s2 != (int)s2)
                System.out.println("They are not perfect numbers.");
        }
    }
}

Q7. Without using if-else statement and ternary operators, accept three unequal numbers and display the second smallest number.

import java.io.*;
class Second{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter first number: ");
        int a = Integer.parseInt(br.readLine());
        System.out.print("Enter second number: ");
        int b = Integer.parseInt(br.readLine());
        System.out.print("Enter third number: ");
        int c = Integer.parseInt(br.readLine());
        int sum = a + b + c;
        int max = Math.max(a, b);
        max = Math.max(max, c);
        int min = Math.min(a, b);
        min = Math.min(min, c);
        int s = sum - max - min;
        System.out.println("Second smallest number: " + s);
    }
}

Q8. Write a program to input three unequal numbers. Display the greatest and the smallest number.

import java.io.*;
class Find{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter first number: ");
        int a = Integer.parseInt(br.readLine());
        System.out.print("Enter second number: ");
        int b = Integer.parseInt(br.readLine());
        System.out.print("Enter third number: ");
        int c = Integer.parseInt(br.readLine());
        int sum = a + b + c;
        int max = Math.max(a, b);
        max = Math.max(max, c);
        int min = Math.min(a, b);
        min = Math.min(min, c);
        System.out.println("Greatest number: " + max);
        System.out.println("Smallest number: " + min);
    }
}

Q9. A pre-paid taxi charges from the passenger as per the tariff given below:

Distance Rate
Up to 5 km Rs. 100
For the next 10 km Rs. 10 / km
For the next 10 km Rs. 8 / km
More than 25 km Rs. 5 / km

Write a program to input the distance covered and calculate the amount paid by the passenger. The program displays the printed bill with the details given below:
Taxi No. ________
Distance covered ________
Amount ________

import java.io.*;
class Taxi{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Taxi number: ");
        int num = Integer.parseInt(br.readLine());
        System.out.print("Distance covered: ");
        double d = Double.parseDouble(br.readLine());
        double amt = 0.0;
        if(d <= 5.0)
            amt = 100.0;
        else if(d <= 15.0)
            amt = 100.0 + (d - 5) * 10;
        else if(d <= 25.0)
            amt = 200.0 + (d - 15) * 8;
        else
            amt = 280.0 + (d - 25) * 5;
        System.out.println("Taxi No: " + num);
        System.out.println("Distance covered: " + d);
        System.out.println("Amount: " + amt);
    }
}

Q10. A cloth showroom has announced festival discounts and the gifts on the purchase of items, based on the total cost as given below:

Total Cost Discount Gift
Up to Rs. 2000 5% Calculator
Rs. 2001 to 5000 10% School Bag
Rs. 5001 to 10000 15% Wall Clock
Above Rs. 10000 20% Wrist Watch

Write a program to input the total cost. Compute and display the amount to be paid by the customer along with the gift.

import java.io.*;
class Showroom{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Total cost: ");
        double cost = Double.parseDouble(br.readLine());
        double amt = 0.0;
        double d = 0.0;
        String gift = "";
        if(cost <= 2000.0){
            d = 5.0;
            gift = "Calculator";
        }
        else if(cost <= 5000.0){
            d = 10.0;
            gift = "School Bag";
        }
        else if(cost <= 10000.0){
            d = 15.0;
            gift = "Wall Clock";
        }
        else{
            d = 20.0;
            gift = "Wrist Watch";
        }
        d = d / 100 * cost;
        cost = cost - d;
        System.out.println("Amount to be paid: " + cost);
        System.out.println("Gift: " + gift);
    }
}

Q11. Given below is a hypothetical table showing rate of income tax for Indian citizen, who is below or up to 60 years.

Taxable Income Income Tax
Up to 250000 NIL
More than 250000 and less than or equal to 500000 (TI – 160000) × 10%
More than 500000 and less than or equal to 1000000 (TI – 500000) × 20% + 34000
More than 1000000 (TI – 1000000) × 30% + 94000

Write a program to input the name, age and taxable income of a person. If the age is more than 60 years then display the message “Wrong Category”. If the age is less than or equal to 60 years then compute and display the income tax payable along with the name of tax payer, as per the table given above.

import java.io.*;
class Tax{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Name: ");
        String n = br.readLine();
        System.out.print("Age: ");
        int a = Integer.parseInt(br.readLine());
        if(a > 60)
            System.out.println("Wrong Category");
        else{
            System.out.print("Taxable Income: ");
            double ti = Double.parseDouble(br.readLine());
            double t = 0.0;
            if(ti > 250000.0 && ti <= 500000.0)
                t = (ti - 160000.0) * 10.0 / 100;
            else if(ti > 500000.0 && ti <= 1000000.0)
                t = (ti - 500000.0) * 20.0 / 100 + 34000.0;
            else if(ti > 1000000.0)
                t = (ti - 1000000.0) * 30.0 / 100 + 94000.0;
            System.out.println("Name: " + n);
            System.out.println("Income tax payable: " + t);
        }
    }
}

Q12. An employee wants to deposit certain sum of money under “Term Deposit” scheme in Syndicate Bank. The bank has provided the tariff of the scheme which is given below:

No. of Days Rate of Interest No. of Days Rate of Interest
Up to 180 days 5.5% Exact 365 days 9.0%
181 to 364 days 7.5% More than 365 days 8.5%

Write a program to calculate the maturity amount taking the sum and number of days as inputs.

import java.io.*;
class Bank{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Sum: ");
        double sum = Double.parseDouble(br.readLine());
        System.out.print("Days: ");
        int days = Integer.parseInt(br.readLine());
        double m = 0.0;
        if(days <= 180)
            m = 5.5;
        else if(days <= 364)
            m = 7.5;
        else if(days == 365)
            m = 9.0;
        else
            m = 8.5;
        m = m / 100 * sum;
        double amt = sum + m;
        System.out.println("Maturity amount = " + amt);
    }
}

Q13. Mr. Kumar is an LIC agent. He offers discount to his policy holders on the annual premium. However, he also gets commission on the sum assured as per the given tariff.

Sum Assured Discount Commission
Up to 100000 5% 2%
100001 to 200000 8% 3%
200001 to 500000 10% 5%
More than 500000 15% 7.5%

Write a program to input name of the policy holder, the sum assured and the first annual premium. Calculate the discount of the policy holder and the commission of the agent. The program displays all the details as:
Name of the policy holder: ________
Sum assured: ________
Premium: ________
Discount on the first premium: ________
Commission of the agent: ________

import java.io.*;
class Agent{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Name: ");
        String name = br.readLine();
        System.out.print("Sum assured: ");
        double sum = Double.parseDouble(br.readLine());
        System.out.print("Premium: ");
        double p = Double.parseDouble(br.readLine());
        double d = 0.0;
        double c = 0.0;
        if(sum <= 100000){
            d = 5.0;
            c = 2.0;
        }
        else if(sum <= 200000){
            d = 8.0;
            c = 3.0;
        }
        else if(sum <= 500000){
            d = 10.0;
            c = 5.0;
        }
        else{
            d = 15.0;
            c = 7.5;
        }
        d = d / 100 * p;
        c = c / 100 * sum;
        System.out.println("Name of the policy holder: " + name);
        System.out.println("Sum assured: " + sum);
        System.out.println("Premium: " + (p - d));
        System.out.println("Discount on the first premium: " + d);
        System.out.println("Commission of the agent: " + c);
    }
}

Q14. A company announces revised Dearness Allowance (DA) and Special Allowances for their employees as per the tariff given below:

Basic DA SA
Up to 10000 10% 5%
10001 to 20000 12% 8%
20001 to 30000 15% 10%
30001 and above 20% 12%

Write a program to accept name and basic salary of an employee. Calculate and display gross salary.
Gross salary = Basic + DA + SA
Print the information in the given format:

Name    Basic    DA    SA    Gross Salary
****       *****    **      **     ************
import java.io.*;
class Company{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Name: ");
        String name = br.readLine();
        System.out.print("Basic salary: ");
        double s = Double.parseDouble(br.readLine());
        double da = 0.0;
        double sa = 0.0;
        if(s <= 10000){
            da = 10.0;
            sa = 5.0;
        }
        else if(s <= 20000){
            da = 12.0;
            sa = 8.0;
        }
        else if(s <= 30000){
            da = 15.0;
            sa = 10.0;
        }
        else{
            da = 20.0;
            sa = 12.0;
        }
        da = da / 100 * s;
        sa = sa / 100 * s;
        double gross = s + da + sa;
        System.out.println("Name\tBasic\tDA\tSA\tGross Salary");
        System.out.println(name + "\t" + s + "\t" + da + "\t" + sa + "\t" + gross);
    }
}

Q15. Using a switch case statement, write a menu-driven program to convert a given temperature from Fahrenheit to Celsius and vice-versa. For an incorrect choice, an appropriate message should be displayed.

import java.io.*;
class Temp{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("1. Fahrenheit to Celsius");
        System.out.println("2. Celsius to Fahrenheit");
        System.out.print("Enter your choice: ");
        int choice = Integer.parseInt(br.readLine());
        switch(choice){
            case 1:
            System.out.print("Enter temperature in Fahrenheit: ");
            double f = Double.parseDouble(br.readLine());
            double c = 5.0 / 9 * (f - 32);
            System.out.println("Temperature in Celsius: " + c);
            break;
            case 2:
            System.out.print("Enter temperature in Celsius: ");
            c = Double.parseDouble(br.readLine());
            f = 9.0 / 5 * c + 32;
            System.out.println("Temperature in Fahrenheit: " + f);
            break;
            default:
            System.out.println("Invalid choice!");
        }
    }
}

Q16. The volume of solids viz. cuboid, cylinder and cone can be calculated by the formula:
a) Volume of cuboid: l * b * h
b) Volume of cylinder: πr2h
c) Volume of cone: 1/3*πr2h
Using switch case statement, write a program to find the volume of different solids by taking suitable variables and data types.

import java.io.*;
class Volume{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("1. Volume of cuboid");
        System.out.println("2. Volume of cylinder");
        System.out.println("3. Volume of cone");
        System.out.print("Enter your choice: ");
        int choice = Integer.parseInt(br.readLine());
        switch(choice){
            case 1:
            System.out.print("Length: ");
            double l = Double.parseDouble(br.readLine());
            System.out.print("Breadth: ");
            double b = Double.parseDouble(br.readLine());
            System.out.print("Height: ");
            double h = Double.parseDouble(br.readLine());
            double v = l * b * h;
            System.out.println("Volume of cuboid = " + v);
            break;
            case 2:
            System.out.print("Radius: ");
            double r = Double.parseDouble(br.readLine());
            System.out.print("Height: ");
            h = Double.parseDouble(br.readLine());
            v = 22.0 / 7 * r * r * h;
            System.out.println("Volume of cylinder = " + v);
            break;
            case 3:
            System.out.print("Radius: ");
            r = Double.parseDouble(br.readLine());
            System.out.print("Height: ");
            h = Double.parseDouble(br.readLine());
            v = 1.0 / 3 * 22.0 / 7 * r * r * h;
            System.out.println("Volume of cone = " + v);
            break;
            default:
            System.out.println("Invalid choice!");
        }
    }
}

Q17. A mega shop has different floors which display varieties of dresses as mentioned below:
1. Ground floor: Kids Wear
2. First floor: Ladies Wear
3. Second floor: Designer Sarees
4. Third floor: Men’s Wear
The user enters floor number and gets the information regarding different items of the mega shop. After shopping, the customer pays the amount at the billing counter and the shopkeeper prints the bill in the given format:
Name of the shop: City Mart
Total Amount: _________
Visit Again!!!
Write a program to perform the above task as per the user’s choice.

import java.io.*;
class Shop{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("1. Ground Floor");
        System.out.println("2. Ladies Wear");
        System.out.println("3. Second Floor");
        System.out.println("4. Third Floor");
        System.out.print("Enter your choice: ");
        int choice = Integer.parseInt(br.readLine());
        double bill = 0.0;
        switch(choice){
            case 1:
            System.out.println("Kids Wear");
            System.out.print("Total Bill: ");
            bill = Double.parseDouble(br.readLine());
            break;
            case 2:
            System.out.println("Ladies Wear");
            System.out.print("Total Bill: ");
            bill = Double.parseDouble(br.readLine());
            break;
            case 3:
            System.out.println("Designer Wear");
            System.out.print("Total Bill: ");
            bill = Double.parseDouble(br.readLine());
            break;
            case 4:
            System.out.println("Men's Wear");
            System.out.print("Total Bill: ");
            bill = Double.parseDouble(br.readLine());
            break;
            default:
            System.out.println("Invalid choice!");
        }
        System.out.println("Name of the shop: City Mart");
        System.out.println("Total Amount: " + bill);
        System.out.println("Visit Again!!!");
    }
}

Q18. The equivalent resistance of series and parallel connections of two resistances are given by the formula:
(a) R1 = r1 + r2 (Series)
(b) R2 = (r1 * r2) / (r1 + r2) (Parallel)
Using a switch case statement, write a program to enter the value of r1 and r2. Calculate and display the equivalent resistances accordingly.

import java.io.*;
class Resistance{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("1. Series");
        System.out.println("2. Parallel");
        System.out.print("Enter your choice: ");
        int choice = Integer.parseInt(br.readLine());
        switch(choice){
            case 1:
            System.out.print("r1 = ");
            double r1 = Double.parseDouble(br.readLine());
            System.out.print("r2 = ");
            double r2 = Double.parseDouble(br.readLine());
            double r = r1 + r2;
            System.out.println("Series Resistance = " + r);
            break;
            case 2:
            System.out.print("r1 = ");
            r1 = Double.parseDouble(br.readLine());
            System.out.print("r2 = ");
            r2 = Double.parseDouble(br.readLine());
            r = (r1 * r2) / (r1 + r2);
            System.out.println("Parallel Resistance = " + r);
            break;
            default:
            System.out.println("Invalid choice!");
        }
    }
}

Q19. The Simple Interest (SI) and Compound Interest (CI) of a sum (P) for a given time (T) and rate (R) can be calculated as:
SI = P × T × R / 100
CI = P((1 + R / 100)T – 1)
Write a program to input the sum, rate, time and type of interest (‘S’ for Simple Interest and ‘C’ for Compound Interest). Calculate and display the sum and the interest earned.

import java.io.*;
class Interest{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Sum: ");
        double p = Double.parseDouble(br.readLine());
        System.out.print("Rate: ");
        double r = Double.parseDouble(br.readLine());
        System.out.print("Time: ");
        double t = Double.parseDouble(br.readLine());
        System.out.print("Type of Interest: ");
        char i = br.readLine().charAt(0);
        switch(i){
            case 'S':
            case 's':
            double si = p * r * t / 100;
            System.out.println("Simple Interest = " + si);
            break;
            case 'C':
            case 'c':
            double ci = p * (Math.pow((1 + r / 100), t) - 1);
            System.out.println("Compound Interest = " + ci);
            break;
            default:
            System.out.println("Invalid choice!");
        }
    }
}

Q20. Kumar Electronics has announced the following seasonal discounts on purchase of certain items:

Purchase Amount Discount on Laptop Discount on Desktop PC
Up to 25000 0.0% 5.0%
25001 to 50000 5.0% 7.5%
50001 to 100000 7.5% 10.0%
More than 100000 10.0% 15.0%

Write a program to input name, amount of purchase and the type of purchase (‘L’ for Laptop and ‘D’ for Desktop) by a customer. Compute and print the net amount to be paid by a customer along with his name.
Net amount = Amount of purchase – Discount.

import java.io.*;
class Electronics{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Name: ");
        String name = br.readLine();
        System.out.print("Amount of purchase: ");
        double amt = Double.parseDouble(br.readLine());
        System.out.print("Type of purchase: ");
        char t = br.readLine().charAt(0);
        switch(t){
            case 'L':
            case 'l':
            double d = 0.0;
            if(amt > 25000 && amt <= 50000)
                d = 5.0;
            else if(amt > 50000 && amt <= 100000)
                d = 7.5;
            else
                d = 10.0;
            double net = amt - d / 100 * amt;
            System.out.println("Name = " + name);
            System.out.println("Net amount = " + net);
            break;
            case 'D':
            case 'd':
            d = 0.0;
            if(amt <= 25000)
                d = 5.0;
            else if(amt > 25000 && amt <= 50000)
                d = 7.5;
            else if(amt > 50000 && amt <= 100000)
                d = 10.0;
            else
                d = 15.0;
            net = amt - d / 100 * amt;
            System.out.println("Name = " + name);
            System.out.println("Net amount = " + net);
            break;
            default:
            System.out.println("Invalid choice!");
        }
    }
}

 

11 replies on “Conditional Statements in Java”

I would suggest not to use Scanner class because BufferedReader is still the best option to receive user input from the user. And since all programs are done in BufferedReader, it is difficult to change all of them to Scanner class.

Leave a Reply to Debatri Agarwal Cancel reply