Scenario – It is Saturday night, and you are watching the Lottery draw for Fanta
ID: 3847676 • Letter: S
Question
Scenario – It is Saturday night, and you are watching the Lottery draw for Fantasy Five. You get inspired to write a program to generate 10 lotto tickets, each ticket has 5 Lotto numbers. What loop should you use, and why? With using only while, do while, or for loops
Scenario – You go to an arcade with 100 tokens, and each game costs a variable number of tokens. What loop should you use, and why?
Scenario – You are playing a guessing game with your little cousin. She wants you to guess her favorite color. What loop should you use for that, and why?
Explanation / Answer
Scenario 1–
We will use two nested while loops as follows:
int ticket =1;
while(ticket <= 10)
{
Lotto_numbers = []
int n = 1;
while(n<=5)
{
int tmp = random_integer();
Lotto_numbers.append( tmp );
n = n + 1;
}
ticket = ticket + 1;
}
Outer While loop will iterate over tickets 1 to 10 and inner while loop will generate 5 Lotto numbers for each ticket.
Scenario 2–
We will use one while loop as follows:
tokens = 100;
while(tokens > 0)
{
current_game = Choose_game();
tokens = tokens - Cost_of(current_game);
}
This while loop will iterate untill all the tokens are used.
Scenario 3–
We will use a for loop.
Colors = Array containing all color names;
for(int i = 0; i< Colors.length(); i++)
{
if(Colors[i] is favorite color )
{
We are done;
break;
}
else
{
Continue();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.