How do you Make A Repeat-Until Loop in C++? As opposed to a standard While or For loop. I need to check the condition at the end of each iteration, rather than at the beginning.
Upvotes: 33
Views: 204807
Reputation: 11
This can also work
int repeat;
repeat = 0;
//to repeat once
do {
....
repeat + 1;
} while(repeat < 1);
This is of course assuming you want to only repeat once, so you can change the value of repeat, not the amount of it's increase from the variable amount from the while();
condition. This code works for C++ 17, but I am not sure for other versions.
Upvotes: 1
Reputation: 19
Repeat is supposed to be a simple loop n times loop... a conditionless version of a loop.
#define repeat(n) for (int i = 0; i < n; i++)
repeat(10) {
//do stuff
}
you can also also add an extra barce to isolate the i variable even more
#define repeat(n) { for (int i = 0; i < n; i++)
#define endrepeat }
repeat(10) {
//do stuff
} endrepeat;
[edit] Someone posted a concern about passing a something other than a value, such as an expression. just change to loop to run backwards, causing the expression to be evaluated only once
#define repeat(n) { for (int i = (n); i > 0; --i)
Upvotes: 0
Reputation: 41
Just use:
do
{
//enter code here
} while ( !condition );
So what this does is, it moves your 'check for condition' part to the end, since the while
is at the end. So it only checks the condition after running the code, just like how you want it
Upvotes: 4
Reputation: 117
You could use macros to simulate the repeat-until syntax.
#define repeat do
#define until(exp) while(!(exp))
Upvotes: 10
Reputation: 481
For an example if you want to have a loop that stopped when it has counted all of the people in a group. We will consider the value X to be equal to the number of the people in the group, and the counter will be used to count all of the people in the group. To write the
while(!condition)
the code will be:
int x = people;
int counter = 0;
while(x != counter)
{
counter++;
}
return 0;
Upvotes: 2
Reputation: 26998
When you want to check the condition at the beginning of the loop, simply negate the condition on a standard while
loop:
while(!cond) { ... }
If you need it at the end, use a do
... while
loop and negate the condition:
do { ... } while(!cond);
Upvotes: 10