ProgramModerate2 marks
Rewrite the following code using the if-else statement: int m = 400; double ch = (m > 300) ? (m / 10.0) * 2 : (m / 20.0) - 2;
Topic: Ternary to if-else
Previous-year question practice database
Answer
Exam answer
int m = 400; double ch; if(m > 300) ch = (m / 10.0) * 2; else ch = (m / 20.0) - 2;
Explanation
Unpack the ternary into its three pieces: the condition (m > 300) becomes the if test the value before the colon becomes the if branch the value after the colon becomes the else branch Declare ch BEFORE the if, not inside it — a variable declared inside a branch would go out of scope the moment the branch ends, and the program would not compile. Keep the division by 10.0 and 20.0 exactly as written. Changing them to 10 and 20 would make the arithmetic integer division and quietly alter the answer. (With m = 400 the if branch runs, giving ch = 80.0.)
More from Revision Tour II
Read the if program segment given below:
if(a > b)
z = 25;
else
z = 35;
Which one of the following is the correct conversion of the if program segment to ternary?2026The earth spins on its axis completing one rotation in a day. The earth revolves around the sun in 365 days to complete one revolution. What is the Java concept depicted in the given picture?2026Rewrite the following program segment using a for loop.
int a = 5, b = 10;
while(b > 0)
{
b -= 2;
}
System.out.println(a * b);2026Users must be above 10 years to open a self-operated bank account. Write this logic using a ternary operator and store the result (the eligibility message) in a String variable named idStatus and print it.2026Give the output of the following program segment and mention how many times the loop is executed.
int K = 1;
do
{
K += 2;
System.out.println(K);
} while(K <= 6);2026Write a program to accept a number and check if it is a Mark number or not. A number is said to be Mark when the sum of the squares of each digit is an even number as well as the last digit of the sum and the last digit of the number given is the same.
Example: n = 246
sum = 2 x 2 + 4 x 4 + 6 x 6 = 56
56 is an even number as well as last digit is 6 for both sum as well as the number.2026