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

5

I need to make a program that multiplies the numbers entered by the user, and when it says 0 (zero), the program shows the multiplication of the numbers entered. However, I am in doubt as to how I will do this without clearing 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);
    
asked by anonymous 17.10.2015 / 21:36

2 answers

5

Force the output of the loop before doing the 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

By doing this, in the background you do not need the condition in while . It could make an infinite loop with while(1) .

    
17.10.2015 / 21:40
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;
    
17.10.2015 / 22:28