Simple Programming: ft_print_comb.c

This is a fun one. Ft_print_comb.c is an exercise given to those in the WeThinkCode bootcamp on Day02. You’ll be challenged to “create a function that displays all different combinations of three different digits in ascending order, listed by ascending order”.

I went through the 3 week intensive C bootcamp earlier this year and it kicked my ass so if you need a hand for this exercise in Day02, here it is.

Include the ft_putchar which I believe was created by the school. We’ve created our own version of ft_putchar (cm_putchar) that allows us to print 3 different variables – instead of only 1.

We’ve created 3 variables to carry each of the digits (a, b, c) and initialized the first variable to 0 because that’s our starting point. The last number they give in the example is 789 so in our While loops we set the corresponding value smaller than or equal to that number.

We want the numbers to scale up at the same time, so we set the variable b as equal to a + 1, and c as equal to b + 1. Our If is there to add the spaces and commas between each item in the list. Then all that’s left to do is increment!


#include

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

void cm_putchar(char x, char y, char z) {
ft_putchar(x);
ft_putchar(y);
ft_putchar(z);
}

void ft_print_comb(void) {
int a;
int b;
int c;

a = 0;
while(a <= '7') { b = a + 1; while(b <= '8') { c = b + 1; while(c <= '9') { cm_putchar(a, b, c) { if(a != '7' || b != '8' || c != '9') { ft_putchar(','); ft_putchar(' '); } c++; } b++; } a++; } } }

If you want to test this, don't forget to add an int main() and call the function. Good luck friend!

© Christie Eveleigh Marx 2020