Trusted answers to developer questions

How to use printf in C

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

printf (print formatted) in C, writes out a cstring to stdout (standard output). The provided cstring may contain format specifiers( beginning with % in the cstring).

If there are format specifiers, those are replaced with their respective arguments that follow the cstring to the printf call. These format specifiers may also contain its length, precision, and other flags.

Syntax

 int printf (const char* c-string, ...);
  • Return Value: If the function successfully executes, it returns the total number of characters written to the standard output. If an error occurs, a negative number is returned.

  • Arguments: c-string is the string passed to the function. There can be additional arguments following c-string, if there exist format specifiers in the c-string, as discussed above.


Format Specifer

The format specifier follows the following prototype:

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

Code

/* Example for printf() */
#include <stdio.h>
int main(){
printf ("Integers: %i %u \n", -3456, 3456);
printf ("Characters: %c %c \n", 'z', 80);
printf ("Decimals: %d %ld\n", 1997, 32000L);
printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
printf ("floats: %4.2f %+.0e %E \n", 3.14159, 3.14159, 3.14159);
printf ("Preceding with empty spaces: %10d \n", 1997);
printf ("Preceding with zeros: %010d \n", 1997);
printf ("Width: %*d \n", 15, 140);
printf ("%s \n", "Educative");
return 0;
}

RELATED TAGS

c
stdout
cstring
formatting
output
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?