Assignment 2
Assignment 2
Exercise 1:
What is the output of each of the following code fragments? justify the answer
(given the declaration int a=1, b=2, c=3;):
1. if (6 < 2 * 5)
System.out.print("Hello");
System.out.print(" There");
2. if(a>b)
if(a>c)
System.out.println("1111");
else System.out.println("2222");
3. if(a>b)
{if(a>c) System.out.println("1111");}
else System.out.println("2222");
4. if (a < c)
System.out.println("*");
else if (a == b)
System.out.println("&");
else
System.out.println("$");
5. if(a<b)
System.out.println("####");
else
System.out.println("&&&&");
System.out.println("****");
6. if(a>b)
System.out.println("####");
else
{System.out.println("&&&&");
System.out.println("****");}
Exercise 2:
4. Write a java statement that prints true if x is an odd number and positive
5. Write a java statement that prints true if both x and y are positive numbers
6. Write a java statement that prints true if x and y have the same sign (-/+)
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 {
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 {
if (x > 0) {
System.out.println(“The value is positive:”);
}
if (x < 0) {
System.out.println(“Good Bye!”); }
// Program C
import java.util.Scanner; class TestPositive {
if (x > 0) {
System.out.println(“The value is positive:”);
}
if (x < 0) {
if (x ==0) {
System.out.println(“The value is zero:”);
System.out.println(“Good Bye!”); }
Exercise 4:
case 1: System.out.println(“January”);
case 2: System.out.println(“February”); break;
case 3: System.out.println(“March”); break;
case 4: System.out.println(“April”);
case 5: System.out.println(“May”); break;
default: System.out.println(“Invalid”); break;
}