What is the output of this program? public class Q_07{public static void main {S
ID: 3821976 • Letter: W
Question
What is the output of this program? public class Q_07{public static void main {String[] args} {int x = 2; Switch(x){case 2: x +=1; case 3: x +=2; case 4: x +=3; case 5: x +=4; System.out.println ("x1 =" + x); case 6: x ++; system out.println("x2 =" +x); case 7: x += 4; break; case 8: x--; System out println("x3 ="+x); case 9: x += 3;} System.out.println("x4 =" +x);}} Write a program that searches for a value in an array, if found replaces it with the last element of the array, given the array: int [] values = {23, 78, 14, 56, 90, 101, 32, 34};Explanation / Answer
9. Output:
x1 = 12
x2 = 13
x4 = 17
Explanation of output:
1. Initially x is 2 when we enter switch statement. It matches with case 2. Hence, x gets incremented by 1. x is now 3.
2. case 2 doesn't have a break statement, hence it executes all cases below it until it finds a break.
3. case 3,4,5 get executed and x gets incremented by 2,3,4 respectively. In total 2+3+4 = 9 gets added to x. x is now 12.
4. Now there's a print statement, so x1 = 12 gets printed.
5. It executes case 6, and x again gets incremented using postfix operator. x is now 13.
6. The print statement is executed, and x2 = 13 gets printed.
7. It goes in case 7 now. Here x gets incremented by 4. x is now 17.
8. It encounters a break statement, hence goes out of switch statement.
9. Finally the print statement outside the break is executed, and x4 = 17 gets printed.
10. Here's the Java code for the same:
import java.util.Scanner;
public class ArrayOp {
int values[] = {23,78,14,56,90,101,32,34};
public static void main(String[] args) {
int n;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a value:");
// Number to be found.
n = sc.nextInt();
// We need an object of this class to refer to values array in a static context.
ArrayOp obj = new ArrayOp();
int i;
for ( i = 0; i < obj.values.length; i++) {
// If value is found, replace it with last e
if (obj.values[i] == n) {
obj.values[i] = obj.values[obj.values.length - 1];
// Optional message to display to user.
System.out.println("Value found and replaced with last element.");
break;
}
}
// Optional message to display to user.
if (i == obj.values.length) {
System.out.println("Value not found in array.");
}
// Print array to test changes. (Optional)
obj.printArray();
}
/**
* Method to print array values.
*/
private void printArray() {
System.out.println("Printing array.");
for (int i = 0; i < values.length; i++) {
System.out.print(values[i] + " ");
}
}
}
I have tried to answer questions as per my knowledge, in case of any problem let me know.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.