How to Write a Program That Prints All Possible Different Combinations of Two Digits in C

How to Write a Program That Prints All Possible Different Combinations of Two Digits in C

A program that prints all possible different combinations of two digits, without repetitions

Introduction

I started with how to print all single digits in C. So I will be going further in this article to show you how to print different combinations of two digits in C, where numbers like 00, 11, 22, 33, 44.... etc are not considered and only one of the numbers that are a mirror image of themselves are to be considered, so since we have 01, we can't have 10, and if we have 12, we can't have 21 etc.

We will also be using the putchar() function to print our digits to the standard output.

How to Generate and Print All Possible Combinations of Two-Digits in C

For this to be possible, we have to take advantage of two loop statements, with one being an inner loop and the other being an outer loop.

This way, we can never have the same digits listed, and once we have any two digits appear, we can't have the same combination of those two digits again. eg. Once we have 01, we can't have 10, 02, 20 won't be listed, 12, 21 will not be listed, and so on.

Using the Betty style of writing C, and also using the putchar function, our code for doing this will be;

#include <stdio.h>
/**
  *main - prints all possible combinations of two digits
  *Return: 0
*/
int main(void)
{
    int i, j;

    for (i = 0; i <= 9; i++)
    {
        for (j = i + 1; j <= 9; j++)
        {
            putchar(i + '0');
            putchar(j + '0');

            if (i < 8 || j < 9)
            {
            putchar(',');
            putchar(' ');
            }
        }
    }
    putchar('\n');
    return (0);
}

The inner and outer loop is to be able to print the numbers without any repetitions of single digits and double digits.

The '0' that is added to the i and j of the two putchar is convert the numbers to characters so that the putchar can print them out.

Used the if control statement and set the first digit i at 8 and the second digit j at 9, because 90 will not be printed since 09 has already been printed, same with 91 down to 99.

Then added a new line after the whole printing is done and then used the return keyword to signify the end of the program.

Once you've done this, simply compile the C program and run it, you should get something like this:

Conclusion

Just as how we used putchar, we can as well use putc, puts and even printf to achieve the same thing.

Thank you for reading, I will like us to connect on Twitter and LinkedIn as I am more active on these platforms.