scanf() Library Function with Examples
scanf()
is formatted input function which is used to read formatted data from standard input device and automatically converts numeric information to integers and floats. It is defined in stdio.h
.
scanf() Syntax
scanf(“format_string”, &var1, &var2, &var3, …, &varN);
& in above syntax is called address operator.
For Examples :
int a;
scanf("%d",&a);
reads the integer value and stores it to variable a.
And, similarlyint a;
float b;
scanf("%d%f", &a, &b);
reads integer and real or floating number and stores to a and b.
scanf() Examples
Example #1 : Reading Integer Value & Displaying
#include<stdio.h>
void main()
{
int a;
printf (“Enter value of a: ”);
scanf(“%d”, &a);
printf(“Inputted value of a = %d”, a);
}
Output of the above program is :
Enter value of a: 67↲ Inputted value of a = 67 Note: ↲ indicates enter is pressed.
Example #2 : Reading Integer and Floating Point Number & Displaying Them
#include<stdio.h>
void main()
{
int a;
float b;
printf (“Enter value of a and b: ”);
scanf(“%d%f”, &a, &b);
printf(“Value of a = %d \n Value of b = %f”, a, b);
}
Output of the above program is :
Enter value of a and b: 77↲ 45.5↲ Value of a = 67 Value of b = 45.500000 Note: ↲ indicates enter is pressed.