Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

What is the difference between while and do-while loop in C++?

Arham Qayyum

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

In C, we use loops to execute the specified code as long as the condition becomes true. We use the while loop to run the code block if the specified condition is true.

Code

In this example, the code in the loop will run if the value of the variable i equals 10.

#include <iostream>
using namespace std;

int main() {
  int i = 0;
  while (i <= 10)
  {
    cout << i << endl;
    i++;
  }
  return 0;
}

Do-while loop

The do-while loop is the form of the while loop. The code in the loop will execute once before checking if the condition is true or not. Then the code will execute as long as the condition is true.

Code

In this example, the code in the loop will execute at least once, whether the condition is true or false, because the code block is executed before the condition is checked.

#include <iostream>
using namespace std;

int main() {
  int i = 0;
  do {
       cout << i <<endl;
       i++;
  }
  while( i <= 10);
  return 0;
}

Difference

The main difference between the while and do-while loop is given below

DIFFERENCE

While Loop

Do/While Loop

The block of code is executed as long as the specified condition becomes true.

The code in the loop will execute at least once, whether the condition is true or false.

RELATED TAGS

c++

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring