C++ do while loop
In C++, the do-while loop is a control structure that allows a block of code to be executed repeatedly as long as a specified condition is true, but with the difference that the code block inside the loop is executed at least once. The syntax of the do-while loop is as follows:
do { // Code to execute for each iteration } while (condition);
The code block inside the do-while loop will be executed at least once before the condition
statement is checked. If the condition is true, the code block will be executed again, and the process will continue until the condition is false.
Here's an example of a do-while loop:
int i = 0; do { cout << i << endl; i++; } while (i < 5);
In this example, the loop initializes the variable i
to 0, executes the code block (cout << i << endl; i++;
), and then checks if i < 5
. This process is repeated until i >= 5
, at which point the loop exits.
The do-while loop is useful when you want to ensure that a block of code is executed at least once, regardless of whether the condition is initially true or false. If you don't need to guarantee that the code block is executed at least once, you may want to use a while loop instead.
You can also use a do-while loop to iterate over the elements of an array or container, like this:
int arr[] = {1, 2, 3, 4, 5}; int i = 0; do { cout << arr[i] << endl; i++; } while (i < 5);
In this example, the loop iterates over the elements of the array arr
, printing each element to the console.