Conditional Statements in Java
I. Multiple choice questions
Tick the correct answer:
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) Isoceles 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 required output. It is due to:
a) the logical error in the program b) the syntax error in the program
c) the runtime error in the program d) none
Ans.
1. b) a default case
2. No matching options. [ Compound statement is a set of statements enclosed within curly brackets.]
3. d) All
4. c) a is the greatest number
5. d) None
6. b) Scalene triangle
7. b) Relational operator
8. a) if
9. b) switch statement
10. a) the logical error in the program
II. Answer the following questions:
1. Name the different ways to manage the flow of control in a program.
Ans.
The flow of control during the execution of a Java program takes place in the following ways:
- Normal flow of control
- Bi-directional flow of control
- Multiple branching flow of control
2. Mention one statement each to achieve:
a) Bi-directional flow of control
b) Multiple branching of control
Ans.
a) Bi-directional flow of control
Sometimes, the programmer may want to operate a block of statements when the given condition is true. If the given condition is false, then the block is ignored and control moves to execute another block. Thus, the block of statements which get executed depends on the condition defined. This is referred to as Bi-directional flow of control. Bi-directional flow of control can be achieved by using ‘if’ statement the following ways:
- if statement
- Nested if with else statement
- if- else statement
- if-else-if statement
b) Multiple branching of control
Switch case statement is a multiple branching statement where a particular block of statements is executed out of a number of available options as per the user’s choice. In this system, the control goes to a specific case and executes that block for a given switch value (value of the control variable). The switch-case statement also includes a ‘default’ case which is executed when the switch value does not match any of the given cases.
Syntax:
switch(control variable)
{
case 1: // This block is executed if the value of control variable is ‘1’
case 2: // This block is executed if the value of control variable is ‘2’
case 3: // This block is executed if the value of control variable is ‘3’
default: // This block is executed when there is no matching case for the control variable
}
3. Explain the following statements with their constructs:
a) nested if
b) if-else
c) if-else-if
a) Nested –if
The term nested means one action is taken within another action. Thus, in a nested if statement, one if statement is placed within another if statement.
Syntax /Construct:
if(condition1)
{
if(condition1a)
{
}
else
{
}
}
else
{
if(condition1b)
{
}
else
{
}
}
Example of Nested-if
if(a<=100)
{
if(a%2= =0)
System.out.print(“even”);
else
System.out.print(“Odd”);
}
else
{ System.out.print(“The number is greater than 100”);
}
b) if – else
It is a logical condition in which either of the two actions is to be performed depending upon the specified condition. When the condition is ‘true’ , it performs one set of statements, otherwise it performs the another set of statements. The syntax is shown below:
if(condition)
{
}
else
{
}
c) if – else – if
It is also a logical situation in which multiple conditions are given. The associated action to be performed for each condition is also given in the code. During execution, the conditions are checked one by one. Whichever condition is true, the statements under that block are executed and the control comes out of the if-else-if block. If none of the conditions are true then the block of statements given under the else part is executed.
The syntax is shown below:
if(condition1)
{
//This block is executed if condition 1 is true
}
else if(condition2)
{
//This block is executed if condition 2 is true
}
else if(condition3)
{
//This block is executed if condition 3 is true
}
else
{
//This block is executed if all the above conditions are false
}
4. Differentiate between if and switch statement.
Ans.
if statement
- It results in a boolean type value (true /false) based on which one of the two blocks of statements are executed.
- if-else does not include a default case to be executed when the value of the control variable doesn’t match any of the given cases.
- It can perform tasks on a relational or a logical expression.
- It can perform tests and comparisons on integers, fractional values (e.g. float) and char type values.
switch statement
- The switch statement does not result in a boolean type value (true/ false). Depending on the value of the control variable, the matching case is selected and that block of code executed.
- Switch statement includes a default case to be executed when the value of the control variable doesn’t match any of the given cases.
- It can perform only tests of equality. It cannot evaluate other relational or logical expressions.
- It cannot evaluate fractional values (float, double) but it can evaluate int, char and String type values and match them to the corresponding cases.
5. What is the purpose of switch statement in a program?
Ans. Switch case statement is used in cases where multiple branching is required. In this system, the value of the control variable must match one of the cases. The control is then transferred to that specific case and the corresponding block of code is executed. If a break statement is present at the end of that case, then the control finally breaks out of the switch-case block. But if a break statement is missing at the end of the matching case, all the subsequent cases are executed until a break statement is encountered.
Suppose if none of the cases match the value of the control variable, then the control is transferred to the default case and the corresponding block of code is executed. Generally, when the user’s choice of option is incorrect, the default case can be used to give the user an “Invalid option /Invalid input” message.
Note: Switch case statements are ideally preferred for menu driven programs in Java although menu driven programs can also be written using if-else-if statements.
Syntax:
switch(control variable)
{
case 1: // This block is executed if the value of control variable is ‘1’
case 2: // This block is executed if the value of control variable is ‘2’
case 3: // This block is executed if the value of control variable is ‘3’
default: // This block is executed when there is no matching case for the control variable
}
6. Explain with the help of an example, the purpose of default in a switch statement.
Ans.
Suppose if none of the cases match the value of the control variable, then the control is transferred to the default case and the corresponding block of code is executed. Generally, when the user’s choice of option is incorrect, the default case can be used to give them an “Invalid option /Invalid input” message.
Example
int choice=4;
switch(choice)
{
case 1: System.out.print( “ Addition”);
case 2: System.out.print( “ Subtraction”);
case 3: System.out.print( “ Multiplication and Division”);
default: System.out.print( “Invalid choice. Enter 1, 2 or 3”);
}
In the above example, the value of the control variable is 4 and it does not have a matching case. Therefore, the default case is executed and the message “Invalid choice. Enter 1, 2 or 3” is printed.
7. Is it necessary to use ‘break’ statement in a switch case statement? Explain.
Ans.
Yes. It is necessary to use the break statement in a switch case. This will ensure that only the matching case is executed for a particular value of the control variable. If the break statement is missing, the matching case and all the other subsequent cases will be executed until a break statement is encountered.
8. Explain ‘fall through’ with reference to a switch case statement.
Ans.
In a switch block, where multiple cases are available, the control needs to execute only the specific case for a given switch value. If the break statement is not applied at the end of a case, the control executes the matching case and all the subsequent cases until a break statement is encountered. This unusual execution of more than one case for a given value of switch is termed as ‘fall through’.
9. What is a compound statement? Give an example.
Ans.
A statement that includes one or more statements within it marked under curly brackets{ }, is said to be a compound statement.
Example:
if(n%2 = = 0)
{
P=x*x;
T=Math.sqrt(x);
}
Since the statements above are enclosed with curly brackets, the statement block is known as compound statement.
10. Explain with an example the if-else-if construct.
Ans. repeated – See the answer to Q3c
11. Name two jump statements and their use.
Ans.
The statements in Java are a) break b) continue and c) return
Break statement (Breaks out of the loop)
The break statement is used to skip all the remaining iterations of the loop and terminate or break out of the loop.
Continue statement (Continues with the next iteration of the loop)
The continue statement is used to skip the remaining statements of the loop and continue with the next iteration of the loop.
12. Give two differences between the switch statement and the if-else statement.
Ans. repeated – See the answer to Q4.
III. Predict the output of the given snippet when executed:
1. 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));
}
Ans.
The first ‘if’ condition fails since b=1. Since the second condition is true, 10 * 5 and 10%2 are calculated.
50
0
2. 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
Ans.
i) when n=1, the condition n>0 becomes true and therefore the values of x and y are incremented. Therefore, the output is as follows:
2
2
ii) when n=0, the condition n>0 becomes false and therefore the values of x and y are not incremented. Therefore, the output is as follows:
1
1
3. int b=3,k,r;
float a=15.15, c=0;
if(k==1)
{
r = (int) a/b;
System.out.println( r) ;
}
else
{
c=a/b;
System.out.println(c );
}
Ans.
Corrections to be made : k should be initialized to 0 and float a=15.15f
The output is 5.0499997 since the else part is executed as 15.15f/3
4. 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’
Ans. [The break statement is missing in this case, therefore fall through occurs and the following output. ]
Object Oriented
Robust and Secure
ii) opn= ‘x’
Ans. [ A matching case is not available, therefore default case is executed and hence the output is shown below]
Wrong Input
iii) opn= ‘a’
Ans. [ Since the break statement is present in case ‘a’, only the first case is executed] and hence the following output]
Platform independent
IV. Correct the errors in the given programs:
1. class public
{
public static void main(String args[])
{
int a=45,b=70,c=65.45;
sum=a+b;
diff=c-b;
System.out.println(sum, diff);
}}
Ans.
Incorrect | Correct |
class public | Incorrect order and missing class name ; public class Cname |
c=65.45 | Incorrect data type; c should be declared as double/float |
sum | Missing declaration; sum should be declared as int |
diff | Missing declaration; diff should be declared as double |
System.out.println(sum, diff); | Variables should be printed using separate print statements or they can be printed with a blank or tab inbetween. System.out.println(sum+ “\t”+diff); |
2. class Square
{
public static void main(String args[])
{
int n=289,r;
r=sqrt(n);
if(n= =r)
System.out.println(“Perfect Square”);
else
System.out.println(“Not a Perfect Square”);
}}
Ans.
Incorrect | Correct |
r=sqrt(n); | Incorrect syntax; r=Math.sqrt(n) |
Data type of ‘r’ | Incorrect data type; Math.sqrt returns double data type so ‘r’ should be declared as double |
r= (int)Math.sqrt(n) | Incorrect logic used. Only the integer part of the square root should be taken to check for perfect square number. |
if(n= =r) | Incorrect logic used. n should be compared with r *r (that is r2 ) if(n= =r*r) |
3. class Simplify
{
public static void main(String args[])
{
int a,b,c,d;
a=10,b=5,c=1,d=2;
c=a2 + b2;
d=(a+b)2;
p=c/d;
System.out.println(c + “ ” + “ ”+d + “ ”+p);
}}
Ans.
Incorrect | Correct |
a=10,b=5,c=1,d=2; | Missing semicolons a=10; b=5; c=1; d=2; |
c=a2 + b2; | Superscript cannot be used in Java like this. Math.pow or a*a format should be used c= a*a + b*b; |
d=(a+b)2; | Superscript cannot be used in Java like this. Math.pow should be used d=Math.pow((a+b),2); |
d=(a+b)2; | Incorrect data type of d; ‘d’ should be declared as double |
p=c/d; | Missing declaration for variable ‘p’. It should be declared as double. |
4. class Sample
{
public static void main(String args[])
{
int n,p;
float k,r;
n=25;p=12;
if(n=25)
{
k=pow(p,2)
System.out.println(“The value of” +p+ “ = ”+k);
}
else
{
r=Math.square root(n);
System.out.println(“The value of”+n+ “ = ”+r);
}}}
Ans.
Incorrect | Correct |
k=pow(p,2) | k=Math.pow(p,2); |
r=Math.square root(n); | r=Math.sqrt(n); |
if(n=25) | Equality operator is = =. So the statement should be, if(n= =25) |
float k, r; | Since the return type of Math.pow( ) and Math.sqrt( ) is double, variables ‘k’ and ‘r’ should be declared as double. |
V Unsolved Java Programs:
1) 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 triangle or an obtuse-angled triangle. Otherwise display “Triangle not possible”.
Sample Input : Enter three angles : 40, 50, 90
Sample Output: Right-Angled Triangle.
Solution:
class Q1{
static void main(int x,int y,int z)
{
if(x+y+z==180)
{ System.out.println(” Triangle is possible”);
if(x<=90 && y<=90 && z<=90)
System.out.println(“Acute angled triangle”);
else if(x==90 && y==90 && z==90)
System.out.println(“Right angled triangle”);
else
System.out.println(“Obtuse angled triangle”);
}
else
System.out.println(“Triangle is not possible”);
}}
2) Write a program to input the cost prince and the selling price of an article. If the selling price is more than the cost price then calculate and display the actual profit and profit percent otherwise, calculate and display actual loss and loss percent. If the cost price and the selling price are equal, the program displays the message “Neither profit nor loss”.
Solution:
class Q2{
static void main(double cp, double sp)
{
double profit,pp,loss,lp;
if(sp>cp)
{
profit=sp-cp;
pp=profit/cp*100.0;
System.out.println(“Profit=Rs.” +profit);
System.out.println(“Profit%=Rs.”+pp);
}
else if(cp>sp)
{ loss=cp-sp;
lp=loss/cp*100.0;
System.out.println(“Loss=Rs.”+loss);
System.out.println(“Loss%=Rs.”+lp);
}
else
System.out.println(“Neither profit nor Loss”);
}}
3) 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”.
Sample Input: 34, 87, 61
Sample Output: 87
Sample Input: 81,81,81
Sample Output: All the numbers are equal.
Solution:
class Q3{
static void main(int x, int y, int z)
{
if(x==y && y==z)
System.out.println(“All numbers are equal”);
else
{int max=(x>y && y>z)?x:(y>z)?y:z;
System.out.println(“Greatest number:”+max);
}
}}
4) 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 divisible by 3 nor by 5?
The program displays the message accordingly.
Solution:
class Q4{
static void main(int num)
{
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 but not by 5”);
else if(num%5==0)
System.out.println(“Divisible by 5 but not by 3”);
else
System.out.println(“Neither divisible by 3 nor by 5”);
}}
5) Write a program to input year and check whether it is:
a) Leap year b) A century leap year c) A century year but not a Leap year.
Sample Input: 2000
Sample Output: It is a Century Leap Year
Solution:
class Q5{
static void main(int yr)
{
if(yr%4==0 && yr%10==0 && yr%100==0)
System.out.println(“Century leap year”);
else if(yr%4==0)
System.out.println(“Leap year but not a Century Leap Year”);
else if(yr%10==0 && yr%100==0)
System.out.println(“Century year but not a Leap year”);
}}
6) 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 of a negative number can’t be determined’.
Sample Input: 81,100
Sample Output: They are perfect square numbers
Sample Input: 225,99
Sample Output: 225 is a perfect square number
99 is not a perfect square number
Solution:
import java.util.*;
class Q6{
static void main()
{
Scanner ob=new Scanner(System.in);
int x,y,a,b;
System.out.println(“Enter two numbers”);
x=ob.nextInt();
y=ob.nextInt();
if(x<0 || y<0)
System.out.println(“Square root of a negative number cannot be determined”);
a=(int)Math.sqrt(x);
if(x==a*a && x>0)
System.out.println(x+” is a perfect square number”);
else
System.out.println(x+” is not a perfect square number”);
b=(int)Math.sqrt(y);
if(y==b*b && y>0)
System.out.println(y+” is a perfect square number”);
else
System.out.println(y+” is not a perfect square number”);
}}
7) Without using if-else statement and ternary operators, accept three unequal numbers and display the second smallest number.
[Hint : Use Math.max() and Math.min() ]
Sample Input: 34,82,61
Sample Output: 61
Solution:
import java.util.*;
class Q7{
static void main()
{
Scanner ob=new Scanner(System.in);
int a,b,c,sm1,sm2;
System.out.println(“Enter 3 unequal numbers”);
a=ob.nextInt();
b=ob.nextInt();
c=ob.nextInt();
sm1=Math.min(a,b);
sm2=Math.max(sm1,c);
System.out.println(“The second smallest number is “+sm2);
}}
8) Write a program to input three unequal numbers. Display the greatest and the smallest number.
Sample Input : 28, 98, 56
Sample Output: Greatest number: 98
Smallest number: 28
Solution:
import java.util.*;
class Q8{
static void main()
{Scanner ob=new Scanner(System.in);
int a,b,c,big,small;
System.out.println(“Enter 3 unequal numbers”);
a=ob.nextInt();
b=ob.nextInt();
c=ob.nextInt();
big=Math.max(a, Math.max(b,c));
small=Math.min(a, Math.min(b,c));
System.out.println(“Greatest number:”+big);
System.out.println(“Smallest number:”+small);
}}
9) A pre-paid taxi charges from the passenger as per the tariff given below:
Distance | Rate |
Up to 5km | Rs.100 |
For the next 10km | Rs.10/km |
For the next 10km | Rs.8/km |
More than 25km | 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 : _______________
Solution:
import java.util.*;
class Q9{
static void main()
{
Scanner ob=new Scanner(System.in);
int taxino,dist,amt;
System.out.println(“Enter the taxi number”);
taxino=ob.nextInt();
System.out.println(“Enter the distance”);
dist=ob.nextInt();
if(dist<=5)
amt=100;
else if(dist>5 && dist<=15)
amt=100+ (dist-5)*10;
else if(dist>15 && dist<=25)
amt=100+ 10*10 +(dist-15)*8;
else
amt=100 +10*10 + 10*8 + (dist-25)*5;
System.out.println(“Taxi number=”+taxino);
System.out.println(“Distance in km=”+dist);
System.out.println(“Amount=Rs. “+amt);
}}
10) 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 |
Upto Rs.2,000 | 5% | Calculator |
Rs.2001 to Rs.5000 | 10% | School Bag |
Rs.5001 to Rs.10,000 | 15% | Wall clock |
Above Rs.10,000 | 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.
Solution:
class Q10{
static void main(double cost)
{
double dis=0,amt;
String gift=””;
if(cost<=2000)
{ dis=5.0/100;
gift=”calculator”;
}
else if(cost>=2001 && cost<=5000)
{
dis=10.0/100;
gift=”schoolbag”;
}
else if(cost>=5001 && cost<=10000)
{
dis=15.0/100;
gift=”wall clock”;
}
else if(cost>=10000)
{ dis=20.0/100;
gift=”wrist watch”;
}
amt=cost- (dis*cost);
System.out.println(“Amount payable=”+amt);
System.out.println(“Gift: “+gift);
}}
11) Given below is a hypothetical table showing the rate of income tax for an Indian citizen, who is below or up to 60 years.
Taxable Income (in Rs) | Income Tax (in Rs) |
Up to Rs.2,50,000 | Nil |
More than Rs.2,50,000 and less than or equal to Rs.5,00,000 | 10% on the income exceeding Rs.2,50,000 |
More than Rs.5,00,000 and less than or equal to Rs.10,00,000 | 20% on the income exceeding Rs.5,00,000 plus an additional Rs.34,000 |
More than Rs.10,00,000 | 30% on the income exceeding Rs.10,00,000 plus and additional Rs.94,000 |
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 the tax payer as per the table given above. [ICSE 2012]
Solution:
import java.util.*;
class Q11{
static void main()
{
Scanner ob=new Scanner(System.in);
String s=””;
int age,ti;
double tax;
System.out.println(“Enter the name”);
s=ob.nextLine();
System.out.println(“Enter the age”);
age=ob.nextInt();
System.out.println(“Enter the taxable income”);
ti=ob.nextInt();
if(age>60)
System.out.println(“Wrong category”);
else
{
if(ti<=250000)
tax=0;
else if(ti>250000 && ti<=500000)
tax=(ti-160000)* (10/100.0);
else if(ti>500000 && ti<=1000000)
tax=(ti-500000)*(20/100.0) +34000;
else
tax=(ti-1000000)*(30/100.0)+94000;
System.out.println(“Name:”+s);
System.out.println(“Tax payable=”+tax);
}
}}
12) 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 |
Upto 180 days | 5.5% |
181 to 364 days | 7.5% |
Exact 365 days | 9.0% |
More than 365 days | 8.5% |
Write a program to calculate the maturity amount taking the sum and number of days as inputs.
Solution:
import java.util.*;
class Q12
{
static void main()
{
Scanner ob=new Scanner(System.in);
int amt,days;
double rate,fin;
System.out.println(“Enter the amount”);
amt=ob.nextInt();
System.out.println(“Enter the number of days”);
days=ob.nextInt();
if(days<=180)
rate=5.5/100;
else if(days >=181 && days<=364)
rate=7.5/100;
else if(days==365)
rate=9.0/100;
else
rate=8.5/100;
fin=amt+(amt*rate);
System.out.println(“Maturity Deposit=”+fin);
}}
13) 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 Rs.1,00,000 | 5% | 2% |
Rs.1,00,001 and up to Rs. 2,00,000 | 8% | 3% |
Rs.2,00,001 and up to Rs.5,00,000 | 10% | 5% |
More than Rs.5,00,000 | 15% | 7.5% |
Write a program to input the 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 :
Solution:
import java.util.*;
class Q13
{
static void main()
{
Scanner sn=new Scanner(System.in);
String n;
double sa,p,dis,comm,dis1,comm1;
System.out.println(“Enter the name”);
n=sn.nextLine();
System.out.println(“Enter the sum assured”);
sa=sn.nextDouble();
System.out.println(“Enter the first annual premium”);
p=sn.nextDouble();
if(sa<=100000)
{
dis=5.0/100;
comm=2.0/100;
}
else if(sa>=100001 && sa<=200000)
{ dis=8.0/100;
comm=3.0/100;
}
else if(sa>=200001 && sa<=500000)
{ dis=10.0/100;
comm=5.0/100;
}
else
{dis=15.0/100;
comm=7.5/100;
}
dis=p*dis;
comm=sa*comm;
System.out.println(“Name of the policy holder: “+n);
System.out.println(“Sum assured: “+sa);
System.out.println(“Premium: “+p);
System.out.println(“Discount on the first premium: “+dis);
System.out.println(“Commission of the agent: “+comm);
}}
14) A company announces revised Dearness Allowance(DA) and Special Allowances (SA) for their employees as per the tariff given below:
Basic | Dearness Allowance (DA) | Special Allowances(SA) |
Up to Rs.10,000 | 10% | 5% |
Rs.10,001 to Rs.20,000 | 12% | 8% |
Rs.20,001 to Rs.30,000 | 15% | 10% |
Rs.30,001 and above | 20% | 12% |
Write a program to accept name and basic salary (BS) of an employee. Calculate and display gross salary.
Gross Salary = Basic + Dearness allowance + Special allowance
Print the information in the given format:
Name Basic DA Spl. Allowance Gross Salary
Solution:
import java.util.*;
class Q14
{
static void main()
{
Scanner ob=new Scanner(System.in);
String n;
double basic,da,sa,gross;
System.out.println(“Enter the name”);
n=ob.nextLine();
System.out.println(“Enter the basic”);
basic=ob.nextDouble();
if(basic<=10000)
{ da=10.0/100;
sa=5.0/100;
}
else if (basic>10001 && basic<=20000)
{ da=12.0/100;
sa=8.0/100;
}
else if (basic>20001 && basic<=30000)
{ da=15.0/100;
sa=10.0/100;
}
else
{ da=20.0/100;
sa=12.0/100;
}
gross=basic+da+sa;
System.out.println(“Name \t\t Basic \t\t DA \t Special Allowance \t Gross Salary”);
System.out.println(n+”\t\t”+basic+”\t\t”+da+”\t\t”+sa+”\t\t”+gross);
}}
15) 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.
Hint: c=5/9 * (f-32) and f=1.8*c +32
Solution:
import java.util.*;
class Q15
{
static void main()
{
Scanner ob=new Scanner(System.in);
double c,f;
int var;
System.out.println(“MENU”);
System.out.println(“1.Celsius to Fahrenheit”);
System.out.println(“2.Fahrenheit to Celsius”);
System.out.println(“Enter your choice 1 or 2”);
var=ob.nextInt();
switch(var)
{
case 1:
System.out.println(“Enter the temperature in Celsius”);
c=ob.nextDouble();
f=1.8*c + 32;
System.out.println(“Temp in Fahrenheit =”+f);
break;
case 2:
System.out.println(“Enter the temperature in Fahrenheit”);
f=ob.nextDouble();
c=(5/9.0)*(f-32);
System.out.println(“Temp in Celsius =”+c);
break;
default:System.out.println(“Invalid choice”);
}}}
16) The volume of solids, viz cuboid, cylinder and cone can be calculated by the formula:
1. Volume of a cuboid (v =l*b*h)
2. Volume of a cylinder (v=Pi *r2 * h)
3. Volume of a cone (v=1 * Pi * r2 * h)
3
Using a switch case statement, write a program to find the volume of different solids by taking suitable variables and data types.
Solution:
import java.util.*;
class Q16
{
static void main()
{
Scanner ob=new Scanner(System.in);
double l,b,h,r,v;
int var;
System.out.println(“MENU”);
System.out.println(“1.Volume of a Cuboid”);
System.out.println(“2. Volume of a Cylinder”);
System.out.println(“3.Volume of a Cone”);
System.out.println(“Enter your choice”);
var=ob.nextInt();
switch(var)
{case 1: System.out.println(“Enter the length”);
l=ob.nextDouble();
System.out.println(“Enter the breadth”);
b=ob.nextDouble();
System.out.println(“Enter the height”);
h=ob.nextDouble();
v=l*b*h;
System.out.println(“Volume of a Cuboid=”+v);
break;
case 2: System.out.println(“Enter the radius”);
r=ob.nextDouble();
System.out.println(“Enter the height”);
h=ob.nextDouble();
v=(22/7.0)*r*r*h;
System.out.println(“Volume of a Cylinder=”+v);
break;
case 3: System.out.println(“Enter the radius”);
r=ob.nextDouble();
System.out.println(“Enter the height”);
h=ob.nextDouble();
v=(1/3.0)*(22/7.0)*r*r*h;
System.out.println(“Volume of a Cone=”+v);
break;
default:System.out.println(“Invalid choice”);
}
}}
17) A Mega shop has different flows 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 tasks as per the user’s choice.
Solution:
import java.util.*;
class Q17
{
static void main()
{
Scanner ob=new Scanner(System.in);
int choice,f;
double amt;
System.out.println(“***MENU***”);
System.out.println(“1.Floor Information”);
System.out.println(“2.Billing”);
System.out.println(“Enter your choice …1 or 2”);
choice=ob.nextInt();
switch(choice)
{
case 1: System.out.println(“Enter the floor number”);
f=ob.nextInt();
if(f==1) System.out.println(“Kids Wear”);
else if(f==2) System.out.println(“Ladies Wear”);
else if(f==3) System.out.println(“Designer Sarees”);
else if(f==4) System.out.println(“Men’s Wear”);
else System.out.println(“Invalid floor number”);
break;
case 2:System.out.println(“Enter the total bill amount”);
amt=ob.nextDouble();
System.out.println(“\n\n***Bill***”);
System.out.println(“Name of the shop: City Mart”);
System.out.println(“Total Amount :Rs.”+amt);
System.out.println(“Visit Again!!!”);
break;
default: System.out.println(“Invalid Menu choice”);
}
}}
18) The equivalent resistant 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.
Solution:
import java.util.*;
class Q18
{
static void main()
{
Scanner ob=new Scanner(System.in);
int var,r1,r2,R;
System.out.println(“MENU”);
System.out.println(“1. Resistance of series circuit “);
System.out.println(“2. Resistance of parallel circuit “);
System.out.println(“Enter your choice “);
var=ob.nextInt();
System.out.println(“Enter the value of r1”);
r1=ob.nextInt();
System.out.println(“Enter the value of r2”);
r2=ob.nextInt();
switch(var)
{case 1: R=r1+r2;
System.out.println(“Resistance of the series circuit=”+R);
break;
case 2: R=(r1*r2)/(r1+r2);
System.out.println(“Resistance of the parallel circuit=”+R);
break;
default:System.out.println(“Invalid choice”);
}
}}
19) The Simple Interest (SI) and Compound Interest (CI) of a sum (P) for a given time (T) and rate (R ) can be calculated as :
a) SI = p*r*t
100
b) CI = P * ( (1 + R/100)T -1 )
Write a program to input 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.
Solution:
import java.util.*;
class Q19
{
static void main()
{
Scanner ob=new Scanner(System.in);
float p,r,t,si,ci;
char type;
System.out.println(“Enter the principal”);
p=ob.nextFloat();
System.out.println(“Enter the rate”);
r=ob.nextFloat();
System.out.println(“Enter the time”);
t=ob.nextFloat();
System.out.println(” Enter ‘s’ for Simple Interest and ‘c’ for Compound Interest”);
type=ob.next().charAt(0);
if(type==’s’ || type==’S’)
{si=p*r*t/100;
System.out.println(“SI=”+si);
}
else if(type==’c’ || type==’C’)
{ci=p*(float)(Math.pow((1+r/100),t)-1);
System.out.println(“CI=”+ci);
}
else
System.out.println(“Incorrect type”);
}}
20) ‘Kumar Electronics’ has announced the following seasonal discounts on purchase of certain items.
Purchase Amount | Discount on Laptop | Discount on Desktop PC |
Up to Rs.25000 | 0.0% | 5.0% |
Rs.25,001 to Rs.50,000 | 5.0% | 7.5% |
Rs.50,001 to Rs.1,00,000 | 7.5% | 10.0% |
More than 1,00,000 | 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. Comput and print the net amount to be paid by a customer along with his name.
(Net amount = Amount of purchase – discount ) [ICSE – 2009 ]
Solution:
import java.util.*;
class Q20
{
static void main()
{
Scanner ob=new Scanner(System.in);
String n=””;
char type;
double amt,dis=0,net,d1,d2;
System.out.println(“Enter your name”);
n=ob.nextLine();
System.out.println(“Enter the amount of purchase”);
amt=ob.nextDouble();
System.out.println(“Enter ‘L’ for Laptop and ‘D’ for Desktop”);
type=ob.next().charAt(0);
if(amt<=25000)
{d1=0;
d2=5.0/100;
}
else if(amt>=25001 && amt<=50000)
{d1=5.0/100;
d2=7.5/100;
}
else if(amt>50001 && amt<=100000)
{d1=7.5/100;
d2=10.0/100;
}
else
{d1=10.0/100;
d2=15.0/100;
}
if(type==’L’ || type==’l’)
dis=d1*amt;
else if(type==’D’ || type==’d’)
dis=d2*amt;
else
System.out.println(“Incorrect type of purchase”);
net=amt-dis;
System.out.println(“Name of the customer :”+n);
System.out.println(“Net amount payable :”+net);
}}
**************