Sitemap
rakibul rushel

rakibul rushel

Control Statement Part-7

2 min readDec 27, 2023

In this chapter, we are going to discuss the do-while statement.

Previous Chapter
First Chapter

You must read the previous chapter before reading this one.

Do-While Statement

The do-while statement is similar to the while-do statement with a small twist. In the case of a while-do statement execution of the statements in the body was not guaranteed. If the expression inside the parenthesis is not evaluated to be true at the very first time then the statements in the body will never be executed. But, in the case of a do-while statement it is ensured that the statements in the body will be executed at least once. Following is the pseudocode of the do-while statement:

  1. Execute the statements in the body of the do-while statement.
  2. Evaluate the expression.
  3. If the evaluated value is true then go to Step 1.
  4. otherwise, if the evaluated value is false then the next statement if any (after the do-while statement) executes.

Let us write the same program we wrote in the previous chapter using the do-while statement:

Fig 1.1

Let us see each iteration:

Get rakibul rushel’s stories in your inbox

Join Medium for free to get updates from this writer.

Iteration 1:

  1. The variable counter contains value 1. Then the variable counter is printed to the console and is incremented by 1 (the body is executed at least once). So, the variable counter contains 2 now.
  2. The expression “counter <= 3” is evaluated.
  3. The evaluated value is true we need to go to iteration 2 (the body going to be executed a second time).

Iteration 2:

  1. The variable counter contains value 2. Then the variable counter is printed to the console and is incremented by 1. So, the variable counter contains 3 now.
  2. The expression “counter <= 3” is evaluated.
  3. As the evaluated value is true we need to go to iteration 3 (the body going to be executed a third time).

Iteration 3:

  1. The variable counter contains value 3. Then the variable counter is printed to the console and is incremented by 1. So, the variable counter contains 4 now.
  2. The expression “counter <= 3” is evaluated.
  3. The evaluated value is false.
  4. The execution is done with do-while statement and moves to the next statement if any.

Here is the output of the program:

Press enter or click to view image in full size
Fit 1.2

This is it for this chapter.

Next Chapter

--

--