In this exercise, you use what you have learned whle loops. Study the following
ID: 3719232 • Letter: I
Question
In this exercise, you use what you have learned whle loops. Study the following code, and then answer the Questions 1-5.
import java.util.*;
public class Test
{
public static void main(String args[])
{
Scanner scan = new Scanner (System.in);
int no, counter;
System.out.print ("How many pages do you want to print? ");
no = scan.nextInt();
counter = 1;
while (counter <= no) ;
{
System.out.print (counter);
counter++;
}
}
}
Answer the following questions.
1- What is the output if the user enters 6 ? ____________
2. What is the problem with this code, and how can you fix it? ____________
3. Assume you fix the problem, if the user enters 50 as the number of pages to print, what is the value of counter when the loop exits? ______________
4. Assume you fix the problem, if the user enters 0 as the number of pages to print, how many pages will print? ______________
5. Assume you fix the problem discussed in Q2, and then delete the curly braces. Now, what is the output if the user enters 5 as the number of pages to print? ______________
Explanation / Answer
1. prints Nothing. It loops infinitely.
2. Problem was semi colon after while (while (counter <= no) ;). We can fix it by removing semicolon ';' after while condition.
3. 51
Loop exits when counter becomes greater than 50. So, counter value will be 51
4. It prints nothing. As counter is initialized to 1 and no valueis 0, it will not enter the loop as counter<=no is false
5. It prints 1 infinitely. If we remove curly braces then it considers only first statement System.out.print (counter); As we are not incrementing counter, loop goes infinitely.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.