no hand written answers please. for loop VS while loop for loop and while loop a
ID: 3737866 • Letter: N
Question
no hand written answers please. for loop VS while loop for loop and while loop are equivalent, just a different syntax for the same thing. You can emulate a for loop with a while loop in mostly any language, here is an example of that: code output while int i-0; loop while (i-3) System.out.println("i3 for or int i-0 loop i-3:i++) System.out.println("i3 One main difference is while loops are best suited when you do not know ahead of time the number of iterations that you need to do. When you know this before entering the loop you can use for loop. Can we emulate a for loop to a while loop? When it is best to do a while loop instead of for loop?Explanation / Answer
yes we can formulate the for loop to while loop
see in the above pic only the for loop to while loop is already given
since for loop takes three parts initialization, condition and increment
and in while loop we initialize the counter variable before use and use condition inside the () and we increment the value inside the body of the while loop
int i=1; // initialization of variable before use
while(i<10){ // condition to check
// body of while loop
i++; // increment of the counter variable
}
while loops are to be preferred when the exiting condition has nothing to do with control variable or the number of loops
else you can convert any for loop to while loop or viceversa
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.