How do I force entry into "while"?

Asked

Viewed 208 times

1

This program allows to calculate the table from up to 10 to a given number x. But in the cycle of the while after the first iteration it does not enter and jumps to the end. For example, if I insert 2 my output is:

Introduza o numero da tabuada que quer!

3
tabuada do 0

 0x3=0

 1x3=0

 2x3=0

 3x3=0

 4x3=0

 5x3=0

 6x3=0

 7x3=0

 8x3=0

 9x3=0

 10x3=0

 tabuada do 1


 tabuada do 2


 tabuada do 3

The code that generates the above output is as follows:

void main()
{


int i,x, a, resultado;

printf(" Introduza o numero da tabuada que quer!\n\n");

scanf("%d", &a);

i = 0;

x = 0;

do  {
    printf(" tabuada do %d\n\n", x);

{

        while (i <= 10)
        {
            resultado = i*x;
            printf(" %dx%d=%d\n", i, a, resultado);
            i++;
        }
    }

        x++;

} while (x <= a);

}
  • 1

    You need to get back the i for 0 after printing the first times table.

  • But if you only want to tabulate the number typed, I did not understand why there is the outside loop (the do..while)

  • I want all tabs to the number typed

  • I’ve noticed the error, thank you :)

  • The problem is that you are considering the position of the table as the starting point of your calculation, and not the type of table you want to perform the calculation. This way whenever you choose one of them it will continue the loop from this position until the end.

2 answers

6


You are not restarting the tab counter every time you change your number. I took the opportunity to have an organized code. There are some conceptual errors about the table that I took to solve.

#include <stdio.h>

int main() {    
    int i = 1, x = 1, a, resultado;
    printf(" Introduza a quantidade de tabuadas que quer! ");
    scanf("%d", &a);
    do  {
        printf("\nTabuada do %d\n", x);
        while (i <= 10) {
            resultado = i*x;
            printf(" %dx%d=%d\n", i, a, resultado);
            i++;
        }
        i = 1; // <============ seu problema estava aqui.
        x++;
    } while (x <= a);
}

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

4

Just reset the counter i, because he is the control of his tables.

After the while switch to:

i = 0;

Thus remaining:

void main()
{
int i,x, a, resultado;

printf(" Introduza o numero da tabuada que quer!\n\n");

scanf("%d", &a);

i = 0;

x = 0;

do  {
    printf(" tabuada do %d\n\n", x);
    {
        while (i <= 10)
        {
            resultado = i*x;
            printf(" %dx%d=%d\n", i, a, resultado);
            i++;
        }
        i = 0;
    }
    x++;
} while (x <= a);
}

Browser other questions tagged

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