222k views
18 votes
Q1: Identify and correct the errors in each of the following pieces of code. [Note: There maybe more than one error in each piece of code. a) int x = 1, total; while (x <= 10) { total += x; ++x; } b) while (x <= 100) total += x; ++x; c) public class Mystery { public static void main(String[] args) { int x = 1; int total = 0; while (x <= 10) { int y = x * x; System.out.println(y); total += y; ++x; }// end of while System.out.printf("Total is %d%n", total); }//end of main }//end of class Mystery2 *********************** Q2 What does the following program print? public class Mystery3 { public static void main(String[] args) { int row = 10; while (row >= 1) { int column = 1; while (column <= 10) { System.out.print(row % 2 == 1 ? "<" : ">"); ++column; }// end of while column<=10 --row; System.out.println(); }//end of while }//end of main }// end of class Mystery3

User Kokoko
by
4.3k points

1 Answer

7 votes

Answer:

a. int x = 1, total = 0;

while (x <= 10){

total += x;

++x;

}

b. while (x <= 100){

total += x;

++x;

}

c. public class Mystery{

public static void main(String[] args){

int x = 1;

int total = 0;

while (x <= 10){

int y = x * x;

System.out.println(y);

total += y;

++x;

}

System.out.printf("Total is %d%n", total);

}

Step-by-step explanation:

For the first code, the variable "total" was not initialized, so to avoid raising an error message, an integer value must be assigned to it before the increment. Code block two of the second while statement must be enclosed in curly braces, while the third code must be indented properly.

User Andy R
by
4.4k points