while not running

0

In the following code, the second while is never executed, what is the reason?

int main(){

    int a,b;
    int producto=0;
    int cociente=0;

    printf ("Escribe primer número.\n");
    scanf ("%d", &a);
    printf ("Escribe segundo número.\n");
    scanf ("%d", &b);

    printf ("Suma: %d.\n", a+b);
    printf ("Resta: %d.\n", a-b);

    while (a!=0 && b!=0){
      producto+=b;
      a--;
    }
    printf ("Producto: %d.\n", producto);

    while (a>= b){
        a=a-b;
        cociente++;
    }
    printf ("División: %d.\n", cociente);

    return 0;
}
    
asked by Adri 29.05.2018 в 00:44
source

2 answers

0

The second loop will never be executed by the a--; of the first loop. Let me clarify.

The first loop is run as long as a and b are not 0 (Initially I assume you have used values greater than 0). The only way to get out of the loop, judging the code is that the variable a becomes 0, which you can achieve by decreasing it with a--; . Once that loop is executed, the value of a will always be 0 .

Now, when you get to the second loop, the initial condition is never fulfilled. b will always be greater than 0 , and as a is 0 , the code is never executed inside.

The only way that the second loop is executed is if b is 0 or negative. No matter if b is 0 or negative, you will find an infinite loop, because a will not change its value (subtract 0 ), or will increase (subtract a negative number, which translates to a sum ). a will always be greater than b .

    
answered by 29.05.2018 / 01:40
source
1

In the first loop we have:

while (a!=0 && b!=0){
  producto+=b;
  a--;
}

That is, the loop will repeat as a and b are different from zero ... but inside the loop we do not update b ... then the loop will repeat indefinitely ... this loop has only to take into account the value of a :

while (a!=0){
  producto+=b;
  a--;
}

Although, of course, if the value of a you have to use it also in the division, you should copy its value so as not to lose it:

// opcion 1
int i=a;
while( i!=0 )
{
  producto += b;
  i--;
}

// opcion 2
for( int i=a; i!=0; i--){
  producto+=b;
}

Although, if it is not a restriction of the exercise, you may prefer to calculate the product directly:

producto = a*b;
    
answered by 29.05.2018 в 07:34