Multiply n numbers in c

Asked

Viewed 675 times

0

What reason does my code, regardless of the numbers typed multiply with the number I put in order for the loop to be false? I just wanted to multiply the values I typed and not multiply the number to exit the loop.

#include <stdlib.h>

int main()
{

int multi=1, val;

do
{
printf("Digite um valor");
scanf("%d",&val);
multi= multi*val;
}
while(val!=0);
printf("%d",multi);
return 0;

}

1 answer

2


What’s happening is that by typing the 0 it will multiply by multi and so the result is 0

do
{
printf("Digite um valor");
scanf("%d",&val); // ao inserir 0
multi= multi*val; // multi= multi * 0
 }while(val!=0);  // para o ciclo
 // multi vai ter o valor de 0

The way to fix it is not to leave the 0 multiply by multi and so, as soon as you enter 0 for the cycle, for example:

  while(1) //ciclo infinito
    {
    printf("Digite um valor");
    scanf("%d",&val); // ao inserir o 0
    if(val==0) // val==0 -> true
        break; // sai fora do ciclo
    multi= multi*val; //multi NÃO multiplica por 0
    }

See these differences:

while(1) // é igual a dizer `while(true)` ou seja, é sempre verdade, ciclo infinito
{
scanf("%d",&val); 
if(val==0) //o ciclo é parado AQUI
   break;
//caso val==0 este pedaço de codigo nao é executado
}

do{
scanf("%d",&val); 
//caso val==0 este codigo é executado
}while(val==0) // o ciclo é apenas parado AQUI

Although these codes are very similar can make a difference, as is the case.

Code in the Ideone


I could also do it this way:

int multi=1, val=1;
    do
    {
    multi= multi*val;
    printf("Digite um valor"); 
    scanf("%d",&val); // caso seja inserido 0
    }while(val!=0); // PARA logo o ciclo
  • 1

    Please avoid long discussions in the comments; your talk was moved to the chat

  • @Maniero You are right, began to arise doubts through the middle. Thank you for having moved.

  • That’s standard system message, I just accepted his signage.

  • I posted a duplicate question because I was not finding this topical!!! Thanks @Fábiomoral , sorry!!

Browser other questions tagged

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