The do while loop in C

do… while loop

Syntax:

In do while 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 of do while are executed. This process keeps repeating until the condition becomes false. As usual, if the body if do while loop contains only one statement, then braces ({}) can be omitted. Notice that unlike while loop, in do while a semicolon(;) is placed after the condition.

The do while loop differs significantly from 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 condition is checked first before executing statements in the body of the loop.

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 6, 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 i is executed. i++ is used to increment the value. 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 in 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 factorial is only valid for 0 and positive numbers. Here is one way you can approach this problem.

Let’s say a user entered a negative number, so instead of displaying an error message and existing 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. Once a positive number 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

Notice that 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. do while loop achieve 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 program calculates the Simple interest.

Expected Output:

Leave a Comment