Lab 3 Input and Output Operations
Lab 3 Input and Output Operations
Input means to provide the computer program with some data to be used in the program and
Output means to display data on screen or write the data to a printer or a file.
C programming language provides many built-in functions to read any given input and to display
data on screen when there is a need to output the result.
In this session, we will learn about such functions, which can be used in our program to take
input from user and to output the result on screen.
All these built-in functions are present in C header files, we will also specify the name of header
files in which a particular function is defined while discussing about it.
The standard input-output header file, named stdio.h contains the definition of the functions
printf() and scanf(), which are used to display output on screen and to take input from user
respectively.
#include<stdio.h>
void main()
{
// defining a variable
int i;
/*
displaying message on the screen
asking the user to input a value
*/
printf("Please enter a value...");
/*
reading the value entered by the user
*/
scanf("%d", &i);
/*
displaying the number as output
*/
printf( "\nYou entered: %d", i);
}
When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered on screen.
You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It
is known as format string and this informs the scanf() function, what type of input to expect.
In printf()function it is used to give a heads up to the compiler, what type of output to
expect.
Format String Meaning
%d Scan or print an integer as signed decimal number
%f Scan or print a floating point number
%c To scan or print a character
%s To scan or print a character string. The scanning ends at whitespace.
We can also limit the number of digits or characters that can be input or output, by adding a
number with the format string specifier, like "%1d" or "%3s", the first one means a single
numeric digit and the second one means 3 characters, hence if you try to input 42, while scanf()
has "%1d", it will take only 4 as input. Same is the case for output.
Input a string:
#include <stdio.h>
void main(){
char str[100];
scanf("%s", str);
Here we first declare the string variable str as a character data type. Then in scanf we use the
format string specifier to read the input string a store it in the variable str.
char str[100];
scanf("%[^\n]s",str);
Here, [ ] is the scanset character. ^\n tells to take input until newline doesn’t get encountered.
In C Language, computer monitor, printer etc output devices are treated as files and the same
process is followed to write output to these devices as would have been followed to write the
output to a file.