Input Function In C

The function scanf( ) is used to take input from the user to perform the desired operation. It reads the data from the standard input device such as keyboard.

C Input Function for Integer

The following example illustrates the working of scanf( ) to take an integer type input from user :

#include <stdio.h>
int main( )
{
int x;
printf ( “ Enter a number : ” );
scanf ( “ % d ” , &x);
printf ( “ Entered Number = %d ” , x);
return 0;
}

Output

Enter a number: 5
Entered number = 5

Here, %d specifies that the input type is int i.e. integer type. The value of integer is stored in variable x.

Note: &x is used in the scanf( ) function to get the address of x.

 

C Input Function for Character

The following example illustrates the working of scanf( ) to take character type input from user :

#include <stdio.h>
int main( )
{
char ch;
printf ( “ Enter a character : ” );
scanf ( “ % c ” , &ch);
printf ( “ Entered character is %c ” , ch);
return 0;
}

Output

Enter a character: p
Entered character is p

 

C Input Function for Float/Double

The following example illustrates the working of scanf( ) to take float/double type input from user :

#include <stdio.h>
int main( )
{
float ft;
double db;
printf (“ Enter a number: ” );
scanf ( “ %f , &ft);
printf ( “ Enter another number : ”);
scanf ( “ %1f” , &db);

printf ( “ ft = %f \n ” , &ft );
printf ( “ db = %1f ” , &db );
return 0;

}

Output

Enter a number: 23.56
Enter another number: 41.899
ft = 23.560000
db = 41.890000

%f : To read float value.
%1f : To read double value.

 

Output Function In C

The function printf( ) is used to display output on the screen after the desired operation is performed.

 

C Output Function for Integer

The following example illustrates the working of printf( ) for an integer.

#include <stdio.h>
int main( )
{
int x = 5;
printf ( “ Entered Number = %d ” , x);
return 0;
}

Output

Entered Number = 5

 

C Output Function for Character

The following example illustrates the working of printf( ) for a character.

#include <stdio.h>
int main( )
{
char ch = ‘p’
printf ( “ Entered character is %c ” , ch);
return 0;
}

 

Output

Entered character is p

 

C Output Function for Float/Double

The following example illustrates the working of printf( ) for float/double.

#include <stdio.h>
int main( )
{
float ft = 23.560000;
double db = 41.890000;

printf ( “ ft = %f \n ” , &ft );
printf ( “ db = %1f ” , &db );
return 0;
}

Output :
ft = 23.560000
db = 41.890000

Leave a Reply

Your email address will not be published. Required fields are marked *