printf() and scanf() Functions in C

In C programming, printf() and scanf() are the most commonly used functions for performing input and output (I/O) operations. These functions are part of the Standard Input/Output Library (stdio.h), which needs to be included in your program to use them.


1. printf() Function

The printf() function is used to output (print) data to the standard output device, typically the console.

Syntax:

  • format_string: A string containing text and format specifiers.
  • argument_list: Values to be printed that correspond to the format specifiers.

Common Format Specifiers:

SpecifierMeaning
%dInteger
%fFloating-point number
%cSingle character
%sString (sequence of characters)
%lfDouble-precision floating-point
%x%XHexadecimal integer
%oOctal integer

Example:

Output:

Explanation:

  • %d: Prints an integer.
  • %.2f: Prints a floating-point number with 2 decimal places.
  • %c: Prints a single character.
  • %s: Prints a string.

2. scanf() Function

The scanf() function is used to get input from the user and store it in variables.

Syntax:

  • format_string: A string containing format specifiers.
  • variable_list: The addresses of the variables where the input will be stored.

Common Format Specifiers:

SpecifierMeaning
%dInteger
%fFloating-point number
%cSingle character
%sString (no need to use & with strings)
%lfDouble-precision floating-point

Example:

Output (Example of user input):

Explanation:

  • %d: Reads an integer.
  • %f: Reads a floating-point number.
  • %c: Reads a single character (space before %c is used to ignore any newline left in the buffer).
  • %s: Reads a string (does not require the & operator).

Important Points About printf() and scanf()

  1. Format Specifiers:
    • Make sure the format specifier matches the type of variable you are using, or the output/input may be incorrect.
    • Example: Use %d for integers, %f for floats, %s for strings, etc.
  2. Reading Input:
    • scanf() requires the address of the variable using the & operator, except for strings.
    • Always leave a space before %c in scanf() when reading a character after other inputs to handle newline characters left in the buffer.
  3. Handling Strings:
    • In scanf(), string input stops at the first whitespace character (space, tab, or newline).
    • To read multi-word strings, use gets() (deprecated) or fgets().
  4. Floating-Point Precision:
    • You can control the number of decimal places displayed using %.nf in printf() where n is the number of decimal places.
  5. Escape Sequences:
    • Use escape sequences in printf() to format the output:
      • \n: Newline
      • \t: Tab
      • \\: Backslash
      • %%: Prints a percent sign

Advanced Example Using printf() and scanf()

Output:


error: Content is protected !!
Open chat
1
Hi,how Can We Help You ?