Read values in C- scanf() function

Preview

Read values in C- scanf() function

scanf() function() is used to read different types of values in C.

Syntax: scanf(“Control-string”, &arg1,&arg2,&arg3,……);

Control-string is the format to enter data. It has % sign followed by format specifier indicating the type of variable whose value is to be input .

&arg1,&arg2,&arg3,… refer to variables whose values is to be entered by user.



1. Input int data

Format Specifier: %d                                              

 Program to input int data
#include<stdio.h>
int main()
{
int n1;
printf(“Enter int value=”);
scanf(“%d”,&n1);
printf(“\n Value=%d”,n1);
return(0);
}
Output
Enter int value=20
Value=20
 

2. Input short data

Format Specifier: %hd                                                

Program to input short data
#include<stdio.h>
int main()
{
short m;
printf(“Enter short value=”);
scanf(“%hd”,&m);
printf(“\nValue=%hd”,m);
return(0);
}
Output
Enter short value=25
Value=25



3. Input long data

Format Specifier: %ld                                                 

Program to input long data
#include<stdio.h>
int main()
{
long k;
printf(“Enter long value=”);
scanf(“%ld”,&k);
printf(“\nValue=%ld”,k);
return(0);
}
Output
Enter a long value=1560
Value=1560
 



  
4. Input float data

Format Specifier: %f                                                      

Program to input float data
#include<stdio.h>
int main()
{
float no;
printf(“Enter float value =”);
scanf(“%f”,&no);
printf(“\nValue=%f”,no);
return(0);
}
Output
Enter float value=2.55
Value=2.55

5. Input long double data

Format Specifier: %lf

Program to input long double data
#include<stdio.h>
int main()
{
long double n1;
printf(“Enter long double value=”);
scanf(“%lf”,&n1);
printf(“Value=%lf”,n1);
return(0);
}
Output
Enter long double value=7015.544444
Value=7015.544444
 



6. Input char data

Format Specifier: %c                                                      

Program to input char type data
#include<stdio.h>
int main()
{
char choice;
printf(“\nEnter your choice(Y/N)”);
scanf(“%c”,&choice);
printf(“\nchoice=%c”,choice);
return(0);
}
Output
Enter your choice(Y/N)Y
choice=Y



7. Input string data

Format Specifier: %s                                                      

Program to input string data
#include<stdio.h>
void main()
{
char sname[20];
printf(“\nEnter name=”);
scanf(“%s”,sname);
printf(“\nsname=%s”,sname);
return(0);
}
Output
Enter name=Aman
sname=Aman

Best Books of C



Spread the love
Lesson tags: formatted input function in c, formatted input in c, get input in c, input values in c, input values using scanf, read values in c, read variables in c, scanf function
Back to: C Programming Language
Spread the love