c-language double-repeated statements

Asked 2 years ago, Updated 2 years ago, 105 views

#include <stdio.h>  

void dice(int , int );

int main(void)
{
int input1, input2;
scanf_s("%d%d", &input1, &input2);
dice(input1, input2);

return 0;
}

void dice(int num1, int num2)
{
int a = 1, b = 1;

while (num1 >= a)
{


      while (num2 >= b)
      {
           printf("%d %d\n", a, b);
           b++;

      }
a++;
}
}

If you enter 2 or 2 in this function, it should be output (1,1)(2,1)(2,2) (braces are used for convenience)

However, if you enter 2 and 2, it is printed as (1,1) (1,2), and a cannot be repeated. In the same way, if you do the for statement, it will be output normally, but if you do the while statement, a cannot be repeated...What's wrong??

c loops while-loop

2022-09-20 22:30

1 Answers

That's because printf(...) is on the second while statement When b starts at 1, and the second while statement ends, the value of b becomes 3.

Then, when a=2 is the value, b is still 3, so we don't print it out.

You can set the value of b back to 1 in the first while statement.


2022-09-20 22:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.