Printf() function in C
printf() is a predefined inbuilt standard library function used to display output on the screen. The printf() function is defined in the stdio.h header file, printf() is case sensitive, it is always written as printf(). Generally printf() function looks like, and anything written in the printf() function gets printed on the output screen.
printf(“Your Message”, list of variables);
printf() Example:
#include<stdio.h>
void main()
{
printf("Welcome to C Programming");
}
Output:
Welcome to C Programming
Points About the printf() Function
- The printf() function is an inbuilt library function.
- The printf() function is defined within the C library’s <stdio.h> header file.
- To use the printf() function, you must include the stdio.h header file in the C program.
- printf() function is case-sensitive i.e. printf() is different from Printf(), infact C is a case-sensitive programming language.
Use the printf() Function in 2 Ways
For better understanding, the use of the printf() function can be done in two ways.
- printf() function without variables/values
- printf() function with variables/values.
printf() function without variables/values
This scenario of the printf() function is used to print simple/general messages as output in C programming, see below syntax and examples.
Example
#include<stdio.h>
void main()
{
printf("This message from printf function \n");
printf("--------------------------------- \n");
printf("This is message 1 \n This is message 2 \n Both above two line are from same printf fuction\n");
printf("This is last message");
}
Newline Character (\n)
"\n" is used for new lines in output. All text/content after "\n" will appear in the next line.
Placeholder
Placeholder is used to insert a value/variable value in a message in printf() function, the below table contains the type of value and placeholder representation.
Data Types [Placeholder Representation]
- int [%d]
- char [%c]
- float [%f]
- double [%lf]
- string [%s]
- octal [%o]
- hexadecimal [%x]
printf() function with variables/values
This scenario of the printf() function is used to print a message along with some value stored in variables. You can use a placeholder representation to insert the value of the variable in the message. Let's understand with an example.
Syntax
printf(“Message with list of placeholder symbol”, variable1, variable2, variable3,....);
Rules/Explanation:
- In the above example, a, b, and sum are variables.
- All three %d is called a placeholder.
- %d symbols are replaced by int type values.
- Variable order matters, for example [ a, b, sum ---> 10,20,30 ] and [ a, sum, b ---> 10, 30, 20 ]
- Placeholder representation symbols and variable data type must match, and the order should be correct.