Search code examples
cmodulo

Modulus in for-loop no output


#include <stdio.h>

int main() {

    int num = 90;
    for (int x = 0; x <= num; x++) {
        printf("%d", num % x);
    }
    return 0;
}

My code doesn't seem to do anything.

I wanted my code to print the remainders if we divide 0 to 90 to 90 but my code doesn't seem to do anything, please help. :(


Solution

  • Your program does not print anything because it crashes at the first iteration of the loop when computing num % x for x = 0. This is a division by 0, which has undefined behavior and stops the program on most current systems.

    Start the loop at 1 to avoid this case.

    Also output a newline after each value to make the output readable:

    #include <stdio.h>
    
    int main(void) {
        int num = 90;
        for (int x = 1; x <= num; x++) {
            printf("%d\n", num % x);
        }
        return 0;
    }