Data Structures Using C 2nd Edition A. K. Sharma Download
Data Structures Using C 2nd Edition A. K. Sharma Download
Sharma
pdf download
https://ebookname.com/product/data-structures-using-c-2nd-
edition-a-k-sharma/
Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...
https://ebookname.com/product/data-structures-with-c-using-
stl-2nd-edition-william-h-ford/
https://ebookname.com/product/c-data-structures-a-laboratory-
course-stefan-brandle/
https://ebookname.com/product/object-oriented-data-structures-
using-java-chip-weems/
https://ebookname.com/product/the-cyberspace-handbook-media-
practice-1st-edition-jason-whittaker/
https://ebookname.com/product/10-less-democracy-why-you-should-
trust-elites-a-little-more-and-the-masses-a-little-less-garett-
jones/
https://ebookname.com/product/modular-electricity-storage-
benefits-and-costs-1st-edition-brent-n-mendell/
https://ebookname.com/product/long-term-durability-of-structural-
materials-1st-edition-j-larsen-basse/
https://ebookname.com/product/international-law-and-post-
conflict-reconstruction-policy-1st-edition-matthew-saul-editor/
My Word Plagiarism and College Culture 1st Edition
Susan D. Blum
https://ebookname.com/product/my-word-plagiarism-and-college-
culture-1st-edition-susan-d-blum/
Data Structures Using C
This page is intentionally left blank.
Data Structures Using C
Second Edition
A. K. Sharma
Professor and Dean
YMCA University of Science and Technology
Delhi • Chennai
Copyright © 2013 Dorling Kindersley (India) Pvt. Ltd.
Licensees of Pearson Education in South Asia
No part of this eBook may be used or reproduced in any manner whatsoever without the publisher’s
prior written consent.
This eBook may or may not include all assets that were part of the print version. The publisher
reserves the right to remove any material in this eBook at any time.
ISBN 9788131792544
eISBN 9789332514225
Head Office: A-8(A), Sector 62, Knowledge Boulevard, 7th Floor, NOIDA 201 309, India
Registered Office: 11 Local Shopping Centre, Panchsheel Park, New Delhi 110 017, India
To
my parents,
wife Suman and daughter Sagun
This page is intentionally left blank.
Contents
Preface to the Second Edition xiii
Preface xiv
About the Author xv
Chapter 1: Overview of C 1
1.1 The History 1
1.2 Characters Used in C 2
1.3 Data Types 2
1.3.1 Integer Data Type (int) 2
1.3.2 Character Data Type (char) 3
1.3.3 The Floating Point (f loat) Data Type 3
1.4 C Tokens 4
1.4.1 Identifiers 4
1.4.2 Keywords 5
1.4.3 Variables 5
1.4.4 Constants 7
1.5 Structure of a C Program 8
1.5.1 Our First Program 8
1.6 printf() and scanf() Functions 8
1.6.1 How to Display Data Using printf() Function 9
1.6.2 How to Read Data from Keyboard Using scanf() 10
1.7 Comments 10
1.8 Escape Sequence (Backslash Character Constants) 11
1.9 Operators and Expressions 13
1.9.1 Arithmetic Operators 13
1.9.2 Relational and Logical Operators 14
1.9.3 Conditional Operator 16
1.9.4 Order of Evaluation of Expressions 17
1.9.5 Some Special Operators 18
1.9.6 Assignment Operator 18
1.9.7 Bitwise Shift Operators 19
1.10 Flow of Control 20
1.10.1 The Compound Statement 21
1.10.2 Selective Execution (Conditional Statements) 21
1.10.3 Repetitive Execution (Iterative Statements) 25
1.10.4 The exit() Function 27
1.10.5 Nested Loops 28
1.10.6 The Goto Statement (Unconditional Branching) 28
viii Data Structures Using C
Index 501
Preface to the
Second Edition
I have been encouraged by the excellent response given by the readers to the first edition of the book to
work on the second edition. As per the feedback received from the teachers of the subject and the input
provided by the team at Pearson Education, the following topics in various chapters of the book have
been added:
1. Sparse matrices
2. Recursion
3. Hashing
4. Weighted binary trees
a. Huffman algorithm
5. Spanning trees, minimum cost spanning trees
a. Kruskal algorithm
b. Prims algorithm
6. Shortest path problems
a. Warshall’s algorithm
b. Floyd’s algorithm
c. Dijkstra’s algorithm
7. Indexed file organization
While revising the book, the text has been thoroughly edited and the errors found thereof have been
corrected. More examples on important topics have been included.
I hope the readers will like this revised edition of the book and, as before, will provide their much
needed feedback and comments for further improvement.
Acknowledgements
I am thankful to Khushboo Jain and Anuradha Pillai for helping me in preparing the solution manual
of the book.
A. K. Sharma
Preface
As a student, programmer, and teacher of computer engineering, I find ‘Data Structures’ a core course of
computer engineering and particularly central to programming process.
In fact in our day-to-day life, we are confronted with situations such as where I would keep a bunch
of keys, a pen, coins, two thousand rupees, a chalk, and five hundred thousand rupees.
I would keep the bunch of keys and coins in the left and right pockets of my pants, respectively. The
pen gets clipped to the front pocket of the shirt whereas two thousand rupees would go into my ticket
pocket. I would definitely put the five hundred thousand rupees into a safe, i.e., under the lock and key.
While teaching, I will keep the chalk in hand. The decision of choosing the places for these items is based
on two factors: ease of accessibility and security.
Similarly, given a problem situation, a mature programmer chooses the most appropriate data
structures to organize and store data associated with the problem. The reason being that the intel-
ligent choice of data structures will decide the fate of the software in terms of effectiveness, speed
and efficiency—the three most important much-needed features for the success of a commercial
venture.
I have taught ‘Data Structures’ for more than a decade and, therefore, the demand to write a book on
this subject was there for quite some time by my students and teacher colleagues.
The hallmark of this book is that it would not only help students to understand the concepts govern-
ing the data structures but also to develop a talent in them to use the art of discrimination to choose the
right data structures for a given problem situation. In order to provide a hands-on experience to budding
software engineers, implementations of the operations defined on data structures using ‘C’ have been
provided. The book has a balance between the fundamentals and advanced features, supported by solved
examples.
This book would not have been possible without the well wishes and contribution of many people
in terms of suggestions and useful remarks provided by them during its production. I record my
thanks to Dr Ashutosh Dixit, Anuradha Pillai, Sandya Dixit, Dr Komal Bhatia, Rosy Bhatia, Harsh, and
Indu Grover.
I am indebted to my teachers and research guides, Professor J. P. Gupta, Professor Padam Kumar,
Professor Moinuddin, and Professor D. P. Agarwal, for their encouragement. I am also thankful to
my friends, Professor Asok De, Professor Qasim Rafiq, Professor N.S. Gill, Rajiv Kapur and Professor
Rajender Sahu, for their continuous support and useful comments.
I am also thankful to various teams at Pearson who made this beautiful book happen.
Finally, I would like to extend special thanks to my parents, wife Suman and daughter Sagun for
saying ‘yes’ for this project when both wanted to say ‘no’. I know that I have stolen some of the quality
time which I ought to have spent with them.
Some errors might have unwittingly crept in. I shall be grateful if they are brought to my notice.
I would also be happy to acknowledge suggestions for further improvement of this book.
A. K. Sharma
About the Author
A. K. Sharma is currently Chairman, Department of Computer Engineering, and
Dean of Faculty, Engineering and Technology at YMCA University of Science and
Technology, Faridabad. He is also a member of the Board of Studies committee of
Maharshi Dayanand University, Rohtak. He has guided ten Ph.D. theses and has
published about 215 research papers in national and international journals of re-
pute. He heads a group of researchers actively working on the design of different
types of ‘Crawlers.
This page is intentionally left blank.
Overview of C
1
Chapter
n Loose typing
n Structured language
n Wide use of pointers to access data structures and physical memory of the system
Besides the above characteristics, the C programs are small and efficient. A ‘C’ program can be
compiled on variety of computers.
2 Data Structures Using C
n Long integer: A long integer is referred to as long int or simple long. It is stored in 32 bits and
The unsigned int is stored in one word of the memory whereas the unsigned short is stored in
16 bits and does not depend upon the word size of the memory.
Examples of invalid integers are:
(i) 9, 24, 173 illegal-comma used
(ii) 5.29 illegal-decimal point used
(iii) 79 248 blank used
Overview of C 3
n double: The numbers of double data type are stored in 64 bits of memory.
4 Data Structures Using C
A summary of C basic data types is given the Table 1.1. From this table, it may be observed that charac-
ter and integer type data can also be declared as unsigned. Such data types are called unsigned data types.
In this representation, the data is always a positive number with range starting from 0 to a maximum
value. Thus, a number twice as big as a signed number can be represented through unsigned data types.
1.4 C TOKEnS
A token is a group of characters that logically belong together. In fact, a programmer can write a program
by using tokens. C supports the following types of tokens:
n Identifiers
n Keywords
n Constants
n Variables
1.4.1 Identifiers
Symbolic names can be used in C for various data items. For example, if a programmer desires to store a
value 27, then he can choose any symbolic name (say, ROLL) and use it as given below:
ROLL = 27;
Where ROLL is a memory location and the symbol ‘5’ is an assignment operator.
The significance of the above statement is that ‘ROLL’ is a symbolic name for a memory location
where the value 27 is being stored. A symbolic name is generally known as an identifier.
The identifier is a sequence of characters taken from C character set. The number of characters in
an identifier is not fixed though most of the C compilers allow 31 characters. The rules for the formation
of an identifier are:
n An identifier can consist of alphabets, digits and and/or underscores.
n C is case sensitive, i.e., upper case and lower case letters are considered different from each other.
n An identifier can start with an underscore character. Some special C names begin with the
underscore.
n Special characters such as blank space, comma, semicolon, colon, period, slash, etc. are not allowed.
n The name of an identifier should be so chosen that its usage and meaning becomes clear. For
example, total, salary, roll no, etc. are self explanatory identifiers.
Overview of C 5
1.4.2 Keywords
A keyword is a reserved word of C. This cannot be used n Table 1.2 Standard keywords in C
as an identifier by the user in his program. The set of C
auto double int struct
keywords is given in Table 1.2.
break else long switch
1.4.3 Variables case enum register typedef
A variable is the most fundamental aspect of any com- char extern return union
puter language. It is a location in the computer memory const float short unsigned
which can store data and is given a symbolic name for continue for signed void
easy reference. The variables can be used to hold differ-
default goto sizeof volatile
ent values at different times during a program run. To
do if static while
understand this concept, let us have a look at the follow-
ing set of statements:
Total 5 500.25; ...(i)
Net 5 Total 2 100.00; ...(ii)
In statement (i), value 500.25 has been stored in a memory location called Total. The variable Total
is being used in statement (ii) for the calculation of another variable Net. The point worth noting is that
‘the variable Total is used in statement (ii) by its name not by its value’.
Before a variable is used in a program, it has to be defined. This activity enables the compiler to
make available the appropriate amount of space and location in the memory. The definition of a variable
consists of its type followed by the name of the variable. For example, a variable called Total of type float
can be declared as shown below:
float Total;
Similarly, the variable net of type int can also be defined as shown below:
int Net;
Examples of valid variable declarations are:
(i) int count;
(ii) int i, j, k;
(iii) char ch, first;
6 Data Structures Using C
From Figure 1.3, we can see that besides its type a variable has three entities associated with it, i.e.,
the name of variable (val), its physical address (4715), and its contents (100). The content of a variable
is also called its rvalue whereas the physical address of the variable is called its lvalue. Thus, lvalue
and rvalue of variable val are 4715 and 100, respectively. The lvalue is of more importance because it
is an expression that should appear on the left hand side of assignment operator because it refers to the
variable or object.
Memory
1.4.4 Constants
A constant is a memory location which can store data in such a manner that its value during execu-
tion of a program does not change. Any attempt to change the value of a constant will result in an
error message. A constant in C can be of any of the basic data types, i.e., integer constant, float-
ing point constant, and character constant. const qualifier is used to declare a constant as shown
below:
const <type> <name> 5 <val>;
where
const: is a reserved word of C
<type>: is any of the basic data types
<name>: is the identifier name
<val>: is the value to be assigned to the constant.
(1) Integer constant: It is a constant which can be assigned integer values only. For example, if we
desire to have a constant called rate of type integer containing a fixed value 50, then the follow-
ing declaration can be used:
const int rate 5 50;
The above declaration means that rate is a constant of type integer having a fixed value 50. Consider
the following declaration:
const int rate;
rate 5 50;
The above initialization of constant rate is illegal. This is because of the reason that a constant can-
not be initialized for a value at a place other than where it is declared. It may be further noted that if a
program does not change or mutates\a constant or constant object then the program is called as const
correct.
(2) Floating point constant: It is a constant which can be assigned values of real or floating point
type. For example, if it is desired to have a constant called Pi containing value 3.1415, then the
following declaration can be used.
const float Pi = 3.1415;
The above declaration means that Pi is a constant of type float having a fixed value 3.1415. It may be
noted here that by default a floating point constant is of type double.
(3) Character constant: A character constant can contain a single character of information. Thus,
data such as ‘Y’ or ‘N’ is known as a character constant. Let us assume that it is desired to have a
constant called Akshar containing the character ‘Q’; following declaration can be used to obtain
such a constant.
const char Akshar = ‘Q’;
The above declaration means that Akshar is a constant of type char having a fixed value ‘Q’.
A sequence of characters enclosed within quotes is known as a string literal. For example, the
character sequence “computer” is a string literal. When a string literal is assigned to an identifier
declared as a constant, then it is known as a string constant. In fact, a string is an array of
characters. Arrays are discussed later in the chapter.
8 Data Structures Using C
Note:
(i) C is a case sensitive language, i.e., it distinguishes between upper case and lower case characters.
Thus, main() is different from Main(). In fact, most of the characters used in C are lowercase.
Hence, it is safest to type everything in lower case except when a programmer needs to capitalize
some text.
(ii) Every C program has a function called main followed by parentheses. It is from here that
program execution begins. A function is basically a subprogram and is complete in itself.
(iii) The task to be performed by a function is enclosed in curly braces called its body, i.e., {}.
These braces are equivalent to begin and end keywords used in some other languages like
Pascal. The body of function contains a set of statements and each statement must end with
a semicolon.
The above statement would display the following data on the screen:
The age of student = 25
Thus, the text between the quotes has been displayed as such but for %d, the data stored in the
variable age has been displayed.
A float can be displayed on the screen by including a format specifier (%f) within the pair of quotes
as shown below:
float rate = 9.5;
printf (“The rate of provident fund = %f”, rate);
The above set of statements declares the variable roll of type int, and reads the value for roll from
the keyboard. It may be noted that ‘&’, the address operator, is prefixed to the variable roll. The reason for
specifying ‘&’ would be discussed later in the book.
Similarly, other format specifiers can be used to input data from the keyboard.
Example 1: Write an interactive program that reads the marks secured by a student for four subjects
Sub1, Sub2, Sub3, and Sub4, the maximum marks of a subject being 100. The program shall compute
the percentage of marks obtained by the student.
Solution: The scanf() and prinf() functions would be used to do the required task. The required
program is as follows:
#include <stdio.h>
main()
{
int sub1, sub2, sub3, sub4;
float percent;
printf (“Enter the marks for four subjects:”);
scanf (“%d %d %d %d”,&sub1, &sub2, &sub3, &sub4);
percent 5 (sub1 1 sub2 1 sub3 1 sub4)/ 400.00*100;
printf (“The percentage 5 %f”, percent);
}
For input data 45 56 76 90, the above program computes the percentage and displays the following output:
The percentage 5 66.750000
Though the output is correct, but it has displayed unnecessary four trailing zeros. This can be con-
trolled by using field width specifiers discussed later in the chapter.
1.7 COMMEnTS
A comment can be added to the program by enclosing the text between the pair / * ... * /, i.e.,
the pair ‘/*’ indicates the beginning of the comment whereas the pair ‘*/’ marks the end of it. It is also
known as multiple line comment. For example, the following line is a comment:
Overview of C 11
/* This is my first program */
Everything written within `/*´ and `*/´ is ignored by the compiler. A comment written in this
fashion can overflow to multiple lines as shown below:
/* This is an illustration of multiple line comment. The C compiler ignores
these lines. A programmer can use comment lines for documentation of his
programs*/
The character constant “\n” has been placed at the beginning of the text of the second printf()
statement and, therefore, the output of the program would be:
A back slash character constant
prints the output on the next line.
12 Data Structures Using C
The output of the above statement would be on the new line with spacing as shown below:
hello Comp-Boy
(2) ’\b’ (Backspace): This character is also called backspace character. It is equivalent to the back-
space key symbol ( )available on the computer or typewriter. It moves one column back-
ward and positions the cursor on the character displayed on that column. An example of usage
of character '\b' is given below:
#include <<stdio.h
main()
{
printf(“\n ASHOKA\b-”);
}
The output of the above statement would be the following message on the screen and a sounding of
a bell on the system speaker.
Error in data
(4) ’\n’ (new line): As discussed earlier, this character is called newline character. Wherever it
appears in the output statement, the immediate next output is taken to the beginning of the next
new line on the screen. Consider the statement given below:
#include <stdio.h>
main()
{
printf(“\n This is \n a test.”);
}
C supports many types of operators such as arithmetic, relational, logical, etc. An expression that
involves arithmetic operators is known as an arithmetic expression. The computed result of an arithmetic
expression is always a numerical value. The expression which involves relational and/or logical operators
is called as a boolean expression or logical expression. The computed result of such an expression is a
logical value, i.e., either 1 (True) or 0 (False).
The rules of formation of an expression are:
n A signed or unsigned constant or variable is an expression.
1.9.1.1 Unary Arithmetic Operators A unary operator requires only one operand or data item.
The unary arithmetic operators supported by C are unary minus (‘-’), increment (‘++’), and decrement
(‘--’). As compared to binary operators, the unary operators are right associative in the sense that they
evaluate from right to left.
14 Data Structures Using C
The unary minus operator is written before a numerical value, variable or an expression. Examples
of usage of unary minus operator are:
(i) 257 (ii) 22.923 (iii) 11x (iv) 22(a*b) (v) 8*(22(a + b))
It may be noted here that the result of application of unary minus on an operand is the negation of
its operand.
The operators ‘++’ and ‘--’ are unique to C. These are called increment and decrement operators,
respectively. The increment operator ‘++’ adds 1 to its operand. Therefore, we can say that the following
expressions are equivalent.
i = i + 1 ≡ ++i;
For example, if the initial value of i is 10 then the expression ++i will increment the contents of
i to 11. Similarly, the decrement operator ‘--’ subtracts 1 from its operand. Therefore, we can say that
the following expressions are equivalent:
j = j - 1 ≡ --j;
For example, if the initial value of j is 5 then the expression --j will decrement the contents of j to 4.
The increment and decrement operators can be used both as a prefix and as a postfix to a variable
as shown below:
++ x or x++
--y or y--
As long as the increment or decrement operator is not used as part of an expression, the prefix and
postfix forms of these operators do not make any difference. For example, ++x and x++ would produce
the same result. However, if such an operator is part of an expression then the prefix and postfix forms
would produce entirely different results.
In the prefix form, the operand is incremented or decremented before the operand is used in
the program. Whereas in the postfix form, the operand is used first and then incremented or decre-
mented.
Example 2: Take two variables x and y with initial values 10 and 15, respectively. Demonstrate the usage
of relational operators by using x and y as operands.
Solution: The usage of relational operators is illustrated below with the help of a table:
x = 10, y = 15
Expression Result
x.y False
x 1 5> 5 y True
x<y True
x<5y True
x55y False
x 1 555y True
x! 5 y True
A logical operator is used to connect two relational expressions or logical expressions. The result of
such an operation is always logical, i.e., either true or false. The valid logical operators supported by C
are given in Table 1.5.
If x evaluates to false (zero), then the outcome of the above expression is bound to be false irrespec-
tive of y evaluating to any logical value. Therefore, there is no need to evaluate the term y in the above
expression.
Similarly, in the following expression, if x evaluates to true (non zero) then the outcome is bound to
be true. Thus, y will not be evaluated.
x || y
The expression x > y is evaluated. If x is greater than y, then z is assigned x otherwise z gets y.
Examples of valid conditional expressions are:
(i)
y 5 (x . 5 10)?0:10;
Overview of C 17
true
E1 ? E2 : E3
false
(ii)
Res 5 (i < j)? sum 1 i : sum 1 j;
(iii)
q 5 (a 5 5 0)?0:(x/y);
It may be noted here that the conditional operator (? :) is also known as a ternary operator because
it operates on three values.
It may be noted here that in C, false is represented as zero and true as any non-zero value. Thus,
expressions that use relational and logical operators return either 0 (false) or 1 (true).
18 Data Structures Using C
2. Comma operator: The comma operator is used to string together a number of expressions
which are performed in a sequence from left to right.
For example, the following statement
a 5 (x 5 5, x 1 2)
executes in the following order
(i) value 5 is assigned to variable x.
(ii) x is incremented by 2.
(iii) the value of expression x 1 2 (i.e., 7) is assigned to the variable a.
The following points may be noted regarding comma operator:
n A list of expressions separated by a comma is always evaluated from left to right.
n The final value and type of a list of expressions separated by a comma is always same as the type
The expression on the right hand side could be a constant, a variable or an arithmetic, relational, or
logical expression. Some examples of assignment statements are given below:
a 5 10;
a 5 b;
a 5 b*c;
(i) The assignment operator is a kind of a store statement, i.e., the value of the expression on the
right hand side is stored in the variable appearing on the left side of the assignment operator.
Overview of C 19
The variable on the left side of the assignment operator is also called lvalue and is an accessible
address in the memory. Expressions and constants on the right side of the assignment operator
are called rvalues.
(ii) The assignment statement overwrites the original value contained in the variable on the left
hand side with the new value of the right hand side.
(iii) Also, the same variable name can appear on both sides of the assignment operator as shown
below:
(iv) Multiple assignments in a single statement can be used, especially when same value is to be
assigned to a number of variables.
a 5 b 5 c 5 30;
These multiple assignment statements work from right to left and at the end, all variables have the
same value. The above statement assigns the value (i.e., 30) to all variables c, b, and a. However, the
variables must be of same type.
(v) A point worth nothing is that C converts the type of value on the right hand side to the data
type on the left.
0 1 0 1 1 1 0 1
Lost bits
1 1 1 0 1 0 0 0
Appended zero bits
Similarly, the following expression would shift the contents of y to right by two bits:
y >> 2
In this case, the rightmost two bits would be lost and the resultant 2 vacant leftmost bits would be
filled by zeros as shown in Figure 1.6.
1 1 0 1 1 0 1 1
Lost bits
0 0 1 1 0 1 1 0
Appended zero bits
The high level languages are designed for computers based on Von-Neumann architecture. Since this
architecture supports only sequential processing, the normal flow of execution of statements in a high
level language program is also sequential, i.e., each statement is executed in the order of its appearance
in the program. For example in the following C program segment, the order of execution is sequential
from top to bottom.
:
x 5 10;
y 5 20; Order of execution
z 5 x 1 y;
:
Overview of C 21
The first statement to be executed is ‘x 5 10’, and the second statement to be executed is ‘y 5
20’. The execution of statement ‘z 5 x 1 y’ will take place only after the execution of the statement
‘y 5 20’. Thus, the processing is strictly sequential. Moreover, every statement is executed once and
only once.
Depending upon the requirements of a problem, it is often required to alter the normal sequence
of execution in the program. This means that we may desire to selectively and/or repetitively execute a
program segment. A number of C control structures are available for controlling the flow of processing.
These structures are discussed in the following sections.
In fact, the function of curly braces ‘{‘ and `}’ in a C program to create a block, is same as the
function of begin and end, the reserved words in Pascal. C calls these braces as delimiters.
(2) The if-else statement: It can be observed from the above examples that the simple if statement
does nothing when the expression is false. An if-else statement takes care of this aspect. The
general form of this construct is given below:
if (expression)
{
statement sequence1
}
else
{
statement sequence2
}
where if: is a reserved word.
expression: is a boolean expression, written within parentheses.
statement sequence1: can be a simple or a compound statement.
else: is a reserved word.
statement sequence2: can be a simple or a compound statement.
Examples of if-else statements are:
(i) if (A > B) C = A;
else C 5 B;
(ii) if (x == 100)
printf (“\n Equal to 100”);
else
printf (“\n Not Equal to 100”);
It may be noted here that both the ‘if ’ and ‘else’ parts are terminated by semicolons.
(3) Nested if statements (if-else-if ladder): The statement sequence of if or else may contain an-
other if statement, i.e., the if-else statements can be nested within one another as shown below:
if (exp1)
if (exp2)
{
Overview of C 23
:
}
else
if (exp3)
{
:
}
else
{
:
}
It may be noted here that sometimes the nesting may become complex in the sense that it becomes
difficult to decide “which if does the else match”. This is called “dangling else problem’’. The C
compiler follows the following rule in this regard:
Rule: Each else matches to its nearest unmatched preceding if.
Consider the following nested if:
if (x < 50) if (y > 5) Net = x + y; else Net = x – y;
In the above statement, the else part matches the second if (i.e., if (y . 5)) because it is the nearest
preceding if. It is suggested that the nested if(s) should be written with proper indentation. The else(s)
should be lined up with their matching if(s). Nested if(s) written in this fashion are also called if-else-if
ladder. For example, the nested if given above should be written as:
if (x < 50)
if (y > 5)
Net = x + y;
else
Net = x – y;
However, if one desires to match the else with the first if, then the braces should be used as shown
below:
if (x < 50) {
if (y > 5)
Net = x + y;
}
else
Net = x – y;
The evaluation of if-else-if ladder is carried out from top to bottom. Each conditional expression
is tested and if found true, only then its corresponding statement is executed. The remaining ladder is,
therefore, by passed. In a situation where none of the nested conditions is found true, the final else part
is executed.
(4) Switch statement (selection of one of many alternatives): If it is required in a program to
select one of several different courses of action, then the switch statement of C can be used. In
fact, it is a multibranch selection statement that makes the control to jump to one of the several
statements based on the value of an int variable or expression. The general form of this state-
ment is given as:
24 Data Structures Using C
switch (expression)
{
case constant 1:
statement;
break;
case constant 2:
statement;
break;
:
default:
statement;
}
n If a match is found then its corresponding statements are executed and when break is encountered,
the flow of control jumps out of the switch statement. If break statement is not encountered, then
the control continues across other statement. In fact, switch is the only statement in C which is error
prone. The reason is that if the control is in a particular case and then it keeps running through all
cases in the absence of a proper break statement. This phenomenon is called “fall-through”.
n If no match is found and if a default label is present, then the statement corresponding to default
is executed.
n The values of the various case constants must be unique.
(ii)
switch (code)
Overview of C 25
{
case 101 : Rate = 50; break;
case 102 : Rate = 70; break;
case 103 : Rate = 100; break;
default : Rate = 95;
}
In the statement (ii), it can be observed that depending on the value of the code one out of the four
instructions is selected and obeyed. For example, if the code evaluates to 103, the third instruction (i.e.,
Rate 5100) is selected. Similarly if the code evaluates to 101, then the first instruction (i.e., Rate 5 50) is
selected.
The variable i and j have been initialized to values 1 and 10, respectively. Please note that these
initialization expressions are separated by a `comma’. However, the required semicolon remains
as such. During the execution of the loop, i increases from 1 to 10 whereas j decreases from 10 to 1
simultaneously. Similarly, the increment and decrement operations have been separated by a `comma’
in the ‘for statement’.
Though the power of the loop can be increased by including more than one initialization and
increment expression separated with the comma operator but there can be only one test expression
which can be simple or complex.
Overview of C 27
1.10.3.1 The ‘break’ and ‘continue’ Statements The break statement can be used in any ‘C᾽ loop
to terminate execution of the loop. We have already seen that it is used to exit from a switch statement. In
fact, whenever the break statement is encountered in a loop the control is transferred out of the loop. This
is used in a situation where some error is found in the program inside the loop or it becomes unnecessary
to continue with the rest of the execution of the loop.
Consider the following program segment:
:
while (val != 0)
{
:
printf (“\n %d”, val);
if (val < 0) {
printf (“\n Error in input”);
break;
}
:
}
Whenever the value contained, in variable val becomes negative, the message `Error in input’
would be displayed and because of the break statement the loop will be terminated.
The continue statement can also be used in any ‘C᾽ loop to bypass the rest of the code segment of
the current iteration of the loop. The loop, however, is not terminated. Thus, the execution of the loop
resumes with the next iteration. For example, the following loop computes the sum of positive numbers
in a list of 50 numbers:
:
sum = 0;
for (i = 0; i < 50; i ++)
{
printf (“\n %d”, val);
if (val <= 0) continue;
sum = sum + val;
}
:
It may be noted here that continue statement has no relevance as far as the switch statement is con-
cerned. Therefore, it cannot be used in a switch statement.
It may be noted here that the file process.h has to be included as header file because it contains the
function prototype of the library function exit().
-
-
goto rpara;
-
-
rpara: -
-
-
Overview of C 29
The goto statement will cause the control to be transferred to a statement whose label is rpara. The
normal flow of execution will continue from this statement (i.e., having label rpara) onwards. Consider
the following program segment:
:
k = 50;
back: I++
:
sum = sum + k*I ;
k--;
goto back;
:
It is clear from the above segment that as and when the control reaches the goto statement, it is
transferred to the statement with label back.
Statement label A statement label is an identifier which can be placed before any C statement followed
by a colon (i.e., :) as shown below:
again: C 5 A 1 B;
Thus, again is a label attached to the statement C 5 A 1 B and the control of execution can be
transferred to this statement by the following goto statement.
goto again;
It may be noted here that the transfer of control out of a control structure is allowed. However, a goto
branch into a control structure is not allowed.
Some example programs using control structures are given below.
Example 3: Write a program that reads three numbers and prints the largest of them.
Solution: The if-else ladder would be used. The required program is given below:
/* This program displays the largest of three numbers */
#include <stdio.h>
main()
{
int A, B, C;
printf (“\n Enter the Numbers A, B, C:“);
scanf (“%d %d %d”, &A, &B, &C);
/* if-else ladder */
if (A > B)
if ( A > C)
printf (“\n A is largest”);
else
printf (“\n C is largest”);
else
if (B > C)
printf (“\n B is largest”);
else
30 Data Structures Using C
printf (“\n C is largest”);
/* end of ladder */
}
Example 4: Write a program that prints all perfect numbers between 2 and 9999, inclusive. A perfect
number is a positive integer such that the number is equal to the sum of its proper divisors. A proper
divisor is any divisor whose value is less than the number.
Solution: The remainder operator ‘%’ would be used to find whether a number is divisor of an-
other or not. The maximum value of perfect divisor cannot be more than the half the value of the
number.
The required program is given below:
/* This program finds out all the perfect numbers between 2 and 9999 both
inclusive */
#include <stdio.h>
main()
{
int num, divisor;
int sum;
char ch;
In order to use the above functions, the programmer must include the ‘stdio.h᾽ header file at the
beginning of his program. The C or ‘C environment’ assumes keyboard as the standard input device and
VDU as standard output device. A consol comprises both keyboard and VDU.
By default, all stream I/Os are buffered. At this point, it is better that we understand the term buff-
ered I/O before we proceed to discuss the stream I/O functions.
Input buffer
Stream
I/O devices
Outbut buffer
Similarly, data written by an output stream pointer is not directly written onto the device but into an
output buffer. As soon as the output buffer becomes full, a block of data is written on to the I/O device
making output buffer empty.
32 Data Structures Using C
When the header file stdio.h is included in a program, the following standard stream pointers are
automatically opened:
name Meaning
stdin standard input
stdout standard output
stderr standard error
stdaux auxiliary storage
stdprn printer
In the computer, ‘stdin’ and ‘stdout’ refer to the user’s console, i.e., input device as keyboard
and output device as VDU (screen). The stream pointers ‘stdprn’ and ‘stdaux’ refer to the printer and
auxiliary storage, respectively. The error messages generated by the stream are sent to standard error
(stderr).
In order to clear the buffers, a function called ‘fflush()’ can be used. For example, input buffer of
standard input device can be cleared by invoking the function: ‘fflush(stdin)’.
Since the function getchar() is a stream I/O function, it is buffered in the sense that the character
typed by the user is not passed to the variable ch until the user hits the enter or return key, i.e., ↵. The
enter key is itself a character and it also gets stored in the buffer along with the character typed by the
user. The entry of `enter key’ character into the buffer creates problems in the normal functioning of
getchar() function. Therefore, it is suggested that after an input operation from the standard input
device (i.e., keyboard) the input buffer should be cleared. This operation is required to avoid interference
with subsequent input operations. The function call for this activity is: fflush (stdin). The usage is
shown below:
:
char ch;
ch = getchar();
fflush (stdin);
:
Overview of C 33
The function putchar() is used to send a single character to the standard output device. The character
to be displayed on the VDU screen is included as an argument to the putchar() function as shown below:
:
ch = `A’;
putchar (ch);
:
Once the above program segment is executed, the character ‘A’ will be displayed on the screen.
The putchar() function is also buffered. The function call for clearing the output buffer is fflush
(stdout). The output buffer is cleared on its own only when a new line character `\n’ is used.
(2) getc() and putc() Functions: The getc() and putc() functions are also character-
based functions. They have been basically designed to work with files. However, these
functions can also be used to read and write data from standard input and output devices by
specifying stdin and stdout as input and output files, respectively.
For example, the function getc(stdin) is equivalent to the function getchar(). Both will get a
character from the standard input device (keyboard). The function getchar() by default reads from
keyboard whereas the argument stdin of function getc(stdin) makes it read from a file represented
by the standard input device which is nothing but the keyboard.
Similarly, the function putc(ch, stdout) is equivalent to the function putchar(ch). Both the
functions send the character ch to the standard output device, i.e., VDU screen.
(3) getche() and putch() Functions: These two functions are character-based versions of con-
sole I/O functions. Therefore, the header file conio.h has to be included. In fact, these functions
act as an extension to the stream I/O functions. The console I/O functions read from the key-
board and write to the screen directly.
n getche(): This function directly reads a character from the console as soon as it is typed
without waiting for the enter key (↵) to be pressed. There is another similar function getch()
which also reads a character from the keyboard exactly in the same manner but does not show
it on the screen. This function is useful in menu selections where the programmer does not
want to display the character typed by the user. In fact, the extra ‘e’ in the getche() function
stands for echo, i.e., display the character.
Examples of usage of these functions are:
(i) ch 5 getche();
(ii) ch 5 getch();
n putch(): This function directly writes a character on the console. It takes character as an
argument.
Examples of usage of this function are:
(i) putch (‘\n’); //It takes the cursor to next line of the screen.
(ii) putch (ch); //It displays the character stored in the variable ch on the screen.
(iii) putch (‘A’); //It displays the character ‘A’ on the screen.
Note: These functions cannot read special keys from the keyboard such as function keys.
HE [E ONE
The text on this page is estimated to be only 28.73%
accurate
DA v, !
The text on this page is estimated to be only 27.86%
accurate
A HISTORY OF ESSEX
The text on this page is estimated to be only 8.93%
accurate
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com