0% found this document useful (0 votes)
35 views26 pages

BIT104 SLM Library - SLM - Unit 04

Uploaded by

pavanmay227597
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views26 pages

BIT104 SLM Library - SLM - Unit 04

Uploaded by

pavanmay227597
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Principles of C Programming Unit 4

Unit 4 Data Types and Input/Output Operators

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

Sikkim Manipal University B2074 Page No.: 69


Principles of C Programming Unit 4

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

4.2 Floating-point Numbers


All numeric data item with fractional part belong to floating (real) type.

Sikkim Manipal University B2074 Page No.: 70


Principles of C Programming Unit 4

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

Type Size (bits) Range


Float 32 3.4E-38 to 3.4E+38
Double 64 1.7E-308 to 1.7E+308
long double 80 3.4E-4932 to 1.1E+4932

Sikkim Manipal University B2074 Page No.: 71


Principles of C Programming Unit 4

Program 4.1: The following program illustrates typical declarations,


assignments and values stored in various types of variables.

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

Sikkim Manipal University B2074 Page No.: 72


Principles of C Programming Unit 4

Program 4.2: Program to compute the roots of a quadratic equation

#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

4.3 The data type char


A single character used in the program is called the character type. The
keyword char is used to denote character type data. The size of char type is
one byte. The qualifier signed or unsigned may be explicitly applied to char.
The unsigned char type consists of an area of 8-bits used by the CPU to
store unsigned bits. This means that if the content of the 8-bits is to be
interpreted as an integer, unsigned chars have values between 0 and 255
(2^8). A variable of unsigned character type can be declare as,
unsigned char char1;
char1 is declared to be variable of unsigned char type

Sikkim Manipal University B2074 Page No.: 73


Principles of C Programming Unit 4

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

Sikkim Manipal University B2074 Page No.: 74


Principles of C Programming Unit 4

Self Assessment Questions


1. A double data type represented using __________ bits.
2. ________is the format character to display the value of a char variable.
3. The output of the following C statement is _____________.
printf(“%c”, 98);
4. The _______ chars have values from -128 to 127.

4.4 Type Conversion Expressions


When variables and constants of different types are combined in an
expression, they are converted to same data type. The process of
converting one predefined type into another is called type conversion. Type
conversions are explicitly or implicitly carried out in C.
4.4.1 Implicit Type Conversion in Expressions
When the type conversion is performed automatically by the compiler
without programmer intervention, such type of conversion is known as
implicit type conversion or type promotion. The compiler converts all
operands into the data type of the largest operand.
In type conversion, the data type is promoted from lower to higher because
converting higher to lower involves loss of precision and value.
In Implicit type conversion, C follows some general rules that are listed
below:
1. Integer types are lower than floating point types
2. Signed types are lower than unsigned types
3. Short whole number types are lower than longer types
4. Here is the type hierarchy of data type.
long double (Highest data type)
double
float
unsigned long
long
int
short
char (the lowest data type)

Sikkim Manipal University B2074 Page No.: 75


Principles of C Programming Unit 4

While Programming consider the following points:


1. An arithmetic operation between an integer and integer always yields an
integer result.
2. An operation between a float and float always yields a float result
3. An operation between an integer and float always yields a float result. In
this operation the integer is first promoted to a float and then the
operation is performed. The net result is a float.
4. If the expression contains one operand as double data type and another
operand as some other lower data type then the other operand is also
converted to double and the result will be double.
5. If the expression contains long and unsigned integer data types, the
unsigned integer is converted to unsigned long and the result will be
unsigned long.
6. Character and short data are promoted to integer.
7. Unsigned char and unsigned short are converted to unsigned integer.
Example 4.2: Table 4.2 shows examples, how above rules work with
different types of data.
Table 4.2: Examples of implicit conversion

Operation Result Operation Result


5/2 2 2/5 0
5.0 / 2 2.5 2.0 / 5 0.4
5 / 2.0 2.5 2 / 5.0 0.4
5.0 / 2.0 2.5 2.0 / 5.0 0.4

4.4.2 Type Conversion in Assignment


