Friday 23 November 2012

Input and Output operators in C

Programming with C Unit 5

Unit 5 Input and Output operators
Structure
5.0 Introduction
5.1 Character Input and Output
Self Assessment Questions
5.2 Formatted input
Self Assessment Questions
5.3 Formatted output
Self Assessment Questions
5.4 The gets() and puts() functions
Self Assessment Questions
5.5 Interactive Programming
5.6 Conclusion
5.7 Terminal Questions
5.8 Answers for Self Assessment Questions
5.9 Answers for Terminal Questions
5.10 Exercises
5.0 Introduction
We have already seen that the C language is accompanied by some library
functions to handle input/output(I/O) operations. In this unit we will make use
of six I/O functions : getchar(), putchar(), scanf(), printf(), gets() and
puts(). These functions are used to transfer the information between the
computer and the standard input/output devices. Throughout this course we
assume that keyboard is the standard input device and the user screen is
the standard output device. The first two functions, getchar() and putchar(),
allow single character to be transferred into and out of the computer; the
functions scanf() and printf() permit the transfer of single character,
numerical values and strings; the functions gets() and puts() facilitate the
Programming with C Unit 5
Sikkim Manipal University Page No. 64
input and output of strings. These functions can be accessed within a
program by including the header file stdio.h.
Objectives
At the end of this unit you will be able to understand:
· How to transfer a character between the computer and I/O devices
· How to transfer a numerical value and a string between the computer
and I/O devices
· How to write programs using I/O functions to handle single character,
numerical values and strings
5.1 Character Input and Output
The most basic way of reading input is by calling the function getchar().
getchar() reads one character from the “standard input,'' which is usually
the user's keyboard. getchar() returns (rather obviously) the character it
reads, or, if there are no more characters available, the special value EOF
(“end of file''). This value will be assigned within the stdio.h file. Typically,
EOF will be assigned the value 1,
but this may vary from one compiler to
another.
The syntax of the getchar() function is written as
character variable= getchar()
where character variable refers to some previously declared character
variable.
Example:
char c;

