1. Find and correct the error(s) in each of the following segments of co de: Poi
ID: 3601020 • Letter: 1
Question
1. Find and correct the error(s) in each of the following segments of co de: Points: 8 int x For ( x-100 , x>= 10 ,x++) System.out.printin(x b) Correct following code so that it should output the even integers from 2 to 1 00. int counter. 2; // not allowed to change counter value do System.out.println"counter-" counter); counter +=2; 3 while (counter 100); c) Correct the following code so that it finds the sum of 10 numbers. sum=0; count-1; // not allowed to change value of sum and count Scanner keyboard new. Scanner(System.in); while (count 0) x=x + 2; System.out.printIn("x=" + x);Explanation / Answer
1. Decrement x, because incrementing x will cause a infinite loop
int x;
for(x=100;x>=10;x--){ //Change made
System.out.println(x);
}
2. change while condtion to counter<=100, to include 100 in output as well
int counter=2;
do{
System.out.println("counter = "+counter);
counter+=2;
}while(counter<=100); //Change made
3. Change while condtion to count<=10, to iterate loop 10 time because initial value of count is 1.
Secondly, increment count variable instead of decrementing (It will lead to infinite loop)
int sum=0,count=1;
int num;
Scanner keyboard=new Scanner(System.in);
while(count<=10) //Change made
{
num=keyboard.nextInt();
sum+=num;
++count; //Change made
}
4. Decrement x instead of incrementing because increasing x's value will never terminate the while loop because it's value will always be greeater than 0.
int x=5;
while(x>0){
x=x-2; //Change made
System.out.println("x= "+x);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.