Search code examples
cwhile-loopnested-loops

Why my outer while loop doesn't work after the inner one stops?


I am trying to create a function that displays all different combination of two digits between 00 and 99, listed by ascending order. Here's what i wrote so far.

#include <unistd.h>

void    ft_putchar(char c)

{

    write(1, &c, 1);

}



void    ft_print_comb2(void)

{

    int x;

    int y;

    x = 0;

    y = x + 1;

    while(x <= 98)

    {

        while(y <= 99)

        {

            ft_putchar((x / 10) + '0');

            ft_putchar((x % 10) + '0');

            write(1, " ", 1);

            ft_putchar((y / 10) + '0');

            ft_putchar((y % 10) + '0');

            write(1, ", ", 2);

            y++;

        }

        x++;

    }

}



int main()

{

    ft_print_comb2();

    return (0);

}

My code stops after giving the output of 00 99. Why it doesn't add 1 to x and start from the outer while loop again?

Here's the desired output

00 01, 00 02, 00 03, 00 04, 00 05, ..., 00 99, 01 02, ..., 97 99, 98 99$>

Solution

  • You need to reset the variable y to the value x + 1 before the inner while loop in each iteration of the outer while loop.

    For example

    x = 0;
    
    while(x <= 98)
    
    {
        y = x + 1;
    
        while(y <= 99)
        //...