Mwaura
In this article, we dive deep into the low levels. This tutorial demonstrates how to print an integer in C. Here is the fun part, the printf() function will not be used. I found the approach extremely elegant. (You will too) Lets dive in.
I know, this may seem intimidating. Don't worry, we will take it step by step.
We start by importing the standard input/output library.
This allows us access to the putchar function, contained in the library. (I will soon be writing about how putchar works)
Tip: stdio actually means standard input/output
In brief, here is the function prototype of putchar from the linux man pages.
with the description:
putchar takes an integer, and prints the ACII represented by the integer to stdout.
There are two functions in the code, i.e.,
The main function is the entry point to our program. The text surrounded by /* comment */ are the comments, describing what each function does.
The main function calls the print_number function several times, with a specific number each time. The print_number function then does its magic and prints each number.
putchar is used to print a new line after every call of print number.
Compiling and running our code produces the following output:
We will go through the step compilation later.
Here is where all the magic happens. The function takes an integer n.
In our case, we print "-" .
After the assignment above, i is now equal to 87.
In our case we call the function print_numbers(87 / 10 = 8)
All the steps above are repeated for n = 8.
In this case we print 8 since 8 % 10 = 8.
We pass (i % 10 + '0') to putchar because we want to print the digit i / 10, 7 in our case and not the character represented by 7 in ascii. By adding '0', we are printing the 7th character after '0', i.e., 7
To compile our code, run the command bellow, change it accordingly based on how you have named your files.
gcc print_number.c -o print_number
We are simply telling gcc to compile the file print_number.c and output the result to the file print_number.
Run the program as shown below. (This may be different depending on your developer environment).
./print_number
The output will be as observed earlier.
And that's it.
Feel free to air any concerns on the comment section.