How to Write a Program That Prints All Single-Digit Numbers in C

How to Write a Program That Prints All Single-Digit Numbers in C

A Step-by-Step Guide


In this article, you will learn how to print out all the single-digit numbers in C starting from 0 down to 9. Here we will print the numbers followed by a comma and a space, and we will only be using the putchar function and lastly, we will only be using the int data type and not char.

How to Print All Single-Digit Numbers in C

Here I will be using the Betty style of comment to write the code that will enable us to be able to print all single digits using the C programming language;

#include <stdio.h>
  *main - prints all single digits
  *Return: 0
int main(void)
    int num;

    num = 0;

    while (num <= 9)
        putchar(num + '0');
        if (num < 9)
            putchar(' ');
    return (0);

First, you use your #include <stdio.h> since we are using putchar, it is a function gotten from the standard input and output C library, so we have to bring the standard library for the function to work.

Next, we have to declare our main function, we are using void because it won't be taking any arguments, next we declared num as an int, and then initialized it with 0, next we used a while loop, you can also use a for loop to achieve the same result. Next, we used putchar to print the num and we had to add '0' to it, since the putchar function cannot print numbers, only characters, so adding the '0' will help convert the integer num to a character that the putchar can now print to standard output.

Next, we have to print the comma followed by the space, but we don't want it to come after the last digit, which is 9, so we have to give it a condition to stop before it gets to the last digit so as not to be included after the last digit. Then we went ahead to increase the value of num by 1 using num++, so that as we loop through num, each time it prints out the next number in ascending order.

Finally, we used the putchar to include a new line as the end of the whole while loop and then return (0) to mark the end of the program.

when you compile the c program and run it, you will get the following:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9


You can use other functions that print to standard output as well, such as printf, putc, puts etc, here we just decided to make use of the putchar so we could further understand the flow of the C programming.

Thank you for reading. I will like to connect with you on Twitter and LinkedIn as I am more active on those two platforms.