The do while loop in C

do… while loop

Syntax:

In do while loop first the statements in the body are executed then the condition is checked. If the condition is true then once again statements in the body are executed. This process keeps repeating until the condition becomes false. As usual, if the body of do while loop contains only one statement, then braces ({}) can be omitted. Notice that unlike the while loop, in do while a semicolon(;) is placed after the condition.

The do while loop differs significantly from the while loop because in do while loop statements in the body are executed at least once even if the condition is false. In the case of while loop the condition is checked first and if it true only then the statements in the body of the loop are executed.

The following program print numbers between 1 and 100 which are multiple of 3 using the do while loop:

Expected Output:

How it works:

In line 5, we have declared and initialized variable i. Then, the control comes inside the body of the do while loop. Inside the body of the loop the if condition (i%3==0) is tested, if it is true, then the statement inside the if block  is executed. The statement i++ increments the value of i by 1. At last, the do while condition (i<100) is checked. If it is true then statements inside the body of the loop are executed once again. This process keeps repeating as long as the value of i is less than 100.

Where should I use do while loop?

Most of the time you will use while loop instead of do while. However, there are some scenarios where do while loop suits best. Consider the following problem.

Let’s say you want to create a program to find the factorial of a number. As you probably know that factorial is only valid for 0 and positive numbers. Here is one way you can approach this problem.

Let’s say the user entered a negative number, so instead of displaying an error message and quitting the program, a better approach would be to ask the user again to enter a number. You have to keep asking until the user enters a positive number or 0. Once a positive number or 0 is entered, calculate factorial and display the result.

Let’s see how we can implement it using while and do while loop.

Using while loop

Using do while loop

Notice that the solution using while loop is more involved, to achieve the same thing we have to create an extra variable num_ok, and an additional if statement. On the other hand, the do while loop achieves the same thing without any trickery and it’s more elegant and concise.

Before we leave do while loop, let’s take one more example.

The Following program calculates Simple interest:

Expected Output:

Leave a Comment

%d bloggers like this: