The Wayback Machine - https://web.archive.org/web/20240915143536/https://www.geeksforgeeks.org/printf-in-c/
Open In App

printf in C

Last Updated : 27 Oct, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C language, printf() function is used to print formatted output to the standard output stdout (which is generally the console screen).  The printf function is a part of the C standard library <stdio.h> and it can allow formatting the output in numerous ways.

Syntax of printf

printf ( "formatted_string", arguments_list);

Parameters

  • formatted_string: It is a string that specifies the data to be printed. It may also contain a format specifier to print the value of any variable such as a character and an integer.
  • arguments_list: These are the variable names corresponding to the format specifier.

Return Value

  • printf() returns the number of characters printed after successful execution.
  • If an error occurs, a negative value is returned.

Example of printf

In this example, we are printing the string “Hello Geek!” in the output using printf() function. In printf() function what we will write inside the double quotes (” “) is printed in the output.

C




// C program to illustrate the use of printf function
#include <stdio.h>
 
int main()
{
    // using printf to print "Hello Geek!"
    printf("Hello Geek!");
 
    return 0;
}


Output

Hello Geek!

Formatting in C printf

In C, a value can be a character type, integer type, float type, and so on. To display and format these values using printf, we have format specifiers that are used in the formatted string. These format specifiers start with the percentage symbol ‘%’.

Syntax of Format Specifier

%[flags][width][.precision][length]specifier

1. Specifier

It is the character that denotes the type of data. Some commonly used specifiers are:

  • %d: for printing integers
  • %f: for printing floating-point numbers
  • %c: for printing characters
  • %s: for printing strings
  • %p: for printing memory addresses
  • %x: for printing hexadecimal values

Example

printf("%c", char_variable);

2. Width

It is the sub-specifier that denotes the minimum number of characters that will be printed.

If the number of characters is less than the specified width, the white space will be used to fill the remaining characters’ places. But if the number of characters is greater than the specified width, all the characters will be still printed without cutting off any.

Example

printf("%25s", some_string);

or

printf("%*s", 25, some_string);

3. Precision

Precision subspecifier meaning differs for different format specifiers it is being used with.

  • For Integral data(d, i, u, o, x, X): Specifies the minimum number of digits to be printed. But unlike the width sub-specifier, instead of white spaces, this sub-specifier adds leading zeroes to the number. If the number has more digits than the precision, the number is printed as it is.
  • For Float or Double Data(f, e, a, A): Specifies the number of digits to be printed after the decimal point.
  • For String (s): Specifies the length of the string to be printed.

Example

printf("%.10d", some_integer);
printf("%.3f", some_float);
printf("%.25s", some_string);

or

printf("%.*d", 10,  some_integer);
printf("%.*f", 3, some_float);
printf("%.*s", 25, some_string);

4. Length

Specifies the length of the data type in the memory. It is used in correspondence with data type modifiers.

There are 3 length sub-specifiers:

  • h: With short int and unsigned short int
  • l: With long int and unsigned long int.
  • L: With long double

Example

printf("%lf", double_variable);

Examples of printf() in C

Example 1:  Print a Variable using Specifier in printf()

In this example, we are printing an integer using a format specifier “%d” which is used for an integer. In the printf() function we are printing integers along with string using %d and in the arguments, we have passed variable names in a sequence corresponding to their format specifiers.

C




// C program to print a variable
#include <stdio.h>
int main()
{
    int num1 = 99;
    int num2 = 1;
    printf("The sum of %d and %d is %d\n", num1, num2,
           num1 + num2);
    return 0;
}


Output

The sum of 99 and 1 is 100

Example 2: printf with Specified Width

In this example, we will specify the width of the output which will be printed by the printf() function.

C




// C program to illustrate the use of printf with width
// specifier
#include <stdio.h>
int main()
{
    // number to be printed
    int num = 123456;
    // printing the num with 10 width and getting the
    // printed characters in char_printed
    printf("Printing num with width 10: ");
    int chars_printed = printf("%10d", num);
    printf("\nNumber of characters printed: %d",
           chars_printed);
 
    // specifying with using other method
    printf("\nPrinting num with width 3: ");
    chars_printed = printf("%*d", 3, num);
    printf("\nNumber of characters printed: %d",
           chars_printed);
 
    return 0;
}


Output

Printing num with width 10:     123456
Number of characters printed: 10
Printing num with width 3: 123456
Number of characters printed: 6

As we can see, even if we define the width that is less than the present characters, all the characters are still printed. Also, we have seen the two ways in which we can define the width.

Example 3: printf with Precision Sub-Specifier

