Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a counting loop that initializes an int variable called begin to 2 and dou

ID: 3761011 • Letter: W

Question

Write a counting loop that initializes an int variable called begin to 2 and doubles this value each iteration until it reaches 65,536. The loop will contain a single line that increments the value of an int variable called counter.

for ( int begin = 2; begin < 65536; begin * 2 )

{

      counter++;

}

If the counter is initialized to 0 within counting loop in the question above(before incremented), what will the value of counter be when the loop ends? I posted this earlier but didnt specify it needs to be in java. Please explain as I do not understand

Explanation / Answer

1.

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Counter
{
   public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
       int begin = 2;
       int counter = 0;

       for(begin=2;begin<65536;begin*=2)
           counter++;

        System.out.println("Counter : "+counter);
   }
}

2.

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Counter
{
   public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
       int begin = 2;
       int counter = 0;

       for(begin=2;begin<65536;begin*=2)
       {
           counter = 0;
           counter++;
       }
        System.out.println("Counter : "+counter);
   }
}

Value will be 1

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote