Reputation: 781
I have a Program in R where i'm using do while loop in the following format
for(i in 1:n)
{
repeat
{
#code
if(condition){break}
}
}
I have a problem even if the condition in if statement is true the loop is been executed still.Can anyone help me with this
Thank you
Upvotes: 1
Views: 22368
Reputation: 171
Are you sure you need both control structures below?
for(i in 1:n)
and
if(condition){break}
The second of those could easily be replaced with a while() command. You could include both the if- condition and the i<=n condition inside the while loop.
Upvotes: 0
Reputation: 51680
The structure of your code is a bit strange... why do you have the for
loop if you do not want to loop through it?
In your code i
will be assigned 1
then the repeat
loop will start until the condition is met and you break
out of it. Then i
will be assigned 2
and the repeat
loop will be reexecuted etc.
If you want the break
to go out of the for
loop that means you do not need the for
loop at all!
Anyways, the way to do it would be:
flag = 0
for(i in 1:n)
{
if (flag == 1)
break;
repeat
{
#code
if (condition)
{
flag <- 1
break
}
}
}
Although this would make no sense unless you have several different conditions to exit the repeat
loop, some of which do not set flag<-1
Upvotes: 1
Reputation: 787
I do not have experience on your language but it seams to me you are using to nested loop one is for loop another is repeat lope inside for loop.If so then my suggestion is You can use either loop with break statement. If you really want to use both loop then you have to use goto statement to come out of the for loop.
for(i in 1:n)
{
#code
if(condition){break}
}
repeat
{
#code
if(condition){break}
}
You also can use
for(i in 1:n)
{
repeat
{
#code
if(condition){goto label;}
}
}
label:
Please look at syntax of goto statement of you language,I don't know whether your language supports goto statement or not. But you can handle in this way.
Thanks
Upvotes: 0
Reputation: 3215
Are you absolutely sure the condition is saying what you think it is?
And also, the break only takes you out of the "repeat" statement, you'll still be inside the for-loop.
Upvotes: 1