Loading, please wait...

A to Z Full Forms and Acronyms

How to use printf() and scanf() functions in C Programming

Jun 24, 2021 function, scanf, printf, 8231 Views
you will learn about functions
  • printf() and scanf() functions are inbuilt library functions in C which are available in C library by default. These functions are declared and related macros are defined in “stdio.h” which is a header file.
  • We have to include “stdio.h” file to make use of this printf() and scanf() library functions.

  • C users these functions to write and read from I/O devices respectively.

printf() function:

  1. Printf() function is used to print the “character”, string, float, integer, octal, and hexadecimal values onto the output screen.

  2. We use printf() function with a %d format specifier to display the value of an integer variable.

  3. Similarly, %c is used to display character, %f for float variable, %s for a string variable, %f for double and %x hexadecimal variable.

  4. To generate a newline, we use “\n” in the C printf() statement.

How to display data using printf() function:-

An integer stored in a variable can be displayed on the screen by including a format specifier (%d) within a pair of quotes as shown below.

#include<stdio.h>
main()
{
int age=25;
printf(“%d”,age);
}

the above program does the following:

Declare a variable of type int.

Initialize age to 25 as an integer value specify %d a format specifier indicating that an integer is to be displayed by printf(). The data is stored in a variable called age.

It may be noted that printf() has 2 arguments separated by comma i.e. a format specifier written within quotes and the variable age. It may be further noted that both messages and format specifier can be included within the pair quotes as shown below printf(“the age of student=%d”, age); the above statement displays the following of students on the screen.

The age of st8udent=25

integer

%d

Float

%f

char

%c

 

scanf() function:

  • Scanf() function is used to read character, string, numeric data from keyboard

  • consider below example program where the user enters a character. This value is assigned to the variable “ch” and then displayed.

  • Then, the user enters a string and this value is assigned to the variable “str” and then displayed.

How to read data from the keyboard using scanf() function:

Similar to printf() function scanf() function also uses the %d %f %c and other format specifiers to specify the kind of data to be from the keyboard.

Int roll;

scanf(“%d”,&roll);

the above statement declares the variable roll of type int and reads the value of roll from the keyboard. It must be noted that & operator i.e. the address operator is prefixed to the variable roll. The reason for specifying & would be discussed later.

A to Z Full Forms and Acronyms