Scanf() Function


scanf() function

  1. Read data from the standard input device and store it in a variable
  2. Requires stdio.h header file used to read input from keyboard

Syntax

  scanf(“Format string”, &variable);

 

Format String                

Variable

int

   %d

float

     %f

char

     %c

string

     %s

 

Getting Single Input

  • scanf function is normally used in combination with printf function
  • When using scanf for input, it is best to first issue a prompt
  • Including printf prompt before scanf maximizes user-friendly input/output

                   printf (“Enter a number:”);


  • Waits for user input, then stores the input value in the memory space that was assigned to n

Getting Multiple same Inputs

printf(“Please enter your height and weight:”);

scanf(“%f%f”, &height, &weight);

 

Getting Multiple different Inputs

scanf(“%d %d %f”, &n1, &n2, &avg);       // will get different types of input

#include<stdio.h>    
int main(){    
int n;    
printf("enter a number:");    
scanf("%d",&n);    
printf("Cube of Number is: %d ",n*n*n);    
return 0;  

Output 

enter a number: 2
Cube of Number is: 16

Post a Comment

0 Comments

Close Menu