Conditional Statement: If-Then, If-Else, Switch
Conditional Statement: If-Then, If-Else, Switch
Conditional Statement: If-Then, If-Else, Switch
Objectives:
After completing the following exercises, students will be able to:
Trace programs that use if-then , if-else and switch statement
Analyze programs with nested conditional statement
rewrite switch statements as if-else statements or if-then statements
Exercise 1:
What is the output of each of the following code fragments?
(given the declaration int a=1, b=2, c=3;):
Answers:
1. if (y > 0) x = 1;
2. if (score >= 80 && score <=90) score += 5;
3. item = i >= 10 && i < 50
4. if (x % 2 != 0 && x > 0) System.out.println(true);
or
System.out.println(x%2 !=0 && x>0); // This prints false otherwise
5. if (x > 0 && y > 0) System.out.println(true);
or
System.out.println(x > 0 && y > 0); // This prints false otherwise
6. if (x * y > 0) System.out.println(true);
or
System.out.println(x * y > 0); // This prints false otherwise
Exercise 3:
Two programs are equivalent if given the same input they produce the same output.
Which of the following programs are equivalent? Why?
// Program A
import java.util.Scanner;
class TestPositive {
public static void main(String [] args) {
Scanner S = new Scanner(System.in);
System.out.print(“Enter a value: ”);
int x = S.nextInt();
if (x > 0) {
System.out.println(“The value is positive:”);
}
else {
if (x < 0) {
System.out.println(“The value is negative:”);
} else {
System.out.println(“The value is zero:”);
}
}
System.out.println(“Good Bye!”);
}
}
// Program B
import java.util.Scanner;
class TestPositive {
public static void main(String [] args) {
Scanner S = new Scanner(System.in);
System.out.print(“Enter a value: ”);
int x = S.nextInt();
if (x > 0) {
System.out.println(“The value is positive:”);
}
if (x < 0) {
System.out.println(“The value is negative:”);
} else {
System.out.println(“The value is zero:”);
}
System.out.println(“Good Bye!”);
}
}
// Program C
import java.util.Scanner;
class TestPositive {
public static void main(String [] args) {
Scanner S = new Scanner(System.in);
System.out.print(“Enter a value: ”);
int x = S.nextInt();
if (x > 0) {
System.out.println(“The value is positive:”);
}
if (x < 0) {
System.out.println(“The value is negative:”);
}
if (x ==0) {
System.out.println(“The value is zero:”);
}
System.out.println(“Good Bye!”);
}
}
Answer:
Programs A and C are equivalent. Program B is different since it gives different output if input
is a positive number greater than zero. For example, 3
Exercise 4:
Convert the following switch statement into if-else statements then into if-then statements:
String dayString1, dayString2, dayString3;
int day = KB.nextInt();
switch (day) {
case 1: dayString1 = "Saturday";
case 2: dayString2 = "Sunday";
break;
case 3: dayString3 = "Monday";
break;
case 4: dayString1 = "Tuesday";
case 5: dayString2 = "Wednesday";
break;
default: dayString3 = "Invalid day";
break;
}
Answer:
if-else:
if-then: