tutorial05_1
tutorial05_1
Exercise 1:
Convert each of the following phrases to a Java boolean expression as in the first example:
Answers:
2 x % y == 0
4 x - y < 5 || y – x < 5
or
x - y < 5 || x – y > -5
or
Math.abs(x - y) < 5
6 x >= 10000
or
Math.log10(x) >= 4
Exercise 3:
Write a Java program that prompts the user to enter two positive integers, then displays whether
the first is a multiple of the second or not.
Answer:
import java.util.Scanner;
class Ex3 {
public static void main(String[] args) {
Scanner SC = new Scanner(System.in);
System.out.print(”Please enter the first number: );
int num1 = SC.nextInt();
System.out.print(”Please enter the second number: );
int num2 = SC.nextInt();
if (num1 % num2 == 0)
System.out.println(num1 + ” is a multiple of ” + num2);
else
System.out.println(num1 + ” is not a multiple of ” + num2);
}
}
Exercise 4:
Rewrite the following Java program replacing if-else statement with if-then statements.
import java.util.Scanner;
class Ex4 {
public static void main(String[] args) {
Scanner SC = new Scanner(System.in);
System.out.print(”Please enter your age: );
int age = SC.nextInt();
if (age >= 13 && age <= 60)
System.out.println(”You can proceed.”);
else
System.out.println(”Your age does not qualify you to procees”);
}
}
Answer:
import java.util.Scanner;
class Ex4 {
public static void main(String[] args) {
Scanner SC = new Scanner(System.in);
System.out.print(”Please enter your age: );
int age = SC.nextInt();
if (age >= 13 && age <= 60)
System.out.println(”You can proceed.”);
If (age < 13 || age > 60)
System.out.println(”Your age does not qualify you to procees”);
}
}
Exercise 5:
Trace the following two code fragments for a = +3, a = 0, a = -5, then tell whether these
fragments are equivalent or not.
if (a < 0) { if (a < 0) {
System.out.println(“Negative”); System.out.println(“Negative”);
a = a * -1; a = a * -1;
System.out.println(“Absolute System.out.println(“Absolute
value is: ” + a); value is: ” + a);
} }
else { if (a >= 0) {
System.out.println(“Positive”); System.out.println(“Positive”);
System.out.println(“Absolute System.out.println(“Absolute
value is: ” + a); value is: ” + a);
} }
Answer:
a = +3
Positive Positive
Absolute value is: 3 Absolute value is: 3
a=0
Positive Positive
Absolute value is: 0 Absolute value is: 0
a = -5
Negative Negative
Absolute value is: 5 Absolute value is: 5
Positive
Absolute value is: 5