How to use printf() in C programming language
An ALX Software Engineering group project.
This is an ALX Software Engineering done by Thandiwe Khalaki and Thulani Moko. The main task of this project is to write a function that uses printf() to produce output according to this format
int _printf(const char *format, ...)
For example
_printf("Halo %s\n", "World");
will output
Halo World
To find the source code of this project you can go to printf
However, in this short article, we are going to explore how to use basic c types with print() format specifiers.
Table of Contents
- Basic data types in C
- C conversion specifiers
- Printf() function
Let's go....
1. Basic data types in C
The basic data types in C can be categorized into three different types, characters, integral values and floating-point values. Integral values cover "int' and 'long' data types while 'float' and 'double' data types are covered under floating-point values. The void data type is primarily used to declare functions that return no values.
To learn more about data types in c language, click here
2. C conversion specifiers
In C programming language, specifiers are used to format different data types. Specifiers are also used to define the data types that are printed on the standard output.
Below is a table of basic specifiers that are used in C
To learn more about specifiers, click here
3. Printf()
In C, the print() function send formatted output to standard output(also known as stdout). Printf() is declared in the following way
int _printf(const char *format, ...);
*format is a string to be printed to stdout.
printf() function can also take additional parameters
printf(formatString,[parameters..]);
Now, let us use print() function to print out some of the specifiers in the above table.
"print out" in this article means to send to standard output(stdout)
Character
#include <stdio.h>
void main()
{
printf("%c",'A');
}
which will output
A
Signed decimal integer
#include <stdio.h>
void main()
{
printf("My favorite number is %d", 8);
}
which will output
My favorite number is 8
String
#include <stdio.h>
void main()
{
printf("My first name is %s, and my second name is %s", "Jane", "Doe");
}
Remember to always put the string in double quotes
" Jane", "Doe"
The output of this code will be
My first name is Jane, and my second name is Doe
Float
#include <stdio.h>
void main()
{
printf("I weigh %f", 155.96);
}
The output will be
I weigh 155.960000
Unsigned integer
#include <stdio.h>
void main()
{
printf("Unsigned integer %u", 1-2);
}
The output is
Unsigned integer 4294967295
Long int
#include <stdio.h>
void main()
{
printf("long int %lld", 7-9);
}
The output will be
long int 42520468288176126