c=getchar();
Programming with C Unit 5
Sikkim Manipal University Page No. 65
The first statement declares that c is a charactertype
variable. The second
statement causes a single character to be entered from the keyboard and
then assign to c.
A companion function is putchar(), which writes one character to the
“standard output.'' (The standard output is usually the user's screen).
The syntax of the putchar() function is written as
putchar(character variable)
where character variable refers to some previously declared character
variable.
Example:
char c;

putchar(c);
The first statement declares that c is a charactertype
variable. The second
statement causes the current value of c to be transmitted to the user monitor
where it will be displayed.
Using these two functions, we can write a very basic program to copy the
input, a character at a time, to the output:
Program 5.1: Program to copy the input, a character at a time, to the
output
#include <stdio.h>
/* copy input to output */
main()
{
int c;
c = getchar();
while(c != EOF)
Programming with C Unit 5
Sikkim Manipal University Page No. 66
{
putchar(c);
c = getchar();
}
return 0;
}
Execute the above program and observe the result.
It reads one character, and if it is not the EOF code, enters a while loop,
printing one character and reading another, as long as the character read is
not EOF. A char variable could hold integers corresponding to character set
values, and that an int could hold integers of more arbitrary values(from 32768
to + 32767). Since most character sets contain a few hundred
characters (nowhere near 32767), an int variable can in general comfortably
hold all char values, and then some. Therefore, there's nothing wrong with
declaring c as an int. But in fact, it's important to do so, because getchar()
can return every character value, plus that special, noncharacter
value EOF,
indicating that there are no more characters. Type char is only guaranteed
to be able to hold all the character values; it is not guaranteed to be able to
hold EOF value without possibly mixing it up with some actual character
value. Therefore, you should always remember to use an int for anything
you assign getchar()'s return value to.
When you run the character copying program, and it begins copying its input
(you’re typing) to its output (your screen), you may find yourself wondering
how to stop it. It stops when it receives endoffile
(EOF), but how do you
send EOF? The answer depends on what kind of computer you're using. On
Unix and Unixrelated
systems, it's almost always controlD.
On MSDOS
machines, it's controlZ
followed by the RETURN key.
Programming with C Unit 5
Sikkim Manipal University Page No. 67
(Note, too, that the character you type to generate an endoffile
condition
from the keyboard is not the same as the special EOF value returned by
getchar(). The EOF value returned by getchar() is a code indicating that
the input system has detected an endoffile
condition, whether it's reading
the keyboard or a file or a magnetic tape or a network connection or
anything else. In a disk file, at least, there is not likely to be any character in
the file corresponding to EOF; as far as your program is concerned, EOF
indicates the absence of any more characters to read.)
Another excellent thing to know when doing any kind of programming is how
to terminate a runaway program. If a program is running forever waiting for
input, you can usually stop it by sending it an endoffile,
as above, but if it's
running forever not waiting for something, you'll have to take more drastic
measures. Under Unix, controlC
(or, occasionally, the DELETE key) will
terminate the current program, almost no matter what. Under MSDOS,
controlC
or controlBREAK
will sometimes terminate the current program.
Self Assessment Questions
i) State true or false:
getchar() function is an output function.
ii) In order to stop reading the input character, you can use a value
called __________________.
5.2 Formatted Input
Input data can be entered into the computer from a standard input device by
means of the standard C library function scanf(). This function can be used
to enter any combination of numerical values, single character and strings.
The function returns the number of data items that have been entered
successfully.
Programming with C Unit 5
Sikkim Manipal University Page No. 68
The syntax of scanf function is as follows:
scanf(control string, arg1, arg2, …argn)
where control string refers to a string containing certain required formatting
information, and arg1, arg2,…, argn are arguments that represent the
individual input data items. The arguments represent pointers that indicate
addresses of the data items within the computer’s memory.
The control string consists of control characters, whitespace characters, and
nonwhitespace
characters. The control characters are preceded by a %
sign, and are listed in Table 5.1
Control Character Explanation
%c a single character
%d a decimal integer
%i an integer
%e, %f, %g a floatingpoint
number
%o an octal number
%s a string
%x a hexadecimal number
%p a pointer
%n an integer equal to the number of characters read so far
%u an unsigned integer
%[] a set of characters
%% a percent sign
Table 5.1
scanf() reads the input, matching the characters from format. When a
control character is read, it puts the value in the next variable. Whitespaces
Programming with C Unit 5
Sikkim Manipal University Page No. 69
(tabs, spaces, etc) are skipped. Nonwhitespace
characters are matched to
the input, then discarded. If a number comes between the % sign and the
control character, then only that many characters will be entered into the
variable. If scanf() encounters a set of characters, denoted by the %[]
control character, then any characters found within the brackets are read
into the variable. The return value of scanf() is the number of variables that
were successfully assigned values, or EOF if there is an error.
Program 5.2: Program to use scanf() to read integers, floats,
characters and strings from the user.
#include<stdio.h>
main()
{
int i;
float f;
char c;
char str[10];
scanf(“%d %f %c %s”, &i, &f, &c, str);
printf(“%d %f %c %s”, i, f, c, str);
}
Execute this program and observe the result.
Note that for a scanf() function, the addresses of the variable are used as
the arguments for an int, float and a char type variable. But this is not true
for a string variable because a string name itself refers to the address of a
string variable.
A scontrol
character is used to enter strings to string variables. A string
that includes whitespace characters can not be entered. There are ways to
work with strings that include whitespace characters. One way is to use the
Programming with C Unit 5
Sikkim Manipal University Page No. 70
getchar() function within a loop. Another way is to use gets() function which
will be discussed later.
It is also possible to use the scanf() function to enter such strings. To do so,
the scontrol
character must be replaced by a sequence of characters
enclosed in square brackets, designated as […]. Whitespace characters
may be included within the brackets, thus accommodating strings that
contain such characters.
Example:
#include<stdio.h>
main()
{
char str[80];

scanf(“%[ ABCDEFGHIJKLMNOPQRST]”, str);

}
This example illustrates the use of the scanf() function to enter a string
consisting of uppercase letters and blank spaces. Please note that if you
want to allow lowercase letters to be entered, all the lowercase letters( i.e
from az)
must be included in the list of control string.
Self Assessment Questions
i) What are the different characters included in a control string?
ii) The control string used to read a hexadecimal character is –
iii) State true or false.
scanf() functions needs address of the data item to be read as the
argument.
Programming with C Unit 5
Sikkim Manipal University Page No. 71
5.3 Formatted Output
Output data can be written from the computer onto a standard output device
using the library function printf(). This function can be used to output any
combination of numerical values, single characters and strings. It is similar
to the input function scanf(), except that its purpose is to display data rather
than enter into the computer.
The syntax of the printf function can be written as follows:
printf(control string, arg1, arg2, …, argn)
where control string refers to a string that contains formatting information,
and arg1, arg2, …, argn are arguments that represent the individual output
data items. The arguments can be written as constants, single variable or
array names, or more complex expressions.
Examples:
printf("Hello, world!\n");
printf("i is %d\n", i);
printf(“%d”, 10);
printf(“%d”, i+j);
The first statement simply displays the string given as argument to the
printf() function. In the second statement, printf() function replaces the two
characters %d with the value of the variable i. In the third statement the
argument to be printed is a constant and in the fourth, the argument is an
expression.
Programming with C Unit 5
Sikkim Manipal University Page No. 72
There are quite a number of format specifiers for printf(). Some of them are
listed in Table 5.2.
%d Print an int argument in decimal
%ld print a long int argument in decimal
%c print a character
%s print a string
%f print a float or double argument
%e same as %f, but use exponential notation
%g use %e or %f, whichever is better
%o print an int argument in octal (base 8)
%x print an int argument in hexadecimal (base 16)
%% print a single %
Table 5.2
It is also possible to specify the width and precision of numbers and strings
as they are inserted ; For example, a notation like %3d means to print an
int in a field at least 3 spaces wide; a notation like %5.2f means to print a
float or double in a field at least 5 spaces wide, with two places to the right
of the decimal.)
To illustrate with a few more examples: the call
printf("%c %d %f %e %s %d%%\n", '3', 4, 3.24, 66000000, "nine", 8);
would print
3 4 3.240000 6.600000e+07 nine 8%
The call
printf("%d %o %x\n", 100, 100, 100);
would print
100 144 64
Successive calls to printf() just build up the output a piece at a time, so the
calls
printf("Hello, ");
printf("world!\n");
would also print Hello, world! (on one line of output).
Programming with C Unit 5
Sikkim Manipal University Page No. 73
Earlier we learned that C represents characters internally as small integers
corresponding to the characters' values in the machine's character set
(typically ASCII). This means that there isn't really much difference between
a character and an integer in C; most of the difference is in whether we
choose to interpret an integer as an integer or a character. printf is one
place where we get to make that choice: %d prints an integer value as a
string of digits representing its decimal value, while %c prints the character
corresponding to a character set value. So the lines
char c = 'A';
int i = 97;
printf("c = %c, i = %d\n", c, i);
would print c as the character A and i as the number 97. But if, on the other
hand, we called
printf("c = %d, i = %c\n", c, i);
we'd see the decimal value (printed by %d) of the character 'A', followed by
the character (whatever it is) which happens to have the decimal value 97.
You have to be careful when calling printf(). It has no way of knowing how
many arguments you've passed it or what their types are other than by
looking for the format specifiers in the format string. If there are more format
specifiers (that is, more % signs) than the arguments, or if the arguments
have the wrong types for the format specifiers, printf() can misbehave badly,
often printing nonsense numbers or (even worse) numbers which mislead
you into thinking that some other part of your program is broken.
Because of some automatic conversion rules which we haven't covered yet,
you have a small amount of latitude in the types of the expressions you pass
as arguments to printf(). The argument for %c may be of type char or int,
and the argument for %d may be of type char or int. The string argument
for %s may be a string constant, an array of characters, or a pointer to some
Programming with C Unit 5
Sikkim Manipal University Page No. 74
characters. Finally, the arguments corresponding to %e, %f, and %g may be
of types float or double. But other combinations do not work reliably: %d
will not print a long int or a float or a double; %ld will not print an
int; %e, %f, and %g will not print an int.
Self Assessment Questions
i) What is the output of the following statement:
printf("%d %o %x\n", 64, 10, 75);
ii) To print an int argument in octal, you can use ___ format string
iii) What is the output of the following program segment?
int a=97;
printf(“%c”, a);
5.4 The gets() and puts() functions
gets() and puts() functions facilitate the transfer of strings between the
computer and the standard input/output devices. Each of these functions
accepts a single argument. The argument must be a data item that
represents a string( an array of characters). The string may include
whitespace characters. In the case of gets(), the string will be entered from
the keyboard, and will terminate with a newline character(i.e. a string will
end when the user presses the RETURN key).
Example: Reading and writing a line of text.
#include<stdio.h>
main()
{
char line[80];
gets(line);
puts(line);
}
Programming with C Unit 5
Sikkim Manipal University Page No. 75
This program uses gets() and puts() functions rather than scanf() and
printf(), to transfer the line of text into and out of the computer.
Self Assessment Questions
i) State true or false:
gets() is a formatted input statement.
ii) The argument for a gets() and puts() functions are – variables
iii) State true or false.
Using gets() function, you can not include whitespace characters in
the input string.
5.5 Interactive Programming
Creating interactive dialog between the computer and the user is a modern
style of programming. These dialogs usually involve some form of questionanswer
interaction, where the computer asks the questions and the user
provides the answer, or vice versa.
In C, such dialogs can be created by alternate use of the scanf() and
printf() functions.
Program 5.3: Program to calculate the simple interest
#include<stdio.h>
main()
{
/* Sample interactive program*/
float principle, rate, time, interest;
printf(“ Please enter the principle amount: “);
scanf(“%f”, &principle);
printf(“ Please enter the rate of interest: “);
scanf(“%f”, &rate);
printf(“ Please enter the period of deposit: “);
Programming with C Unit 5
Sikkim Manipal University Page No. 76
scanf(“%f”, &time);
interest=principle*rate*time/100.0;
printf(“Principle=%7.2f\n”, principle);
printf(“Rate of interest=%5.2f\n”,rate);
printf(“Period of deposit=%5.2f\n”, time);
printf(“Interest=%7.2f\n”, interest);
}
Execute the above program and observe the result.
5.6 Conclusion
getchar(), putchar(), scanf(), printf(), gets() and puts() are the commonly
used input/output functions in C. These functions are used to transfer of
information between the computer and the standard input/output devices.
getchar() and putchar() are the two functions to read and write single
character. scanf() and printf() are the two formatted input/output functions.
These functions can handle characters, numerical values and strings as well.
gets() and puts() functions are used to handle strings. scanf(), printf(),
gets() and puts() functions are used in interactive programming.
5.7 Terminal Questions
1. What are the commonly used input/output functions in C? How are they
accessed?
2. Distinguish between getchar() and putchar() functions?
3. When entering a string using scanf() function, how can a single string
which includes whitespace characters be entered?
4. Distinguish between gets() and scanf() functions.
5. A C program contains the following statements:
#include<stdio.h>
int i, j, k;
Programming with C Unit 5
Sikkim Manipal University Page No. 77
Write an appropriate scanf() function to enter numerical values for i, j
and k assuming
a) The values for i, j and k will be decimal integers
b) The value for i will be a decimal integer, j an octal integer and k a
hexadecimal integer.
c) The values for i and j will be hexadecimal integers and k will be an
octal integer.
5.8 Answers to Self Assessment Questions
5.1 i) False
ii) EOF
5.2 i) The control string consists of control characters, whitespace
characters, and nonwhitespace
characters.
ii) %x
iii) true
5.3 i) 64, 12, 4B
ii) %o
iii) a
5.4 i) False
ii) String
iii) False
5.9 Answers for Terminal Questions
1. The commonly used input/output functions in C are : getchar(),
putchar(), scanf(), printf(), gets() and puts(). These functions can be
accessed within a program by including the header file stdio.h.
2. getchar() function is used to accept a single character from the
keyboard and putchar() function is used to display single character on
the user’s screen.
Programming with C Unit 5
Sikkim Manipal University Page No. 78
3. By using control string %[ ].
4. gets() is not the formatted input function but the scanf() function is a
formatted input function.
5. a) scanf(“%d %d %d”, &i, &j, &k);
b) scanf(“%d %o %x”, &i, &j, &k);
c) scanf(“%x %x %o”, &i, &j, &k);
5.10 Exercises
1. Write a program to print the factors of a given number.
2. Given the length of a side, write a C program to compute surface area
and volume of a cube.
3. Write a program to reverse a number and find sum of the digits.
4. Write a program to print the multiplication table for any given number.
5. Write a program to check whether a given number is palindrome.

No comments:

Post a Comment