while and do-while loop in C++

Suneet Agrawal
2 min readNov 14, 2024

--

Loops are fundamental constructs in programming that allow us to repeat a block of code multiple times. In C++, two commonly used loop structures are the while loop and the do-while loop. In this blog post, we’ll dive into these loops, understand their syntax, and provide examples to illustrate their usage.

This post was originally posted at https://agrawalsuneet.github.io/blogs/while-and-do-while-loop-in-c++/ and later reposted on Medium.

The While Loop

The while loop is a conditional loop that repeats a block of code as long as a specified condition is true. Here’s the basic syntax:

while (condition) {
// Code to be executed while the condition is true
}

Counting from 1 to 10

#include <iostream>int main() {
int i = 1;
while (i <= 10) {
std::cout << i << " ";
i++;
}
return 0;
}

In this example, the while loop continues to execute as long as i is less than or equal to 10. It prints numbers from 1 to 10.

The Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the loop body will be executed at least once before checking the condition for continuation.

Please continue reading at https://agrawalsuneet.github.io/blogs/while-and-do-while-loop-in-c++/

That’s all for now. You can read my other interesting blogs here or you can enjoy my games or apps listed here. Feel free to use my open-source Android components in your app listed here. Or drop an email, if you didn’t find what you are looking for and need some help.

--

--

No responses yet