-
Loop question
Hi
I'm new to this forum. I am currently a freshman at UCI and am in a beginning programming class-introduction to c.
I need to know how to write a for loop within a for loop without one of the loops breaking. For example my program changes based on whether a number is even or odd, so if the number is odd it needs to add, but when its even to subtract. So how can I do this without one of the loops breaking when its condition is not met. For example if the number is odd I use the ++ to make it even but it breaks instead of continuing.
Thanks in advance
-
I don't really see why you want two for loops, based on the description. This sounds an awful lot like
Code:
int sum = 0;
for (int i = 0; i < LARGE_NUMBER; i++) {
if (isEven(i))
sum -= i;
else
sum += i;
}
where of course you're doing whatever it is you do inside the if and the else.
-
This worked but only for one time. I need it to alternate back and forth between even and odd for n amount of times.
-
What do you mean by only one time? The code (assuming you write isEven) will go back and forth, adding and subtracting.
-
does isEven need to be defined or is it already understood?
-
It needs to be defined. (It's a simple enough function that you could just put the calculation right there in the if statement, if you want.)
-
Thanks for the help, I really appreciate it!