In this example, we will demonstrate the precision sub-specifier in the printf() function

C




// C program to illustrate the use of precision
// sub-specifier
#include <stdio.h>
 
int main()
{
    int num = 2451;
    float dec = 12.45126;
    char* str = "GeeksforGeeks";
 
    // precision for integral data
    printf("For integers: %.10d\n", num);
    // precision for numbers with decimal points
    printf("For floats: %.2f\n", dec);
    // for strings
    printf("For strings: %.5s", str);
 
    return 0;
}


Output

For integers: 0000002451
For floats: 12.45
For strings: Geeks

Example 4: printf with Length Sub-Specifier

C




// C program to illustrate the length modifier
#include <stdio.h>
 
int main()
{
    long var = 3000000000;
    // printing var using %d
    printf("Using %%d: %d", var);
    // printing var using %ld
    printf("\nUsing %%ld: %ld", var);
 
    return 0;
}


Output

Using %d: -1294967296
Using %ld: 3000000000

Related Articles:



Previous Article
Next Article

Similar Reads

Nested printf (printf inside printf) in C
Predict the output of the following C program with a printf inside printf. #include&lt;stdio.h&gt; int main() { int x = 1987; printf(&quot;%d&quot;, printf(&quot;%d&quot;, printf(&quot;%d&quot;, x))); return(0); } Output : 198741 Explanation : 1. Firstly, the innermost printf is executed which results in printing 1987 2. This printf returns total n
1 min read
How to print % using printf()?
Here is the standard prototype of printf function in C: int printf(const char *format, ...); The format string is composed of zero or more directives: ordinary characters (not %), which are copied unchanged to the output stream; and conversion specifications, each of argument (and it is an error if insufficiently many arguments are given). The char
1 min read
Return values of printf() and scanf() in C/C++
What values do the printf() and scanf() functions return ? printf() : It returns total number of Characters Printed, Or negative value if an output error or an encoding error Example 1: The printf() function in the code written below returns 6. As 'CODING' contains 6 characters. C/C++ Code // C/C++ program to demonstrate return value // of printf()
2 min read
Use of &amp; in scanf() but not in printf()
Why there is need of using '&amp;' in case of scanf function while not in case of printf function. Examples: scanf("%d %d", &amp;a, &amp;b);printf("%d %d", a, b);As a and b above are two variable and each has their own address assigned but instead of a and b, we send the address of a and b respectively. The reason is, scanf() needs to modify values
1 min read
How to Write Your Own printf() in C?
In this article, we will learn how to implement your own custom printf() function in C language. The printf() function is present in &lt;stdio.h&gt; header and uses a const char* and variable length arguments as its parameters. Hence we would be using &lt;stdarg.h&gt; header file which provides operations available on variable arguments passed to a
4 min read
Difference between return and printf in C
In C programming, return and print serve fundamentally different purposes and they are used in distinct contexts to achieve specific tasks. Let's see each of them and see what are their functions and differences. 1. Return Statement In C, return is a statement used within a function to terminate the function's execution and return a value to the ca
2 min read
What is use of %n in printf() ?
In C printf(), %n is a special format specifier which instead of printing something causes printf() to load the variable pointed by the corresponding argument with a value equal to the number of characters that have been printed by printf() before the occurrence of %n. #include&lt;stdio.h&gt; int main() { int c; printf(&quot;geeks for %ngeeks
1 min read
puts() vs printf() for printing a string
In C, both puts() and printf() functions are used for printing a string on the console and are defined in &lt;stdio.h&gt; header file. In this article, we will discuss the differences in the usage and behavior of both functions. puts() FunctionThe puts() function is used to write a string to the console and it automatically adds a new line characte
3 min read
How to Change the Output of printf() in main() in C?
To change the output of printf() in main(), we can use Macro Arguments. #define macro can be used for this task. This macro is defined inside the function. Although, #define can be used without declaring it in the function, in that case always the printf() will be changed. The function needs to be called first to change the output of printf() in ma
2 min read
What is the difference between printf, sprintf and fprintf?
printf: printf function is used to print character stream of data on stdout console. Syntax : printf(const char* str, ...); Example : C/C++ Code // simple print on stdout #include &lt;stdio.h&gt; int main() { printf(&quot;hello geeksquiz&quot;); return 0; } Outputhello geeksquiz sprintf: String print function instead of printing on console store it
2 min read
Passing NULL to printf in C
Consider the following C code snippet. char* p = NULL; printf("%s", p); What should be the output of the above program? The print expects a '\0' terminated array of characters (or string literal) whereas it receives a null pointer. Passing NULL to printf is undefined behavior. According to Section 7.1.4(of C99 or C11) : Use of library functions If
1 min read
Cin-Cout vs Scanf-Printf
Regular competitive programmers face common challenge when input is large and the task of reading such an input from stdin might prove to be a bottleneck. Such problem is accompanied with “Warning: large I/O data”. Let us create a dummy input file containing a line with 16 bytes followed by a newline and having 1000000 such lines, making a file of
3 min read
Execution of printf With ++ Operators in C
Consider the following statement in C and predict its output. printf("%d %d %d", i, ++i, i++);This statement invokes undefined behavior by referencing both ‘i’ and ‘i++’ in the argument list. In C, the evaluation order of function arguments is not specified. It means the compiler is free to evaluate arguments in any order. That is why, Similar thin
3 min read
C Programming Language Tutorial
In this C Tutorial, you’ll learn all C programming basic to advanced concepts like variables, arrays, pointers, strings, loops, etc. This C Programming Tutorial is designed for both beginners as well as experienced professionals, who’re looking to learn and enhance their knowledge of the C programming language. What is C?C is a general-purpose, pro
8 min read
Pattern Programs in C
Printing patterns using C programs has always been an interesting problem domain. We can print different patterns like star patterns, pyramid patterns, Floyd's triangle, Pascal's triangle, etc. in C language. These problems generally require the knowledge of loops and if-else statements. In this article, we will discuss the following example progra
15+ min read
C Programs
To learn anything effectively, practicing and solving problems is essential. To help you master C programming, we have compiled over 100 C programming examples across various categories, including basic C programs, Fibonacci series, strings, arrays, base conversions, pattern printing, pointers, and more. These C Examples cover a range of questions,
8 min read
Switch Statement in C
Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases). Switch case statements follow a selection-control mechanism and allow a value to change control of
8 min read
C Programming Interview Questions (2024)
At Bell Labs, Dennis Ritchie developed the C programming language between 1971 and 1973. C is a mid-level structured-oriented programming and general-purpose programming. It is one of the old and most popular programming languages. There are many applications in which C programming language is used, including language compilers, operating systems,
15+ min read
scanf in C
In C programming language, scanf is a function that stands for Scan Formatted String. It is used to read data from stdin (standard input stream i.e. usually keyboard) and then writes the result into the given arguments. It accepts character, string, and numeric data from the user using standard input.scanf also uses format specifiers like printf.sc
2 min read
C Hello World Program
The “Hello World” program is the first step towards learning any programming language and also one of the simplest programs you will learn. To print the "Hello World", we can use the printf function from the stdio.h library that prints the given string on the screen. C Program to Print "Hello World"The following C program displays "Hello World" in
2 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
Since C is a structured language, it has some fixed rules for programming. One of them includes changing the size of an array. An array is a collection of items stored at contiguous memory locations.  As can be seen, the length (size) of the array above is 9. But what if there is a requirement to change this length (size)? For example,  If there is
9 min read
Substring in C++
The substring function is used for handling string operations like strcat(), append(), etc. It generates a new string with its value initialized to a copy of a sub-string of this object. In C++, the header file which is required for std::substr(), string functions is &lt;string&gt;. The substring function takes two values pos and len as an argument
8 min read
Strings in C
A String in C programming is a sequence of characters terminated with a null character '\0'. The C String is stored as an array of characters. The difference between a character array and a C string is that the string in C is terminated with a unique character '\0'. C String Declaration SyntaxDeclaring a string in C is as simple as declaring a one-
8 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Operators in C
In C language, operators are symbols that represent operations to be performed on one or more operands. They are the basic components of the C programming. In this article, we will learn about all the built-in operators in C with examples. What is a C Operator?An operator in C can be defined as the symbol that helps us to perform some specific math
14 min read
C Pointers
Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. In this article, we will discuss C pointers in detail, their
14 min read
Data Types in C
Each variable in C has an associated data type. It specifies the type of data that the variable can store like integer, character, floating, double, etc. Each data type requires different amounts of memory and has some specific operations which can be performed over it. The data type is a collection of data with values having fixed values, meaning
7 min read
C Arrays
Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more
15+ min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The &amp; (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1.  The | (bitwise OR) in C takes two n
7 min read
C Language Introduction
C is a procedural programming language initially developed by Dennis Ritchie in the year 1972 at Bell Laboratories of AT&amp;T Labs. It was mainly developed as a system programming language to write the UNIX operating system. The main features of the C language include: General Purpose and PortableLow-level Memory AccessFast SpeedClean SyntaxThese
6 min read
Article Tags :