How do I exit a loop by typing a specific value?

Asked

Viewed 540 times

5

I need to make a program that multiplies the numbers informed by the user, and when it reports 0 (zero), the program shows the multiplication of the numbers typed. However, I am in doubt of how I will do this without zeroing in my multiplication.

 else if(op==2){
    printf("Foi escolhida a multiplicacao:\n\n");
    do{
        printf("Informe os valores desejados e 0 (zero) para concluir:");
        scanf("%d", &valor);
        mult= mult*valor;
        result=mult;
    }while(valor!=0);

2 answers

4


Force the loop output before doing multiplication:

else if (op == 2) {
    printf("Foi escolhida a multiplicacao:\n\n");
    do {
        printf("Informe os valores desejados e 0 (zero) para concluir:");
        scanf("%d", &valor);
        if (valor == 0) {
            break;
        }
        mult = mult * valor;
    } while (valor != 0);
    result = mult; //não precisava estar dentro do laço

I put in the Github for future reference.

Doing this, deep down does not need the condition in the while. Could make a loop infinity with while(1).

4

else if (op == 2) {
    printf("Foi escolhida a multiplicacao:\n\n");
    mult=1;
    do {
        printf("Informe os valores desejados e 0 (zero) para concluir:");
        scanf("%d", &valor);
        if (valor != 0)
            mult = mult * valor;
    } while (valor != 0);
    result = mult;

Browser other questions tagged

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