2
$\begingroup$

Implemented is done in C++.

Supposing we have defined a class T with no restrictions and three functions cond, next and f returning bool, void and anything respectively, are

for(T k = T(); cond(); next())
    f();

and

{
T k = T();

while(cond()) {
    f();
    next();
}
}

So, I would like know that time complexity of the following algorithms are same?

$\endgroup$
2
  • 3
    $\begingroup$ Programming questions are off topic here. $\endgroup$
    – fade2black
    Commented Dec 30, 2017 at 22:49
  • $\begingroup$ If the while loop always runs 100 times slower then time complexity is the same. Same if the while loop always runs 100 times faster. $\endgroup$
    – gnasher729
    Commented Dec 31, 2017 at 15:47

2 Answers 2

0
$\begingroup$

I'm not familiar with C++ but it looks like that both codes are equivalent, for loop and while loop has the same power.

In your examples, in both cases you first you initial the variable k, and the loop doesn't stop as coud() condition holds, inside the loop there is a call to f(); method, and finally to next();.

$\endgroup$
0
$\begingroup$

As your code stands, yes they are algorithmically the same in that both have a starting state, a condition, and an incrementing step.

The difference between the two would be if the code within the body of the for and the while had a continue statement. With a for the continue statement would cause the next() to be executed before the condition is checked since the next() is part of the for and not part of the body of the for.

However with the while a continue statement that is before the next() would cause execution to jump to the end of the while body which would bypass the next(). This would result in next() not be called with a possible infinite loop. This is because the next() is within the body of the while.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.