Write a program that prints all possible combinations of single-digit numbers
Using both putchar and printf functions with for and while loops
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
The question is about writing a C program that produces the outcome above.
There are several ways we can have a program to print all the possible combinations of single-digit numbers. In this tutorial, we will look at how to use:
putchar
printf
Also, for each of them, we can look at multiple ways of achieving the expected outcome. In this tutorial we will take a look at how to use two different types of loops to achieve the result;
- For loop
- While loop
Using putchar
to print all combinations of single-digit numbers
First we will look at how to do that with a for
loop and afterwards implement the same code using a while
loop.
By default, the putchar
function is used for displaying single characters to the screen, but we need to make it print integers this time round.
What can help us here is the fact that the putchar
function recognizes ASCII codes and is able to print the corresponding integer value of any ASCII code. This means we would also need to know the ASCII codes for the digits (0, 1, 2...9).
ASCII Code | Interger Value |
---|---|
048 | 0 |
049 | 1 |
050 | 2 |
051 | 3 |
052 | 4 |
053 | 5 |
054 | 6 |
055 | 7 |
056 | 8 |
057 | 9 |