need help for this qestion

hello, I'm a student and i got this question in my book ,please help.

How many times does the following for loop will run
for (i=1; i<= n; i*2)
{
k = k + 1;
break;
}
break;
thanx, i got it, and what if we remove the break ;
for (i=1; i<= n; i*2)
{
k = k + 1;
}
Depends on the value of n. Is this really the exact question in your book?
yes, but in COMPLEXITY topic. This question is actually not specifically related to c++ .
Last edited on
It will either run once, or forever. If you can't see that yourself, you need to go back and start again. A for loop is very simple.
Are you sure about the code you provide? Your increment statement merely says i*2. Did you meani = i*2 or i *= 2 instead?

Since this is a complexity issue:

With the break statement in the code, the complexity is constant. It will either not run or run 1 time, depending on whether n < 1 or n >= 1.

Without the break statement, with the code as written, as @Moschops said, the code will either run once or forever, because i never changes.

However, if the 3rd part of your for loop is supposed to be i = i * 2, the complexity becomes log(n). The code will run log2(n) + 1 times (if n >= 1).
Last edited on
Topic archived. No new replies allowed.