Code does not display result

Asked

Viewed 48 times

0

My code receives as input the value of n, i and j and calculates the n first multiples of i and j. I’ve gone through my loop loop and I can’t find anything wrong, but the compiler just stands still and doesn’t report the values.

int i, j, n, k;

printf("Digite o valor de n : ");
scanf("%d",&n);

printf("Digite o valor de i : ");
scanf("%d",&i);

printf("Digite o valor de j : ");
scanf("%d",&j);

k = 0;

printf("Os %d primeiros multiplos de %d e %d sao : ",n,i,j);

while (k < n){
    if (k % i == 0 || k % j == 0 || (k % i == 0 && k % j == 0){
        printf("%d \t",k);
        k++;
    }
}

1 answer

0


There is a syntax error there, so the compiler has an error, it doesn’t get stuck. The code has several errors even of interpretation, at least for what it can infer from the messages contained in it, and it is more complex than it should.

What gave to understand is that you must learn as many results as are indicated in n. So you need to have a counter to control when you get to this condition. , and this is done with the variable k. But to control the progress of numbers you need to walk 1 in 1, so you need another variable to control step by step. This clearly works best with a for.

To find a multiple just use arithmetic, do not need to use this lot of operator, which probably causes a logical error Dew and maybe the application gets in infinite loop.

#include <stdio.h>

int main(void) {
    int i, j, n;
    printf("Digite o valor de n: ");
    scanf("%d", &n);
    printf("Digite o valor de i: ");
    scanf("%d", &i);
    printf("Digite o valor de j: ");
    scanf("%d", &j);
    printf("Os %d primeiros multiplos de %d e %d sao : ", n, i, j);
    for (int c = 0, k = 0; k < n; c++) {
        if (c % (i * j) == 0) {
            printf("%d \t", c);
            k++;
        }
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks friend, I had done with a loop for earlier but had only used a single variable that was k, so it n ran correctly, then I ended up going for while. I hadn’t thought about the possibility of two variables.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.