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

Can somebody help me with While and do...While looops? What are they? Can you gi

ID: 3615159 • Letter: C

Question

Can somebody help me with While and do...While looops? What are they? Can you give me an example? can it be used in this example: you need the correct number of candy guessed. when the correctnumber is selected, the program ends. I haven't learned loops yet so I'm completely starting fromsquare zero. I'm taking java by the way =) Can somebody help me with While and do...While looops? What are they? Can you give me an example? can it be used in this example: you need the correct number of candy guessed. when the correctnumber is selected, the program ends. I haven't learned loops yet so I'm completely starting fromsquare zero. I'm taking java by the way =)

Explanation / Answer

Can somebody help me with While and do...While looops? What are they? These 2 loops are done whenyou have no idea when they will finish, just the condition theywill finish at. for example take 10 steps to the door youknow exactly how many steps you are going to take, so you would usea for loop,
but walk until you get to the door you have no idea.
the difference between a do..while and a while loop is the while iscalled a pretest loop, it is tested before you execute the loop,which means if the condition is true first time, you will neverexecute the loop. the do...while is a posttest loop, you dothe test when you get to the end of the loop, so you must executeit at least once.


this is a simple example of a guessing game with both loops

import java.util.*;
public class untitled
{
public static void main(String[] args)
{Random random = new Random();
int num,guess;
num=random.nextInt(100)+1;
Scanner in=new Scanner(System.in);
//do...while sample
   do
    {System.out.print("How many candy's are there(hint it's <=100): ");
         guess=in.nextInt();
   if(guess<num)
         System.out.println("Your guess is too low.");
    else if(guess>num)
         System.out.println("Your guess is too high.");
   else
         System.out.println("Youwon!");
    }while(guess!=num);
num=random.nextInt(100)+1;
//while sample
guess=-1;    //must initialize loop, so it hassomething, that will be false 1st time thru  
while(guess!=num)
    {System.out.print("How many candy's are there(hint it's <=100): ");
        guess=in.nextInt();
       if(guess<num)
         System.out.println("Your guess is too low.");
    else if(guess>num)
         System.out.println("Your guess is too high.");
   else
         System.out.println("Youwon!");

    }
  
  
}
}

                  



can it be used in this example: you need the correct number of candy guessed. when the correctnumber is selected, the program ends. YES