if condition in a for loop
An answer to this question on Stack Overflow.
Question
I want to execute for loop based on some condition depending which variable is greater.The code is this,but I am getting error ,I actually don`t know if it is legal to write short if condition in a for loop.
int main()
{
int Frow=5;
int Rowi=1;
int i;int red=2;
for((Rowi<Frow) ? i=Rowi : i=Frow ;(Rowi<Frow) ? i<Frow : i>Rowi;(Rowi<Frow) ? i++ : i--){
printf("%i\n",i);
}
return 0;
}
So the idea is if Rowi is smaller than Frow i=Rowi; then again if Rowi is smaller i<Frow and finally incrementing i.
for(i=Rowi;i<Frow;i++)
If it is the other way the for loop should be
for(i=Frow;i>Rowi;i--)
Edit : actually my logic was wrong ,what I wanted to achieve was this
typedef int Bool;
#define False 0
#define True 1
int main()
{
Bool pomalko=False;
Bool increment=False;Bool decrement=False;
Bool pogolqmo=False;
int i;int red=2;
if(Rowi<Frow){
i=Rowi;pomalko=True;increment=True;
}
else if(Frow<Rowi){
i=Rowi;pogolqmo=True;decrement=True;
}
for(i;(pomalko) ? i<Frow : i>Frow;(increment) ? i++ : i--){
printf("%i\n",i);
}
return 0;
}
Answer
It's legal, but you're trying to cram some complicated logic into that for construct.
Your program would be easier to write and easier to debug if you wrote it this way:
int main(){
int Frow=5;
int Rowi=1;
int i;
int red=2;
i=(Rowi<Frow)?Rowi:Frow;
while( (Rowi<Frow && i<Frow) || (Rowi>=Frow && i>Rowi)){
printf("%i\n",i);
if(Rowi<Frow)
i++;
else
i--;
//Alternatively: i+=(Rowi<Frow)?1:-1;
}
return 0;
}
From there, you may be able to further simplify the code:
if(Rowi<=Frow){
for(i=Rowi;i<Frow;i++){
// TODO
}
} else {
for(i=Frow;i>Rowi;i--){
// TODO
}
}
Remember, compact code usually does not lead to faster execution but almost always leads to slower thinking.