What is printf and from where it comes from in C code.?
You must have used printf so many times in your Car programs but do you really know everything about printf? Let's see.
What is the full form of printf?
Printf function name is made of two words 'Print format'. Here format means format specifiers like%d %f etc.
Printf and scanf functions are actually included in your code by line #include header file. This file contents only header of standard IO functions and respective stdio.c file contains function definitions.
How to print Hex, Oct and Decimal number formats?
printf("%x", 10) ; this will print small 'a' on screen which is hex value of number 10.
printf("%X", 10) ; this will print capital A' on screen.
printf("%#x", 10) ; this will print small '0xa' with prefix 0x on screen.
printf("%o", 10) ; this will print '12' on screen which is octal value of number 10
printf("%5d", 10) ; this will print 3 spaces and then number 10 on screen because right alignment given in format i.e. "%5d".
For left alignment use "%-5d" Negative number it will print 10 and then 3 spaces.
What if you want a variable number of spaces instead of a constant number in format specifiers then use the star as below.
int s = 5;
printf("%*d", s, 10); this will give s number of spaces before printing number 10.
%g - is used to print float number without trialling zero. For example.
printf("%g", 10.2); this will print only 10.2 and not like%f prints 10.200000 always 6 trialling zeros.
%p - is used to print pointer values. That means addresses which are hex values.
%u - is used to print unsigned numbers that means positive numbers.
%i and %d are equivalent.
%c - is for character and%s is for word.
There are also many escape sequence characters which are commonly used but not known to all are:
To print% sign use double%% to avoid conflict with format specifiers and the actual per cent sign.
Example
printf("i got %d%% in practicals\n", 100) ; this will print I got 100% in practicals
Similarly, to print double quotes use \" .
Example
printf("I love \"C\" Language\n", 100) ; this will print I love "C" Language.
To print backslash use double backslash \\
To bring back cursor to start of the line use \r and to backspace or delete previously printed char on-screen use \b.
Using above \r and \b we can really create loading or progress bar effect on screen because we can display on same line different text with time delay.
for(I = 0; I <= 100; I ++)
{
printf("loading.... %d\r") ;
// some delay...
}
This will print loading..... 0 till 100 on same line.
There are so many such things you must explore to know what printf can do, isn't it?