It may so happen that the type of the expression and the type of the variable
on the left-hand side of the assignment operator may not be same. In such
a case the value of the expression is promoted or demoted depending on
the type of the variable on left-hand side of =. However, the following
changes are introduced during the final assignment:
1. float to int causes truncation of the fractional part.
2. double to float causes rounding of digits.
3. long int to int causes dropping of the excess higher order bits

Sikkim Manipal University B2074 Page No.: 76


Principles of C Programming Unit 4

Example 4.3: consider the following assignment statement


int a;
float b;
a=5.5;
b=100;
In the first statement a=5.5; a is declared as int so the float value 5.5 cannot
be stored in a. In such a case float is demoted to an int and then its value is
stored. Hence 5 is stored in a.
In the second statement b=100; since b is a float variable 100 is promoted
to 100.000000 and then stored in b.
Example 4.4: Consider the following statement
float x,y,z, y, z;
int result;
result=x*y*z/100+32/8-3*1.5;
In the above statement some operands are ints where as others are floats.
During evaluation of the expression the ints would be promoted to floats and
the result of the expression would be a float. But when this float value is
assigned to result, it is again demoted to an int and then stored in result.
4.4.3 Type Cast Operator
We can override automatic type conversion and explicitly cast variables to
be of a certain type when used in an expression.
Syntax is
(type-name) expression;
Type-name is any data type supported by C or any user-defined data type
and expression may be a single variable, constant or and expression itself.
Type casting does not change the actual value of the variable but the
resultant value may be put in temporary storage.
Example 4.5: Consider the following statements
int n;
float x;
x=(float)n;
The above statement will convert the value of n to a float value before
assigning to x. but n is not altered.
The cast operator has the same high precedence as other unary operators.

Sikkim Manipal University B2074 Page No.: 77


Principles of C Programming Unit 4

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.

Program 4.4: The following program shows the use of casts

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);
}

Casting can be used to round-off a given value. Consider the following


statement:
X= (int) (y+0.5);
If y is 37.7, y+0.5 is 38.2 and on casting, the result becomes 38, the value
that is assigned to X. Of course, the expression, being cast is not changed.
When combining two different types of variables in an expression, never
assume the rules of automatic conversion. It is always a good practice to
explicitly force the conversion. It is safer and more portable. For example,
when y and p are double and m is int, the following two statements are
equivalent.

Sikkim Manipal University B2074 Page No.: 78


Principles of C Programming Unit 4

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
______________.

4.5 Character Input and Output


In order to read a single character from standard input device or output
(display) a single character on standard output device, character Input
/Output (I/O) functions are used. The functions for character I/O in C are:
(i) getchar()
(ii) putchar()
4.5.1 The getchar() Function:
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. The function does not require any arguments, though a
pair of empty parentheses must follow the word getchar. It returns a single
character from a standard input device typically a keyboard.
The syntax of the getchar() function is written as
character variable= getchar()
where character variable refers to some previously declared character
variable.
Example 4.7:
char c;
c=getchar();

Sikkim Manipal University B2074 Page No.: 79


Principles of C Programming Unit 4

The first statement declares that c is a character-type variable. The second


