Search code examples
cgcccompilationoutput

Compiling problem with simple exercise in C to create all possible combinations of two two-digit numbers


Given task:
Create a function that displays all different combination of two digits between 00 and 99, listed by ascending order. Allowed functions - write

My Problem: After compiling with gcc, the a.out file shows no output/is empty.

My solution:

#include <unistd.h>

void ft_putchar(char c)
{
    write(1, &c, 1);
}

void add_space(void)
{
    ft_putchar(' ');
}


void add_comma_space(void)
{
    ft_putchar(',');
    ft_putchar(' ');
}

void ft_print_comb2(void)
{
    char i, j, k, l;
    for(i = '0'; i <= '9'; i++)
    {
        for(j = i + '1'; j <= '9'; j++)
        {
            ft_putchar(i);
            ft_putchar(j);
            add_space();    
        }
        for(k = '0'; k <= '9'; k++)
        {
            for(l = k + '1'; l <= '9'; l++)
            {
                ft_putchar(k);
                ft_putchar(l);
                if(k != '8' && l != '9')
                    add_comma_space();
            }
        }
    }
}

int main(void)
{
    ft_print_comb2();
    return (0);
}

What I tried:
I asked ChatGPT and Bing Chat. The code seems fine and should be able to complete the task AFAIK.
I also compiled the code in an online compiler to make sure its not a problem with my compiler. The result was the same (no output/empty a.out file).

EDIT:
To elaborate, I'm compiling with gcc "filename" and then try to access a.out with ./a.out.
I had no problems with other exercises doing it this way prior to this one.
Here is my console:

PC@PC MINGW64 /filepath
$ gcc ft_print_comb2.c

PC@PC MINGW64 /filepath
$ ./a.out

PC@PC MINGW64 /filepath
$

Solution

  • Open a book and start to study from that.

    The code you've presented won't output anything:

    for(j = i + '1'; j < '9'; ...
    

    Starting with i holding 48 (the ASCII value of '0') then adding 49 (the ASCII for '1') results in 97... That is NOT less than the ASCII value for '9', so the inner loop never runs...

    And this happens two times in your code.

    Crack open a book and learn to write your own code.