BIT104 SLM Library - SLM - Unit 04
BIT104 SLM Library - SLM - Unit 04
Structure:
4.1 Introduction
Objectives
4.2 Floating-point Numbers
4.3 The Data Type char
4.4 Type Conversion Expression
Implicit Type Conversion
Type Conversion in Assignment
The Type Cast Operator
4.5 Character Input and Output
The getchar() function
The putchar() function
4.6 Formatted Input and Output
4.7 Interactive Programming
4.8 Summary
4.9 Terminal Questions
4.10 Answers
4.11 Exercises
4.1 Introduction
In the previous unit, we discussed about the operators that the C
programming language supports. We also learnt how the operators are
used in C programs. In this unit, we will discuss about the data types that
are supported in C. We will also discuss about the Input/output operators
which make C the most efficient and powerful programming language.
A data type defines a set of values that a variable can store along with a set
of operations that can be performed on that variable. All C compilers
support four fundamental data types, namely integer (int), character (char),
floating point (float), and double-precision floating point (double). Like
integer data type, other data types also offer extended data types such as
long double or signed char.
An operator is a symbol that tells the computer to perform certain
mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables. They usually form a part of the mathematical
or logical expressions. C supports a rich set of operators. We have already
used several of them, such as =, +, -, *, / and %.
It is possible to combine operands of different data types in arithmetic
expressions. Such expressions are called mixed-mode arithmetic
expressions. If the operator is taking operands of different data types, then
they are converted to a common data types called the type conversions
rules. The process of converting one predefined type into another is called
type conversion. Type conversions are explicitly or implicitly carried out in C.
In C language, all input/output operations are carried out through function
calls such as printf and scanf. There exist several functions that have
become standard for input and output operation in C. These functions are
collectively known as the standard I/O library. In this unit, we will discuss
following common I/O functions: getchar(), putchar(), scanf() and printf().
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. These functions can be accessed within a
program by including the header file stdio.h. The file name stdio.h is
abbreviation for standard input-output header file.
Objectives:
After studying this unit, you should be able to:
discuss the concept of real (floating point) numbers and characters in C
transfer a character, numerical value and a string between the
computer and I/O devices
discuss the concept of type conversion
write programs using I/O functions to handle single character, numerical
values and strings
float: The keyword float is used to declare variable of float (real) type. Float
numbers are stored in four bytes (on all 16 bit and 32 bit machines), with 6
digits of precision. The range of floating point number is 3.4E-38 to 3.4E+38.
The floating point numbers stored in a float variable are called single-
precision numbers. We can declare a variable of float type as,
float f;
f is declared to be variable of float type
The modifiers of float type include double and long double. The modifiers
facilitate storage of higher range of floating point numbers.
double: We can use double when the range provided by float is not
sufficient. A double data type number are represented using 64 bits
(8 bytes) giving a precision of 14 digits. A double can range from 1.7E-308 to
1.7E+308. These are known as double precision numbers. We can declare a
variable of double type as,
double d;
d is declared to be variable of double type.
long double: A variable of long double type requires 10 bytes (80 bits) in
memory. A long double can range from 3.4E-4932 to 1.1E+4932. We can
declare a variable of long double type as,
long double f2;
f2 is declared to be a variable of long double type.
The table 4.1 shows all the allowed combinations of floating point numbers
and qualifiers and their size and range on a 16-bit machine and 32- bit
machine.
Table 4.1: Floating point numbers and qualifiers and their size and range
main()
{
/* …….DECLARATIONS……………………..*/
float x, p;
double y, q;
unsigned k;
/* ……………….DECLARATIONS AND ASSIGNMENTS………..*/
int m=54321;
long int n=1234567890;
/*…………..ASSIGNMENTS……………………*/
x = 1.234567890000;
y = 9.87654321;
k = 54321;
p=q=1.0;
/*…………….PRINTING………………….*/
printf(“m=%d\n”,m);
printf(“n=%ld\n”,n);
printf(“x=%.12lf\n”,x);
printf(“x=%f\n”,x);
printf(“y=%.12lf\n”,y);
printf(“y=%lf\n”,y);
printf(“k=%u p= %f q=%.12lf\n”,k,p,q);
}
Output
m = -11215
n = 1234567890
x = 1.234567880630
x = 1.234568
y = 9.876543210000
y = 9.876543
k = 54321 p = 1.000000 q= 1.000000000000
#include <math.h>
main()
{
float a,b,c,discriminant, root1, root2;
printf(“input the values of a,b and c\n”);
scanf (“%f %f %f”, &a, &b, &c);
discriminant = b * b – 4 * a *c;
if (discriminant<0)
printf(“roots are imaginary\n”);
else
{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf (“Root1 = %5.2f \n Root2 = %5.2f \n”, root1, root2);
}
}
Output:
input the values of a, b and c
2 4 -16
Root1 = 2.00
Root2 = -4.00
input the values of a, b and c
123
roots are imaginary
The signed char type consists of an area of 8-bits, 7 of which store a value,
and one bit is used to identify sign of the other 7-bits. If the sign of the 7-bits
is to be interpreted as an integer, the value is from -127 to 127 (-2^7 to
+2^7). A variable of signed character type can be declared as,
signed char char1;
or
char char1;
char1 is declared to be variable of signed char type.
A character constant is formed by enclosing the character within a pair of
single quote marks. So ‘a’, ‘.’ and ‘8’ are all valid examples of character
constants. Note that a character constant, which is a single character
enclosed in single quotes is different from a character string, which is any
number of characters enclosed in double quotes.
Every character in C programming is given an integer value to represent it.
That integer value is known as ASCII (American Standard Code for
Information Interchange) value of that character. For example: ASCII value
for char 'a' is 97. The format characters %c can be used in a printf
statement to display the value of a char variable at the terminal.
Example 4.1: Consider following statements:
char c=’a’; declare and assign char ‘a’ to variable c
printf(“%c”,c); // would display the character c on the screen
printf(“%d”,c); // would display the ASCII value of character ‘a’ i.e. 97
Note that with the format characters %d, the ASCII value of the character is
displayed. With the format character %c, the character is displayed.
Program 4.3: The following sample program illustrates the difference
between signed and unsigned char.
#include<stdio.h>
main()
{
signed char char1=255;
unsigned char char2=255;
printf("Signed char : %d\n",char1);
printf("Unsigned char : %d\n",char2);
}
output:
Signed char : -1
Unsigned char : 255
Example 4.6: The Table 4.3 shows some examples of casts and their
actions:
Table 4.3: Use of Casts
Example Action
X=(int) 8.5 8.5 is converted to integer by truncation.
A=(int) 21.3 / (int) 4.5 Evaluated as 21/4 and the result would be 5.
B=(double) sum/n Division is done in floating point mode.
Y= (int) (a+b) The result of a+b is converted to integer.
Z= (int) a+b a is converted to integer and then added to b.
P=cos(( double)x) Converts x to double before using it.
main()
{
/* Program to find average of two integers */
float avg;
int n=2,n1,n2;
printf(“enter any 2 numbers\n”);
scanf(“%d %d”,&n1,&n2);
avg=(n1+n2)/(float)n;
printf(“ their average is\n”,avg);
}
y = p + m;
y = p + (double)m;
However, the second statement is preferable. It will work the same way on
all machines and is more readable.
Self-Assessment Questions
5. In arithmetic expression, if the operands are of different data types, the
‘lower’ type is automatically converted to the ‘higher’ type before the
operation proceeds by c compiler. (True/False)
6. The value of the expression 22.0/10 is ________.
7. Casting can be used to round-off a given value. (True/False)
8. The value of the expression (int)11.35/(int)14.5 is ___________.
9. If the value of X is 35.2, then the value of the expression (int)(X+0.5); is
______________.
main( )
{
char ch ;
printf ( "\nPress any key to continue" ) ;
ch=getch( ) ; /* will not echo the character */
printf ( "\nType any character" ) ;
ch = getche( ) ; /* will echo the character typed */
printf ( "\nType any character" ) ;
ch=getchar( ) ; /* will echo character, must be followed by enter key */
}
Output:
Press any key to continue
Type any character B
Type any character W
Continue Y/N Y
Self-Assessment Questions:
10. getchar() function is a character output function. (True/False)
11. _________ function returns the character typed without echoing it on
the screen.
where arg1, arg2,…, argn are arguments that represent the individual input
variables (data item). The arguments specify the address of locations where
the data is stored.
control string (also known as format string) contains field specifications,
which direct the interpretation of input data. The control string consists of
format specifier, whitespace characters, and non-whitespace characters.
Whitespace Character: The function will read and ignore any whitespace
characters encountered before the next non-whitespace character
(whitespace characters include spaces, newline and tab characters).
Non-whitespace Character, Except Format Specifier (%): Are those
characters that are not either whitespace characters (blank, newline or tab)
or part of a format specifier (which begin with a % character). Non-
Whitespace characters are used to match the next non-white space
character of the input stream.
Format Specifier: A sequence formed by an initial percentage sign (%)
indicates a format specifier, which is used to specify the type and format of
the data to be retrieved from the stream and stored into the locations
pointed by the arguments. The general form field specifier is
%[optional width specifier][data type specifier]
The data-type specifier indicates the type of the corresponding argument in
the argument-list. Format specifiers commonly used in scanf function are
listed in table 4.4.
Example 4.9: To accept a value into variable number of int type, following
statement is used.
scanf ( "%d", &number) ;
Here %d is the format specifier for the int variable number.
Examples 4.10: Following scanf() statements is to accept a character into
the character type variable c:
scanf(“%c”,&c); // format specifier used is %c
Example 4.11: To read values into three variables i, f and c of type int, float
and char respectively, using a single scanf statement is as:
scanf(“%d%f%c”,&i,&f,&c);
Note, that the order of the format specifiers matches with that of the
arguments. The values entered must be delimited by spaces, tab or newline
characters.
Optional Width Specifier: The width specifier (suppose value n), a decimal
integer, controls the maximum number of characters to be read from the
current input field. Up to n characters are read, converted, and stored in the
current address argument. If the input field contains fewer than n characters,
the scanf function reads all the characters in the field, and then proceeds
with the next field and format specifier.
Example 4.12: Consider the following example:
scanf(“%2d %4d”, &x,&y);
Consider the Input data: 10 8901
The value 10 is assigned to x and 89012 to y. suppose input data is as
follows:
8901 10
The value 89 will be assigned to variable x and 01 to y. The value 10 will
unread by this scanf call and will be assigned to the first variable in the next
scanf call. This kind of error can be eliminated if we use the field specifiers
without field width specifications. That is, the statement
scan(“%d”,%d”, &x,&y);
Example 4.13: An example of a format string is
"%7d%s %c%lf"
The above format string scans the first seven characters as a decimal
integer, then reads the remaining as a string until a space, new line or tab is
found. It then scans the character input and finally a double-precision
floating-point number.
The return value of scanf() is the number of variables that were successfully
assigned values. For example, the statement
scanf(“%d %f %s”, &a, name, &b);
will return the value 3 if the input data is:
8 9.0 Programming
and will return the value 1 if the input data is:
8 Programming 9.0
This is because the function would encounter a string when it was expecting
a floating-point value.
#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);
}
Formatted Output
The printf() function is used to display data to the standard output device
(screen), according to format specifiers and other arguments passed to
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. Control string consists of the
following three items.
1. Format specifiers – Conversion specification that begins with % sign
2. Sequence of characters, which will be displayed on the screen as they
are.
3. Escape sequence characters that begins with \ sign, for example \n, \t
and \b etc.
Example 4.15:
To display the value of variable n of int type, the following statement is used.
printf(“%d”,n);
Here %d is the format specifier for the int variable n.
Example 4.16: Below are some more examples for printf
printf("Hello, world! ");
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.
The %d and %f used in the printf() are called format specifiers. There are
quite a number of format specifiers for printf(). Some of them are listed in
Table 4.5.
Table 4.5: Format specifiers for printf().
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.)
Program 4.7: Program to illustrate formatting of output with printf
function
#include<stdio.h>
main()
{
int a,b;
float c,d;
b=7;
printf("%d\n",b);
printf("%3d\n",b);
printf("%03d\n",b);
c = 15.3;
d = c / 3;
printf("%3.2f\n",d);
}
Output:
7
7
007
5.10
As we can see in the first printf statement we print a decimal. In the second
printf statement we print the same decimal, but we use a width (%3d) to say
that we want three digits (positions) reserved for the output with right
justification. The result is that two “space characters” are placed before
printing the character. In the third printf statement what we say is almost
similar to the previous one. It prints the output with a width of three digits,
but fills the space with 0. In the fourth printf statement we want to print a
float. In this printf statement we want to print three positions before the
decimal point (called width) and two positions behind the decimal point
(called precision).
We have to be careful when calling printf(). It has no way of knowing how
many arguments we have 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, often
printing useless numbers or (even worse) numbers which mislead into
thinking that some other part of program is broken.
Escape Sequence: Escape sequence is used to display non-printing and
hard-to-print characters. In general, these characters control how the text is
positioned on the screen, for example, newlines and tabs.
Table 4.6 shows the common escape sequences and the corresponding
special characters:
#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: “);
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);
}
Self-Assessment Questions:
12. The control string used to read a hexadecimal character is
_______________.
13. scanf() functions needs address of the data item to be read as the
argument. (True/False)
14. The output of the following statement is ________________.
printf("%d %o %x\n", 64, 10, 75);
15. To print an int argument in octal, we can use ____________ format
string.
4.8 Summary
Let us recapitulate important points discussed in this unit:
Float numbers defined using float keyword, are stored in 32 bit (on all 16
bit and 32 bit machines), with 6 digits of precision.
When the accuracy provided by a float number is not sufficient, the type
double or long double can be used to define the real number.
Characters are usually stored in 8 bits (one byte) of internal storage.
The qualifier signed or unsigned may be explicitly applied to char.
The process of converting one predefined type into another is called
type conversion. Type conversions are explicitly or implicitly carried out
in C.
There are instances when we want to force a type conversion in a way
that is different from the automatic conversion. That is, by using type
cast operator.
The getchar() and putchar() are the two functions used to read and write
single character form standare I/O device respectively.
The scanf() and printf() are the two formatted input/output functions
available in C language. These functions can use for characters,
numerical values and strings data types. They are useful function in
interactive program development using C.
4.10 Answers
Self Assessment Questions
1. 64
2. %c
3. b
4. signed
5. True
6. 2.2
7. True
8. 0
9. 35
10. False
11. getch()
12. %x
13. True
14. 64, 12, 4B
15. %o
Terminal Questions
1. a) invalid, because % can be used only with integers.
b) valid, answer is 3
c) valid, answer is 1
d) valid, answer is 10.25
(For more details, refer to section 4.2)
2. Errors in the following statements
i) Float x;
Can be written as
float x;
ii) double = p, q
Can be written as
double p,q;
iii) exponent alpha, beta;
There is no data type exponent in C.
iv) m,n,z:INTEGER
Can be written as
int m,n,z;
v) long int m; count;
Can be written as
long int m,count;
vi) long float temp;
There is no data type long float in C
(For more details, refer to section 4.2)
3. 107
4. The unsigned char type consists of an area of 8-bits used by the CPU to
store unsigned bits. The qualifier unsigned is applied to char. (Refer
section 4.3 for more details)
5. The commonly used formatted input/output functions in C are: scanf()
and printf(). These functions can be accessed within a program by
including the header file stdio.h.(Refer section 4.6 for more details)
6. getchar() function is used to accept a single character from the keyboard
and putchar() function is used to display single character on the users
screen. (Refer section 4.5 for more details)
7. By using control string %[…]. (For more details, refer to section 4.6)
8. Format specifier used for printf function is %d, %c… (Refer section 4.6
for more details)
Sikkim Manipal University B2074 Page No.: 93
Principles of C Programming Unit 4
4.11 Exercises
1. Represent the following numbers using scientific notation:
a) 0.001 b) -1.5
2. Represent the following scientific numbers into decimal notation:
a) 1.0E+2 b) 0.001E-2
3. What is short char? Explain.
4. Distinguish between float and double data types.
5. Given the length of a side, write a C program to compute surface area
and volume of a cube.
6. Write a program to read value of a and b, and print the result of the
following expressions.
i. (a+b)(a-b) ii. a*a + 2*a*b + b*b
7. Write a program to read the following numbers , round them off to the
nearest integers and print out the results in integer form:
i. 45.2 ii. 80.30 iii. -15.30 iv. -44.90