Jonte
Jonte

Reputation: 21

Can someone explain to me how the modulo character works to output a leading zero

This is the original question: Create a function that displays all different combination of two digits between 00 and 99, listed by ascending order.

This was how a fellow student did it. It compiles. So all the first single digit outputs have to have a leading zero. I dont understand how he achieved it. Can someone explain to me this a%10 +0 part and how that works to print leading zeros? Thank you in advance.

 void   ft_print_comb2(void)
 {
int x;
int y;
enter code here
x = 0;
while (x < 99)
{
    y = x + 1;
    while (y < 100)
    {
        output_format(x, y);
        printlines(x, y);
        y++;
    }
    x++;
    }
}

void    output_format(int x, int y)
{
 if (!((x == 99 && y == 99) || (x == 0 && y == 1)))
 {
    write(1, ", ", 2);
    }
}

void    printlines(int x, int y)
{
char xmodule;
char xdiv;
char ymodule;
char ydiv;

xmodule = (x % 10 + '0');
xdiv = (x / 10 + '0');
ymodule = (y % 10 + '0');
ydiv = (y / 10 + '0');
write(1, &xdiv, 1);
write(1, &xmodule, 1);
write(1, " ", 1);
write(1, &ydiv, 1);
write(1, &ymodule, 1);
}

Upvotes: 0

Views: 298

Answers (1)

Paul Hankin
Paul Hankin

Reputation: 58320

For numbers between 0 and 100, x%10 + '0' is the ASCII value of the lowest digit of x, and x/10 + '0' is the ASCII value[1] of the tens digit (or 0 if the number is less than 10). '0' is the ASCII value that represents the character 0, and x%10 is the remainder when dividing x by 10. That's the trick used by your friend's code.

[footnote 1] (or more accurately, the character code from the character set of the execution environment which may or may not be ASCII).

However, the code written is quite complicated, and formatting numbers for output (including leading zeros) is provided by the standard library. Loops that range between two numbers can be conveniently described using a for loop. The function write used by the program is POSIX, and not part of the C standard library.

Here's a complete version using printf:

#include <stdio.h>

int main(int argc, char *argv[]) {
    for (int x = 0; x < 100; x++) {
        for (int y = x+1; y < 100; y++) {
            if (y!=1) printf(", "); // skip comma for the first pair output.
            printf("%02d %02d", x, y);
        }
    }
    printf("\n");
    return 0;
}

Upvotes: 1

Related Questions