Ads

Scanf

- This function reads the data we provide on screen during execution of program.
Actually it reads data from standard input i.e stdin. Standard input is a stream which consist all the input values from keyboard.
- Its header file is same as printf i.e. stdio.h


Syntax:
scanf(“<list_of_format_specifers>”, <list_of_variables>);

scanf(“<formatspecifier1> <formatspecifier2>... <formatspecifier N>”, &<variable1>, &<variable2>, …. &<variable N>);

- Angled brackets are used for demonstration purpose only and should not be used in your c program
- Remember we have to indicate & (ampersand) before the variables in scanf function, when we say &x we are telling scanf() at which memory location should it store the value supplied by the user from keyboard.


Program:

/* Capture a value from console, store it, and print it */ 

#include<stdio.h>
int main()
{
 int x;
 printf("\n Enter any integer value to store in x:");
 scanf("%d", &x);
 printf("\n The value stored in x is %d", x);

 return 0;
}

Output:

Enter any integer value to store in x:2
The value stored in x is 2


Program:

/* Take a character value from console and print it.*/ 

#include<stdio.h>
int main()
{
 char x;
 printf("\n Enter any character value to store in x: ");
 scanf("%c", &x);
 printf("\n The value stored in x is %c", x);

 return 0;
}

Output:

Enter any character value to store in x: a
The value stored in x is a



Program:



/* Take any float value from console and print it.*/

#include<stdio.h>
int main()
{
 float x;
 printf("\n Enter any float value to store in x: ");
 scanf("%f", &x);
 printf("\n The value stored in x is %f", x);

 return 0;
}




Output:

Enter any float value to store in x: 8.9
The value stored in x is 8.90000


Program:


/* A Program to know ascii value of a character */

#include<stdio.h>
int main()
{
 char x;
 x='a';
 printf("\nThe ascii value of the character present in memory x is %d",x);
 printf("\n Ascii value of 'a' is %d",'a');

 return 0;
}


Output:

The ascii value of the character present in memory x is 97
Ascii value of 'a' is 97

Program:

/* A Program to know ascii value of a character; Character is fed during execution */

#include<stdio.h>
int main()
{
 char x;
 printf(" \n Enter the character of which you want to know the ascii value : ");
 scanf("%c",&x);
 printf(" \nThe ascii value of the character '%c' is %d\n",x,x);

 return 0;
} 

Output:

Enter the character, of which you want to know the ascii value : a
The ascii value of the character 'a' is 97


No comments:

Post a Comment