Before performing input and output in C programs let us first understand the concept from scratch. This section deals with the basic understanding of the streams involved in accepting input and printing output in C programs.
INPUT/OUTPUT
STATEMENTS IN C
Before
performing input and output in C programs let us first understand the concept
from scratch. This section deals with the basic understanding of the streams
involved in accepting input and printing output in C programs.
A
stream acts in two ways. It is the source of data as well as the destination of
data. Streams are associated with a physical device such as a monitor or with a
file stored on the secondary memory. C uses two forms of streams-text and
binary, as shown in Figure 2.11.
In
a text stream, sequence of characters is divided into lines with each line
being terminated with a new- line character (\n). On the other hand, a binary
stream contains data values using their memory representation.
We
can do input/output from the keyboard/monitor or from any file but in this
chapter we will assume that the source of data is the keyboard and destination
of the data is the monitor (Figure 2.12). File handling, i.e., handling input
and output via C programs, will be discussed later as a separate chapter.
C
language supports two formatting functions printf
and scanf. printf is used to
convert data stored in the program into a text stream for output to the
monitor, and scanf is used to convert the text stream coming from the keyboard
to data values and stores them in program variables. In this section, we will
discuss these functions.
Background
The
most fundamental operation in a C program is to accept input values from a
standard input device (keyboard) and output the data produced by the program to
a standard output device (monitor). So far we had been assigning values to
variables using the assignment operator =. For example,
int a = 3;
But
what if we want to assign value to variable that is inputted by the user at
run-time. This is done by using the scanf
function that reads data from the keyboard. Similarly, for outputting results
of the program, printf function is
used that sends results to a terminal. Like printf
and scanf, there are different
functions in C that can carry out the input/output operations. These functions
are collectively known as Standard Input/Output
Library. A program that uses standard input/output functions must contain the
statement
#include <stdio.h>
at
the beginning of the program.
The printf function (stands for print
formatting) is used to display information required by the user and also prints
the values of the variables. For this, the printf function takes data values,
converts them to a text stream using formatting specifications in the control
string and passes the resulting text stream to the standard output. The control
string may contain zero or more conversion specifications, textual data, and
control characters to be displayed (Figure 2.13).
Each
data value to be formatted into the text stream is described using a separate
conversion specification in the control string. The specification in the
control string describes the data value's type, size and specific format
information as shown in Figure 2.13.
The
syntax of printf function can be
given as
printf ("control string",
variable list);
The
function accepts two parameters-control string and variable list. The control
string may also contain text to be printed like instructions to the user,
captions, identifiers, or any other text to make the output readable. In some printf statements you may find only a
text string that has to be displayed on screen (as seen in the first program in
this chapter). The control characters can also be included in the printf statement. These control
characters include \n, \t, \r, \a, etc.
After
the control string, the function can have as many additional arguments as
specified in the control string. The parameter control string in the printf() function is nothing but a C
string that contains the text that has to be written on to the standard output
device.
Note
that there must be enough arguments, otherwise the result will be completely
unpredictable. However, if by mistake you specify more number of arguments, the
excess arguments will simply be ignored. The prototype of the control string
can be given as below.
% [flags] [width] [.precision]
[length modifier] type specifier
Each
control string must begin with a % sign. The % character specifies how the next
variable in the list of variables has to be printed. After % sign follows:
Flags
is an optional argument which specifies output justification such as numerical
sign, trailing zeros or octal, decimal, or hexadecimal prefixes. Table 2.5
shows the different types of flags with their decription.
Note
that when data is shorter than the specified width then by default the data is
right justified. To left justify the data use minus sign (-) in the flags
field.
When
the data value to be printed is smaller than the width specified, then padding
is used to fill the unused spaces.
By
default, the data is padded with blank spaces. If zero is used in the flag
field then the data is padded with zeros. One thing to remember here is that
zero flag is ignored when used with left justification because adding zeros
after a number changes its value.
Width
is an optional argument which specifies the minimum number of positions in the
output. If data needs more space than specified, then printf overrides the width specified by the user. However, if the
number of output characters is smaller than the specified width, then the
output would be right justified with blank spaces to the left. Width is a very
important field especially when you have to align output in columns. However,
if the user does not mention any width then the output will take just enough
room for data.
Precision
is an optional argument which specifies the maximum number of characters to
print.
•
For integer specifiers (d, i, o, u, x, X):
precision flag specifies the minimum number of digits to be written.
However, if the value to be written is shorter than this number, the result is
padded with leading zeros. Otherwise, if the value is longer, it is not
truncated.
•
For character strings, precision specifies the maximum number of characters to
be printed.
•
For floating point numbers, the precision flag specifies the number of decimal
places to be printed.
Its
format can be given as .m, where m
specifies the number of decimal digits. When no precision modifier is
specified, printf prints six decimal
positions.
When
both width and precision fields are used, width must be large enough to contain
the integral value of the number, the decimal point and the number of digits
after the decimal point. Therefore, a conversion specification %7.3f means print a floating point value
of maximum 7 digits where 3 digits are allotted for the digits after the
decimal point.
Length modifiers
can be explained as given in Table 2.6
Type specifiers
are used to define the type and the interpretation of the value of the
corresponding argument (Table 2.7).
Note
that if the user specifies a wrong specifier then some strange things will be
seen on the screen and the error might propagate to other values in the printf() list. The most simple printf statement is
printf ("Welcome to the world
of C language");
When
executed, the function prompts the message enclosed in the quotation to be
displayed on the screen.
Note
The
minimum field width and precision specifiers are usually constants. However,
they may also be provided by arguments to printf(). This is done by using the *
modifier as shown in the printf statement below.
printf("%*.*f",
10, 4, 1234.34);
Here,
the minimum field width is 10, the precision is 4, and the value to be
displayed is 1234.34.
Examples
Programming Tip:
Not
placing a comma after the format string in a read or write statement is a
compiler error.
printf("\n Result:
%d%c%f", 12, 'a', 2.3);
Result:
12a2.3
printf("\n Result: %d %c
%f", 12, 'a', 2.3);
Result:
12 a 2.3
printf("\n Result:
%d\t%c\t%f", 12, 'a', 2.3);
Result:12
a 2.3
printf("\n Result:
%d\t%c\t%6.2f", 12, 'a', 245.37154);
Result:
12 a 245.37
printf("\n Result: %5d \t %x
\t %#x", 234, 234, 234);
Result:
234 EA OXEA
printf("\n The number is
%6d", 12);
The
number is 12
printf("\n The number is
%2d", 1234);
The
number is 1234
printf("\n The number is
%6d", 1234);
The
number is 1234
printf("\n The number is
%-6d", 1234);
The
number is 1234_ // 2 indicates 2_ white spaces
printf("\n The number is
%06d", 1234);
The
number is 001234
printf("\n The price of this
item is %09.2f rupees", 123.456);
The
price of this item is 000123.45 rupees
printf("\n This is \'so\'
beautiful");
This
is 'so' beautiful
printf("\n This is
\"so\" beautiful");
This
is "so" beautiful
printf("\n This is \\ so
beautiful ");
This
is \so beautiful
printf("\n a = |%-+7.2f| b = %0+7.2f
c = %-0+8.2f", 1.2, 1.2, 1.2);
a
= +1.20 b = 0001.20 c = 1.20
(Note
that in this example, - means left justify, + means display the sign, 7
specifies the width, and 2 specifies the precision.)
printf("\n %7.4f \n %7.2f \n
%-7.2f \n %f\n %10.2e \n %11.4e \n %-10.2e \n %e", 98.7654, 98.7654,
98.7654, 98.7654, 98.7654, 98.7654, 98.7654, 98.7654);
98.7654
98.77
98.77
98.7654
9.88e+01
9.8765e+01
9.88e+01
9.876540e+01
char ch = 'A';
printf("\n %c \n %3c \n
%5c", ch, ch, ch);
A
A
A
char
str[] = "Good Morning";
printf("\n
%s", str);
printf("\n
%20s", str);
printf("\n
%20.10s", str);
printf("\n
%.7s", str);
printf("\n
%-20.10s", str);
printf("\n
%7s", str);
Programming Tip:
Placing
an address operator with a vari- able in the printf statement will gener- ate a
run-time error.
Good
Morning
Good Morning
Good Morni
Good
Mo
Good
Morni
Good
Morning
(Note that
in the last printf statement the complete string "Good Morning" is
printed. This is because if data needs more space than specified, then printf
function overrides the width specified by the user.)
The
scanf() function stands for scan
formatting and is used to read formatted data from the keyboard. The scanf function takes a text stream from
the keyboard, extracts and formats data from the stream according to a format control
string and then stores the data in specified program variables. The syntax of
the scanf() function can be given as:
scanf ("control string",
arg1, arg2, arg3,…….argn);
The
control string specifies the type and format of the data that has to be
obtained from the keyboard and stored in the memory locations pointed by
arguments arg1, arg2,..., argn, i.e.,
the arguments are actually the variable addresses where each piece of data are
to be stored.
The
prototype of the control string can be give as:
% [*] [width] [modifier] type
Here*
is an optional argument that suppresses assignment of the input field, i.e., it
indicates that data should be read from the stream but ignored (not stored in
the memory location).
Width
is an optional argument that specifies the maximum number of characters to be
read. However, fewer characters will be read if the scanf function encounters a white space or an inconvertible
character because the moment scanf function
encounters a white space character it will stop processing further.
Modifier
is an optional argument that can be h, 1, or L for the data pointed by the
corresponding additional arguments. Modifier h is used for short int or unsigned short
int, 1 is used for long int, unsigned long int, or double values. Finally,
L is used for long double data values.
Type
specifies the type of data that has to be read. It also indicates how this data
is expected to be read from the user. The type specifiers for scanf function are same as given for printf() function in Table 2.7.
The scanf function ignores any blank
spaces, tabs, and newlines entered by the user. The function simply returns the
number of input fields successfully scanned and stored.
We
will not discuss functions in detial in this chapter. So understanding scanf function in depth will be a bit
difficult here, but for now just understand that the scanf function is used to store values in memory locations
associated with variables. For this, the function should have the address of
the variables. The address of the variable is denoted by an '&' sign
followed by the name of the variable.
Note
Whenever
data is read from the keyboard, there is always a return character from a
previous read operation. So we should always code at least one white space
character in the conversion specification in order to flush that whitespace
character. For example, to read two or more data values together in a single
scanf statement, we must insert a white space between two fields as shown
below: scanf("%d %c", &i, &ch);
Now
let us quickly summarize the rules to use a scanf
function in our C programs.
Rule 1:
The scanf function works until:
(a)
the maximum number of characters has been processed,
(b)
a white space character is encountered, or
(c)
an error is detected.
Rule 2:
Every variable that has to be processed must have a conversion specification
associated with it. Therefore, the following scanf statement will generate an error as num3 has no conversion
specification associated with it.
scanf("%d %d", &num1,
&num2, &num3);
Rule 3:
There must be a variable address for each conversion specification. Therefore,
the following scanf statement will
generate an error as no variable address is given for the third conversion
specification.
scanf("%d %d %d",
&num1, &num2);
Remember
that the ampersand operator (&)
before each variable name specifies the address of that variable name.
Rule 4:
An error would be generated if the format string is ended with a white space
character.
Rule 5:
The data entered by the user must match the character specified in the control
string (except white space or a conversion specification), otherwise an error
will be generated and scanf will stop
its processing. For example, consider the scanf
statement given below.
scanf("%d/%d", &num1,
&num2);
Here,
the slash in the control string is neither a white space character nor a part
of conversion specification, so the users must enter data of the form 21/46.
Rule 6:
Input data values must be separated by spaces.
Rule 7:
Any unread data value will be considered as a part of the data input in the
next call to scanf.
Rule 8:
When the field width specifier is used, it should be large enough to contain
the input data size.
Look
at the code given below that shows how we input values in variables of
different data types.
int num;
scanf("%d", &num);
The
scanf function reads an integer value
(because the type specifier is %d)
into the address or the memory location pointed by num.
float salary;
scanf("%f", salam
&salary);
The scanf function reads a floating point
number (because the type specifier is %f)
into the address or the memory location pointed by salary.
char ch;
scanf("%c", &ch);
The
scanf function reads a single
character (because the type specifier is %c)
into the address or the memory location pointed by ch.
char str[10]; scanf("%s",
str);
The
scanf function reads a string or a
sequence of characters (because the type specifier is %s) into the address or the memory location pointed by str. Note
that in case of reading strings, we do not use the & sign in the scanf function. This will be discussed
in the chapter on Strings.
Programming Tip:
A
compiler error will be generated if the read and write parameters are not
separated by commas.
Look
at the code given below which combines reading of variables of different data
types in one single statement
int num;
float fnum;
char ch;
char str[10];
scanf("%d %f %c %s",
&num, &fnum, &ch, str);
Look
at the scanf statement given below
for the same code. The statement ignores the character variable and does not
store it (as it is preceded by *).
scanf("%d %f %*c %s",
&num, &fnum, &ch, str);
Remember
that if an attempt is made to read a value that does not match the expected
data type, the scanf function will
not read any further and would immediately return the values read.
Look
at the codes given below that show how we output values of variables of
different data types.
int num;
scanf("%d", &num);
printf("%d", num);
The
printf function prints an integer
value (because the type specifier is %d)
pointed by num on the screen.
float salary;
scanf("%f", &salary);
printf(".2%f", salary);
The
printf function prints the floating
point number (because the type specifier is %f)
pointed by salary on the screen. Here, the control string specifies that only
two digits must be displayed after the decimal point.
Programming Tip: A float specifier cannot be used to read an integer value.
char ch;
scanf("%c", &ch);
printf("%c", ch);
The
printf function prints a single
character (because the type specifier is %c)
pointed by ch on the screen.
char str[10];
scanf("%s", str);
The
printf function prints a string or a
sequence of characters (because the type specifier is %s) pointed by str on the
screen.
scanf("%2d %5d",
&num1, &num2);
The
scanf statement will read two integer
numbers. The first integer number will have two digits while the second can
have maximum of 5 digits.
Look
at the code given below which combines printing all these variables of
different data types in one single statement.
int num;
float fnum;
char ch;
char str[10];
double dnum;
short snum;
long int lnum;
printf("\n Enter the values :
");
scanf("%d %f %c %s %e %hd
%ld", &num, &fnum, &ch, str, &dnum, &snum, &lnum);
printf("\n num = %d\n fnum = %.2f
\n ch = %c \n str %s\n dnum %e \n snum %hd \n lnum = %ld", num, fnum, ch,
str, dnum, snum, lnum);
Note
In
the printf statement, `\n', is called the newline character and is used to
print the succeeding text on the new line. The following output will be
generated on execution of the print function.
Enter the values
2 3456.443 a abcde 24.321E-2 1
12345678
num = 2
fnum = 3456.44
ch = a
str = abcde
dnum = 0.24321
snum = 1
lnum = 12345678
Remember
one thing that scanf terminates as
soon as it encounters a white space character so if you enter the string as abc def, then only abc is assigned to str.
1.
Find out the output of the following program.
#include <stdio.h>
int main()
{
int a, b;
printf("\n Enter two four
digit numbers: ");
scanf("%2d %4d", &a,
&b);
printf("\n The two numbers
are: %d and %d", a, b);
return 0;
}
Output
Enter two four digit numbers : 1234
5678
The two numbers are : 12 and 34
Programming Tip:
Using
an incorrect specifier for the data type being read or written will generate a
run-time error.
Here,
the variable a is assigned the value 12 because it is specified as %2d, so it
will accept only the first two digits. The rest of the number will be assigned
to b. The value 5678 that is unread will
be assigned to the first variable in the next call to the scanf function.
Note
The
%n specifier is used to assign the number of characters read till the point at
which the %n was encountered to the variable pointed to by the corresponding
argument. The code fragment given below illustrates its use.
int
count;
printf("Hello
%n World!", &count);
printf("%d",
count);
The
output would be-Hello World! 6 because 6 is the number of characters read
before the %n modifier.
2.
Write a program to demonstrate the use of printf statement to print values of
variables of different data types.
#include <stdio.h>
int main()
{
// Declare and initialize variables
int num = 7;
float amt = 123.45;
char code = 'A';
double pi = 3.1415926536;
long int population_of_india =
10000000000;
char msg [ ] "Hi=";
// Print the values of variables
printf("\n NUM %d\n AMT = %f
\n CODE = %c \n PI = %e \n POPULATION OF INDIA %ld \n MESSAGE = %s", num,
amt, code, pi, population_of_india, msg);
return 0;
}
Output
NUM = 7
AMT = 123.450000
CODE = A
PI = 3.141590e+00
POPULATION OF INDIA = 10000000000
MESSAGE = Hi
3.
Write a program to demonstrate the use of
printf and scanf statements to
read and print values of variables of different data types.
#include <stdio.h>
int main()
{
int num;
float amt;
char code;
double pi;
long int population_of_india;
char msg [10];
printf("\n Enter the value of
num : ");
scanf("%d", &num);
printf("\n Enter the value of
amt : ");
scanf("%f", &amt);
printf("\n Enter the value of
pi : ");
scanf("%e", &pi);
printf("\n Enter the
population of India : ");
scanf("%ld",
&population_of_india);
printf("\n Enter the value of
code : ");
scanf("%c", &code);
printf("\n Enter the message:
");
scanf("%s", msg);
printf("\n NUM = %d\n AMT = %f
\n PI = %e \n POPULATION OF INDIA = %ld\n CODE = %c \n MESSAGE = %s", num,
amt, pi, population_of_india, code, msg);
return 0;
}
Output
Enter the value of num : 5
Enter the value of amt : 123.45
Enter the value of pi : 3.14159
Enter the population of India :
12345
Enter the value of code : с
Enter the message : Hello
NUM = 5
AMT = 123.450000
PI = 3.141590e+00
POPULATION OF INDIA = 12345
CODE = c
MESSAGE = Hello
4.
Write a program to calculate the area of a triangle using Hero's formula.
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
float a, b, c, area, S;
printf("\n Enter the lengths
of the three sides of the triangle: ");
scanf("%f %f %f", &a,
&b, &c);
S = (a + b + c)/2;
// sqrt is a mathematical function
defined in math.h header file
area = sqrt (S* (S-a) * (S-b) *
(S-c)); printf("\n Area %f", area);
return 0;
}
Output
Enter the lengths of the three
sides of the triangle: 12 16 20
Area = 96
5.
Write a program to calculate the distance between two points.
#include <stdio.h>
#include <conio.h>
#include <math.h>
int main()
{
int x1, x2, y1, y2;
float distance;
printf("\n Enter the x and y
coordinates of the first point: ");
scanf("%d %d", &x1,
&y1);
printf("\n Enter the x and y
coordinates of the second point :");
scanf("%d %d", &x2,
&y2);
// sqrt and pow are mathematical functions
defined in math.h header file
distance = sqrt (pow((x2-x1),
2)+pow ((y2-yl), 2));
printf("\n Distance =
%f", distance);
return 0;
}
Output
Enter
the x and y coordinates of the first point: 2 5
Enter
the x and y coordinates of the second point: 3 7
Distance
= 2.236068
When
the scanf function completes reading all the data values, it returns number of
values that are successfully read. This return value can be used to determine
whether there was any error while reading the input. For example, the
statement,
scanf("%d %f %c", &a,
&b, &c);
will
return 3 if the user enters, say,
12 12.34 A
It
will return 1 if the user enters erroneous data like
12 ABC 12.34
Programming in C: Unit I (b): Introduction to C : Tag: : Syntax with Example C Programs - Input/Output Statements in C
Programming in C
CS3251 2nd Semester CSE Dept 2021 | Regulation | 2nd Semester CSE Dept 2021 Regulation