What will the following program segments display\" Write a for loop that display
ID: 3682305 • Letter: W
Question
What will the following program segments display" Write a for loop that displays you name I0 times. Write a for loop that displays all of the odd numbers. I through 49. Write a for loop that displays every fifth number, zero through 100. In your own words, briefly describe the difference between the for. while, and do-while loops and in what situation you? Would use one loop over another. Which loop should you use in situations where you? Want the loop to repeat until the Boolean expression is false, but the loop should execute at least once? Write a do-while loop that asks the user to enter two numbers. The numbers should be added and the sum displayed. The loop should ask the user if he or she wishes to perform the operation again. If so, the loop should repeat, otherwise it should terminate.Explanation / Answer
Output:
0 2 4 6 8 9 10
-5 -4 -3 -2 -1 0 1 2 3 4
5 8 11
14
//loop to display the name 10 times
for(int i=0; i<10; i++)
System.out.println(" your name is Sandy");
// loop to display all odd numbers 1 to 49
for(i=1; i<49; i++)
{
if(i%2 != 0)
System.out.println(i);
}
// loop to display every fifth number
for(int i=0; i<100; i+=5)
System.out.println(i);
// difference between for, while and do-while loops
1. 'for' loop is generally used when we know the number of iterations beforehand.
e.g. to traverse an array of 10 elements we can use for loop and increment the counter from 0 to 9(or 1 to 10 in 1 based indexing).
2. On the other hand 'while' is used when you have an idea about the range of values on which to iterate, but don't know the exact number of iterations taking place.
3. The only difference between while loop and do-while loop is the condition checks first in while loop where's the condition checks last in do-while loop. Both are used to perform iterations.
// loop used
while loop is used to perform iterations until it is false in this case.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.