C Programming Data Structures 4th Edition E. Balagurusamy - Read the ebook online or download it to own the full content
C Programming Data Structures 4th Edition E. Balagurusamy - Read the ebook online or download it to own the full content
com
https://ebookgate.com/product/c-programming-data-
structures-4th-edition-e-balagurusamy/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/programming-in-ansi-c-6th-edition-e-
balagurusamy/
ebookgate.com
https://ebookgate.com/product/computer-programming-1st-edition-e-
balagurusamy/
ebookgate.com
https://ebookgate.com/product/c-programming-program-design-including-
data-structures-5ed-edition-malik-d-s/
ebookgate.com
https://ebookgate.com/product/data-structures-and-algorithms-in-c-4th-
edition-adam-drozdek/
ebookgate.com
C Programming Program Design Including Data Structures 7th
Edition D. S. Malik
https://ebookgate.com/product/c-programming-program-design-including-
data-structures-7th-edition-d-s-malik/
ebookgate.com
https://ebookgate.com/product/c-programming-program-design-including-
data-structures-6th-edition-d-s-malik/
ebookgate.com
https://ebookgate.com/product/data-structures-and-other-objects-
using-c-4th-edition-michael-main/
ebookgate.com
https://ebookgate.com/product/data-structures-using-c-2nd-edition-d-s-
malik/
ebookgate.com
https://ebookgate.com/product/data-structures-other-objects-using-
java-4th-edition-michael-mann/
ebookgate.com
As per the
Revised
Syllabus Effective
August 2007
C Programming
and
Data Structures
Fourth Edition
About the Author
E Balagurusamy, former Vice Chancellor, Anna University, Chennai, is currently Member, Union
Public Service Commission, New Delhi. He is a teacher, trainer, and consultant in the fields of Informa-
tion Technology and Management. He holds an ME (Hons) in Electrical Engineering and Ph.D in
Systems Engineering from the Indian Institute of Technology, Roorkee. His areas of interest include
Object-Oriented Software Engineering, Electronic Business, Technology Management, Business
Process Re-engineering, and Total Quality Management.
A prolific writer, he has authored a large number of research papers and several books. His best
selling books, among others include:
· Programming in C#, 2/e
· Programming in Java, 3/e
· Object-Oriented Programming with C++, 4/e
· Programming in BASIC, 3/e
· Programming in ANSI C, 4/e
· Numerical Methods
· Reliability Engineering
A recipient of numerous honours and awards, he has been listed in the Directory of Whos Who of
Intellectuals and in the Directory of Distinguished Leaders in Education.
As per the
Revised
Syllabus Effective
August 2007
C Programming
and
Data Structures
Fourth Edition
E Balagurusamy
Member, UPSC
New Delhi
Information contained in this work has been obtained by Tata McGraw-Hill, from sources believed to be
reliable. However, neither Tata McGraw-Hill nor its authors guarantee the accuracy or completeness of any
information published herein, and neither Tata McGraw-Hill nor its authors shall be responsible for any
errors, omissions, or damages arising out of use of this information. This work is published with the under-
standing that Tata McGraw-Hill and its authors are supplying information but are not attempting to render
engineering or other professional services. If such services are required, the assistance of an appropriate
professional should be sought.
Typeset at Script Makers, 19, A1-B, DDA Market, Paschim Vihar, New Delhi 110 063, and printed at Shakti
Packers, 5C/9, New Rohtak Road, Karol Bagh, New Delhi-110 005
Cover: SDR Printers
DALZCRBFRAALX
Contents
Foreword xi
Preface xiii
Road Map to the Syllabus xv
The C99 Standard xvii
UNIT I
1. Algorithms 1.31.15
1.1 Introduction ......................................................................................................................... 1.3
1.1.1 Algorithm/pseudocode .......................................................................................... 1.3
1.1.2 Flow Chart............................................................................................................ 1.4
1.2 Three Basic Operations ....................................................................................................... 1.5
1.2.1 Sequence .............................................................................................................. 1.5
1.2.2 Selection ............................................................................................................... 1.6
1.2.3 Iteration .............................................................................................................. 1.13
Review Questions and Exercises ..................................................................................... 1.14
2. Overview of C 2.12.12
2.1 Introduction ......................................................................................................................... 2.1
2.2 Importance of C .................................................................................................................. 2.1
2.3 Sample C Programs ............................................................................................................. 2.2
2.4 Program Development Steps ............................................................................................... 2.5
2.5 Structure of a C Program .................................................................................................... 2.9
Review Questions and Exercises ..................................................................................... 2.11
3. Constants, Variables, and Data Types 3.13.26
3.1 Introduction ........................................................................................................................ .3.1
3.2 Character Set ....................................................................................................................... 3.1
3.3 C Tokens ............................................................................................................................. 3.1
3.4 Keywords and Identifiers .................................................................................................... 3.2
3.5 Constants ............................................................................................................................. 3.3
3.6 Variables ............................................................................................................................. 3.7
3.7 Basic Data Types and Sizes ................................................................................................ 3.8
3.8 Declaration of Variables ................................................................................................... 3.11
3.9 Assigning Values to Variables .......................................................................................... 3.14
3.10 Defining Symbolic Constants ........................................................................................... 3.21
Review Questions and Exercises ................................................................................... 3.24
vi Contents
4. Operators and Expressions 4.14.22
4.1 Introduction ......................................................................................................................... 4.1
4.2 Arithmetic Operators .......................................................................................................... 4.1
4.3 Relational Operators ........................................................................................................... 4.4
4.4 Logical Operators ............................................................................................................... 4.5
4.5 Assignment Operators ......................................................................................................... 4.5
4.6 Increment and Decrement Operators .................................................................................. 4.7
4.7 Conditional Operator .......................................................................................................... 4.8
4.8 Bitwise Operators ............................................................................................................... 4.8
4.9 Special Operators ................................................................................................................ 4.9
4.10 Arithmetic Expressions ..................................................................................................... 4.11
4.11 Evaluation of Expressions ................................................................................................ 4.11
4.12 Precedence of Arithmetic Operators ................................................................................. 4.12
4.13 Some Computational Problems ......................................................................................... 4.14
4.14 Type Conversions in Expressions ..................................................................................... 4.15
4.15 Operator Precedence and Associativity ............................................................................ 4.18
Case Studies ..................................................................................................................... 4.19
Review Questions and Exercises ..................................................................................... 4.20
5. Managing Input and Output Operations 5.15.25
5.1 Introduction ......................................................................................................................... 5.1
5.1.1 Input/Output Statements and Header Files ........................................................... 5.1
5.2 Reading a Character ............................................................................................................ 5.2
5.3 Writing a Character ............................................................................................................ 5.4
5.4 Formatted Input ................................................................................................................... 5.5
5.5 Formatted Output .............................................................................................................. 5.14
Case Studies ..................................................................................................................... 5.21
Review Questions and Exercises ..................................................................................... 5.24
6. Decision Making and Branching 6.16.29
6.1 Introduction ......................................................................................................................... 6.1
6.2 Decision Making with If Statement .................................................................................... 6.1
6.3 Simple If Statement ............................................................................................................. 6.2
6.4 The If K Else Statement ..................................................................................................... 6.5
6.5 Nesting of If ... Else Statements .......................................................................................... 6.7
6.6 The Else If Ladder ............................................................................................................ 6.11
6.7 The Switch and Break Statements .................................................................................... 6.13
6.8 The ? : Operator ................................................................................................................ 6.17
6.9 The Goto Statement .......................................................................................................... 6.20
6.9.1 Label .................................................................................................................. 6.20
Case Studies ..................................................................................................................... 6.22
Review Questions and Exercises ..................................................................................... 6.26
7. Decision Making and Looping 7.17.30
7.1 Introduction ......................................................................................................................... 7.1
7.2 The While Statement ........................................................................................................... 7.3
7.3 The Do Statement ................................................................................................................ 7.4
Contents vii
7.4 The For Statement ............................................................................................................... 7.6
7.5 Jumps in Loops ................................................................................................................. 7.14
7.6 Structured Programming ................................................................................................... 7.20
Case Studies ..................................................................................................................... 7.21
Review Questions and Exercises ..................................................................................... 7.27
UNIT II
8. Arrays 8.38.31
8.1 Introduction ......................................................................................................................... 8.3
8.2 One-Dimensional Arrays .................................................................................................... 8.3
8.3 Two-Dimensional Arrays.................................................................................................... 8.8
8.4 Initializing Two-Dimensional Arrays ............................................................................... 8.13
8.5 Multidimensional Arrays .................................................................................................. 8.15
Case Studies ..................................................................................................................... 8.17
Review Questions and Exercises ..................................................................................... 8.28
9. Handling of Character Strings 9.19.23
9.1 Introduction ......................................................................................................................... 9.1
9.2 Declaring and Initializing String Variables ........................................................................ 9.2
9.3 Reading Strings from Terminal ........................................................................................... 9.2
9.4 Writing Strings to Screen .................................................................................................... 9.5
9.5 Arithmetic Operations on Characters ................................................................................. 9.8
9.6 Putting Strings Together ................................................................................................... 9.10
9.7 Comparison of Two Strings .............................................................................................. 9.12
9.8 String-Handling Functions ................................................................................................ 9.13
9.9 Table of Strings ................................................................................................................. 9.15
Case Studies ..................................................................................................................... 9.18
Review Questions and Exercises ..................................................................................... 9.22
10. User-Defined Functions 10.110.50
10.1 Introduction ....................................................................................................................... 10.1
10.1.1 Standard Library Functions ................................................................................ 10.1
10.2 Need for User-Defined Functions ..................................................................................... 10.4
10.3 A Multi-Function Program ................................................................................................ 10.5
10.4 The Form of C Functions .................................................................................................. 10.7
10.5 Return Values and their Types .......................................................................................... 10.8
10.6 Calling a Function ............................................................................................................. 10.9
10.7 Category of Functions ..................................................................................................... 10.10
10.8 No Arguments and no Return Values ............................................................................. 10.10
10.9 Arguments but no Return Values .................................................................................... 10.12
10.10 Arguments with Return Values ....................................................................................... 10.14
10.11 Handling of Non-Integer Functions ................................................................................ 10.18
10.12 Nesting of Functions ....................................................................................................... 10.21
10.13 Recursion ........................................................................................................................ 10.22
10.14 Functions with Arrays ..................................................................................................... 10.23
10.15 The Scope and Lifetime of Variables in FunctionsStorage Classes ............................ 10.26
viii Contents
10.16 ANSI C Functions ........................................................................................................... 10.36
10.17 The Preprocessor ............................................................................................................. 10.39
10.18 ANSI Additions .............................................................................................................. 10.42
Case Study ...................................................................................................................... 10.45
Review Questions and Exercises ................................................................................. 10.49
UNIT III
UNIT IV
UNIT V
UNIT VI
UNIT VII
UNIT VIII
DR K. RAJAGOPAL
Vice-Chancellor
Jawaharlal Nehru Technological University
Hyderabad
Chapter
1
Preface
E BALAGURUSAMY
Chapter
1
Road Map to the Syllabus
(Effective from August 2007)
CHAPTER 1 ALGORITHMS
CHAPTER 2 OVERVIEW OF C
CHAPTER 3 CONSTANTS, VARIABLES, AND DATA TYPES
Go To CHAPTER 4 OPERATORS AND EXPRESSIONS
CHAPTER 5 MANAGING INPUT AND OUTPUT OPERATIONS
CHAPTER 6 DECISION MAKING AND BRANCHING
CHAPTER 7 DECISION MAKING AND LOOPING
Unit II
Designing structured programs, functions, basics, parameter passing, storage classes- extern, auto,
register, static, scope rules, block structure, user-defined functions, standard library functions, recursive
functions, header files, C preprocessor, C program examples.
CHAPTER 8 ARRAYS
Go To CHAPTER 9 HANDLING OF CHARACTER
STRINGS
CHAPTER 11 POINTERS
Unit IV
Derived types- structures- declaration, definition and initialization of structures, accessing structures,
nested structures, arrays of structures, structures and functions, pointers to structures, self-referential
structures, unions, typedef, bitfields, C program examples.
Unit VII
Introduction to data structures, singly linked lists, doubly linked lists, circular list, representing stacks
and queues in C using arrays and linked lists, infix to post fix conversion, postfix expression evaluation.
CHAPTER 14 DATA STRUCTURES
Go To CHAPTER 15 DYNAMIC MEMORY ALLOCATION
AND LINKED LISTS
Unit VIII
Trees- binary trees, terminology, representation, traversals, graphsterminology, representation, graph
traversals (dfs and bfs)
Computer languages are not static; they evolve, reacting to changes in methodologies, applications gen-
erally accepted practices, and hardware. C is no exception. In the case of C, two evolutionary paths were
set in motion. The first is the continuing development of the C language. The second is C++, for which
C provided the starting point. While most of the focus of the past several years has been on C++, the
refinement of C has continued unabated.
For example, reacting to the internationalization of the computing environment, the original C89
standard was amended in 1995 to include various wide-character and multibyte functions. Once the
1995 amendment was complete, work began on updating the language, in general. The end result is, of
course, C99. In the course of creating the 1999 standard, each element of the C language was thoroughly
reexamined, usage patterns were analyzed, and future demands were anticipated. As expected, C's rela-
tionship to C++ provided a backdrop for the entire process. The resulting C99 standard is a testimonial
to the strengths of the original. Very few of the key elements of C were altered. For the most part, the
changes consist of a small number of carefully selected additions to the language and the inclusion of
several new library functions. Thus C is still C!
Here we will examine those features added by C99, and the few differences between C99 and C89.
C99
Perhaps the greatest cause for concern that accompanies the release of a new language standard is the
issue of compatibility with its predecessor. Does the new specification render old programs obsolete?
Have important constructs been altered? Do I have to change the way that I write code? The answers to
these types of questions often determine the degree to which the new standard is accepted and, in the
longer term, the viability of the language itself. Fortunately, the creation of C99 was a controlled, even-
handed process that reflects the fact that several experienced pilots were at the controls. Put simply: If
you liked C the way it was, you will like the version of C defined by C99. What many programmers
think of as the world's most elegant programming language, still is! In this chapter we will examine the
changes and additions made to C by the 1999 standard. Many of these changes were mentioned in
passing in Part One. Here they are examined in closer detail. Keep in mind, however, that as of this
writing, there are no widely used compilers that support many of C99s new features. Thus, you may
need to wait a while before you can test drive such exciting new constructs as variable-length arrays,
restricted pointers, and the long long data type.
xviii The C99 Standard
C89 vs. C99: AN OVERVIEW
There are three general categories of changes between C89 and C99:
· Features added to C89
· Features removed from C89
· Features that have been changed or enhanced
Many of the differences between C89 and C99 are quite small, and clarify nuances of the C language.
This book will concentrate on the larger changes that affect the way programs are written.
Features Added
Perhaps the most important features added by C99 are the new keywords:
· inline
· restrict
_Bool
_Complex
_Imaginary
Other major additions include
· Variable-length arrays
· Support for complex arithmetic
· The long long int data type
· The //comment
· The ability to intersperse code and data
· Additions to the preprocessor
· Variable declarations inside the for statement
· Compound literals
· Flexible array structure members
· Designated initializers
· Changes to the printf( ) and scanf( ) family of functions
· The _ _func_ _ predefined identifier
· New libraries and headers
Most of the features added by C99 are innovations created by the standardization committee, of
which many were based on language extensions offered by a variety of C implementations. In a few
cases, however, features were borrowed from C++. The inline keyword and // style comments are exam-
ples. It is important to understand that C99 does not add C++-style classes, inheritance, or member
functions. The consensus of the committee was to keep C as C.
Features Removed
The single most important feature removed by C99 is the 'implicit int rule. In C89, in many cases when
no explicit type specifier is present, the type int is assumed. This is not allowed by C99. Also removed
is implicit function declaration. In C89, if a function was not declared before it is used, an implicit
declaration is assumed. This is not supported by C99. Both of these changes may require existing code
to be rewritten if compatibility with C99 is desired.
The C99 Standard xix
Features Changed
C99 incorporates several changes to existing features. For the most part, these changes expand features
or clarify their meaning. In a few cases, the changes restrict or narrow the applicability of a feature.
Many such changes are small, but a few are quite important, including:
· Increased translation limits
· Extended integer types
· Expanded integer type promotion rules
· Tightening of the return statement
As it affects existing programs, the change to return has the most significant effect because it might
require that code be rewritten slightly.
Throughout the remainder of this chapter, we will examine the major differences between C89 and
C99.
RESTRICT-QUALIFIED POINTERS
One of the most important innovations in C99 is the restrict type qualifier. This qualifier applies only to
pointers. A pointer qualified by restrict is initially the only means by which the object it points to can be
accessed. Access to the object by another pointer can occur only if the second pointer is based on the
first. Thus, access to the object is restricted to expressions based on the restrict-qualified pointer.
Pointers qualified by restrict are primarily used as function parameters, or to point to memory allocated
via malloc( ). The restrict qualifier does not change the semantics of a program. By qualifying a
pointer with restrict, the compiler is better able to optimize certain types of routines by making the
assumption that the restrict-qualified pointer is the sole means of access to the object. For example, if
a function specifies two restrict-qualified pointer parameters, the compiler can assume that the pointers
point to different (that is, non-overlapping) objects. For example, consider what has become the classic
example of restrict: the memcpy( ) function.
In C89, it is prototyped as shown here:
void *memcpy(void *str1, const void *str2, size_t size);
The description for memcpy( ) states that if the objects pointed to by str1 and str2 overlap, the
behaviour is undefined. Thus, memcpy( ) is guaranteed to work for only non-overlapping objects. In
C99, restrict can be used to explicitly state in memcpy( )s prototype what C89 must explain with
words.
Here is the C99 prototype for memcpy( ):
void *memcpy
(void * restrict str1, const void * restrict str2, size_t size);
By qualifying str1 and str2 with restrict, the prototype explicitly asserts that they point to non-overlap-
ping objects. Because of the potential benefits that result from using restrict, C99 has added it to the
prototypes for many of the library functions originally defined by C89.
Inline
C99 adds the keyword inline, which applies to functions. By preceding a function declaration with
inline, you are telling the compiler to optimize calls to the function. Typically, this means that the
xx The C99 Standard
functions code will be expanded in line, rather than called. However, inline is only a request to the
compiler, and can be ignored. Specifically, C99 states that using inline suggests that calls to the func-
tion be as fast as possible. The inline specifier is also supported by C++, and the C99 syntax for inline
is compatible with C++.
To create an in-line function, precede its definition with the inline keyword. For example, in the
following program, calls to the function max( ) are optimized:
#include <stdio.h>
inline int max(int a, int b)
{
return a > b ? a : b;
}
int main(void)
{
int x=5, y=10;
printf("Max of %d and %d is: %d\n", x, y, max(x, y));
return 0;
}
For a typical implementation of inline, the preceding program is equivalent to this one:
#include <stdio.h>
int main(void)
{
int x=5, y=10;
printf("Max of %d and %d is: %d\n", x, y, (x>y ? x : y));
return 0;
}
The reason that inline functions are important is that they help you create more efficient code while
maintaining a structured, function-based approach. As you probably know, each time a function is
called, a significant amount of overhead is generated by the calling and return mechanism. Typically,
arguments are pushed onto the stack and various registers are saved when a function is called, and then
restored when the function returns. The trouble is that these instructions take time.
However, when a function is expanded in line, none of those operations occur. Although expanding
function calls in line can produce faster run times, it can also result in larger code size because of
duplicated code. For this reason, it is best to inline only very small functions. Further, it is also a good
idea to inline only those functions that will have significant impact on the performance of your program.
Remember: Although inline typically causes a functions code to be expanded in line, the com-
piler can ignore this request or use some other means to optimize calls to the function.
C99 adds several new built-in data types. Each is examined here.
The C99 Standard xxi
_Bool
C99 adds the _Bool data type, which is capable of storing the values 1 and 0 (true and false). _Bool is
an integer type. As many readers know, C++ defines the keyword bool, which is different from _Bool.
Thus, C99 and C++ are incompatible on this point. Also, C++ defines the built-in Boolean constants
true and false, but C99 does not. However, C99 adds the header <stdbool.h>, which defines the macros
bool, true, and false. Thus, code that is compatible with C/C++ can be easily created.
The reason that _Bool rather than bool is specified as a keyword is that many existing C programs
have already defined their own custom versions of bool. By defining the Boolean type as _Bool, C99
avoids breaking this preexisting code. However, for new programs, it is best to include <stdbool.h> and
then use the bool macro.
C99 adds support for complex arithmetic, which includes the keywords _Complex and _Imaginary,
additional headers, and several new library functions. However, no implementation is required to imple-
ment imaginary types, and freestanding implementations (those without operating systems) do not have
to support complex types. Complex arithmetic was added to C99 to provide better support for numerical
programming.
The following complex types are defined:
· float _Complex
· float _Imaginary
· double _Complex
· double _Imaginary
· long double _Complex
· long double _Imaginary
The reason that _Complex and _Imaginary, rather than complex and imaginary, are specified as
keywords, is that many existing C programs have already defined their own custom complex data types
using the names complex and imaginary. By defining the keywords _Complex and _Imaginary, C99
avoids breaking this preexisting code.
The header <complex.h> defines (among other things) the macros complex and imaginary, which
expand to Complex and _Imaginary. Thus, for new programs, it is best to include <complex.h> and
then use the complex and imaginary macros.
C99 adds the long long int and unsigned long long int data types. A long long int has a range of at
least(2631) to 2631. An unsigned long long int has a minimal range of 0 to 2641. The long long
types allow 64-bit integers to be supported as a built-in type.
Array Enhancements
C99 has added two important features to arrays: variable length and the ability to include type qualifiers
in their declarations.
xxii The C99 Standard
Variable-Length Arrays
In C89, array dimensions must be declared using integer constant expressions, and the size of an array is
fixed at compile time. C99 changes this for certain circumstances. In C99, you can declare an array
whose dimensions are specified by any valid integer expression, including those whose value is known
only at run time. This is called a variable-length array (VLA). However, only local arrays (that is,
those with block scope or prototype scope) can be of variable length.
Here is an example of a variable-length array:
void f(int dim1, int dim2)
{
int matrix[dim1] [dim2]; /* a variable-length, 2-D array */
/* . . . */
}
Here, the size of matrix is determined by the values passed to f( ) in dim1 and dim2. Thus, each call to
f( ) can result in matrix being created with different dimensions.
It is important to understand that variable-length arrays do not change their dimensions during their
lifetime. (That is, they are not dynamic arrays.) Rather, a variable-length array can be created with a
different size each time its declaration is encountered.
You can specify a variable-length array of an unspecified size by using * as the size.
The inclusion of variable-length arrays causes a small change in the sizeof operator. In general, sizeof is
a compile-time operator. That is, it is normally translated into an integer constant whose value is equal
to the size of the type or object when a program is compiled. However, when it is applied to a variable-
length array, sizeof is evaluated at run time. This change is necessary because the size of a variable-
length array cannot be known until run time.
One of the major reasons for the addition of variable-length arrays to C99 is to support numeric
processing. Of course, it is a feature that has widespread applicability. But remember, variable-length
arrays are not supported by C89 (or by C++).
In C99 you can use the keyword static inside the brackets of an array declaration when that declaration
is for a function parameter. It tells the compiler that the array pointed to by the parameter will always
contain at least the specified number of elements. Here is an example:
int f(char str [static 80])
{
// here, str is always a pointer to an 80-element array
// . . .
}
In this example, str is guaranteed to point to the start of an array of chars that contains at least 80
elements.
You can also use the keywords restrict, volatile, and const inside the brackets, but only for function
parameters. Using restrict specifies that the pointer is the sole initial means of access to the object.
The C99 Standard xxiii
Using const states that the same array is always pointed to (that is, the pointer always points to the same
object). The use of volatile is allowed, but meaningless.
Single-Line Comments
C99 adds the single-line comment to C. This type of comment begins with // and runs to the end of
the line.
For example:
// This is a comment
int i; // this is another comment
Single-line comments are also supported by C++. They are convenient when only brief, single-line
remarks are needed. Many programmers use Cs traditional multiline comments for longer descriptions,
reserving single-line comments for play-by-play explanations.
Interspersed Code and Declarations In C89, within a block, all declarations must precede the first
code statement. This rule does not apply for C99.
For example:
#include <stdio.h>
int main(void)
{
int i;
i = 10;
int j; // wrong for C89; OK for C99 and C++
j = i;
printf(“%d %d”, i, j);
return 0;
}
Here, the statement i = 10; comes between the declaration of i and the declaration of j. This is not
allowed by C89. It is allowed by C99 (and by C++). The ability to intersperse declarations and code is
widely used in C++.
Adding this feature to C makes it easier to write code that will be used in both environments.
PREPROCESSOR CHANGES
Perhaps the most important change to the preprocessor is the ability to create macros that take a variable
number of arguments. This is indicated by an ellipsis (. . .) in the definition of the macro. The built-in
preprocessing identifier _ _VA_ARGS_ _ determines where the arguments will be substituted.
xxiv The C99 Standard
For example, given this definition
#define MyMax(. . .) max(__VA_ARGS__)
this statement
MyMax(a, b);
is transformed into
max(a, b);
There can be other arguments prior to the variable ones. For example, given
#define compare(compfunc, . . .) compfunc(__VA_ARGS__)
this statement
compare(strcmp, “one”, “two”);
is transformed into
strcmp(“one”, “two”);
As the example shows, _ _VA_ARGS_ _ is replaced by all of the remaining arguments.
C99 includes another way to specify a pragma in a program: the _Pragma operator. It has the following
general form:
_Pragma (directive)
Here, directive is the pragma being invoked. The addition of the _Pragma operator allows pragmas to
participate in macro replacement.
Built-in Pragmas
_ _STDC_ISO_10646_ _ A value of the form yyyymmL that states the year and
month of the ISO/IEC 10646 specification supported by the
compiler.
C99 enhances the for loop by allowing one or more variables to be declared within the initialization
portion of the loop. A variable declared in this way has its scope limited to the block of code controlled
by that statement. That is, a variable declared within a for loop will be local to that loop. This feature
has been included in C because often the variable that controls a for loop is needed only by that loop. By
localizing this variable to the loop, unwanted side effects can be avoided.
Here is an example that declares a variable within the initialization portion of a for loop:
#include <stdio.h>
int main(void)
{
// declare i within for
for(int i=0; i < 10; i++)
printf(“%d ”, i);
return 0;
}
Here, i is declared within the for loop, rather than prior to it.
As mentioned, a variable declared within a for is local to that loop. Consider the following program.
Notice that the variable i is declared twice: at the start of main( ) and inside the for loop.
#include <stdio.h>
int main(void)
{
int i = -99;
// declare i within for
for(int i=0; i < 10; i++)
printf(“%d”, i);
printf(“\n”);
xxvi The C99 Standard
printf(“Value of i is: %d”, i); // displays-99
return 0;
}
This program displays the following:
0123456789
Value of i is: -99
As the output shows, once the for loop ends, the scope of the i declared within that loop ends. Thus, the
final printf( ) statement displays 99, the value of the i declared at the start of main( ).
The ability to declare a loop-control variable inside the for has been available in C++ for quite some
time, and is widely used. It is expected that most C programmers will do the same.
Compound Literals
C99 allows you to define compound literals, which are array, structure, or union expressions designat-
ing objects of the given type. A compound literal is created by specifying a parenthesized type name,
which is then followed by an initialization list, which must be enclosed between curly braces. When the
type name is an array, its size must not be specified. The object created is unnamed.
Here is an example of a compound literal:
double *fp = (double[]) {1.0, 2.0, 3.0};
This creates a pointer to double, called fp, which points to the first of a three-element array of double
values.
A compound literal created at file scope exists throughout the lifetime of the program. A compound
literal created within a block is a local object that is destroyed when the block is left.
C99 allows you to specify an unsized array as the last member of a structure. (The structure must have
at least one other member prior to the flexible array member.) This is referred to as a flexible array
member. It allows a structure to contain an array of variable size. The size of such a structure returned
by sizeof does not include memory for the flexible array.
Typically, memory to hold a structure containing a flexible array member is allocated dynamically,
using malloc( ). Extra memory must be allocated beyond the size of the structure to accommodate the
desired size of the flexible array.
For example, given
struct mystruct {
int a;
int b;
float fa[]; // flexible array
};
the following statement allocates room for a 10-element array:
The C99 Standard xxvii
struct mystruct *p;
p = (struct mystruct *) malloc(sizeof(struct mystruct) + 10 *
sizeof(float));
Since sizeof(struct mystruct) yields a value that does not include any memory for fa, room for the 10-
element array of floats is added by the expression
10 * sizeof(float)
when malloc( ) is called.
Designated Initializers
A new feature of C99 that will be especially helpful to those programmers working with sparse arrays is
designated initializers. Designators take two forms: one for arrays and one for structures and unions.
For arrays, the following form is used,
[index] = val
where index specifies the element being initialized to the value val. For example:
int a[10] = { [0] = 100, [3] = 200 };
Here, only elements 0 and 3 are initialized.
For structure or union members, the form used is:
. member-name
Using a designator with a structure allows an easy means of initializing only selected members of a
structure.
For example:
struct mystruct {
int a;
int b;
int c;
} ob = { .c = 30, .a = 10 };
Here, b is uninitialized.
Using designators also allows you to initialize a structure without knowing the order of its members.
This is useful for predefined structures, such as div_t, or for structures defined by some third party.
C99 adds to the printf( ) and scanf( ) family of functions the ability to handle the long long int and
unsigned long long int data types. The format modifier for long long is ll.
For example, the following fragment shows how to output a long long int and an unsigned long long
int:
long long int val;
unsigned long long int u_val;
printf(“%lld %llu”, val, val2);
xxviii The C99 Standard
The II can be applied to the d, i, o, u, and x format specifiers for both printf( ) and scanf( ).
C99 adds the hh modifier, which is used to specify a char argument when using the d, i, o, u, or x
format specifiers. Both the ll and hh specifiers can also be applied to the n specifier.
The format specifiers a and A, which were added to printf( ), cause a floating-point value to be
output in a hexadecimal format. The format of the value is
[-]0xh.hhhhp+d
When A is used, the x and the p are uppercase. The format specifiers a and A were also added to
scanf( ), and read a floating-point value.
In a call to printf( ), C99 allows the 1 modifier to be added to the %f specifier (as in %lf), but it has
no effect. In C89, %lf is undefined for printf( ).
C99 adds several new libraries and headers. They are shown here:
Header Purpose
<complex.h> Supports complex arithmetic.
<fenv.h> Gives access to the floating-point status flags and other
aspects of the floating-point environment.
<inttypes.h> Defines a standard, portable set of integer type names.
Also supports functions that handle greatest-width inte-
gers.
<iso646.h> Added in 1995 by Amendment 1. Defines macros that
correspond to various operators, such as && and ^.
<stdbool.h> Supports Boolean data types. Defines the macros bool,
true, and false, which help with C++ compatibility.
<stdint.h> Defines a standard, portable set of integer type names.
This header is included by <inttypes.h>.
<tgmath.h> Defines type-generic floating-point macros.
<wchar.h> Added in 1995 by Amendment 1. Supports multibyte and
widecharacter functions.
<wctype.h> Added in 1995 by Amendment 1. Supports multibyte and
widecharacter classification functions.
C99 defines _ _func_ _, which specifies the name (as a string literal) of the function in which
_ _func_ _ occurs.
For example:
void StrUpper(char *str)
The C99 Standard xxix
{
static int i = 0;
i++;
printf(“%s has been called %d time(s).\n”, __func__, i);
while(*str) {
*str = toupper(*str);
str++;
}
}
When called the first time, StrUpper( ) will display this output:
StrUpper has been called 1 time(s).
The term translation limits refers to the minimum number of various elements that a C compiler must
be able to handle. These include such things as the length of identifiers, levels of nesting, number of case
statements, and number of members allowed in a structure or union. C99 has increased several of these
limits beyond the already generous ones specified by C89.
Here are some examples:
Limit C89 C99
Nesting levels of blocks 15 127
Nesting levels of conditional inclusion 8 63
Significant characters in an internal identifier 31 63
Significant characters in an external identifier 6 31
Members of a structure or union 127 1023
Arguments in a function call 31 127
Several years ago, C++ dropped the implicit int rule, and with the advent of C99, C follows suit. In C89,
the implicit int rule states that in the absence of an explicit type specifier, the type int is assumed. The
most common use of the implicit int rule was in the return type of functions. In the past, C programmers
often omitted the int when declaring functions that returned an int value.
For example, in the early days of C, main( ) was often written like this:
main ()
{
/* . . . */
}
xxx The C99 Standard
In this approach, the return type was simply allowed to default to int. In C99 (and in C++) this default no
longer occurs, and the int must be explicitly specified, as it is for all of the programs in
this book.
Here is another example. In the past a function such as
int isEven(int val)
{
return !(val%2);
}
would often have been written like this:
/* use integer default */
isEven (int val)
{
return !(val%2);
}
In the first instance, the return type of int is explicitly specified. In the second, it is assumed by default.
The implicit int rule does not apply only to function return values (although that was its most
common use).
For example, for C89 and earlier, the isEven( ) function could also be written like this:
isEven(const val)
{
return ! (val%2);
}
Here, the parameter val also defaults to intin this case, const int. Again, this default to int is not
supported by C99.
Note Technically, a C99-compatible compiler can accept code containing implied ints after re-
porting a warning error. This allows old code to be compiled. However, there is no requirement
that a C99-compatible compiler accept such code.
In C89, if a function is called without a prior explicit declaration, then an implicit declaration of that
function is created. This implicit declaration has the following form:
extern int name( );
Implicit function declarations are no longer supported by C99.
Note Technically, a C99-compatible compiler can accept code containing implied function dec-
larations after reporting a warning error. This allows old code to be compiled. However, there is
no requirement that a C99-compatible compiler accept such code.
The C99 Standard xxxi
Restrictions on return
In C89, a function that has a non-void return type (that is, a function that supposedly returns a value)
could use a return statement that did not include a value. Although this creates undefined behaviour, it
was not technically illegal. In C99, a non-void function must use a return statement that returns a
value. That is, in C99, if a function is specified as returning a value, any return statement within it must
have a value associated with it. Thus, the following function is technically valid for C89, but invalid for
C99:
int f(void)
{
/* . . . */
return ; // in C99, this statement must return a value
}
C99 defines several extended integer types in <stdint.h>. Extended types include exact-width, mini-
mum-width, maximum-width, and fastest integer types.
Here is a sampling:
C99 adds several format modifiers to printf( ): hh, ll, j, z, and t. The hh modifier can be applied to d, i,
o, u, x, X, or n. It specifies that the corresponding argument is a signed or unsigned char value or, in
the case of n, a pointer to a signed char variable. The ll modifier also can be applied to d, i, o, u, x, X,
or n. It specifies that the corresponding argument is a signed or unsigned long long int value or, in the
case of n, a pointer to a long long int. C99 also allows the l to be applied to the floating-point specifiers
a, A, e, E, f, F, g, and G, but it has no effect. The j format modifier, which applies to d, i, o, u, x, X, or
n, specifies that the matching argument is of type intmax_t or uintmax_t. These types are declared in
<stdint.h> and specify greatest-width integers. The z format modifier, which applies to d, i, o, u, x, X,
or n, specifies that the matching argument is of type size_t. This type is declared in <stddef.h> and
specifies the result of sizeof.
The t format modifier, which applies to d, i, o, u, x, X, or n, specifies that the matching argument is of
type ptrdiff_t. This type is declared in <stddef.h> and specifies the difference between two pointers.
Sample code
#include <stdio.h>
int main(void)
{
/* This prints ''this is a test" left justified
in 20 character field.
*/
printf(“%-20s”, “this is a test”);
/* This prints a float with 3 decimal places in a 10
character field. The output will be " 12.235".
*/
printf(“%10.3f”, 12.234657);
return 0;
}
C99 enhances the integer promotion rules. In C89, a value of type char, short int , or an int bit-field can
be used in place of an int or unsigned int in an expression. If the promoted value can be held in an int,
the promotion is made to int; otherwise, the original value is promoted to unsigned int.
The C99 Standard xxxiii
In C99, each of the integer types is assigned a rank. For example, the rank of long long int is greater
than int, which is greater than char, and so on. In an expression, any integer type that has a rank less
than int or unsigned int can be used in place of an int or unsigned int.
Code Format
%a Hexadecimal output in the form 0xh.hhhhp+d (C99 only).
%A Hexadecimal output in the form 0Xh.hhhhP+d (C99 only).
%c Character.
%d Signed decimal integers.
%i Signed decimal integers.
%e Scientific notation (lowercase e).
%E Scientific notation (uppercase E).
%f Decimal floating point.
%F Decimal floating point (C99 only; produces uppercase INF, INFINITY,
or NAN when applied to infinity or a value that is not a number. The %f
specifier produces lowercase equivalents.)
%g Uses %e or %f, whichever is shorter.
%G Uses %E or %F, whichever is shorter.
%o Unsigned octal.
%s String of characters.
%u Unsigned decimal integers.
%x Unsigned hexadecimal (lowercase letters).
%X Unsigned hexadecimal (uppercase letters).
%p Displays a pointer.
%n The associated argument must be a pointer to an integer. This specifier
causes the number of characters written (up to the point at which the
%n is encountered) to be stored in that integer.
%% Prints a percent sign.
RESTRICT-QUALIFIED POINTERS
The C99 standard has added a new type qualifier that applies only to pointers: restrict. A pointer
qualified by restrict is initially the only means by which the object it points to is accessed. Access to the
object by another pointer can occur only if the second pointer is based on the first. Thus, access to the
object is restricted to expressions based on the restrict-qualified pointer. Pointers qualified by restrict
are primarily used as function parameters or to point to memory allocated via malloc( ). By qualifying
a pointer with restrict, the compiler is better able to optimize certain types of routines. For example, if
a function specifies two restrict-qualified pointer parameters, then the compiler can assume that the
pointers point to different (that is, non-overlapping) objects. The restrict qualifier does not change the
semantics of a program.
xxxiv The C99 Standard
1. /* Write a program to test the given string is palindrome or not. implement the program
by using _Bool datatype */
#include<stdio.h>
#include<string.h>
enum _Bool{false,true}; // _Bool DataType which is capable of
storing the vales 0 and 1
enum _Bool IsPalindrome(char string[]) // _Bool datatype
{
int left,right,len=strlen(string);
enum _Bool matched=true; // _Bool datatype
if(len==0)
return 0;
left=0;
right=len-1;
/* Compare the first and last letter,second & second last & so
on */
while(left<right&&matched)
{
if(string[left]!=string[right])
matched=false;
else
{
left++;
right--;
}
}
return matched;
}
int main()
{
char string[40];
clrscr();
printf("****Program to test if the given string is a
palindrome****\n");
printf("Enter a string:");
scanf("%s",string);
if(IsPalindrome(string))
printf("The given string %s is a palindrome\n",string);
else
printf("The given string %s is not a palindrome\n",string);
getch();
return 0;
}
The C99 Standard xxxv
2. /* In C89, within a block, all declarations must precede the first code statement. This rule
does not apply for C99 */
#include<stdio.h>
int main(void)
{
int i;
i=10;
int j; //wrong for c89; ok for c99
j=i;
clrscr();
printf("%d %d",i,j);
return 0;
getch();
}
3. /* Write a program to print the signed and unsigned numbers by using C99 standards*/
#include<stdio.h>
int main(void)
{
int i= -99;
{
for(int i=0; i<10; i++) //declare i within for
printf("%d",i);
printf("\n");
}
printf("Value of i is: %d",i); //display-99
return 0;
}
4. /* Write a program to open the file by using C99 standards */
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
FILE *fp;
if((fp=fopen("test","wb"))==NULL);
{
printf("cannot open file.\n");
exit(1);
fprintf(fp,"this is a test %d %f", 10,20.01); // fprintf
fclose(fp);
return 0;
}
}
xxxvi The C99 Standard
5. /* Write a C program that uses functions to perform the following operations by using
C99 standards(_Complex, _Imaginary):
(i) Reading a complex number
(ii) Writing a complex number
(iii) Addition of two complex numbers
(iv) Multiplication of two complex numbers
(Note: represent complex number using a structure.) */
#include<stdio.h>
#include<math.h>
#include<complex.h>
struct comp
{
double realpart;
double _Imaginary;
};
void main()
{
int opern;
clrscr();
printf("\n\n \t\t\t***** MAIN MENU *****");
printf("\n\n Select your option: \n1 : ADD\n2 : MULTIPLY\n0 :
EXIT \n\n\t\t Enter your Option [ ]\b\b");
scanf("%d",&opern);
switch(opern)
{
case 0:
exit(0);
case 1:
case 2:
_Complex(opern);
default:
main();
}
{
struct comp w1, w2, w;
printf("\n Enter two Complex Numbers (x+iy):\n Real Part of
First Number:");
scanf("%lf",&w1.realpart);
printf("\n Imaginary Part of First Number:");
scanf("%lf",&w1._Imaginary);
printf("\n Real Part of Second Number:");
scanf("%lf",&w2.realpart);
printf("\n Imaginary Part of Second Number:");
scanf("%lf",&w2._Imaginary);
switch(opern)
{
/*addition of complex number*/
case 1:
w.realpart = w1.realpart+w2.realpart;
w._Imaginary = w1._Imaginary+w2._Imaginary;
break;
w._Imaginary=(w1.realpart*w2._Imaginary)+(w1._Imaginary*w2.realpart);
break;
}
if (w._Imaginary>0)
printf("\n Answer = %lf+%lfi",w.realpart,w._Imaginary);
else
printf("\n Answer = %lf%lfi",w.realpart,w._Imaginary);
getch();
main();
}
6. /* Write a program to find the maximum number by using C99 standards(inline keyword)
*/
#include <stdio.h>
inline int max(int a, int b) // inline keyword
{
return a > b ? a : b;
xxxviii The C99 Standard
}
int main(void)
{
int x=5, y=10;
printf("Max of %d and %d is: %d\n", x,y,max(x,y));
return 0;
}
7. /* Write a C program to generate Pascal's Triangle by using C99 standards */
#include<stdio.h>
#include<conio.h>
void main()
{
int bin,q,r;
clrscr();
bin=1;
q=0;
printf("\nPascal's Triangle:\n");
while(q<r)
{
for(int p=40-3*q;p>0;--p) // declare p with in for
printf(" ");
for(int x=0;x<=q;++x) // declare x with in for
{
if((x==0)||(q==0))
bin=1;
else
bin=(bin*(q-x+1))/x;
printf("%6d",bin);
}
printf("\n");
++q;
}
getch();
}
The C99 Standard xxxix
8. /* Write a C program to generate all the prime numbers between 1 and n, where n is a
value supplied by the user by using C99 standards.(long long int,declare variables with in
for loop) */
#include <stdio.h>
void main()
{
long long int no,check; // long long int
clrscr();
printf("<-----------------------PRIME NO. SERIES--------------
---------->");
printf("\n\n\n\t\t\tINPUT THE VALUE OF N: ");
scanf("%d",&no);
printf("\n\nTHE PRIME NO. SERIES B/W 1 TO %lld : \n\n",no);
10. /* Write a program for addition of matrices by using the restrict keyword */
void fadd(double a[static restrict 10],
const double b[static restrict 10]) // restrict keyword, restricrts a and b
{
int i;
for(i=0; i<10; i++)
{
if(a[i] < 0.0)
return;
a[i] += b[i];
}
return;
}
11. /* Write a C program to find the roots of a quadratic equation by using format modifiers
in C99. */
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float a,b,c,root1,root2;
clrscr();
printf("\n Enter values of a,b,c for finding roots of a qua-
dratic eq:\n");
scanf("%f%f%f",&a,&b,&c);
/*checking condition*/
if(b*b>4*a*c)
{
root1=-b+sqrt(b*b-4*a*c)/2*a;
root2=-b-sqrt(b*b-4*a*c)/2*a;
printf("\n*****ROOTS ARE*****\n");
printf("\nroot1=%1.3f\nroot2=%1.2f",root1,root2); //format
modifiers for printf()
}
else
printf("\n Imaginary Roots.");
getch();
}
The C99 Standard xli
12. /* Write a C program to find the sum of individual digits of a positive integer by using long
long int in C99 standards*/
#include<stdio.h>
#include<conio.h>
void main()
{
long long int num, k=1, sum=0; // long long int
clrscr();
printf("Enter the number whose digits are to be added:");
scanf("%lld",&num);
while(num!=0)
{
k=num%10;
sum=sum+k;
k=num/10;
num=k;
}
printf("Sum of the digits:%lld",sum);
getch();
}
UNIT I
Chapter
1
Algorithms
1.1 INTRODUCTION
There is a tremendous similarity between the human actions and the way a computer performs various
functions. Nicholas Wirththe inventor of a computer languagePascal used to say A program is
equal to algorithm + data. In the next few chapters, we will explore the meaning of these terms; first
learning about and clearly analyzing human actions and then showing how computers also act similarly,
thereby demystifying the complexity that surrounds computers.
We perform hundreds of activities during a day. An activity could be anything from brushing teeth to
making tea and from going to work to having dinner. There are two basic ways to describe in detail, any
of these activities:
1. By describing the process step-by-stepcalled as algorithm.
2. By representing the various steps in the form of a diagramcalled as flow chart.
1.1.1 Algorithm/pseudocode
The term algorithm is very popular in the computer literature. An algorithm is also called pseudocode.
At first, it might sound very complex. However, it is very simple to understand. In fact, we all perform
hundreds of algorithms in our daily life without even realizing it!
Algorithm is the step-by-step method of performing any task. When we break up a big task into
smaller steps, what we actually do is to create an algorithm. In other words, we perform hundreds of
algorithms. Brushing teeth, making tea, getting ready for school or office, are all different algorithms.
For example, when making a cup of tea, we follow the algorithm as shown in Fig. 1.1 (with a few
variations, of course!).
An interesting observation: Many steps can be further sub-divided into still smaller sub-steps. For
example, we can write an algorithm for Step 1 (Boil water) by writing detailed steps for boiling water.
However, it is up to an individual as to how detailed steps one should describe. Each step can be called
as an instruction. Also, we can notice that steps 4 and 5 can be executed in parallel, i.e. we can boil
milk while we wait. In actual life, there is a tremendous amount of parallelism in many of our actions.
We normally hear, see and feel simultaneously to comprehend a situation. Within this also, when we see
1.4 C Programming and Data Structures
a picture, for example, actually we see millions of spots of the picture to generate an image on our retina
while we compare all dots in parallel with already stored millions of images to identify an object instan-
taneously! Therefore, parallel computing was developed to speed up things and ultimately try to
imitate human actions in artificial intelligence. We need not discuss these in detail in later chapters,
but continue with serial algorithms for now.
Begin
1. Boil water.
2. Put tea powder in the kettle.
3. Pour boiled water in the kettle.
4. Wait for three minutes.
5. Boil milk.
6. Put boiled milk in a cup.
7. Add sugar to the cup.
8. Empty the kettle in the cup.
9. Stir the cup with a spoon.
End
There is another way to write the steps involved in any process. This is by making use of various
symbols. The symbols form a diagram that represents the steps in a pictorial fashion similar to an
algorithm. This is also very easy to understand. Such a diagram is called flow chart. In its simplest
form, a flow chart consists of a series of rectangles connected to each other by arrows. The rectangles
represent the various steps and the arrows designate the flow. A flow chart for our tea-making example
could be drawn as in Fig. 1.2.
The tea-making algorithm and flow chart discussed earlier were quite simple. One step followed another
in a sequential fashion. However, things are not so simple in real life! There are so many ifs and buts.
For example, consider the following statements:
∑ If it is 9 am, I must go to the office.
∑ If it is raining, take your umbrella with you.
∑ Read each line and say it loudly until the end of this page.
How do we take care of such things in an algorithm and a flow chart? And how many different kinds
of situations we must cater to? This section attempts to answer these questions.
In general, the steps in an algorithm can be divided in three basic categories as listed below:
∑ SequenceA series of steps that we perform one after the other
∑ SelectionMaking a choice from multiple available options
∑ IterationPerforming repetitive tasks
These three basic categories of activities combined in different ways can form the basis for describ-
ing any algorithm. It might sound surprising initially. But it is true. Think of any situation in our daily
life and try to fit it in one of the three categories: it works!
Let us now look at each of the categories in more detail.
1.2.1 Sequence
A sequence is a series of steps that we follow in any algorithm without any break, i.e. unconditionally.
The algorithm for making tea described in Fig. 1.1 belongs to this category. Figure 1.3 describes another
algorithm in this category for boiling water. What this means is that we have exploded further the step
or instruction 1 in the algorithm for making tea given in Fig. 1.1. We can explode all such steps in Fig.
1.1 in the following way.
Begin
1. Take a utensil.
2. Take the utensil to the water tap.
3. Open the tap.
4. Fill the utensil with water.
5. Close the tap.
6. Put the utensil on the gas or in the oven.
7. Start the gas or the oven.
8. Wait until the water boils.
9. Switch off the gas or the oven.
End
We will not draw the flow chart for boiling water. It should be clear by now that it is a matter of
writing all of the above 9 steps in rectangles one after the other; each connected to its successor by an
arrow.
1.2.2 Selection
We will quickly realize that only sequence is not good enough to express an algorithm. Quite a few of
our actions depend on certain events. Thus, there is a need to be able to make a choice from many
available options. Therefore, there is a process of selection. A selection statement generally takes the
form as shown in Fig. 1.4.
1. If
2. Then
3. End-if
We take so many decisions, small and big, in our daily life without even realizing it. For example, if
it is hot, we switch on the fan. We can depict this selection process as shown in Fig. 1.5.
1. If it is hot
2. Then switch on the fan
3. End-if
Note that End-if is an additional step that indicates the end of the selection process. A question may
be asked: is End-if really necessary? Let us illustrate this by the following selection process that does
not have an End-if. Refer to Fig. 1.6.
1. If the guest wants tea
2. Then make tea
3. Offer biscuits
What do we do if the guest does not want tea? Do we offer him biscuits? It is not clear from the
selection process described above. It can be argued and proved either way. That is, we are not sure
whether the Offer biscuits portion is a part of our If condition or not. A miserly person would always say
that he considers Offer biscuits as a part of the condition, and hence would only offer biscuits to some-
one who wants tea! Hence, it is always better to end a selection process with an End-if to avoid any
confusion at least for our algorithms. Different computer programming languages have different con-
ventions.
The position and placement of End-if instructions can change the meaning of the entire algorithm as
shown in Fig. 1.7 (a) and 1.7 (b). Let us study the algorithm shown in Fig. 1.7 (a). If the guest wants tea,
the algorithm will execute step 2 after step 1 (i.e. make tea), then fall through step 3 and then step 4 (i.e.
offer biscuits). Thus, if the guest wants tea, he gets the biscuits, too! Now, let us trace the algorithm if
the guest does not want tea. In this case, the algorithm will follow step 3 after step 1 (i.e. skip the tea)
and then fall through step 4 (i.e. offer biscuits). Thus, biscuits will be offered regardless of tea. If we
study algorithm shown in Fig. 1.7 (b), we will notice that biscuits are offered only with tea. If the guest
Exploring the Variety of Random
Documents with Different Content
reflections of the kind. Speaking of a new arbour he had made, be
says—
The Wrekin was a favourite object; to its summit he made his annual
pilgrimage, together with his family, his Dale relations, his clerks,
and most of the members of the little Society of Friends. The
following bit of landscape painting betrays a master hand, and is so
faithful in itself, depicting no less the features of the country than
the genius of his mind, that we incorporate it with our present
sketch:—
“We went upon the Wrekin,” he writes, “sooner than usual this
year, that my children might partake of the pleasure. The
weather was pleasant, though rather windy. From the top of
that hill the prospect is so rich, so extensive, so various, that,
considered as a landscape only, it beggars all description; and
yet I cannot forbear, as thou desirest it, mentioning the tufted
trees in the adjoining woods, upon which, occasioned perhaps
by the uncommonness of the scene, I always look down with a
particular pleasure, as well as survey those more distant, which
are interspersed among the corn and meadows, contrasted with
the new-ploughed fallow-grounds and pastures with cattle; the
towns and villages, gentlemen’s seats, farm-houses, enrich and
diversify the prospect, whilst the various companies of harvest
men in the different farms within view enliven the scene. Nor
are the rivers that glitter among the laughing meadows, or the
stupendous mountains which, though distant, appear awfully
dreary without their effect considered part of the landscape
only. But not to confine the entertainment to visual enjoyment,
what an intellectual feast does the prospect from that hill afford
when beheld, ‘or with the curious or pious eye.’ Is not infinite
power exerted, and infinite goodness displayed, in the various
as well as plentiful provision for our several wants. Should not
the consideration expand over hearts with desires to contribute
to the relief of those whose indigence, excluding them from an
equal participation of the general feast, is for a trial of their faith
and patience and of our gratitude and obedience! Whilst with
an appropriation of sentiment which receives propriety from the
consciousness of our unworthiness, we substitute a particular
for the general exclamation of humble admiration, in the word
of the psalmist—‘Lord, what is man, that thou art mindful of
him? or the son of man that thou (thus) visitest him?’ The
romantic scenes of Benthall Edge,—its rocks and precipices, its
sides and top covered with wood; the navigable Severn, in
which its feet are immersed; the populousness of the opposite
shore; the motion, noise, and life on the river; the adjoining
wharves and manufactories, are capable of affording a high
entertainment, and I should willingly devote one day in the year
to a repetition of the enjoyments of the pleasures I have
heretofore received from them: though equally near, and equally
desirable, a jaunt to Benthall Edge is not equally facile with one
to the Wrekin. It seems more out of my province.”
“John Birtell has paid £48 4s. 7d. for the pictures, frames and
cases, which should be repaid to him. I understood from S. A.
it was thy wish to make thy sister a present of one of them, and
in that case please to remit the amount to John Birtell; if she (S.
A.) is mistaken, remit the money to J. B. nevertheless, and I will
repay thee the half of it; but I insist upon one condition both
from thee and thy sister: that as long as I live, the pictures be
nowhere but in your bed-chambers. The first was begun
without my knowledge, and indirect means used to accomplish
it; at length I was candidly told it was determined to have it,
and when I saw what was done, I thought it better to sit for the
finishing than to have it a mere caricature; but I think it a very
moderate performance at last. I was willing too, to avail myself
of the opportunity, if such a one must be presented, of
exhibiting my belief of Christianity as exhibited in the 5th
chapter of the Romans; and my estimation of certain authors,
by affixing their names to the books delineated in the back
ground.”
The years 1774, 1782, and 1796 were periods of great distress.
Haggard hunger, despairing wretchedness, and ignorant force were
banded to trample down the safeguards of civil right, and armed
ruffians took the initiative in scrambles for food. The gravity of the
occasion, in the latter case, may be estimated by the subscriptions
for the purchase of food for the starving population. We give those
of the iron companies of this district only: Messrs. Bishton and Co.
gave £1,500; Mr. Botfield, for the Old Park Company, £1,500; Mr.
Joseph Reynolds, for the Ketley Company, £2,000; Mr. R. Dearman,
for the Coalbrookdale Company, £1,500; Mr. William Reynolds, for
the Madeley-Wood Company, £1000. Mr. Richard Reynolds gave
£500 as his individual subscription. Applications, in times of distress,
from far and near were made to Mr. Reynolds for assistance. Taking
a general view of the distress existing in the beginning of the year
1811, he says, in reply to a letter from a clergyman, “I am thankful I
am not altogether without sympathy with my fellow-men, or
compassion for the sufferings to which the want of employment
subjects the poor, or the sufferings still more severe of some of their
former employers. Thou mentions Rochdale, Bolton, Leeds, and
Halifax. Wilt thou apply the enclosed towards the relief of some of
them, at thy discretion? Those who want it most and deserve it best
should have the preference,—the aged, honest, sober, and
industrious. I am sensible how limited the benefits from such a sum
in so populous a district must be, and of the difficulty of personal
investigation before distribution. If it could be made subservient to
the procuring an extensive contribution it would be of more
important service. If it cannot I think it would be best to commit it
to some judicious person or persons in each place, to distribute with
the utmost privacy, and (that) for their own sakes, were it only to
avoid applications from more than they could supply, and yet the
refusal would subject them to abuse. But in whatever manner thou
shalt dispose of it, I send it upon the express condition that nobody
living knows thou ever had it from me; this is matter of conscience
with me. In places where we are known, and on public occasions,
when one’s example would have an influence, it may be as much a
duty to give up one’s name as one’s money; but otherwise I think
we cannot too strictly follow the injunction:—‘Take heed that ye do
not your alms before men to be seen of them, otherwise ye have no
reward of your Father which is in heaven.’”
If some poor tradesman in London or elsewhere was tottering on the
verge of bankruptcy, and a friend was found to write to Richard
Reynolds, he was put upon his legs again. Poor debtors found
themselves relieved from the King’s Bench by an unknown hand.
Unwilling to be known as the giver of large sums, he would
sometimes forward his subscriptions with his name, and send a
larger contribution anonymously afterwards. In this way he gave a
sum in his own name on behalf of the distress in Germany, and then
forwarded a further sum of £500 privately. For years he had
almoners in London and elsewhere, dispensing sums to meet
distress, and on behalf of public and private charities, scrupulously
enacting that his name should not appear in the transactions. To
one party he sent £20,000 during the distress of 1795. He had four
distributors of his bounty constantly employed in Bristol alone. They
brought in their accounts weekly, giving the names of persons or
families, the sums given, and the circumstances under which they
were relieved. Not the least to be appreciated was the consideration
and delicacy with which he assisted persons not ostensibly objects of
charity (to use the word in its common sense) and many who,
through relationship, personal interest, or estimable conduct were
felt to have claims on his kindness and generosity.
He solicited in Bristol subscriptions on a large scale for augmenting
the fund for the payment of a weekly sum to the inhabitants of the
almshouses, going from house to house,—his own zeal kindling that
of others. One gentleman to whom he applied, of acknowledged
wealth and importance in the city, having given him a cheque for
£500, he said he would give him back the cheque, as such a sum
from him would do more harm than good. The gentleman
immediately wrote another for £1000. He himself gave £2000 (one
of his friends says £4000), and £4000 to the Trinity almshouses. In
1808 he placed in the hands of the trustees the sum of £10,500 to
be invested in land, the rent of which was to be devoted to seven
charitable institutions in Bristol, named in the deed and trust, in such
manner and proportion, either to one alone, or between any, as
should at the time appear expedient to the trustees. An addition to
the infirmary being needed, he devoted much of his time to that
object, subscribing £2,600. The committee also received an
anonymous donation of £1000, entertaining no doubt who was the
giver; and on the following day one of their number happening to
meet Richard Reynolds, thanked him in the name of the committee
for his acceptable donation. He said—“Thou hast no authority for
saying I sent the money,” and the gentleman repeating the
acknowledgment of the committee, Mr. Reynolds quietly said—“Well,
I see thou art determined that I should give thee a thousand
pounds,” and the next day they received a donation of that sum with
his name attached, thus doubling his first contribution. To these
gifts may be added (besides his annual subscription) donations:—
£1,260 to the Stranger’s Friend; £900 to the Misericordia; £500 to
the Refuge, and the same to the Orphan Asylum; and to the Bible
Society, £900. Of several other small amounts one need only be
mentioned, from his purse,—that of £300 to the Temple parish,
towards providing a better supply of water to the poor.
Mr. Reynolds’s last visit to Ketley, the scene of his labours, and the
source of his vast income, was in June, 1816. His funeral took place
on the 18th of September, amidst a manifestation of respect, as
marked and profound as ever was paid to the remains of mortal
man. The city of Bristol offered spontaneously to his memory that
signal tribute of general regard that a name embalmed by good
deeds alone can win. Columns of schoolboys, with mournful
recollections of the good man’s smile, formed a melancholy passage
to the dwelling of their benefactor. These were flanked by vast
crowds of sympathising poor, who felt they had lost a friend. The
clergy of the Church of England, ministers of dissenting
congregations, gentlemen forming the committees of various
societies, and other leading men, besides a large body of the Society
of Friends, followed the several members and relatives of the family
in procession. So great was public curiosity excited on this occasion,
and such the eagerness manifested by the poor, who had lost their
best friend, to pay their last respect to his remains, that not only
was the spacious burial-ground filled with spectators and mourners,
but the very tops of walls and houses surrounding the area were
covered. The behaviour of the vast concourse of people was in the
highest degree decent, orderly and respectful, the poor, considering
it a favour to be permitted in their turn to approach the grave of
their departed friend, and to drop the silent tear as a mark of their
regard for the man whose life had been spent in doing good.
Montgomery, in verses from which we extract the following, paid a
just tribute to his memory:
William Reynolds.
The father, Richard Reynolds, as will be seen from our sketch,
managed to realize immense wealth at Ketley, and, what is more, to
remain superior to the influence wealth too often has upon its
possessor. The finer feelings of the man never succumbed to the
vulgar circumstances of his position, but maintained their freshness,
and graduated to maturity by the mastering force of a resolute will
and a well-disciplined and highly enlightened mind. Never so
completely absorbed in the arts and intricacies of money-making as
to lose sight of higher and worthier aims, he sought an opportunity
earlier than men in his circumstances usually do of enjoying the
well-earned fruits of an active life; of indulging in that repose and
retirement congenial to minds similarly constituted to his own.
Accordingly, his shares in the works were turned over to his two
sons, William and Joseph. William was the more distinguished of the
two in carrying out improvements connected with the works. Like
his father, he possessed an active mind, an elevated taste, and a
desire for knowledge; to which were added a mechanical genius,
and an aptitude for turning to account resources within his reach.
He saw the necessity of uniting science with practice in developing
the rich resources of the district; and that knowledge and discovery
must keep pace with aptitude in their use.
Upon this principle Mr. Reynolds placed himself under the teaching of
Dr. Black, the discoverer of latent heat, a gentleman who by his
eminent ability and teaching did so much to inspire a love for the
science in England during the latter part of the last century. He was
thus enabled to bring the knowledge he possessed of elementary
substances and of their peculiar qualities, gained in the laboratory,
to bear upon the manufacture of iron in the furnace and the forge,
and to anticipate some of the discoveries of later times.
Steel and iron have long been manufactured at Ulverstone, and the
quality or fitness of the ore for the purpose is attributed to the
presence of manganese in the ore, which since the establishment of
railways has come into general use. In Mr. Reynolds’s time we
imported large quantities of iron and steel; and ignorant of what
constituted the difference between our own and that of foreign
markets, had with some humiliation to confess our dependence. In
no case had a uniform quality of bar-iron with the superior marks of
Sweden and Russia been produced. A great variety of processes
had been tried, and makers were not wanting who made laudable
efforts for the accomplishment of the object, feeling that in so doing
they devoted their time to the service of their country, and that in a
national as well as a commercial point of view no experiments were
fraught with more important consequences.
Mr. Reynolds thought he saw the solution of the problem how to
produce metal equal to that made from the magnetic and richer ores
of the Swedish and Siberian mines, when Bergman published his
analysis of Swedish iron, showing the large percentage of
manganese it contained. The analysis showed the following results:
Cast Iron.
Parts.
Plumbago 2.20
Manganese 15.25
Silicious Earth 2.25
Iron 80.30
100
Steel.
Plumbago .50
Manganese 15.25
Silicious Earth .60
Iron 83.65
100
Bar-Iron.
Plumbago .50
Manganese 15.25
Silicious Earth 1.75
Iron 84.78
100
This contrivance has been in use up to the present time. During Mr.
Reynolds’s life a representation of it figured upon copper tokens, one
of the first iron bridge being upon the opposite or obverse side.
Another of these contrivances is still in use near the Hay, in the
parish of Madeley, called the Coalport Incline. This is 207 feet in
length, and the gradient is much greater, being about one in three.
So great indeed that on the chain snapping we have known a canal
boat with five tons of iron pigs on board gain such velocity that on
coming in contact with the water in the lower canal it has broken
away from the iron chains which held it to the carriage, bounded
into the air, clearing two other boats moored on the side, together
with the embankment, and alighted in the Severn, close to the ferry-
boat, into which it pitched some of the iron-pigs it contained. At the
foot of this incline Mr. Reynolds drove a level to the shaft of the
Blissers Hill pits, to bring down the coals to the lower canal for
loading into barges on the Severn. This was the famous Tar Tunnel
from which petroleum was formerly exported in large quantities to
all parts of Europe.
William Reynolds removed from Ketley to a large house formerly
occupied by Lord Dundonald, at the Tuckies, where he continued to
superintend the ironworks he had leased at Madeley Wood, familiarly
known as Bedlam Furnaces, and was succeeded by his brother, Mr.
Joseph Reynolds, who continued to carry on the Ketley Works till the
recurrence of one of those fearful revulsions that have marked the
history of the trade. For a quarter of a century we had been
carrying on wars, levying troops, and interfering with everybody’s
business but that which properly belonged to ourselves. We had
obtained our object of ambition by bribery, strategy, and force of
arms combined. We had restored the ancient families of France,
reduced that country to its ancient limits, and annihilated its
commerce. With glorious victory came fearful collapse, and the
country awoke to find that a fallacy which it had been taught to
regard as truth—that war brings commercial advantages that
compensate for fearful waste and lavish expenditure. To add to the
calamity, a succession of bad harvests was experienced, and the
reduction of the army served to swell the poor’s-rates upon which
working men and their families had been thrown for a bare support.
Iron from £18 had gone down to £7 per ton, carriage paid from
Ketley to Stourport. Mr. Reynolds believed the trade would never
again rally, and resolved to blow out the furnaces at Ketley. This
was in 1817. In 1818, at an immense sacrifice of property,
consisting of the usual apparatus for making and manufacturing iron,
he sold off at an immense loss, and removed to Bristol. Language
cannot paint the deep distress which accompanied and followed this
step. Men, with wives and families dependent upon them, saw their
only ground of hope taken from them. Starving by thousands, and
yoked like horses, they might be seen drawing materials for the
repair of the roads, or conveying coal into Staffordshire. One third
of the Shropshire banks failed. Disturbances were frequent; mobs of
men collected in bodies and went about taking food where they
could find it, and the militia had often to be called out to quell
disturbances. Not only ironmasters, but manufacturers generally
were reduced to despair. The parish authorities of Wellington
advertised in the public journals for persons to come forward and
take the Ketley works; and a company, consisting of the Messrs.
Montford, Shakeshaft, Ogle, Williams, Hombersley, and others, was
formed.
From what we have written, it will be seen that Mr. William Reynolds
was on familiar terms with his men. In severe weather and
distressed times, he made soup to give away three times a week,
and he generally kept “open-house” for his workmen and friends; of
the latter he had a large circle. He did not like idleness or
indiscriminate almsgiving. A number of men thrown out of employ
came to him in a body for relief during a deep snow. He set them to
clear an entire field, and to make him a snow-stack; which they did
of large proportions, receiving daily wages for the same. He allowed
a house and garden rent-free to “Sniggy Oakes,” as he was called—
heaven knows what his right name was, for in that day it was
seldom known in the mining districts—on condition that the said
Sniggy ferry’d him and his family across the river when they required
it. One evening Sniggy, knowing he was out on the other side, went
to bed instead of sitting up, which he found a deal more comfortable
on a cold wet night, and Mr. Reynolds, after calling him first one
name and then another, ringing the changes upon every alias, and
changing it for “boat! boat!” “ferry! ferry!” had to go round by the
bridge. Coming opposite the cottage where Sniggy was snug in bed,
he smashed every window, shouting “boat” at every blow of his
huge stick. Sniggy roared with fright, and promised better things
another time. “On another occasion,” says our informant, “while
having a balcony put up in front of the Tuckies, he gave strict
injunctions that the martins’ nests should not by any means be
disturbed, threatening to shoot the man who violated his
instruction. They all obeyed him but one man, and he—.” “What,
you don’t mean to say he was going to carry out his threat?” said
we. “But he was,” it was replied, “and did.” “What shoot him?”
“Yes; shot him, sir—shot him with a pop-gun!” Being a Quaker,
many anecdotes are told of him not paying church-rates, and what
are called Easter offerings, showing a rich vein of genuine humour
running through a warm and generous nature. Old people too tell
with much glee of a grand illumination they remember to celebrate
one of those interludes of war, termed “a peace rejoicing,” when the
bridge across the river, and a large revolving wheel, were lighted up
with lamps, and the manufactory, in which—together with Messrs.
Horton and Rose—he was a shareholder, was illuminated.
“He is a wise son who knows his own father,” it is said, but it is
sometimes more difficult to trace the paternity of an anecdote, and
we tell the following as it was told to us.
“Mr. Reynolds was kind and generous to a fault, but he did not
like to be tricked. Returning late from a party on horseback, he
was requested to pay again at a turnpike gate. Old Roberts,
who having been in the army, looked with contempt upon all but
a red uniform, and hated Quakers’ plain suits in particular, the
more so as the wearers were known to be averse to war, now
found himself, as he imagined, in a position to ‘take the small
change,’ out of the Quaker. Mr. Reynolds disputed the charge,
knowing from the time he left his friend’s house that he must be
in the right; but, as the other insisted upon being paid, he paid
him. When the latter had opened the gate, Mr. Reynolds
remarked, ‘Well, friend, having paid, I suppose I am at liberty to
pass through as often as I like?’ ‘Certainly, sir,’ said the old
robber—as the juveniles would persist in calling the old man,
adding an additional ‘b’ to his name, and clipping it of the two
terminating letters. Mr. Reynolds had not travelled far on the
home-side of the gate—sufficiently far however to allow the
other to get into bed, before he returned, and called up the
gatekeeper; having occasion, as he said, to go back. By the
time he had again got into bed back came his tormentor at an
easy jog-trot pace; and as he again passed through the gate he
begged to be accommodated with a light. ‘Thou art sure it is
past twelve o’clock, friend?’ said Mr. Reynolds. ‘Quite sure,’ said
the other, adding ‘I thought I had done with you for to-night.’
‘Thou art mistaken,’ said Mr. Reynolds, ‘it is a fine night, and I
intend to make the most of it.’ In about ten minutes time the
hated sound of ‘Gate, gate,’ brought old Roberts to his post,
muttering curses between his teeth. ‘Thou art quite sure it is
past twelve, art thou?’ was the question asked, and asked
again, till at last the gatekeeper begged of his tormentor to take
back the toll. ‘It cured him, though,’ said our informant, ‘and
made him civil; but they called him ‘Past Twelve’ for the rest of
his days.’”
ebookgate.com