statement causes a single character to be entered from the keyboard and
then assigned to c.
getchar() echoes the character that we typed on the screen, but requires
Enter key to be typed following the character that is typed. However, we
often want a function that will read a single character the instant it is typed
without waiting for the Enter key to be hit. getch() and getche() are two
functions which serve this purpose. These functions return the character
that has been most recently typed. The ‘e’ in getche() function means it
echoes (displays) the character that we typed to the screen. As against this
getch() just returns the character that we typed without echoing it on the
screen.
4.5.2 The putchar( ) Function:
We can display single character using the C library function putchar(). The
putchar() function, like getchar(), is a part of the standard C I/O library. It
transmits a single character to a standard output device (The standard
output is usually the user's screen).
The syntax of the putchar() function is:
putchar(character variable)
where character variable refers to some previously declared variable of
character type.
Example 4.8:
char c;
putchar(c);
The first statement declares that c is a character-type variable. The second
statement causes the current value of c to be transmitted to the user
monitor where it will be displayed.

Sikkim Manipal University B2074 Page No.: 80


Principles of C Programming Unit 4

Program 4.5: Sample program that illustrates the use of character


input functions.

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.

4.6 Formatted Input and Output


Formatted input refers to an input data that has been arranged in a
particular format. Input data can be entered into the computer from a
standard input device by means of the standard C library function scanf()
(scanf means scan formatted). This function is used to accept any
combination of numerical values, single character and strings. The function
returns the number of data items that have been entered successfully.
The syntax of scanf function is as follows:
scanf(“control string”, arg1, arg2, …argn);

Sikkim Manipal University B2074 Page No.: 81


Principles of C Programming Unit 4

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.

Sikkim Manipal University B2074 Page No.: 82


Principles of C Programming Unit 4

Table 4.4: Format Specifier for scanf()

Format Specifier Meaning


%c read a single character
%d read a decimal integer
%i read an integer
%e, %f, %g read a floating-point number
%o read an octal number
%s read a string
%x read a hexadecimal number
%p read a pointer
read an integer equal to the number of
%n
characters read so far
%u read an unsigned integer
%[…] read a string of words

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,

Sikkim Manipal University B2074 Page No.: 83


Principles of C Programming Unit 4

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.

Sikkim Manipal University B2074 Page No.: 84


Principles of C Programming Unit 4

Program 4.6: 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 address of the variable is 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.
An s-control 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. To do so, the s-control
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 4.14: To enter string consisting of uppercase and blank spaces
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 we
want to allow lowercase letters to be entered, all the lowercase letters
(i.e. from a-z) must be included in the list of control string.

Sikkim Manipal University B2074 Page No.: 85


Principles of C Programming Unit 4

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.

Sikkim Manipal University B2074 Page No.: 86


Principles of C Programming Unit 4

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().

%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 %

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;

Sikkim Manipal University B2074 Page No.: 87


Principles of C Programming Unit 4

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:

Sikkim Manipal University B2074 Page No.: 88


Principles of C Programming Unit 4

Table 4.6: Escape sequence

Special Character Escape Sequence


alert (beep) \a
Backslash \\
Backspace \b
carriage return \r
double quote \"
Form feed \f
horizontal tab \t
Newline \n
null character \0
single quote \'
vertical tab \v
question mark \?

Example 4.17: The following example shows usage of \n.


printf ( "Hello\nWorld" ) ;
output will be:
Hello
World
The \n character causes a new line to begin following ‘Hello’.

4.7 Interactive Programming


Interactive programming involves the dialog between the computer and the
user. These dialogs usually involve some form of question-answer
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.

Sikkim Manipal University B2074 Page No.: 89


Principles of C Programming Unit 4

Program 4.8: 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: “);
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.

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.

Sikkim Manipal University B2074 Page No.: 90


Principles of C Programming Unit 4

 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.9 Terminal Questions


1. Which of the following arithmetic expressions are valid? If valid, give the
value of the expression; otherwise give reason.
a) 7.5 % 3 b) 14 % 3 + 7 %2
c) 21 % (int) 4.5 d) 15.25 + - 5.0
2. Find errors, if any, in the following declaration statements:
Float x;
float letter, DIGIT;
double = p, q
exponent alpha, beta;
m,n,z:INTEGER
long int m; count;
long float temp;
3. What would be the value of x after execution of the following
statements?
int x, y = 10;
char z = ‘a’;
x = y + z;

Sikkim Manipal University B2074 Page No.: 91


Principles of C Programming Unit 4

4. What is unsigned char? Explain.


5. What are the commonly used formatted input/output functions in C?
How are they accessed?
6. Name and explain character I/O functions available in C.
7. When entering a string using scanf() function, how can a single string
which includes whitespace characters be entered?
8. List the format specifier used in the printf function.
9. A C program contains the following statements:
#include<stdio.h>
int i, j, k;
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.

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

Sikkim Manipal University B2074 Page No.: 92


Principles of C Programming Unit 4

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

9. a) scanf(“%d %d %d”, &i, &j, &k);


b) scanf(“%d %o %x”, &i, &j, &k);
c) scanf(“%x %x %o”, &i, &j, &k);
(Refer to section 4.6 for more detail)

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

Sikkim Manipal University B2074 Page No.: 94

You might also like