Question
1- For each of the following code fragments, what is the value of each variable after the if(/else) statement? int n = 1; int k
1- For each of the following code fragments, what is the value of each variable after the if(/else) statement?
int n = 1; int k = 2; int r = n; if (k < n) { r = k; }
int n = 1; int k = 2; int r; if (n < k) { r = k; } else { r = k + n; }
int n = 1; int k = 2; int r = k; if (r < k) { n = r; } else { k = n; }
int n = 1; int k = 2; int r = 3; if (r < n + k) { r = 2 * n; } else { k = 2 * r; }
2- Describe the difference between
s = 0; if (x > 0) { s++; // same as s=s+1;} if (y > 0) { s++; // same as s=s+1;}
and
s = 0; if (x > 0) { s++; // same as s=s+1;} else { if (y > 0) { s++; // same as s=s+1;} }
3- Find the errors in the following if statements:
if x > 0 then System.out.print(x);
if (1 + x > Math.pow(x, Math.sqrt(2)) { y = y + x; }
if (x = 1) { y++; }
4- What does each of these code fragments print?
int n = 1; int m = -1; if (n < -m) { System.out.print(n); } else { System.out.print(m); }
int n = 1; int m = -1; if (-n >= m) { System.out.print(n); } else { System.out.print(m); }
double x = 0; double y = 1; if (Math.abs(x - y) < 1) { System.out.print(x); } else { System.out.print(y); }
double x = Math.sqrt(2); double y = 2; if (x * x == y) { System.out.print(x); } else { System.out.print(y); } // For part (d), write down an answer based on the logic. // Then, type (or copy-paste) the code into the main method // of a Java program and compile and execute. // What result do you get? Why do you think this happens?
13- True or false? A && B is the same as B && A for any boolean expressions A and B. 14- Suppose the value of the boolean variable b is false and the value of the int variable x is 0. What is the value of each of the following expressions?
a. b && x == 0 b. b || x == 0 c. !b && x == 0 d. !b || x == 0 e. b && x != 0 f. b || x != 0 g. !b && x != 0 h. !b || x != 0
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started