is this loop statement is correct? if not correct then what alternative way? I am trying to o(n) loop statement like this-
for(int i=0 ; i<n ; i++ , j=n ; j<n*2 ; j++){
continue;
}
What you seem to want is something like:
for (int i = 0, j = n; i < n && j < n * 2; ++i, ++j)
{
continue;
}
To help you better understand what I did and why, and how you can do such transformations in the future, you need to understand how a for
loop is really handled by the compiler: As a special while
loop.
For example, if you have
for (a; b; c)
{
d;
}
then that's equivalent to this:
{
a;
while (b)
{
d;
c;
}
}
If we take what you (probably) want, in the form of a while
loop then it would be
{
int i = 0, j = n; // a in my example above
while (i < n && j < n * 2) // b in my example above
{
continue; // d in my example above
++i, ++j; // c in my example above
}
}
Now it's easy to translate it to the for
loop I showed initially.
As noted in a comment, the while
loop shown here is a little misleading, as it won't actually do the increment. But then I assume your real loop doesn't have an unconditional continue
statement as the only statement in the body. That would make the loop rather meaningless. However the principle is still valid, even if the example isn't.
The construct is wrong, you cannot you two loops in one construct, but you can have more than one variable controlling the iteration.
For example, you can have
i
and j
, initialized with certain values.i
and j
(and others, if defined).i
and j
(and others, if defined).A sample construct can be:
for (int i = 0, j = n; i < n && j < n * 2; ++i, ++j)
|^^^^^^^| -------- variable modification
| | |^^^^^^^^^^^^^^^^^| ---------------- loop condition
|^^^^^^^^^^^^^^^|--------------------------------------- initialization
if you want to run the loop only if two of them are true then use && between the two conditions eg: for(int i=0 ; i<n ; i++ && j=n ; j<n*2 ; j++) { continue; }
for(int i=0 ; i<n ; i++ && j=n ; j<n*2 ; j++) { continue; }
or if you want to run the loop only if anyone of them become true use || between the two conditions eg: for(int i=0 ; i<n ; i++ || j=n ; j<n*2 ; j++) { continue; }
for(int i=0 ; i<n ; i++ || j=n ; j<n*2 ; j++) { continue; }
ie, && stands for logical AND || stands for logical OR
for(int i=0 ; i<n ; i++ , j=n ; j<n*2 ; j++){
continue;
}
The above code is wrong but it can be written as
for(int i = 0 ,j = n; i < n ,j < n * 2; i++ ,j++)
The above code is correct i=0
and j=n
is initialization i<n
and j<n*2
is loop condition i++
and j++
is incrementation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.