do while loop (Lesson-16)

A do while loop works much like a while loop. The only difference is that it executes at least once. Did’nt get that? An example will explain it better.

In the above example, we used while loop and as the condition given to the while loop was already false, the code in the body of the loop was never executed.
Now let’s see the syntax of do while loop:

   //Body of loop

Let’s change the while loop with a do while loop in the above program:

In a while loop, the condition is tested before running the code whereas in a  do while loop, the condition is tested after the code is executed. This why the code executes at least once in a do while loop. Otherwise, a do while loop works exactly the same as while loop.

As you saw in the above example, there is no difference in the output of a while loop and a do while loop. The only thing that makes a do while loop unique is that it executes at least once.

Practice Corner:

  • Write a program to find the sum of all the odd numbers from 0 to 100

Leave a Comment