Home > Back-end >  For some reason 7/7 computes as 0 remainder 0, and all following computations are off by one
For some reason 7/7 computes as 0 remainder 0, and all following computations are off by one

Time:10-05

Code I have right now:

#include <stdio.h>

int main() {
    int i, x;
    for (i = 1; i < 1000;   i) {
        printf("%d divided by 7 is %d, remainder %d\n", i, x, i % 7);
        x = i / 7;
    }
}

When I compile/run the code it works as intended until it reaches 7 and then works until it hits 14 etc etc.

Im not really asking for anyone to tell me the answer moreso for someone to guide me in the right direction. its my first time doing an assignment in C and I have no coding experience.

CodePudding user response:

In the first call of printf

printf("%d divided by 7 is %d, remainder %d\n", i, x, i%7);

there is used the uninitialized variable x.

int i, x;

So the call in the first iteration of the loop produces an unexpected output.

The variable x is set after this call

x = i / 7;

But in the next iteration of the loop i was changed (incremented). So the value of x does not corresponds to the current value of i.

Actually the introducing of the variable x is redundant.

You could write

#include <stdio.h>

int main()
{
    for ( int i=1; i<1000;   i )
    {
        printf("%d divided by 7 is %d, remainder %d\n", i, i / 7, i % 7 );
    }
}

CodePudding user response:

The problem is very simple: you print x before computing it!

Here is a modified version:

#include <stdio.h>

int main() {
    int i, x;
    for (i = 1; i < 1000;   i) {
        x = i / 7;
        printf("%d divided by 7 is %d, remainder %d\n", i, x, i % 7);
    }
    return 0;
}
  • Related