 Is it a bug in compiler or error in code?

i was solving one of practise problem and i encountered this . the if statement is executed even if the condition is false while the else statement part is not being executed .

here’s the part of code

while(N[i]!=1)
{
for(j=0;j<N[i];j+=2)
{
if(N[i]%2==0)         //this code is executed even if N is odd
{

for(k=0;k<(N[i]/2);++k)
{
F[k]=D[j];
D[k]=F[k];

}
cout<<" 1";
N[i]=k;

}

else                               //this else part is not executed even after if condition is not true
{
cout<<" 2";
if(N[i]==1)
{
break;
}
else
{  cout<<" 3";
for(k=0;k<((N[i]+1)/2);++k)
{
F[k]=D[j];
D[k]=F[k];

}
cout<<" 4";
N[i]=k;
}
}

}
}

I can’t determine everything without full code, please write full code or try debugging yourself (if you use Dev C++, it’s much easier)

the problem is inside this loop so i did’t posted whole code. the else statement is not being executed

for(j=0;j<N[i];j+2)

i have chaged that to j+=2; but still else part is not being executed

Hi, pkpawan123

It’s definitely not a compiler bug.

I checked your code with a bunch of scenarios, and this line is always executing properly…

if(N[i]%2==0)

That is, if N[i] is even at the time, it executes the “if” portion. Otherwise, it executes the “else” portion.

Of course, the value of N[i] changes over time. For example if it starts at 5, then the cout statements will output: 2 3 4 2 3 4 1.

That’s because N[i] is initially 5, which is odd, so the ‘else’ section executes (resulting in an output of 2 3 4), which eventually changes N[i] to 3.

Then the j-based for loop repeats: j is now 2, so the loop continues, and the ‘else’ section is executed again (so you see another 2 3 4), resulting in N[i] being changed to 2.

Then the j-based for loop repeats again. j is now 4, so the for loop ends, since 4 > N[i]. Then outer while loop executes again: N[i] is still !=1, so while loop continues.

Then the j-based for loop restarts (j is back to 0), and the “if” statement is true (since 2 %2==0) – this results in cout outputting the final 1. That “if” code also results in N[i] being changed to 1.

Then, one final time, the j-based for loop repeats: j is now 2, so the for loop ends. Then the outer while loop kicks in: N[i] is now 1, so it ends.

So, bottom line, the code is working correctly from a compiler point of view. But perhaps it’s not working as you logically intend it to. Good luck!

4 Likes

here j should be 3 i think and it will satisfy j<N[i] so it must do run correctly

j+=2, so j starting from 0 would be 2 next and then 4 and so on…

1 Like

got it thanks. now i will fix it.