Computer Science, asked by ilsashoaib209, 5 months ago

Which loop is efficient and why explain the reason? ​

Answers

Answered by Anonymous
3

Answer:

Loop body and update step: the loop body is the sequence of statements executed when the boolean test is true. These statements (almost always) include a statement that updates a loop control variable (or some other variable) that is used in the boolean test.

Answered by ItzCaptonMack
24

\huge\underline{\underline{\bold{\green{AnSwEr}}}}

A for loop is used where you know at compile time how many times this loop will execute.

A while loop is normally used in a scenario where you don't know how many times a loop will actually execute at runtime.

A do-while loop is used where your loop should execute at least one time.

For example consider a program which writes some text in a file until file size becomes 2KB. You can use while loop in this scenario like this.

In above case we can't use for loop because we don't know how many times we have to write in the file until it becomes full. We can't use do-while because we are not sure if the loop should run at least once. May be at start file size was more than 2K so we won't run loop at all.

Let's consider another scenario where we want to take an integer input from user until user have entered a positive number. In this case we will use a do-while loop like this.

In this case we have to run loop at-least once because we want input from user at-least once. This loop will continue running until user enters a positive number.

Similar questions