Theo Chronic
Theo Chronic

Reputation: 1663

Instruction in for loop only executes once?

I have a for loop in my program. It looks just like this

#include <stdio.h>
int main(){
    int n = 0;
    int i;
    for(i = 0; i < 100; i++){
        n = i*2;
        if(n >= 50)
            n-=50;

        printf("n is %d\n", n); 
    }
    return 0; 
}

The plan was just to have n reset to 0 after it reaches 50. That's all, however when I print this out, n only gets reset one time. What gives?

Upvotes: 0

Views: 957

Answers (4)

nomann
nomann

Reputation: 2267

Because you are just subtracting 50 from the current value of n. Consider this:

When i = 25 your condition will reset n to 0
When i = 26 your condition will reset n to 2
When i = 27 your condition will reset n to 4
When i = 28 your condition will reset n to 6
and so on...

You can just assign 0 to n instead of subtracting 50.

OR

You can replace

if(n >= 50)
    n-=50;

printf("n is %d\n", n); 

with just

printf("n is %d\n", (n >= 50)?0:n); 

Upvotes: 1

Maroun
Maroun

Reputation: 95948

Draw a table and you'll know why:

  i  |  n
-----+------
  0  |  0     n >= 50 ? No
  1  |  2     n >= 50 ? No
  2  |  4
  3  |  6
 ... | ...
  25 | 50     n >= 50 ? YES!
  25 |  0     n-=50
  26 | 52     n >= 50 ? YES!
  26 |  2     n-=50  → n will be 2 and NOT 0

What to do?

Simply reset it to 0 instead of removing 50 from it or n-= i*2 (Which is funny to write because i*2 is n, so simply do n = 0)

Tip: Drawing a table is easy, but using a debugger is ten times easier. Use it.


EDIT: (If I'm really understanding what you mean..)

Regarding your comment, you have to change the condition to:

if(n % 50 == 0)
     n = 0;

Upvotes: 7

haccks
haccks

Reputation: 106012

Try this

 if(n >= 50)
      n = 0;  

to reset n to 0 after it reaches 50.

Upvotes: 1

Oswald
Oswald

Reputation: 31647

If the plan is to have n reset to 0 after it reaches 50, then reset it to 0 instead of subtracting 50:

if(n >= 50)
    n = 0;

Upvotes: 1

Related Questions