C – Printf Tutorial with Examples
C and C++ programming language a
printf function which is used to print given values or data to the standard output or current terminal.
printf supports different formatting types. In this tutorial we will look them in detail.
printf is like below.
printf function can be used simply just providing single variable. In this example we have a integer variable named
age . We print this variable with
%d which is type specifier of the given variable.
printf("My age is %d",age);
Print Multiple Values
We can use
printffunction inorder to print multiple values. We wll add the variables to the end of the
printf function. In this example we will print variables named
char city = "ankara";
printf("Name:%s , Age:%d , City:%s",name, age, city);
We have already used string or character array types to print with
printf . We will use
%s in order to specify string or character array type variables in a output string.
Print Numbers or Integers
Integer variables can be printed with
%d in printf function. In this example we will print
age integer variable.
Float variables type generally holds floating values. These values can be print with
%f in a printf function. We will print the
price floating point type variable value in this example.
List Of Print Format Specifiers
Here we can find all printf supported format specifiers.
|%d||decimal (integer) number (base 10)|
|%e||exponential floating-point number|
|%i||integer (base 10)|
|%o||octal number (base 8)|
|%s||a string of characters|
|%u||unsigned decimal (integer) number|
|%x||number in hexadecimal (base 16)|
|%%||print a percent sign|
|\%||print a percent sign|
How To Print Percent Sign %
As we seen previous examples printf function uses
% as format specifier. So there is a problem how can we print percent sign without breaking code? We can use
\ to specify percent sign is just a character in the printf.
printf("\% is percent sign.");
printf("%% is percent sign.");
Print Left Justified
We may need to beautify the printf function output. The most basic beautification is aligning output. We can print given values left justified with
- and adding the space count.
We can fill integer output before given integer value. We will put
d . In this example we will set
3 total numbers and provide
This will output following
Format Floating Point
Floating points have two part which is decimal part and other is floating part. We can format these two part too. We will use
. and numbers to specify numbers counts. In this example we want
4 as decimal part but
3 for floating point part.
This will print only
3 number after the point.
Printf Special Characters
Printf have some special characters to make special behaviours. We can use these special characters to backspace , newline , tab , vertical tab etc.
|\n||newline, or linefeed|