100% found this document useful (2 votes)
21 views

Computer Programming - eBook PDF instant download

The document provides information on various computer programming eBooks available for download, including titles like 'Python Programming: An Introduction to Computer Science' and 'Programming Language Pragmatics'. It also features details about the author E Balagurusamy, his qualifications, and contributions to the field of computer science. Additionally, the document outlines the contents of a computer programming textbook, covering topics such as C programming basics, decision making, user-defined functions, and arrays.

Uploaded by

bourkassan21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
21 views

Computer Programming - eBook PDF instant download

The document provides information on various computer programming eBooks available for download, including titles like 'Python Programming: An Introduction to Computer Science' and 'Programming Language Pragmatics'. It also features details about the author E Balagurusamy, his qualifications, and contributions to the field of computer science. Additionally, the document outlines the contents of a computer programming textbook, covering topics such as C programming basics, decision making, user-defined functions, and arrays.

Uploaded by

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

Computer Programming - eBook PDF download

https://ebookluna.com/download/computer-programming-ebook-pdf/

Download full version ebook from https://ebookluna.com


We believe these products will be a great fit for you. Click
the link to download now, or visit ebookluna.com
to discover even more!

Python Programming: An Introduction to Computer Science 3rd Edition by John


Zelle (eBook PDF)

https://ebookluna.com/product/python-programming-an-introduction-to-
computer-science-3rd-edition-by-john-zelle-ebook-pdf/

(eBook PDF) Programming Language Pragmatics, 4th Edition

https://ebookluna.com/product/ebook-pdf-programming-language-
pragmatics-4th-edition/

Programming in C 1st Edition - eBook PDF

https://ebookluna.com/download/programming-in-c-ebook-pdf/

(eBook PDF) Computer Systems 5th Edition

https://ebookluna.com/product/ebook-pdf-computer-systems-5th-edition/
Computer Systems 5th Edition (eBook PDF)

https://ebookluna.com/product/computer-systems-5th-edition-ebook-pdf/

(eBook PDF) Computer Networks 6th Edition

https://ebookluna.com/product/ebook-pdf-computer-networks-6th-edition/

(eBook PDF) Linear Programming and Resource Allocation Modeling

https://ebookluna.com/product/ebook-pdf-linear-programming-and-resource-
allocation-modeling/

(eBook PDF) Murach's C++ Programming by Joel Murach

https://ebookluna.com/product/ebook-pdf-murachs-c-programming-by-joel-
murach/

(eBook PDF) MATLAB Programming for Engineers 6th Edition

https://ebookluna.com/product/ebook-pdf-matlab-programming-for-
engineers-6th-edition/
As per
JNTU-Kakinada
Syllabus Regulation
2016

Computer
Programming
About the Author

E Balagurusamy, former Vice Chancellor, Anna University, Chennai and Member, Union Public Service
Commission, New Delhi, is currently the Chairman of EBG Foundation, Coimbatore. He is a teacher, trainer,
and consultant in the fields of Information Technology and Management. He holds an ME (Hons) in Electrical
Engineering and PhD in Systems Engineering from the Indian Institute of Technology (IIT) Roorkee. His
areas of interest include Object-Oriented Software Engineering, E-Governance: 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 ANSI C, 7/e
∑ Fundamentals of Computers
∑ Computing Fundamentals and C Programming
∑ Programming in Java, 5/e
∑ Programming in BASIC, 3/e
∑ Programming in C#, 3/e
∑ Numerical Methods
∑ Reliability Engineering
∑ Introduction to Computing and Problem Solving using Python, 1e

A recipient of numerous honors and awards, E Balagurusamy has been listed in the Directory of Who's
Who of Intellectuals and in the Directory of Distinguished Leaders in Education.
As per
JNTU-Kakinada
Syllabus Regulation
2016

Computer
Programming

E Balagurusamy
Chairman
EBG Foundation
Coimbatore

McGraw Hill Education (India) Private Limited


CHENNAI

McGraw Hill Education Offices


Chennai New York St Louis San Francisco Auckland Bogotá Caracas
Kuala Lumpur Lisbon London Madrid Mexico City Milan Montreal
San Juan Santiago Singapore Sydney Tokyo Toronto
McGraw Hill Education (India) Private Limited

Published by McGraw Hill Education (India) Private Limited


444/1, Sri Ekambara Naicker Industrial Estate, Alapakkam, Porur, Chennai - 600 116

Computer Programming
Copyright © 2017 by McGraw Hill Education (India) Private Limited.
No part of this publication may be reproduced or distributed in any form or by any means, electronic, mechanical, photocopying,
recording, or otherwise or stored in a database or retrieval system without the prior written permission of the publishers.
The program listings (if any) may be entered, stored and executed in a computer system, but they may not be reproduced for
publication.
This edition can be exported from India only by the publishers,
McGraw Hill Education (India) Private Limited

Print Edition:
ISBN-13: 978-93-5260-388-6
ISBN-10: 93-5260-388-5

Managing Director: Kaushik Bellani


Director—Products (Higher Education and Professional): Vibha Mahajan
Manager—Product Development: Koyel Ghosh
Specialist—Product Development: Sachin Kumar
Head—Production (Higher Education and Professional): Satinder S Baveja
Assistant Manager—Production: Jagriti Kundu
AGM—Product Management (Higher Education and Professional): Shalini Jha
Manager—Product Management: Kartik Arora
General Manager—Production: Rajender P Ghansela
Manager—Production: Reji Kumar

Information contained in this work has been obtained by McGraw Hill Education (India), from sources believed to be reliable.
However, neither McGraw Hill Education (India) nor its authors guarantee the accuracy or completeness of any information
published herein, and neither McGraw Hill Education (India) 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 understanding that McGraw Hill Education
(India) 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 The Composers, 260, C.A. Apt., Paschim Vihar, New Delhi 110 063 and printed at

Cover Printer:

Visit us at: www.mheducation.co.in


Contents

Preface xiii
Roadmap to the Syllabus xvi

Chapter 1 Introduction to Computers and Programming 1.1—1.30


1.1 Introduction 1.1
1.2 Computer Systems 1.2
1.2.1 Input Devices 1.3
1.2.2 CPU 1.5
1.2.3 Output Devices 1.6
1.2.4 Memory 1.8
1.3 History of C 1.12
1.4 Data Types 1.13
1.4.1 Integer Types 1.14
1.4.2 Floating Point Types 1.15
1.4.3 Void Types 1.16
1.4.4 Character Types 1.16
1.5 Programming Languages 1.16
1.5.1 Machine Language (Low Level Languages) 1.16
1.5.2 Assembly Language (Symbolic Language) 1.16
1.5.3 High-Level Languages 1.18
1.6 Development of C Algorithms 1.19
1.6.1 Characteristics of Algorithms 1.20
1.6.2 Advantages of Algorithms 1.20
1.6.3 Disadvantages of Algorithms 1.20
1.7 Software Development Method 1.22
1.7.1 Analysing the Requirements 1.23
1.7.2 Feasibility Analysis 1.23
1.7.3 Creating the Design 1.24
1.7.4 Developing Code 1.24
1.7.5 Testing the Software 1.25
1.7.6 Deploying the Software 1.25
1.7.7 Maintaining the Software 1.25
1.8 Applying Software Development Method 1.25
Key Terms 1.27
Just Remember 1.28
Multiple Choice Questions 1.28
vi Contents

Answers 1.29
Review Questions 1.29

Chapter 2 Basics of C 2.1—2.90


2.1 Importance of C 2.1
2.2 Basic Structure of C Programs 2.1
2.3 Programming Style 2.2
2.4 Executing a ‘C’ Program 2.3
2.5 Sample Programs 2.4
2.5.1 Sample Program 1: Printing a Message 2.4
2.5.2 Sample Program 2: Adding Two Numbers 2.6
2.5.3 Sample Program 3: Interest Calculation 2.8
2.5.4 Sample Program 4: Use of Subroutines 2.10
2.5.5 Sample Program 5: Use of Math functions 2.10
2.6 C Character Set 2.12
2.6.1 Trigraph Characters 2.13
2.7 C Tokens 2.14
2.8 Keywords and Identifiers 2.14
2.9 Operators and Expressions 2.15
2.9.1 Arithmetic Operators 2.15
2.9.2 Relational Operators 2.18
2.9.3 Logical Operators 2.19
2.9.4 Assignment Operators 2.20
2.9.5 Increment and Decrement Operators 2.22
2.9.6 Conditional Operator 2.23
2.9.7 Bitwise Operators 2.25
2.9.8 Special Operators 2.25
2.9.9 Operator Precedence 2.27
2.9.10 Precedence of Arithmetic Operators 2.29
2.9.11 Some Computational Problems 2.30
2.9.12 Type Conversions in Expressions 2.31
2.9.13 Operator Precedence and Associativity 2.34
2.10 Constants 2.36
2.10.1 Integer Constants 2.37
2.10.2 Real Constants 2.38
2.10.3 Single Character Constants 2.38
2.10.4 String Constants 2.39
2.11 Variables 2.40
2.12 Declaration of Variables 2.41
2.12.1 Primary Type Declaration 2.41
2.12.2 User-defined Type Declaration 2.42
2.12.3 Declaration of Storage Class 2.43
2.12.4 Assigning Values to Variables 2.44
Contents vii

2.13 ANSI C Library Functions 2.50


2.14 Managing Input and Output Operations 2.53
2.14.1 Reading a Character 2.54
2.14.2 Writing a Character 2.56
2.14.3 Formatted Input 2.58
2.14.4 Points to Remember while Using scanf 2.65
2.14.5 Formatted Output 2.66
2.15 Case Studies 2.71
Key Terms 2.78
Just Remember 2.79
Multiple Choice Questions 2.80
Answers 2.84
Review Questions 2.84
Debugging Exercises 2.86
Programming Exercise 2.87

Chapter 3 Decision Making, Branching and Looping 3.1—3.70


3.1 Introduction 3.1
3.2 Decision Making with If Statement 3.1
3.2.1 Simple If Statement 3.2
3.2.2 The If.....Else Statement 3.6
3.2.3 Nesting of If....Else Statements 3.9
3.2.4 The Else If Ladder 3.11
3.3 Decision Making with Switch Statement 3.15
3.4 The ? : Operator 3.20
3.5 Decision Making with Goto Statement 3.22
3.6 Introduction to Looping Procedure 3.25
3.6.1 Sentinel Loops 3.26
3.7 The While Statement 3.27
3.8 The Do Statement 3.29
3.9 The For Statement 3.33
3.9.1 Simple ‘for’ Loops 3.33
3.9.2 Additional Features of For Loop 3.37
3.9.3 Nesting of For Loops 3.39
3.10 Jumps In Loops 3.43
3.10.1 Jumping Out of a Loop 3.43
3.11 Case Studies 3.45
Key Terms 3.56
Just Remember 3.57
Multiple Choice Questions 3.58
Answers 3.60
Review Questions 3.61
Debugging Exercises 3.65
Programming Exercises 3.66
viii Contents

Chapter 4 User-Defined Functions 4.1—4.52


4.1 Introduction 4.1
4.2 Need for User-Defined Functions 4.1
4.3 A Multi-Function Program 4.2
4.3.1 Modular Programming 4.4
4.4 Category of Functions 4.5
4.4.1 No Arguments and No Return Values 4.5
4.4.2 Arguments but No Return Values 4.7
4.4.3 Arguments with Return Values 4.10
4.4.4 No Arguments but Returns a Value 4.16
4.4.5 Functions that Return Multiple Values 4.16
4.4.6 Nesting of Functions 4.17
4.5 Elements of User-Defined Functions 4.19
4.6 Definition of Functions 4.19
4.6.1 Function Header 4.20
4.6.2 Name and Type 4.20
4.6.3 Formal Parameter List 4.20
4.6.4 Function Body 4.21
4.7 Return Values and their Types 4.21
4.8 Function Calls 4.22
4.8.1 Function Call 4.24
4.9 Function Declaration 4.24
4.9.1 Prototypes: Yes or No 4.25
4.9.2 Parameters Everywhere! 4.25
4.10 Recursion 4.26
4.10.1 Recursion versus Iteration 4.27
4.11 Passing Arrays to Functions 4.27
4.11.1 One-Dimensional Arrays 4.27
4.11.2 Two-Dimensional Arrays 4.31
4.12 Passing Strings to Functions 4.32
4.12.1 Pass by Value versus Pass by Pointers 4.32
4.13 The Scope, Visibility, and Lifetime of Variables 4.33
4.13.1 Automatic Variables 4.33
4.13.2 External Variables 4.35
4.13.3 External Declaration 4.37
4.13.4 Static Variables 4.39
4.13.5 Register Variables 4.40
4.14 Multifile Programs 4.42
4.15 Case Study 4.43
Key Terms 4.46
Just Remember 4.46
Multiple Choice Questions 4.47
Contents ix

Answers 4.48
Review Questions 4.49
Debugging Exercises 4.51
Programming Exercises 4.51

Chapter 5 Arrays 5.1—5.44


5.1 Introduction 5.1
5.1.1 Data Structures 5.2
5.2 One-Dimensional Arrays 5.2
5.3 Declaration of One-dimensional Arrays 5.3
5.4 Initialization of One-dimensional Arrays 5.6
5.4.1 Compile Time Initialization 5.6
5.4.2 Run Time Initialization 5.7
5.4.3 Searching and Sorting 5.11
5.5 Two-Dimensional Arrays 5.12
5.6 Initializing Two-Dimensional Arrays 5.16
5.6.1 Memory Layout 5.19
5.7 Multi-Dimensional Arrays 5.25
5.8 Dynamic Arrays 5.26
5.9 Case Studies 5.26
Key Terms 5.38
Just Remember 5.38
Multiple Choice Questions 5.39
Answers 5.40
Review Questions 5.40
Debugging Exercises 5.41
Programming Exercises 5.42

Chapter 6 Strings 6.1—6.34


6.1 Introduction 6.1
6.2 Declaring and Initializing String Variables 6.2
6.3 Reading Strings from Terminal 6.3
6.3.1 Using scanf Function 6.3
6.3.2 Reading a Line of Text 6.5
6.3.3 Using getchar and gets Functions 6.6
6.4 Writing Strings to Screen 6.11
6.4.1 Using printf Function 6.11
6.4.2 Using putchar and puts Functions 6.14
6.5 Arithmetic Operations on Characters 6.15
6.6 Putting Strings Together 6.16
6.7 Comparison of Two Strings 6.18
6.8 String-Handling Functions 6.18
6.8.1 strcat() Function 6.18
x Contents

6.8.2 strcmp() Function 6.19


6.8.3 strcpy() Function 6.20
6.8.4 strlen() Function 6.20
6.8.5 Other String Functions 6.22
6.9 Table of Strings 6.24
6.10 Case Studies 6.26
Key Terms 6.30
Just Remember 6.30
Multiple Choice Questions 6.30
Answers 6.31
Review Questions 6.31
Debugging Exercises 6.33
Programming Exercises 6.33

Chapter 7 Pointers 7.1—7.42


7.1 Introduction 7.1
7.2 Understanding Pointers 7.2
7.2.1 Underlying Concepts of Pointers 7.3
7.3 Initialization of Pointer Variables 7.3
7.3.1 Pointer Flexibility 7.4
7.4 Declaring Pointer Variables 7.5
7.4.1 Pointer Declaration Style 7.5
7.5 Accessing the Address of a Variable 7.6
7.6 Accessing a Variable Through its Pointer 7.8
7.7 Chain of Pointers 7.10
7.8 Pointer Expressions 7.11
7.9 Pointer Increments and Scale Factor 7.12
7.9.1 Rules of Pointer Operations 7.13
7.10 Pointers as Function Arguments 7.13
7.11 Functions Returning Pointers 7.16
7.12 Pointers to Functions 7.17
7.12.1 Compatibility and Casting 7.19
7.13 Pointers and Arrays 7.19
7.14 Pointers and Character Strings 7.23
7.15 Array of Pointers 7.25
7.16 Dynamic Memory Allocation 7.26
7.17 Allocating a Block of Memory: Malloc 7.27
7.18 Allocating Multiple Blocks of Memory: Calloc 7.29
7.19 Releasing the Used Space: Free 7.33
7.20 Case Studies 7.33
Key Terms 7.38
Just Remember 7.38
Multiple Choice Questions 7.39
Contents xi

Answers 7.40
Review Questions 7.40
Debugging Exercises 7.42
Programming Exercise 7.42

Chapter 8 Structures and Unions 8.1—8.59


8.1 Introduction 8.1
8.2 Defining a Structure 8.1
8.3 Declaring Structure Variables 8.2
8.3.1 Accessing Structure Members 8.4
8.4 Structure Initialization 8.5
8.5 Arrays of Structures 8.8
8.5.1 Arrays Within Structures 8.11
8.5.2 Structures Within Structures 8.13
8.6 Structures and Functions 8.15
8.6.1 Passing Structure Through Pointers 8.17
8.6.2 Self Referential Structure 8.18
8.7 Pointers and Structures 8.18
8.8 Unions 8.21
8.9 Bit Fields 8.23
8.10 Typedef 8.25
8.11 Command Line Arguments 8.37
8.11.1 Application of Command Line Arguments 8.48
8.12 Case Study 8.50
Key Terms 8.53
Just Remember 8.53
Multiple Choice Questions 8.54
Answers 8.54
Review Questions 8.55
Debugging Exercises 8.57
Programming Exercise 8.58

Chapter 9 Data Files 9.1—9.22


9.1 Introduction 9.1
9.2 Defining and Opening a File 9.2
9.3 Closing a File 9.3
9.4 Input/Output Operations on Files 9.4
9.4.1 The getc and putc Functions 9.4
9.4.2 The getw and putw Functions 9.8
9.4.3 The fprintf and fscanf Functions 9.10
9.5 Error Handling During I/O Operations 9.12
9.6 Random Access to Files 9.14
Key Terms 9.20
xii Contents

Just Remember 9.20


Multiple Choice Questions 9.21
Answers 9.21
Review Questions 9.21
Debugging Exercise 9.22
Programming Exercise 9.22

Appendix 1 C99/C11 Features A1.1—A1.8


Solved Question Paper Nov-Dec 2015 (Set 1— Set 4) SQP1—SQP32
Solved Question Paper May 2016 (Set 1— Set 4) SQP1—SQP29
Preface

INTRODUCTION
Computers plays an increasing important role in today’s world and a sound knowledge of computers has
become indispensable for anyone who seeks employment not only in the area of IT but also in any other
field as well. Computer programming is dedicated to the understanding of computer language, and writing
and testing of programs that computers’ follow to perform their functions. The programs are created using
programming languages and C is the most prevalent, efficient and compact programming language. C
combines the features of a high-level language with the elements of the assembler and is thus close to both
man and machine. The growth of C during the last few years has been phenomenal. It has emerged as the
language of choice for most applications due to its speed, portability and compactness of code. Thus, many
institutions and universities in India have introduced a subject covering Computer Programming.
This book is specially designed for first-year students of Jawaharlal Nehru Technological University
Kakinada (JNTU K) and would enable them to master the necessary skills for programming with C language.
The text has been infused with numerous examples and case studies to empower the learner. Furthermore, the
book also covers design and implementation aspect of data structures using standard ANSI C programming
language.

SIGNIFICANT FEATURES
∑ New! Completely in sync with the syllabus of JNTU Kakinada (2016 Regulation)
∑ New! Incorporates all the features of ANSI C that are essential for a C programmer.
∑ New! Solutions to latest 2015 (Nov/Dec) and 2016 (May) JNTU Kakinada question paper is placed
at the end of the book (All 4 sets)
∑ New! 149 Multiple Choice Questions incorporated at the end of each chapters help students tests
their conceptual understanding of the subject
∑ 22 Case Studies in relevant chapters with stepwise solution to demonstrate real-life applications
∑ New! Updated information on C99/C11 features
∑ New! Topics like ANSI C library functions, Negation, Swapping Values, Recursion v/s Iteration are
covered in detail
∑ Learning by example approach ensures smooth and successful transition from a learner to a skilled
C programmer
∑ Enhanced student-friendly chapter design including Outline, Introduction, Section-end Solved
Programs, Case Studies, Key Terms, Just Remember, Multiple Choice Questions, Review Questions,
Debugging Exercises, Programming Exercises
∑ Special box feature highlighting supplementary information that complements the text.
xiv Preface

PEDAGOGICAL FEATURES
∑ 134 Solved C Programs demonstrate the general principles of good programming style
∑ 171 Review Questions helps in testing conceptual understanding
∑ 28 Debugging Exercise helps in participating coding contests
∑ 179 Programming Exercises simulate interest to practice programming applications

CHAPTER ORGANIZATION
The content is spread across 9 chapters. Chapter 1 introduces computer systems, programming languages
and environment, software development method, and algorithms. Chapter 2 gives an overview of C and
explaining the keywords, identifiers, constants, variables, data types and various case studies on these.
Chapters 3 comprises of decision-making, branching and looping methods. Chapter 4 covers the functions
which are used in C language. Chapter 5 focuses on arrays while Chapter 6 deals with strings. Different
types of pointers and its types are discussed in Chapter 7. Chapter 8 presents structures and unions while
Chapter 9 covers file types and their management. Appendix 1 covers C99/C11 features in detail. In addition
to all this, Solved Question Papers of Nov/Dec 2015 (4 sets) and May 2016 (4 sets) are also given in this
book.

CD RESOURCES
The supplementary CD provided along with the book would help the students master programming language
and write their own programs using Computer programming concepts and data structures. The CD comprises
of the following resources:
∑ New! 2012, 2013, 2014, Jan/Feb 2015 solved question papers
∑ New! Lab Programs as per the new syllabus
∑ Two major programming projects—Inventory and Record Entry & two mini projects—Linked List
and Matrix Multiplication
∑ 100 Programming Exercises and 200 Objective Type Questions aligned as per the new syllabus
∑ 5 Solved Model Question Papers
∑ 79 Additional Solved Programs
∑ Additional content on Matrix Operation

ACKNOWLEDGEMENTS
A number of reviewers took pains to provide valuable feedback for the book. We are grateful to all of them
and their names are mentioned as follows:
S. Krishna Rao Sir CR Reddy College of Engineering, Eluru, Andhra Pradesh
Narasimha Rao Kandula Vishnu Institute of Technology, Bhimavaram, Andhra Pradesh
K. Phani Babu, Chundru Raja Ramesh Sri Vasavi Engineering College, Tadepalligudem, Andhra
Pradesh
Preface xv

Rama Rao Adimalla Lendi Institute of Engineering and Technology, Jonnada,


Andhra Pradesh
S. Rama Sree Aditya Engineering College, Peddapuram, Andhra Pradesh
M V S S Nagendranath Sasi Institute of Technology & Engineering, Tadepalligudem,
Andhra Pradesh
S. Satyanarayana Raghu Engineering College, Dakamarri, Andhra Pradesh
S C Satapathy Anil Neerukonda Institute of Technology and Sciences,
Visakhapatnam, Andhra Pradesh
Ch Vijaya Kumar DVR & Dr. HS MIC College of Technology, Kanchikacherla,
Andhra Pradesh

E Balagurusamy

Publisher’s Note
McGraw Hill Education (India) invites suggestions and comments, all of which can be sent to
info.india@mheducation.com (kindly mention the title and author name in the subject line).
Piracy-related issues may also be reported.
Roadmap to the Syllabus

Computer Programming
Revised Course from Academic Year 2016-2017

Unit 1: History and Hardware—Computer hardware, Bits and bytes, Components, Programming
Languages—machine language, assembly language, low-level and high-level languages, procedural and
object-oriented languages, Application and system software, Development of C algorithms, Software
development process

Go to
Chapter 1: Introduction to Computers and Programming

Unit 2: Introduction to C programming, Identifiers, main () function, printf () function, Programming


style, Indentation, Comments, Data types, Arithmetic operations, Expression types, Variables and
declarations, Negation, Operator precedence and associativity, Declaration statements, Initialization
assignment, Implicit type conversions, Explicit type conversions, Assignment variations, Mathematical
library functions, Interactive input, Formatted output, Format modifiers

Go to
Chapter 1: Introduction to Computers and Programming
Chapter 2: Basics of C

Unit 3: Control flow-relational expressions—logical operators, Selection—if-else statement—nested if,


examples—multi-way selection—switch—else-if, examples, Repetition—basic loop structures, Pretest
and post-test loops, Counter-controlled and condition-controlled loops, While statement, For statement,
Nested loops, do-while statement

Go to
Chapter 3: Decision Making, Branching and Looping
Roadmap to the Syllabus xvii

Unit 4: Modular programming: function and parameter declarations, Returning a value, Functions with
empty parameter lists, Variable scope, Variable storage class, Local variable storage classes, Global
variable storage classes, Pass by reference, Passing addresses to a function, Storing addresses variables,
Using addresses, Declaring and using pointers, Passing addresses to a function, Swapping values,
Recursion—mathematical recursion—recursion versus iteration.

Go to
Chapter 4: User-Defined Functions

Unit 5: One-dimensional arrays, Input and output of array values, Array initialization, Arrays as function
arguments, Two-dimensional arrays, Larger dimensional arrays—matrices, String fundamentals, Library
functions, String input and output, String processing

Go to
Chapter 5: Arrays
Chapter 6: Strings

Unit 6: Pointers—concept of a pointer, Initialisation of pointer variables, Pointers as function arguments,


Passing by address, Dangling memory, Address arithmetic, Character pointers and Functions, Pointers to
pointers, Dynamic memory management functions, Command line arguments
Structures—derived types, Structures declaration, Initialization of structures, Accessing structures,
Nested structures, Arrays of structures, structures and functions, Pointers to structures, self-referential
structures, Unions, typedef, bit-fields
Declaring, Opening, and Closing file streams, Reading from and Writing to text files, Random file
access

Go to
Chapter 7: Pointers
Chapter 8: Structures and Unions
Chapter 9: Data Files
Introduction to Computers
1 and Programming

CHAPTER OUTLINE
1.1 Introduction 1.4 Data Types 1.7 Software Development Method
1.2 Computer Systems 1.5 Programming Languages 1.8 Applying Software
1.3 History of C 1.6 Development of C Algorithms Development Method

1.1 INTRODUCTION
The term computer is derived from the word
compute. A computer is an electronic device Data INPUT PROCESS
OUTPUT
Information
that takes data and instructions as an input
from the user, processes data, and provides
useful information known as output. This
cycle of operation of a computer is known as Instructions
the input–process–output cycle and is shown Fig. 1.1 Input–process–output concept
in Fig. 1.1. The electronic device is known as
hardware and the set of instructions is known as software.
A computer consists of various components that function as an integrated system to perform computational
tasks. These components include the following:
Central Processing Unit (CPU) It is the brain of the computer that is responsible for controlling
and executing program instructions.
Monitor It is a display screen, which shows information in visual form.
Keyboard and Mouse These are the peripheral devices used by the computer for receiving inputs
from the user.
Figure 1.2 shows the various components of a computer.
The unique capabilities and characteristics of a computer have made it very popular among its various
users, including engineers, managers, accountants, teachers, students, etc.
Some of the key characteristics of a modern digital computer include, among others the following:
Speed The computer is a fast electronic device that can solve large and complex problems in few
seconds. The speed of a computer generally depends upon its hardware configuration.
Storage capacity A computer can store huge amounts of data in many different formats. The storage
area of a computer system is generally divided into two categories, main memory and secondary storage.
1.2 Computer Programming

Monitor
CPU

Keyboard

Mouse

Fig. 1.2 Components of a computer

Accuracy A computer carries out calculations with great accuracy. The accuracy achieved by a
computer depends upon its hardware configuration and the specified instructions.
Reliability A computer produces results with no error. Most of the computer-generated errors are
in actuality human errors that are instigated by the user itself. Therefore, computers are regarded as
quite trustworthy machines.
Versatility Computers are versatile machines. They can perform varied tasks and can be used for
many different purposes.
Diligence Computers can perform repetitive calculations any number of times with the same level
of accuracy.
These capabilities of computers have enabled us to use them for a variety of tasks. Application areas may
broadly be classified into the following major categories.
1. Data processing (commercial use)
2. Numerical computing (scientific use)
3. Text (word) processing (office and educational use)
4. Message communication (e-mail)
5. Image processing (animation and industrial use)
6. Voice recognition (multimedia)

1.2 COMPUTER SYSTEMS


A computer system comprises of hardware and software components. Hardware refers to the physical
parts of the computer system and software is the set of instructions or programs that are necessary for the
functioning of a computer to perform certain tasks. Hardware includes the following components:
Input devices They are used for accepting the data on which the operations are to be performed.
The examples of input devices are keyboard, mouse and track ball.
Processor Also known as CPU, it is used to perform the calculations and information processing on
the data that is entered through the input device.
Output devices They are used for providing the output of a program that is obtained after performing
the operations specified in a program. The examples of output devices are monitor and printer.
Memory It is used for storing the input data as well as the output of a program that is obtained
after performing the operations specified in a program. Memory can be primary memory as well
as secondary memory. Primary memory includes Random Access Memory (RAM) and secondary
memory includes hard disks and floppy disks.
Introduction to Computers and Programming 1.3

Software supports the functioning of a computer system internally and cannot be seen. It is stored on
secondary memory and can be an application software as well as system software. The application software
is used to perform a specific task according to requirements and the system software is mandatory for running
application software. The examples of application software include Excel and MS Word and the examples of
system software include operating system and networking system.
All the hardware components interact with each other as well as with the software. Similarly, the different
types of software interact with each other and with the hardware components. The interaction between
various hardware components is illustrated in Fig. 1.3.

1.2.1 Input Devices


Input devices can be connected to the computer system using cables. The most commonly used input devices
among others are:

Magnetic Magnetic
Tape Disk

EXTERNAL STORAGE UNITS

Input Input Memory Output Output


Media Unit Unit Unit Media

Arithmetic
Unit

Control
Data and results flow
Unit
Control Instructions to units
Instructions to control unit
CPU

Fig. 1.3 Interaction among hardware components

Keyboard
A standard keyboard includes alphanumeric keys, function keys, modifier keys, cursor movement keys,
spacebar, escape key, numeric keypad, and some special keys, such as Page Up, Page Down, Home, Insert,
Delete and End. The alphanumeric keys include the number keys and the alphabet keys. The function keys
are the keys that help perform a specific task such as searching a file or refreshing a Web page. The modifier
keys such as Shift and Control keys modify the casing style of a character or symbol. The cursor movement
1.4 Computer Programming

keys include up, down, left and right keys and are used to modify the direction of the cursor on the screen.
The spacebar key shifts the cursor to the right by one position. The numeric keypad uses separate keypads for
numbers and mathematical operators. A keyboard is show in Fig. 1.4.

Function Keys
(F1 to F12)
Escape Key
Special Keys

Numeric Keypad

Modifier Keys

Alphanumeric Spacebar Key Cursor Movement


Keys Keys

Fig. 1.4 Keyboard

Mouse
Wheel
The mouse allows the user to select elements on the screen, Right Button
such as tools, icons, and buttons, by pointing and clicking Left Button
them. We can also use a mouse to draw and paint on the
screen of the computer system. The mouse is also known
as a pointing device because it helps change the position of
the pointer or cursor on the screen.
The mouse consists of two buttons, a wheel at the top and
a ball at the bottom of the mouse. When the ball moves, the Fig. 1.5 Mouse
cursor on the screen moves in the direction in which the ball rotates. The left button of the mouse is used to select
an element and the right button, when clicked, displays the special options such as open and explore and shortcut
menus. The wheel is used to scroll down in a document or a Web page. A mouse is shown in Fig. 1.5.

Scanner
A scanner is an input device that converts documents and images as the
digitized images understandable by the computer system. The digitized
images can be produced as black and white images, gray images, or
colored images. In case of colored images, an image is considered
as a collection of dots with each dot representing a combination of
red, green, and blue colors, varying in proportions. The proportions
of red, green, and blue colors assigned to a dot are together called as
color description. The scanner uses the color description of the dots to
produce a digitized image. Fig. 1.6 shows a scanner.
There are the following types of scanners that can be used to
produce digitized images: Fig. 1.6 Scanner
Flatbed scanner It contains a scanner head that moves across a page from top to bottom to read the
page and converts the image or text available on the page in digital form. The flatbed scanner is used
to scan graphics, oversized documents, and pages from books.
Introduction to Computers and Programming 1.5

Drum scanner In this type of scanner, a fixed scanner head is used and the image to be scanned is
moved across the head. The drum scanners are used for scanning prepress materials.
Slide scanner It is a scanner that can scan photographic slides directly to produce files understandable
by the computer.
Handheld scanner It is a scanner that is moved by the end user across the page to be scanned. This
type of scanner is inexpensive and small in size.

1.2.2 CPU
The CPU consists of Control Unit (CU) and ALU. CU stores the instruction set, which specifies the operations
to be performed by the computer. CU transfers the data and the instructions to the ALU for an arithmetic
operation. ALU performs arithmetical or logical operations on the data received. The CPU registers store the
data to be processed by the CPU and the processed data also. Apart from CU and ALU, CPU seeks help from
the following hardware devices to process the data:

Motherboard
It refers to a device used for connecting the CPU with the input and output devices (Fig. 1.7). The components
on the motherboard are connected to all parts of a computer and are kept insulated from each other. Some of
the components of a motherboard are:
Buses Electrical pathways that transfer data and instructions among different parts of the computer.
For example, the data bus is an electrical pathway that transfers data among the microprocessor,
memory and input/output devices connected to the computer. The address bus is connected among
the microprocessor, RAM and Read Only Memory (ROM), to transfer addresses of RAM and ROM
locations that is to be accessed by the microprocessor.
System clock It is a clock used for synchronizing the activities performed by the computer. The
electrical signals that are passed inside a computer are timed, based on the tick of the clock. As a
result, the faster the system clock, the faster is the processing speed of the computer.

Fig. 1.7 A motherboard


1.6 Computer Programming

Microprocessor CPU component that performs the processing and controls the activities performed
by the different parts of the computer. The microprocessor is plugged to the CPU socket placed on the
motherboard.
ROM Chip that contains the permanent memory of the computer that stores information, which
cannot be modified by the end user.

Random Access Memory (RAM)


It refers to primary memory of a computer that stores information and programs, until the computer is used.
RAM is available as a chip that can be connected to the RAM slots in the motherboard.

Video Card/Sound card


The video card is an interface between the monitor and the CPU. Video cards also include their own RAM
and microprocessors that are used for speeding up the processing and display of a graphic. These video cards
are placed on the expansion slots, as these slots allow us to connect the high-speed graphic display cards to
the motherboard. A sound card is a circuit board placed on the motherboard and is used to enhance the sound
capabilities of a computer. The sound cards are plugged to the Peripheral Component Interconnect (PCI)
slots. The PCI slots also enable the connection of networks interface card, modem cards and video cards, to
the motherboard.

1.2.3 Output Devices


The data, processed by the CPU, is made available to the end user by the output devices. The most commonly
used output devices are:

Monitor
A monitor is the most commonly used output device that produces
visual displays generated by the computer (Fig. 1.8). The monitor,
also known as a screen, is connected as an external device using
cables or connected either as a part of the CPU case. The monitor
connected using cables, is connected to the video card placed on the
expansion slot of the motherboard. The display device is used for
visual presentation of textual and graphical information.
The monitors can be classified as cathode ray tube (CRT) monitors
or liquid crystal display (LCD) monitors. The CRT monitors are
large, occupy more space in the computer, whereas LCD monitors
are thin, light weighted, and occupy lesser space. Both the monitors
are available as monochrome, gray scale and color models. However,
the quality of the visual display produced by the CRT is better than Fig. 1.8 Monitor
that produced by the LCD.
Introduction to Computers and Programming 1.7

A monitor can be characterized by its monitor size and resolution. The monitor size is the length of
the screen that is measured diagonally. The resolution of the screen is expressed as the number of picture
elements or pixels of the screen. The resolution of the monitor is also called the dot pitch. The monitor with
a higher resolution produces a clearer image.

Printer
The printer is an output device that is used to produce a hard copy
of the electronic text displayed on the screen, in the form of paper
sheets that can be used by the end user (Fig. 1.9). The printer is an
external device that is connected to the computer system using cables.
The computer needs to convert the document that is to be printed to
data that is understandable by the printer. The printer driver software
or the print driver software is used to convert a document to a form
understandable by the computer. When the computer components are
upgraded, the upgraded printer driver software needs to be installed on Fig. 1.9 Printer
the computer.
The performance of a printer is measured in terms of dots per inch (DPI) and pages per minute (PPM)
produced by the printer. The greater the DPI parameter of a printer, the better is the quality of the output
generated by it. The higher PPM represents higher efficiency of the printer. Printers can be classified based
on the technology they use to print the text and images:
Dot matrix printers Dot matrix printers are impact printers that use perforated sheet to print the
text. The process to print a text involves striking a pin against a ribbon to produce its impression on
the paper.
Inkjet printers Inkjet printers are slower than dot matrix printers and are used to generate high
quality photographic prints. Inkjet printers are not impact printers. The ink cartridges are attached to
the printer head that moves horizontally, from left to right.
Laser printers The laser printer may or may not be connected to a computer, to generate an output.
These printers consist of a microprocessor, ROM and RAM, which can be used to store the textual
information. The printer uses a cylindrical drum, a toner and the laser beam.

Speaker
The speaker is an electromechanical transducer that converts an
electrical signal into sound (Fig. 1.10). They are attached to a computer
as output devices, to provide audio output, such as warning sounds and
Internet audios. We can have built-in speakers or attached speakers in a
computer to warn end users with error audio messages and alerts. The
audio drivers need to be installed in the computer to produce the audio
output. The sound card being used in the computer system decides the
quality of audio that we listen using music CDs or over the Internet.
The computer speakers vary widely in terms of quality and price. The
sophisticated computer speakers may have a subwoofer unit, to enhance
bass output. Fig. 1.10 Speakers
1.8 Computer Programming

Plotter
The plotter is another commonly used output device that is connected to a computer to print large documents,
such as engineering or constructional drawings. Plotters use multiple ink pens or inkjets with color cartridges
for printing. A computer transmits binary signals to all the print heads of the plotter. Each binary signal
contains the coordinates of where a print head needs to be positioned for printing. Plotters are classified on
the basis of their performance, as follows:
Drum plotter They are used to draw perfect circles and other graphic images. They use a drawing
arm to draw the image. The drum plotter moves the paper back and forth through a roller and the
drawing arm moves across the paper.
Flat-bed plotter A flat bed plotter has a flat drawing surface and the two drawing arms that move
across the paper sheet, drawing an image. The plotter has a low speed of printing and is large in size.
Inkjet plotter Spray nozzles are used to generate images by spraying droplets of ink onto the paper
(Fig. 1.11). However, the spray nozzles can get clogged and require regular cleaning, thus resulting in
a high maintenance cost.
Electrostatic plotter As compared to other plotters, an electrostatic plotter produces quality print
with highest speed. It uses charged electric wires and special dielectric paper for drawing.

Control
Buttons

Plotted
Paper

Fig. 1.11 An ink-jet plotter

1.2.4 Memory
The memory unit of a computer is used to store data, instructions for processing data, intermediate results of
processing and the final processed information. The memory units of a computer are classified as primary
memory and secondary memory. Figure 1.12 shows the memory categorization in a computer system.
Introduction to Computers and Programming 1.9

Fig. 1.12 Categorization of memory devices

Primary Memory
The primary memory is available in the computer as a built-in unit of the computer. The primary memory is
represented as a set of locations with each location occupying 8 bits. Each bit in the memory is identified by
a unique address. The data is stored in the machine-understandable binary form in these memory locations.
The commonly used primary memories are:
ROM represents Read Only Memory that stores data and instructions, even when the
computer is turned off. It is the permanent memory of the computer where the contents cannot be
modified by an end user. ROM is a chip that is inserted into the motherboard. It is generally used to
store the Basic Input/Output system (BIOS), which
performs the Power On Self Test (POST).
RAM is the read/write memory unit in
which the information is retained only as long as
there is a regular power supply (Fig. 1.13). When
the power supply is interrupted or switched off, the
information stored in the RAM is lost. RAM is a Integrated
volatile memory that temporarily stores data and chips
applications as long as they are in use. When the
Fig. 1.13 RAM
use of data or the application is over, the content in
RAM is erased.
Cache memory is used to store the data and the related application that was last
processed by the CPU. When the processor performs processing, it first searches the cache memory
and then the RAM, for an instruction. The cache memory is always placed between CPU and the main
memory of the computer system.
1.10 Computer Programming

Table 1.1 depicts some of the key differences between RAM and ROM.

TABLE 1.1 Differences between RAM and ROM


RAM ROM
It is a read/write memory It is a read only memory
It is volatile storage device It is a permanent storage device
Data is erased as soon as power supply is Data remains stored even after power supply
turned off has been turned off
It is used as the main memory of a computer It is used to store Basic input output system
system (BIOS).

Secondary Memory
Secondary memory represents the external storage devices that are connected to the computer. They provide
a non-volatile memory source used to store information that is not in use currently. A storage device is either
located in the CPU casing of the computer or is connected externally to the computer. The secondary storage
devices can be classified as:
The magnetic storage
devices store information that can be read,
erased and rewritten a number of times. These
include floppy disk, hard disk and magnetic tapes
(Fig. 1.14 and Fig. 1.15).
The optical storage
devices are secondary storage devices that use
laser beams to read the stored data. These include Fig. 1.14 Magnetic tape
CD-ROM, rewritable compact disk (CD-RW), and
digital video disks with read only memory (DVD-ROM).

Tracks
Sectors

Fig. 1.15 Magnetic disk


Introduction to Computers and Programming 1.11

Incident laser beam


Reflected laser beam

Fig. 1.16 Optical Disk

Reflective aluminium layer Magneto optical flim

Protective coating

Dielectric
layers

Laser beams

Substrate layer Lens

Fig. 1.17 Magneto-optical disk

The magneto-optical devices


are generally used to store information, such as large programs,
files and backup data (Fig. 1.17). The end user can modify the
information stored in magneto-optical storage devices multiple
times. These devices provide higher storage capacity as they use
laser beams and magnets for reading and writing data to the device.
Examples of magneto-optical devices include Sony MiniDisc,
Maxoptix T5-2600, etc.
USB drive or commonly
known as pen drive is a removable storage device that is interfaced
on the USB port of a computer system (Fig. 1.18). It is pretty Fig. 1.18 USB drive
1.12 Computer Programming

fast and compact in comparison to other storage devices like CD and floppy disk. One of the most
important advantages of a USB drive is that it is larger in capacity as compared to other removable
storage devices. Off late, it has become very popular amongst computer users.

1.3 HISTORY OF C
‘C’ seems a strange name for a programming language. But this strange sounding language is one of the most
popular computer languages today because it is a structured, high-level, machine independent language. It
allows software developers to develop programs without worrying about the hardware platforms where they
will be implemented.
The root of all modern languages is ALGOL, introduced in the early 1960s. ALGOL was the first
computer language to use a block structure. Although it never became popular in USA, it was widely used in
Europe. ALGOL gave the concept of structured programming to the computer science community. Computer
scientists like Corrado Bohm, Guiseppe Jacopini and Edsger Dijkstra popularized this concept during 1960s.
Subsequently, several languages were announced.
In 1967, Martin Richards developed a language called BCPL (Basic Combined Programming Language)

of BCPL and called it simply B. B was used to create early versions of UNIX operating system at Bell
Laboratories. Both BCPL and B were “typeless” system programming languages.
C was evolved from ALGOL, BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972. C uses
many concepts from these languages and added the concept of data types and other powerful features. Since
it was developed along with the UNIX operating system, it is strongly associated with UNIX. This operating
system, which was also developed at Bell Laboratories, was coded almost entirely in C. UNIX is one of the
most popular network operating systems in use today and the heart of the Internet data superhighway.
For many years, C was used mainly in academic environments, but eventually with the release of many
C compilers for commercial use and the increasing popularity of UNIX, it began to gain widespread support
among computer professionals. Today, C is running under a variety of operating system and hardware
platforms.
During 1970s, C had evolved into what is now known as “traditional C”. The language became more popular
after publication of the book ‘The C Programming Language’

community. The rapid growth of C led to the development of different versions of the language that were similar
but often incompatible. This posed a serious problem for system developers.
To assure that the C language remains standard, in 1983, American National Standards Institute (ANSI)
appointed a technical committee to define a standard for C. The committee approved a version of C in
December 1989 which is now known as ANSI C. It was then approved by the International Standards
Organization (ISO) in 1990. This version of C is also referred to as C89.
During 1990’s, C++, a language entirely based on C, underwent a number of improvements and
changes and became an ANSI/ISO approved language in November 1977. C++ added several new
features to C to make it not only a true object-oriented language but also a more versatile language.
During the same period, Sun Microsystems of USA created a new language Java modelled on C and C++.
All popular computer languages are dynamic in nature. They continue to improve their power and scope
by incorporating new features and C is no exception. Although C++ and Java were evolved out of C, the
standardization committee of C felt that a few features of C++/Java, if added to C, would enhance the
usefulness of the language. The result was the 1999 standard for C. This version is usually referred to as C99.
The history and development of C is illustrated in Fig. 1.19.
Introduction to Computers and Programming 1.13

Fig. 1.19 History of C

Although C99 is an improved version, still many commonly available compilers do not support all of the
new features incorporated in C99.

1.4 DATA TYPES


C language is rich in its data types. Storage representations and machine instructions to handle constants
differ from machine to machine. The variety of data types available allow the programmer to select the type
appropriate to the needs of the application as well as the machine.
ANSI C supports three classes of data types:
1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types
The primary data types and their extensions are discussed in this section. The user-defined data types are
defined in the next section while the derived data types such as arrays, functions, structures and pointers are
discussed as and when they are encountered.
1.14 Computer Programming

All C compilers support five fundamental data types, namely integer (int), character (char), floating point
(float), double-precision floating point (double) and void. Many of them also offer extended data types
such as long int and long double. Various data types and the terminology used to describe them are given
in Fig. 1.20. The range of the basic four types are given in Table 1.2. We discuss briefly each one of them in
this section.

NOTE: C99 adds three more data types, namely _Bool, _Complex, and _Imaginary. See Appendix 1.

PRIMARY DATA TYPES

Integral Type

Integer Character

signed unsigned type char


int unsigned int signed char
short int unsigned short int unsigned char
long int unsigned long int

Floating point Type


void
float double Long double

Fig. 1.20 Primary data types in C

TABLE 1.2 Size and Range of Basic Data Types on 16-bit Machines
Data type Range of values
char –128 to 127
int –32,768 to 32,767
float 3.4e–38 to 3.4e+e38
double 1.7e–308 to 1.7e+308

1.4.1 Integer Types


Integers are whole numbers with a range of values supported by a particular machine. Generally, integers
occupy one word of storage, and since the word sizes of machines vary (typically, 16 or 32 bits) the size of
an integer that can be stored depends on the computer. If we use a 16 bit word length, the size of the integer
value is limited to the range –32768 to +32767 (that is, –215 to +215–1). A signed integer uses one bit for sign
and 15 bits for the magnitude of the number. Similarly, a 32 bit word length can store an integer ranging from
-2,147,483,648 to 2,147,483,647.
Introduction to Computers and Programming 1.15

In order to provide some control over the range of numbers and storage space, C has three classes of
integer storage, namely short int, int, and long int, in both signed and unsigned forms. ANSI C defines
these types so that they can be organized from the smallest
to the largest, as shown in Fig. 1.21. For example, short
short int
int represents fairly small integer values and requires half
the amount of storage as a regular int number uses. Unlike int
signed integers, unsigned integers use all the bits for the
long int
magnitude of the number and are always positive.
Therefore, for a 16 bit machine, the range of unsigned
integer numbers will be from 0 to 65,535. Fig. 1.21 Integer types
We declare long and unsigned integers to increase the range of values. The use of qualifier signed on
integers is optional because the default declaration assumes a signed number. Table 1.3 shows all the allowed
combinations of basic types and qualifiers and their size and range on a 16-bit machine.

NOTE: C99 allows long long integer types. See Appendix 1.

TABLE 1.3 Size and Range of Data Types on a 16-bit Machine


Type Size (bits) Range
char or signed char 8 –128 to 127
unsigned char 8 0 to 255
int or signed int 16 –32,768 to 32,767
unsigned int 16 0 to 65535
short int or
signed short int 8 –128 to 127
unsigned short int 8 0 to 255
long int or
signed long int 32 –2,147,483,648 to 2,147,483,647
unsigned long int 32 0 to 4,294,967,295
32 3.4E – 38 to 3.4E + 38
double 64 1.7E – 308 to 1.7E + 308
long double 80 3.4E – 4932 to 1.1E + 4932

1.4.2 Floating Point Types


Floating point (or real) numbers are stored in 32 bits (on all 16 bit and 32 bit machines), with 6 digits of
precision. Floating point numbers are defined in C by the keyword float. When the accuracy provided by
a float number is not sufficient, the type double can be
used to define the number. A double data type number uses
64 bits giving a precision of 14 digits. These are known float
as double precision numbers. Remember that double type double
represents the same data type that float represents, but with
long double
a greater precision. To extend the precision further, we
may use long double which uses 80 bits. The relationship
among floating types is illustrated Fig. 1.22. Fig. 1.22 Floating-point types
1.16 Computer Programming

1.4.3 Void Types


The void type has no values. This is usually used to specify the type of functions. The type of a function is
said to be void when it does not return any value to the calling function. It can also play the role of a generic
type, meaning that it can represent any of the other standard types.

1.4.4 Character Types


A single character can be defined as a character(char) type data. Characters are usually stored in 8 bits (one
byte) of internal storage. The qualifier signed or unsigned may be explicitly applied to char. While unsigned
chars have values between 0 and 255, signed chars have values from –128 to 127.

1.5 PROGRAMMING LANGUAGES


The operations of a computer are controlled by a set of instructions (called a computer program). These
instructions are written to tell the computer:

The communication between two parties, whether they are machines or human beings, always needs a
common language or terminology. The language used in the communication of computer instructions is
known as the programming language. The computer has its own language and any communication with the
computer must be in its language or translated into this language.
Three levels of programming languages are available. They are:

1.5.1 Machine Language (Low Level Languages)


As computers are made of two-state electronic devices they can understand only pulse and no-pulse
(or ‘1’ and ‘0’) conditions. Therefore, all instructions and data should be written using binary codes
1 and 0. The binary code is called the machine code or machine language.
Computers do not understand English, Hindi or Tamil. They respond only to machine language. Added to
this, computers are not identical in design, therefore, each computer has its own machine language. (However,
the script 1 and 0, is the same for all computers). This poses two problems for the user.
First, it is difficult to understand and remember the various combinations of 1’s and 0’s representing
numerous data and instructions. Also, writing error-free instructions is a slow process.
Secondly, since every machine has its own machine language, the user cannot communicate with other
computers (If he does not know its language). Imagine a Tamilian making his first trip to Delhi. He would
face enormous obstacles as the language barrier would prevent him from communicating.
Machine languages are usually referred to as the first generation languages.

1.5.2 Assembly Language (Symbolic Language)


The Assembly language, introduced in 1950s, reduced programming complexity and provided some
standardization to build an application. The assembly language, also referred to as the second-generation
Introduction to Computers and Programming 1.17

programming language, is also a low-level language. In an assembly language, the 0s and 1s of machine
language are replaced with abbreviations or mnemonic code.
The main advantages of an assembly language over a machine language are:

language.

An assembly language program consists of a series of instructions and mnemonics that correspond to a
stream of executable instructions. An assembly language instruction consists of a mnemonic code followed
by zero or more operands. The mnemonic code is called the operation code or opcode, which specifies the
operation to be performed on the given arguments. Consider the following machine code:
10110000 01100001
Its equivalent assembly language representation is:
mov al, 061h
In the above instruction, the opcode “move” is used to move the hexadecimal value 61 into the processor
register named ‘al’. The following program shows the assembly language instructions to subtract two
numbers:
ORG 500 /Origin of program is location 500
LDA SUB /Load subtrahend to AC
CMA /Complement AC
INC /Increment AC
ADD MIN /Add minuend to AC
STA DIF /Store difference
HLT /Halt computer
MIN, DEC 56 /Minuend
SUB, DEC -2 /Subtrahend
DIF, HEX 0 /Difference stored here
END /End of symbolic program
It should be noted that during execution, the assembly language program is converted into the machine
code with the help of an assembler. The simple assembly language statements had one-to-one correspondence
with the machine language statements. This one-to-one correspondence still generated complex programs.
Then, macroinstructions were devised so that multiple machine language statements could be represented
using a single assembly language instruction. Even today programmers prefer to use an assembly language
for performing certain tasks such as:

language code is stored in ROM


1.18 Computer Programming

1.5.3 High-Level Languages


High level languages further simplified programming tasks by reducing the number of computer operation
details that had to be specified. High level languages like COBOL, Pascal, FORTRAN, and C are more
abstract, easier to use, and more portable across platforms, as compared to low-level programming languages.
Instead of dealing with registers, memory addresses and call stacks, a programmer can concentrate more on
the logic to solve the problem with help of variables, arrays or Boolean expressions. For example, consider
the following assembly language code:
LOAD A
ADD B
STORE C
Using FORTRAN, the above code can be represented as:
C=A+B
The above high-level language code is executed by translating it into the corresponding machine language
code with the help of a compiler or interpreter.
High-level languages can be classified into the following three categories:
Procedure-oriented languages (third generation)

Procedure-oriented Languages
High-level languages designed to solve general-purpose problems are called procedural languages or third-
generation languages. These include BASIC, COBOL, FORTRAN, C, C++, and JAVA, which are designed
to express the logic and procedure of a problem. Although, the syntax of these programming languages
is different, they use English-like commands that are easy to follow. Another major advantage of third-
generation languages is that they are portable. We can use the compiler (or interpreter) on any computer and
create the object code. The following program represents the source code in the C language:
if( n>10)
{
do
{
n++;
}while ( n<50);
}
The third generation programming languages are considered as domain-specific programming languages
because they are designed to develop software applications for a specific field. For example, the third
generation programming language, COBOL, was designed to solve a large number of problems specific to
the business field.

Problem-oriented Languages
Problem-oriented languages are used to solve specific problems and are known as the fourth-generation
languages. These include query Languages, Report Generators and Application Generators which have
simple, English-like syntax rules. Fourth-generation languages (4 GLs) have reduced programming efforts
and overall cost of software development. These languages use either a visual environment or a text
environment for program development similar to that of third-generation languages. A single statement in
Introduction to Computers and Programming 1.19

a fourth-generation language can perform the same task as multiple lines of a third-generation language.
Further, the programmer just needs to drag and drop from the toolbar, to create various items like buttons,
text boxes, labels, etc. Also, the programmer can quickly create the prototype of the software application.
These languages are typically used in the WYSIWYG (What You See Is What You Get) environment
to facilitate faster and convenient application development. Visual Studio is one such environment that
encompasses a number of programming tools as well multiple programming language support to ensure
flexibility to the programmer during application development.

Natural Languages
Natural languages are designed to make a computer to behave like an expert and solve problems. The
programmer just needs to specify the problem and the constraints for problem-solving. Natural languages
such as LISP and PROLOG are mainly used to develop artificial intelligence and expert systems. These
languages are widely known as fifth generation languages.
The programming languages of this generation mainly focus on constraint programming, which is
somewhat similar to declarative programming. It is a programming paradigm in which the programmer only
needs to specify the solution to be found within the constraints rather than specifying the method of finding
the desired solution
The programming languages of this generation allow the users to communicate with the computer system
in a simple and an easy manner. Programmers can use normal English words while interacting with the
computer system.

1.6 DEVELOPMENT OF C ALGORITHMS


Algorithms help a programmer in breaking down the solution of a problem into a number of sequential
steps. Corresponding to each step a statement is written in a programming language; all these statements are
collectively termed as a program.
The following is an example of an algorithm to add two integers and display the result:

Algorithm
Step 1 – Accept the first integer as input from the user.
(num1)
Step 2 – Accept the second integer as input from the user.
(num2)
Step 3 – Calculate the sum of the two integers.
(sum = num1 + num2)
Step 4 – Display sum as the result.

There is a time and space complexity associated with each algorithm. Time complexity specifies the amount
of time required by an algorithm for performing the desired task. Space complexity specifies the amount of
memory space required by the algorithm for performing the desired task. While solving a complex problem,
it is possible to have multiple algorithms for obtaining the required solution. The algorithm that ensures best
time and space trade off should be chosen for obtaining the desired solution.
1.20 Computer Programming

1.6.1 Characteristics of Algorithms


The typical characteristics that are necessary for a sequence of instructions to qualify as an algorithm are the
following:

run infinitely.

1.6.2 Advantages of Algorithms


Some of the key advantages of algorithms are the following:

system using any programming language of user’s choice.

solution.

1.6.3 Disadvantages of Algorithms


Apart from the advantages, algorithms also posses certain limitations, which are

the logic becomes relatively difficult.

Example 1.1

Algorithm
Step 1 - Start
Step 2 – Accept a number from the user (num)
Step 3 – Initialize looping counter i = 2
Step 4 – Repeat Step 5 while i < num
Step 5 – If remainder of num divided by i (num%i) is Zero then goto Step 6 else
goto Step 4
Step 6 - Display “num is not a prime number” and break from the loop
Step 7 – If i = num then goto Step 8 Else goto Step 9
Step 8 – Display “num is a prime number”
Step 9 - Stop
Introduction to Computers and Programming 1.21

Example 1.2

Algorithm
Step 1 - Start
Step 2 – Accept the marks in three subjects from the user (marks1, marks2, marks3)
Step 3 – Calculate average marks using formula, average = (marks1 + marks2 +
marks3)/3
Step 4 – Display the computed average of three subject marks
Step 5 - Stop

Example 1.3 Write an algorithm to determine whether the given year is a leap year or not.

Algorithm
Step 1 - Start
Step 2 – Accept an year value from the user (year)
Step 3 – If remainder of year value divided by 4 (year%4) is 0 then goto Step 4
else goto Step 5
Step 4 – Display “’year’ is a leap year” and goto Step 6
Step 5 – Display “’year’ is not a leap year”]
Step 6 - Stop

Example 1.4

Algorithm
Step 1 - Start
Step 2 – Accept a number from the user (num)
Step 3 – If remainder of num divided by 2 (num/2) is Zero then goto Step 4 else
goto Step 5
Step 4 – Display “num is an even number” and goto Step 6
Step 5 – Display “num is an odd number”
Step 6 - Stop
1.22 Computer Programming

Example 1.5 Write an algorithm to determine whether a given string is a palindrome or not.

Algorithm
Step 1 - Start
Step 2 – Accept a string from the user (str)
Step 3 – Calculate the length of string str (len)
Step 4 – Initialize looping counters left=0, right=len-1 and chk = ‘t’
Step 5 – Repeat Steps 6-8 while left < right and chk = ‘t’
Step 6 – If str(left) = str(right) goto Step 8 else goto step 7
Step 7 – Set chk = ‘f’
Step 8 – Set left = left + 1 and right = right + 1
Step 9 - If chk=’t’ goto Step 10 else goto Step 11
Step 10 – Display “The string is a palindrome” and goto Step 12
Step 11 – Display “The string is not a palindrome”
Step 12 - Stop

1.7 SOFTWARE DEVELOPMENT METHOD


The entire process of software development and implementation involves a series of steps. Each successive
step is dependent on the outcome of the previous step. Thus, the team of software designers, developers and
operators are required to interact with each other at each stage of software development so as to ensure that
the end product is as per the client’s requirements. Figure 1.23 shows the various software development steps:

Analysing the requirements

Feasibility Analysis

Creating the Design

Developing code

Testing the software

Deploying the software

Maintaining the software

Fig. 1.23 Software development steps


Introduction to Computers and Programming 1.23

1.7.1 Analysing the Requirements


In this step, the requirements related to the software, which is to be developed, are understood. Analysing
the requirements or requirement analysis is an important step in the process of developing a software. If the
requirements of the user are not properly understood, then the software is bound to fall short of the end user’s
expectations. Thus, requirement analysis is always the first step towards development of a software.
Software is abstract in nature; as a result, the users may not be able to provide the complete set of
requirements pertaining to the desired software during the requirement analysis stage. Thus, there should be
continuous interaction between the software development team and the end users. Moreover, the software
development team also needs to take into account the fact that the requirements of the users may keep changing
during the development process. Thus, proper analysis of user requirements is quite essential for developing
the software within a given timeframe. It will not only help in controlling the software development cost but
will also lead to faster and accurate development of a software.
The task of requirement analysis is typically performed by a business analyst. The person is a professional
in this field who understands the requirements of the novice end user, and documents and shares it with the
development team.

1.7.2 Feasibility Analysis


In this step, the feasibility of developing the software in terms of resources and cost is ascertained. In order
to determine the feasibility of software development, the existing system of the user is analysed properly.
Apart from studying the existing system, this step involves identifying the need of automation in the existing
system. The analysis done in this step is documented in a standard document called feasibility report, which
contains the observations and recommendations related to the task of software development. Some of the
important activities performed during the feasibility analysis stage are as follows:
Determining development alternatives This activity involves searching for the different
alternatives that are available for the development of software. There are mainly four alternatives
available for the development of a software. The first alternative is to allow the existing system
to continue without developing a new software for automation. The second alternative can be to
develop the new software using specific programming languages such as Java, C++, Visual Basic etc.
The third alternative is to develop the software using the architectural technologies such as Java 2
Enterprise Edition (J2EE) and mainframe based with thin clients. The fourth development alternative
is to buy an already developed software along with its source code from the market and customise it
according to the client’s requirements.
Analysing economic feasibility This activity involves determining whether the development of
a new software will be financially beneficial or not. This type of feasibility analysis is performed
to determine the overall profit that can be earned from the development and implementation of
the software. This feasibility analysis activity involves evaluating all the alternatives available for
development and selecting the one which is most economical.
Assessing technical feasibility The technical feasibility assessment involves analysing various
factors such as performance of the technologies, ease of installation, ease of expansion or reduction
in size, interoperability with other technologies, etc. The technical feasibility activity typically
involves the study of the nature of technology as to how easily it can be learnt and the level of
training required to understand the technology. This type of feasibility assessment greatly helps in
selecting the appropriate technologies to be used for developing the software. The selection should
be made after evaluating the requirement specification of the software. In addition, the advantages
and disadvantages of each identified technology must also be evaluated during technical feasibility
assessment.
1.24 Computer Programming

Analysing operational feasibility Operational feasibility assessment involves studying the


software on operational and maintenance fronts. The operational feasibility of any software is done
on the basis of several factors, such as:
– Type of tools needed for operating the software
– Skill set required for operating the software
– Documentation and other support required for operating the software

1.7.3 Creating the Design


After the feasibility analysis stage, the next step is creating the architecture and design of the new software.
This step involves developing a logical model or basic structure of the new software. For example, if the
new software is based on client–server technology then this step would involve determining and specifying
the number of tiers to be used in the client–server design. This step also involves documenting the varied
specifications pertaining to database and data structure design. The flow of the development process is mainly
illustrated in this stage using a special language known as Unified Modelling Language (UML). UML uses
pictorial representation methods for depicting the flow of data in the software. Some of the key features,
which are considered while designing a software are:
Extensibility The design of the software should be extensible so that it allows the addition of some
new options or modules in future. The architecture of the software should be flexible enough to not
get disturbed with the addition of new functionality.
Modularity The software should be modular in nature so that its working and data flow can be
understood easily. Modularity also helps in parallel development of the various software modules,
which are later integrated into a single software product.
Compatibility Software should run correctly in the existing system with an older version or with
other software. Thus, software should be compatible and work well in conjunction with other software.
Security Software must be able to control unauthorised access. While designing a new software, it
is ensured that there are proper security mechanisms incorporated in the product.
Fault tolerance The software should be capable of handling exceptions or faults that may occur
during its operation. The software must have the capability to recover from failures.
Maintainability The design of the software should be created in a simple manner with appropriate
details so that it is easy to maintain.

1.7.4 Developing Code


In this step, the code for the different modules of the new software is developed. The code for the different
modules is developed according to the design specifications of each module. The programmers in the software
development team use tools like compilers, interpreters and debuggers to perform tasks such as finding errors
in the code and converting the code into machine language for its execution. The code can be written using
programming languages such as C, C++ or Java. The choice of the programming language to be used for
developing the code is made on the basis of the type of software that is to be developed. There are certain key
points or conventions, which must be kept in mind while writing code; for instance:
Introduction to Computers and Programming 1.25

1.7.5 Testing the Software


Testing is basically performed to detect the prevalence of any errors in the new software and rectify those er-
rors. One of the reasons for the occurrence of errors or defects in a new software is that the requirements of the
users or client were not properly understood. Another reason for the occurrence of errors is the common mis-
takes committed by a programmer while developing the code. The two important activities that are performed
during testing are verification and validation. Verification is the process of checking the software based on
some pre-defined specifications, while validation involves testing the product to ascertain whether it meets
the user’s requirements. During validation, the tester inputs different values to ascertain whether the software
is generating the right output as per the original requirements. The various testing methodologies include:

1.7.6 Deploying the Software


In this step, the newly developed and fully tested software is installed in its target environment. Software
documentation is handed over to the users and some initial data are entered in the software to make it
operational. The users are also given training on the software’s interface and its other functions.

1.7.7 Maintaining the Software


Once the software has been deployed successfully, a continuous support is provided to it for ensuring its
full-time availability. A corrupt file, a virus infection and a fatal error are some of the situations where the
maintenance personnel are asked to fix the software and bring it back to its normal functioning. Further, a
software may also be required to be modified if its environment undergoes a change. In order to successfully
maintain the software, it is required that it should have been properly documented at the time of its
development. This is because the maintenance person might not be the same who was originally involved in
the development of the software. Thus, a good code documentation serves vital for the maintenance person
to fix the software.

1.8 APPLYING SOFTWARE DEVELOPMENT METHOD


To understand how software development method is applied, consider a simple scenario where it is required
to convert the temperature given in Fahrenheit to its corresponding Celsius value.

Program Objective
To convert the temperature value from Fahrenheit to Celsius

Analysis
Input: Temperature value in Fahrenheit
Output: Temperature value in Celsius
1.26 Computer Programming

Conversion method: The formula C = (F–32) / 1.8 can be used to generate the desired output
Data elements: Real Variable F is used to store the input temperature value in Fahrenheit
Real Variable C is used to store the resultant temperature value in Celsius

Design

Algorithm
Step 1 – Read F
Step 2 – Compute C = (F-32) / 1.8
Step 3 – Display C

Development

Program
#include <stdio.h>
#include <conio.h>

void main()
{
float F, C;
clrscr();

printf("Enter the temperature value in Fahrenheit: ");


scanf("%f",&F);

C=(F-32.0)/1.8;

printf("The equivalent temperature value in degrees Celsius is: %.2f",C);


getch();
}

Testing
The program must be tested with multiple input values so as to ensure that there are no logical errors present
in the code.

Enter the temperature value in Fahrenheit: 0


The equivalent temperature value in degrees Celsius is: –17.78

Enter the temperature value in Fahrenheit: 175


The equivalent temperature value in degrees Celsius is: 79.44

Enter the temperature value in Fahrenheit: 250


The equivalent temperature value in degrees Celsius is: 121.11
Introduction to Computers and Programming 1.27

Key Terms
Computer: It is an electronic device that Input devices: Input devices accept the data
takes data and instructions as input from the from the end users on which the operations
user, processes the data, and generates useful are to be performed.
information as an output. Output devices: Output devices are used for
Vacuum tube: It was used in the first genera- providing the output of a program that is ob-
tion computers for developing the circuitry. It tained after performing the operations speci-
comprised of glass and filaments. fied in a program.
Transistor: It is a solid state device used in CPU: It is the heart of a computer that is used
the second generation computers. It replaced to process the data entered through the input
vacuum tubes. device.
IC: It is a silicon chip that embeds an elec- Memory: It is used for storing the input data
tronic circuit comprising of several compo- as well as the output of a program that is ob-
nents, such as transistors, diodes, and resis- tained after performing the operations in a
tors. It is used in third generation computers. program.
Microprocessor: It is a processor chip used Scanner: It is an input device that converts
in fourth generation computers. It integrates documents and images as the digitized im-
thousands of components on a single chip. ages understandable by the computer system.
LAN: It is a network, where multiple com- Motherboard: It is a device used for con-
puters in a local area, such as home, office, or necting the CPU with the input and output
small group of buildings, are connected and devices.
allowed to communicate among them. RAM: It is the primary memory of a com-
WAN: It is a network, which facilitates con- puter that stores information and programs,
nection and communication of hundreds of until the computer is used.
computers located across multiple locations. Monitor: It is an output device that produces
MAN: It is a network that is used to connect visual displays generated by the computer.
the computers over a large geographical area, Printer: It is an output device that prints the
such as district or city. computer generated information onto the pa-
GUI: It is a user-friendly interface that pro- per sheets.
vides icons and menus to interact with the Speaker: It is an electromechanical trans-
various computer applications. ducer that converts an electrical signal into
Microcomputer: It is defined as a computer sound.
that has a microprocessor as its CPU. Plotter: It is an output device that is connect-
Minicomputer: It is a medium-sized com- ed to a computer to print large documents,
puter that is designed to serve multiple users such as engineering and constructional draw-
simultaneously. ings.
Mainframe computer: It is a computer, System software: It refers to a computer
which helps in handling the information pro- program that manages and controls hardware
cessing of various organizations like banks, components.
insurance companies, hospitals and railways. Application software: It is a computer pro-
Supercomputer: It is the most powerful and gram that is designed and developed for per-
fastest computer. It is used for complex sci- forming specific utility tasks; it is also known
entific applications. as end-user program.
Discovering Diverse Content Through
Random Scribd Documents
number of fugitives was intercepted and made prisoners, and many
of the American riflemen being discovered in the trees, which they
had climbed, to be enabled to take sure aim and escape danger, the
British soldiers called this unfair, and shot them on their perches.
The King's Own had twenty-one men killed and wounded in this
action.
Halting on the field of battle, the bivouac fires were lighted, and
the victorious army reposed a short time under the canopy of
heaven. Two hours after midnight the soldiers were again under
arms; as the first glimmering of dawn appeared, they resumed their
march, and arrived in the evening at the foot of the range of hills in
front of Baltimore, where the grand American army of upwards of
fifteen thousand men appeared occupying a chain of pallisaded
redoubts connected by a breast-work, and defended by a numerous
train of artillery. Trusting to the innate valour and excellent discipline
of his little army, which did not amount to one-third of the number
of the opposing host, Colonel Brooke made arrangements for
storming the hills after dark; but having received intimation from the
commander of the naval forces that the entrance of the harbour was
closed up by vessels sunk for that purpose, and that a naval co-
operation against the town and camp was impracticable, the
enterprise was abandoned. The troops retreated three miles on the
14th of September, and then halted to see if the Americans would
venture to descend from the hills; but though so superior in
numbers, they had no disposition to quit their entrenchments, and
the British forces retired leisurely to their shipping and re-embarked.
The King's Own were commended in the public despatches for their
excellent conduct and discipline; and their commanding officer.
Major Faunce, was included among the officers who distinguished
themselves.
The armament remained a short time on the American coast, and
information having been received of the formation of an American
camp a few miles from the Potomac river, the King's Own, with the
remainder of the second and third brigades, landed on the night of
the 4th of October, and pushed forward to attack the enemy, who,
however, had notice of the movement and fled. The regiment
returned on the 5th, and the season having arrived when active
operations could no longer be continued in the Chesapeake, the fleet
sailed for the West Indies, and anchored in Port Royal harbour,
Jamaica, on the 31st of October, the troops remaining on board,
while the vessels took in a supply of provisions, &c.
While in the West Indies, reinforcements arrived; Major-General
John Keane joined and took the command of the expedition; and
Lieut.-Colonel Brooke of the King's Own arrived from England, where
he had been absent on account of ill health.
The next enterprise undertaken was of a most difficult character,
namely, an attempt on New Orleans, a town of some note, standing
on the eastern bank of the great river Mississippi, one hundred and
ten miles from the gulph of Mexico, and so situated that the
approach of an hostile force was almost impossible. The fleet having
put to sea, anchored on the 10th of December off the coast of
Louisiana, opposite the Chandeleur Islands, where the troops were
removed into light vessels, and entering Lake Borgne on the 13th,
five of the enemy's large cutters, mounting eleven guns each, were
captured by a flotilla of launches and ships' barges. Having
proceeded a short distance along the lake, all the vessels ran
aground; the soldiers were then conveyed twenty miles in open
boats, during a heavy rain, to a barren spot called Pine Island, which
consisted of a swamp with a piece of firm ground at one end. Here
the regiments remained without tents or huts, exposed to heavy
rains by day, and to frost by night, until the 22d of December, when
the King's Own, eighty-fifth, and five companies of the ninety-fifth,
embarked in open boats, and proceeding up the lake a distance of
more than fifty miles, were so cramped up in the boats, drenched
with a heavy rain during the day, and exposed to a sharp frost in the
night, that the men were almost deprived of the use of their limbs.
On the following morning they landed, unobserved by the enemy, on
a desert spot on the verge of a large morass about eight miles from
New Orleans, and when the men had regained the use of their
benumbed limbs, they advanced along an indistinct path on the bank
of a ditch or canal, their movements being concealed by the tall
reeds of the morass. After passing several streams by bridges
constructed at the moment, the troops entered a cultivated region
where the fields were found covered with the stubble of the sugar-
cane, and groves of orange trees were numerous. About noon the
regiments entered a green field on the banks of the Mississippi,
where they halted to await the arrival of the remainder of the army.
Late in the evening, while many of the men were cooking, and
others were asleep, a large vessel was seen stealing quietly up the
river until she arrived opposite the bivouac fires, and before it was
ascertained whether she was British or American a broadside of
grape-shot swept down many soldiers in the camp. Having no means
of attacking this formidable adversary, the soldiers took shelter
behind a bank: the night was dark, and the only light to be seen was
the flashes of the enemy's guns, as he continued to pour showers of
shot into the camp. At length a firing was heard from the advance
posts, and before the import of this was known a loud shout,
followed by a semicircular blaze of musketry, proved that the piquets
were surrounded by a very superior enemy. The King's Own were
instantly ordered to form in column behind the camp, while the
eighty-fifth, and five companies of the ninety-fifth, flew to the
support of the piquets. The enemy had brought forward about five
thousand men, thinking to overwhelm this solitary brigade in the
dark; but the British, regardless of the superior numbers of their
antagonists, rushed upon the opposing legions and fought, bayonet
to bayonet, and sword to sword, with a degree of energy and
resolution impossible to describe. Some of the soldiers having lost
their bayonets in the strife, laid about them with the butt-ends of
their firelocks; numerous feats of individual gallantry were
performed, and the Americans eventually gave way before this
furious and desperate charge, and fled with the loss of many men
killed, wounded, and prisoners. The King's Own had Captain Francis
Johnston and Lieutenant John Sutherland killed; also Lieutenant
Thomas Moody severely wounded; and a number of private men
killed and wounded.
Notwithstanding this victory, the troops were unable to return to
their camp, as it was completely commanded by the fire of the
American schooner, and no provision could be procured. Meanwhile
the other brigades arrived from Pine Island, and the whole were in
position before dark on the 24th of December. Major-General the
Hon. Sir Edward Pakenham also joined to take the command, and he
was accompanied by Major-General Gibbs.
1815

During the night a battery was constructed, and opening a fire of


red-hot shot, it destroyed the American schooner; but when the
troops proceeded towards the town, they encountered so many local
difficulties, were opposed by such immense bodies of Americans,
with extensive fortified lines and batteries, and armed vessels on the
river, that the advance was checked and considerable loss sustained.
Attempts were made to overcome these difficulties; the canal from
Bayo de Catiline was cleared out, widened, and opened to the river,
to admit the boats from the lake; and while the soldiers were
labouring at this work Major-General Lambert joined with two
additional regiments. Arrangements were made for attacking the
enemy's fortified lines at day-break on the morning of the 8th of
January, 1815. The boats were to be brought along the canal in the
night, part of the army was to embark, and proceeding up the river
with muffled oars, to gain the flank and rear of the works
unperceived; and simultaneous attacks were to be made on different
parts of the enemy's fortified position. This plan was, however, partly
disconcerted by the tardy arrival of the boats; and at the moment of
attack the scaling ladders and fascines had to be sent for. Day-light
arriving, the troops were visible to the enemy, who opened a
tremendous fire, with dreadful execution. Under these
disadvantages, the British rushed forward to storm the position in
front. A detachment of the King's Own, twenty-first, and ninety-fifth,
captured a three-gun battery, and advanced to attack a body of
Americans who were forming for its recovery; but having to pass a
deep ditch by a single plank, they were repulsed; and the enemy
forcing his way into the battery, re-captured it with immense
slaughter. Meanwhile the remainder of the King's Own were exposed
to a dreadful fire, and the regiment was nearly annihilated by the
tempest of bullets by which it was assailed. Major-General Pakenham
having galloped to the front to encourage the men, was shot on the
top of the glacis. Major-Generals Gibbs and Keane were borne from
the field dangerously wounded; and success being found
impracticable, the troops withdrew from the unequal contest. The
King's Own had upwards of four hundred men killed and wounded in
this desperate service: also, Lieutenant Edward Field, and Ensign
William Crowe, killed; and Lieutenant-Colonel Francis Brooke, Brevet
Lieutenant-Colonels Alured D. Faunce, and Timothy Jones, Brevet
Major John Williamson, Captains John Wynne Fletcher, Robert
Erskine, and David S. Craig, Lieutenants J. P. Hopkins, Jeffrey Salvin,
W. H. Brooke, Benjamin Martin, George Richardson, Peter Bowlby,
George H. Hearne, William Squires, C. H. Farrington, James Marshall,
Henry Andrews, and Adjutant William Richardson, with Ensigns
Arthur Gerard, Thomas Benwell, J. L. Fernandez, and Edward
Newton, wounded.
The capture of New Orleans appearing impracticable, a temporary
road was constructed through the morass, and the regiments having
reached the lake by a night march, embarked in boats and returned
to the fleet.
An attack on Mobile was afterwards resolved on, and the King's
Own were engaged in the siege of Fort Bowyer, which commanded
the entrance to the harbour; this place surrendered on the 12th of
February, and the second American regiment of the line having
marched out with the honours of war, delivered its arms and colours
to the King's Own.
Further hostilities against the Americans were, however, prevented
by a treaty of peace, and the Fourth being ordered to return to
England, arrived on the 16th of May at Portsmouth, from whence
they sailed to the Downs; and having landed on the 18th, were
stationed in Deal barracks.
On the extension of the Order of the Bath, in the beginning of this
year, Lieut.-Colonel Francis Brooke and Brevet Lieut.-Colonels John
Piper and Alured Dodsworth Faunce, of the King's Own, were nominated
Companions of that Order.
On the arrival in England of the surviving officers and men of the
King's Own from these difficult enterprises in America, they found
Europe involved in another war. Bonaparte had violated the treaty of
1814; he had quitted Elba; had invaded France with a few guards;
had been received with acclamations by the French army; and while
Louis XVIII. fled to Flanders, Napoleon had re-ascended the throne
of France. The nations of Europe declared war against the usurper;
and the King's Own were immediately ordered to proceed to Flanders
to engage in the approaching contest. The effective men of the
second battalion were added to the first battalion, which again
embarked for foreign service on the 10th of June, and having landed
at Ostend on the 12th, proceeded up the country. Bonaparte
attacked the advanced-posts of the army commanded by Field-
Marshal His Grace the Duke of Wellington in the middle of June; and
the King's Own, by forced marches, arrived at the position in front of
the village of Waterloo on the morning of the 18th of June, about an
hour before the battle commenced.
The regiment was commanded by Lieut.-Colonel Brooke, and
being formed in brigade with the twenty-seventh and fortieth
regiments, under the orders of Major-General Lambert, took part in
the gigantic contest which followed. On this occasion the stern
valour and undaunted character of the British troops were pre-
eminently displayed; whether assailed by the thunder of artillery,
volleys of musketry, the bayonets of infantry, or the furious charges
of the French cavalry, the British regiments stood firm, and repulsed
with sanguinary perseverance the legions of Bonaparte, and drove
them back in confusion. After resisting the attacks of the superior
numbers of the enemy for many hours, the Prussians arrived to co-
operate; when the allied army assumed the offensive, and by a
general charge of the whole line, overthrew the French host, and
drove it from the field with dreadful slaughter, and the loss of its
artillery, ammunition waggons, &c.
The King's Own had one hundred and thirty-four men killed and
wounded in this hard-contested and glorious battle; also the
following officers wounded,—Brevet Major G. D. Willson, Captain
James Charles Edgell, Lieutenants John Brown, B. M. Collins, Hygat
Boyd, George Richardson, William Squire, Arthur Gerard, Adjutant
William Richardson, and Ensign W. M. Matthews.
The honour of bearing the word Waterloo on the colours was
conferred on the regiment; every officer and man present received a
silver medal; and Major Willson, being second in command, was
promoted to the rank of lieut.-colonel, and nominated a companion
of the Order of the Bath.
The Fourth advanced with the army in pursuit of the enemy, and
were present at the surrender of Paris on the 7th of July. They were
afterwards encamped at Neuilly; on the 27th of October they went
into quarters at St. Germain-en-Laye; and being selected to form
part of the British contingent of the army of occupation appointed to
remain in France, they were formed in brigade with the fifty-second
and seventy-ninth regiments, under Major-General Sir Denis Pack.
On this occasion the Duke of Wellington observed in general orders:

"Upon breaking up the army which the field marshal has had the
honour of commanding, he begs leave again to return thanks to the
general officers, and the officers and troops, for their uniform good
conduct. In the late short but memorable campaign they have given
proofs to the world that they possess in an eminent degree all the
good qualities of soldiers; and the field marshal is happy to be able
to applaud their regular good conduct in their camps and
cantonments, not less than when engaged with the enemy in the
field. Whatever may be the future destination of those brave troops
of which the field marshal now takes his leave, he trusts that every
individual will believe that he will ever feel the deepest interest in
their honour and welfare, and will be happy to promote either."
Major-General Lambert, also, in taking leave of the Fourth,
expressed his approbation of their conduct, particularly at the "ever
memorable battle of Waterloo, which afforded him an opportunity of
personally observing that the high character the King's Own always
bore in the field has been most justly merited."
In consequence of a reduction in the army, the second battalion
transferred its private men to the first, and was disbanded at Deal
on the 25th of December, 1815.

1816

In January, 1816, the regiment was quartered at Franquemberg


and adjacent villages in the Pas de Calais, where it was presented
with a new pair of colours. In August it encamped near St. Omer,
and was reviewed on the 7th of September by the Duke of
Wellington, who expressed his approbation of its appearance and
discipline.
On the 15th of October, the Fourth quitted the vicinity of St. Omer,
and encamping near Mastaing, was reviewed on the 22d with the
remainder of the British, Danish, and Saxon forces, on the plain of
St. Denain, by their Royal Highnesses the Dukes of Kent and
Cambridge; the regiment afterwards returned to Franquemberg, &c.;
and its establishment was reduced to forty officers, forty-five
serjeants, twenty-two drummers, and eight hundred rank and file.

1817

The regiment again pitched its tents in July, 1817, near St. Omer,
where it was reviewed on the 5th of August by Lieut.-General Lord
Hill; on the 3d of September it encamped on the glacis of
Valenciennes, and on the 6th it was reviewed with the remainder of
the army commanded by the Duke of Wellington, by the King of
Prussia.
Having been again reviewed by Lord Hill on the 20th of
September, and having received the expressions of his lordship's
approbation, the regiment went into barracks at Valenciennes; but it
was again encamped in October, near St. Denain, and reviewed, with
the remainder of the British, Saxon, Danish, and Hanoverian troops
in France, by his grace the Duke of Wellington, on which occasion all
the evolutions of an engagement were performed in presence of a
number of distinguished personages. The King's Own subsequently
returned to their former winter quarters at Franquemberg, &c.

1818

On the 4th of June, 1818 the Fourth were again encamped near
St. Omer, and received the thanks of Lord Hill for their appearance
and correct discipline at the review on the 24th of June; also the
expression of the Duke of Wellington's approbation at the review on
the 31st of July: they were subsequently encamped on the horn-
work of Valenciennes; they formed a guard for the Duke of Kent
during his residence at that city, and were reviewed on the 10th of
September, with the remainder of the army commanded by his grace
the Duke of Wellington, in presence of their Royal Highnesses the
Duke and Duchess of Kent; when a number of evolutions were gone
through, and during the manœuvres the army crossed the Scheldt
by pontoon bridges.
The King's Own having returned to Valenciennes on the 21st of
October, furnished guards of honour for the Emperor of Russia, King
of Prussia, Prince of Orange, and Grand Dukes Constantine and
Michael, who reviewed the Russian, British, Danish, Saxon, and
Hanoverian contingents of the army of occupation, on the 23d of
October. This force amounted to between fifty and sixty thousand
men; the evolutions of a mock engagement were gone through, and
two rivers were passed by pontoon bridges.
The Emperor of Russia was so well pleased with the conduct of
the King's Own, that on quitting Valenciennes he presented one
hundred and nineteen Napoleons (pieces of twenty francs each) to
be divided among the men of the grenadier company composing his
guard; also ten Napoleons each to the two serjeants who were his
orderlies; and directed the aide-de-camp to give them his feather to
keep in remembrance of the Emperor's regard for the corps. The
King of Prussia also gave money to the men of the light company of
the King's Own forming his guard.
On the breaking up of the army of occupation in France, the King's
Own received, with the other corps, the expressions of the
approbation of the Duke of Wellington, in general orders; also of
Lieut.-General Lord Hill in general orders to the two divisions under
his command; of Lieut.-General Sir Charles Colville in division orders;
and of Major-General Sir Denis Pack in brigade orders.
The regiment embarked at Calais on the 29th of October, landed
at Dover on the following morning, and proceeding from thence to
Winchester barracks, was immediately afterwards ordered to hold
itself in readiness to embark for the West Indies; at the same time
the establishment was reduced to seven hundred and forty-six
officers and men.

1819

In the early part of January, 1819, the regiment marched to


Cumberland fort; on the 1st of February it embarked at Portsmouth,
and having landed at Barbadoes on the 5th of April, was reviewed by
Lieut.-General Lord Combermere on the same day, and afterwards
returned on board the transports. His lordship expressed in general
orders his approbation of the appearance and discipline of the
regiment.
On the following day six companies sailed for Grenada (head-
quarters) under the command of Lieut.-Colonel Piper; two companies
to Trinidad under Lieut.-Colonel Faunce; and two to Tobago under
Captain Fletcher.
At the half-yearly inspection in July, Major-General Sir Frederick
Robinson expressed in brigade orders "the very high satisfaction he
had enjoyed in the military appearance and the report of the good
conduct of the King's Own regiment, which he perceives has not lost
any of its former character,—hitherto a subject for praise and
admiration with officers of the highest rank and military reputation."

1820
The two companies at Tobago suffered very severely from fever,
and having lost four officers and eighty-four serjeants and rank and
file, the remaining one officer, four serjeants, two drummers, and
thirty-five rank and file were relieved in September 1820 by the
twenty-first regiment, and sent to Barbadoes, from whence they
were removed to Grenada.

1821

A general change of quarters took place among the troops


stationed in the Windward and Leeward Islands in March 1821,
when the King's Own proceeded to Barbadoes. On leaving Grenada
Major-General Riall expressed in brigade orders his approbation of
the conduct of the King's Own, and the satisfaction he experienced at
hearing from the magistrates and principal inhabitants of the island
their esteem for the corps, and their regret at its departure.
The loss from disease during the short period the regiment had
been in the West Indies was great. Quarter-Master Thomas Richards
and fifty-four men had died at Grenada; Lieutenant William Blagrave,
Ensign Robert Gamble, and seven men at Trinidad, which had
proved a comparatively healthy station, the two companies having
occupied the barracks at St. Joseph's and the hospital had frequently
been without a patient; at Tobago, Lieutenants John Westby,
Frederick P. Robinson, and Isaac Beer, with Ensign Frederick Clarke,
and eighty-four men, had fallen victims to the climate; Captain
Charles James Edgell died on the passage, near Barbadoes: the total
loss of life in one year and eleven months was eight officers and one
hundred and forty-five soldiers.
The regiment was, however, still in an efficient state, and having
been inspected by Lieut.-General Sir Henry Warde on the 27th of
August, an order was issued on the same day, expressing "the great
satisfaction felt by the lieut.-general at the appearance of that old
and respectable corps under arms, as well as the steadiness of the
regiment, the correct advance in line, and the close firing, which
evince that great attention has been paid to its discipline, and is
highly creditable to Lieut.-Colonel Piper and to the officers generally."
In October the establishment was reduced to eight companies,
making a total of thirty-three officers and six hundred and seventeen
men.

1822
1823

Lieut.-Colonel Piper died at Barbadoes soon afterwards, and was


succeeded in January, 1822, by Brevet Lieut.-Colonel A. D. Faunce.
In the following year this officer obtained permission to return to
England for the benefit of his health, on which occasion Lieut.-
General Sir Henry Warde observed in general orders—"He was aware
that no encomium of his could add lustre to the already well-
established and high military character of Lieut.-Colonel Faunce, yet
the particularly exemplary state of discipline, in every respect, which
the Fourth or King's Own regiment has attained since he assumed the
command, calls loudly on the lieut.-general, as an imperious duty to
the service, to express his warmest praise and thanks to Lieut.-
Colonel Faunce, for the truly able and unremitted attention which he
has daily and hourly paid to his regiment, the effect of which confers
on him the highest credit and honour as its commander, and at the
same time reflects them strongly on every individual, both officer
and private, composing the corps under his command."
In December the regiment was withdrawn from Barbadoes, and
proceeded,—four companies and head-quarters to the Ridge at
Antigua, three to Brimstone-hill, St. Kitt's, and one to Montserrat and
Nevis. Previous to its embarkation Lieut.-General Sir Henry Warde
expressed in general orders his "high approbation of the conduct of
the corps." During the two years and nine months it was stationed at
Barbadoes, it was in a healthy state, excepting towards the end of
1821, when a fever carried off Lieut.-Colonel John Piper, Ensigns H.
N. Shipton, and H. J. Loraine, with Quarter-Master Doran, and
Assistant-Surgeon Morrow; its total loss in serjeants and rank and
file was fifty-eight.

1824

The detachment at Nevis suffered from the unhealthy situation of


the barracks, and lost seventeen men out of thirty; it was
subsequently withdrawn. In October, 1824, the regiment lost Brevet
Major John Wynne Fletcher.[34]

1825

In April, 1825, the regiment was augmented to ten companies,


and the total establishment to eight hundred and thirty-six officers
and men.

1826

The regiment was relieved from duty at Antigua, St. Kitt's, and
Montserrat, in February, 1826, by the ninety-third, and sailed for
England. The first division landed at Gosport on the 16th of March,
the second on the 1st of April, and the last on the 6th of April.
During the seven years the regiment was in the West Indies its
total loss was sixteen officers, twenty-one serjeants, one drummer,
and two hundred and forty-five rank and file. It brought home four
hundred and twenty rank and file, (without leaving a sick man
behind;) and on the 25th of April sent out thirteen recruiting parties,
twelve to different parts of England, and one to Ireland.
On the 8th of August the Adjutant-General of the Forces, Major-
General Sir Henry Torrens, inspected the regiment, and expressed
his approbation of its appearance and discipline, adding that he
should make a most favourable report to His Royal Highness the
Duke of York. In the autumn it quitted Winchester, and proceeding
to Portsmouth, was employed in the duty of that garrison. At the
half-yearly inspection, Major-General Sir James Lyon expressed his
perfect approbation of its appearance and discipline.
The regiment was soon afterwards called upon to transfer its
services to the Peninsula, the scene of many of its toils and
triumphs. After Spain and Portugal had been delivered by British skill
and valour from the power of Bonaparte, these kingdoms became
convulsed by opposing interests, one party striving for the liberties
possessed by other nations, and another for a return to ancient
usages; and the granting of a constitution to Portugal, which
conferred on the people privileges previously unknown in that
country, was followed by internal commotions; at the same time the
kingdom was menaced with an invasion from Spain. The Portuguese
government applied for the aid of a body of British troops; six
companies of the King's Own formed part of a force of five thousand
men, commanded by Lieut.-Gen. Sir William H. Clinton, ordered for
this service, and embarking from Portsmouth on the 15th of
December, arrived at Lisbon towards the end of that month.

1827

Having landed on the 1st of January, 1827, the King's Own


occupied the barracks of Valle de Pereiro, and were formed in
brigade with the tenth, twenty-third, and first battalion of the
sixtieth rifles, under the command of Major-General Sir Edward
Blakeney. The brigade having been inspected by Sir William Clinton
on the 14th of January, advanced up the country nine stages to
Coimbra, and was quartered in convents, the King's Own occupying
the convent of St. Bernard. On the advance of the British, the
Spaniards withdrew from the frontiers, and declared a friendly
disposition towards the Portuguese government; a mutiny in the
Portuguese army was also suppressed; and there being no further
occasion for the British troops, they marched back to Lisbon, where
the King's Own arrived on the 12th of July, and occupied the barracks
of La Lippe at Belem. Three companies of the regiment were
subsequently stationed at Oeiras, a small town on the right bank of
the Tagus, two leagues from Lisbon, and the other three at Feitovia
barracks, near Fort St. Julian.
1828

In these quarters the King's Own remained until the spring of 1828,
when the British troops were withdrawn from Portugal; the six
companies having received the expressions of the approbation of
Major-General Sir Edward Blakeney in brigade orders, for their
exemplary conduct, embarked from Belem stairs on the 31st of
March, and on their arrival at Portsmouth, they were ordered to
proceed to Scotland: they landed at Leith on the 26th and 29th of
April, and proceeded to Edinburgh Castle, where the remainder of
the regiment had previously arrived.
The regiment marched in July to Glasgow, where it received a new
pair of splendid regimental colours, which cost £150, with belts
which cost £21, and a richly-mounted staff, &c., for the drum-major;
which were presented by the colonel, General the Earl of Chatham.

1829

From Glasgow, the regiment embarked, in July, 1829, in steam-


vessels for Ireland, and after landing at Belfast in the early part of
August, marched to Newry, with detached companies at Cavan and
Clones.

1830

In June, 1830, the regiment marched to Dublin, and occupied


Richmond-barracks; in September it embarked from Dublin, and
having landed at Liverpool, the two flank companies remained there
a short time to attend on the occasion of the opening of the railroad
from that town to Manchester, while the battalion companies
proceeded to Stockport, Bolton, and Oldham; the flank companies
arrived at Stockport on the 18th of September.

1831

In January, 1831, the head-quarters were at Ashton-under-Lyne;


in March at Northampton; and in April at Chatham.
Part of the regiment embarked in this year for New South Wales,
in detachments, as guards to convict-ships.

1832

The head-quarters, under the command of Lieut.-Colonel


M'Kenzie, embarked for the same destination at Deptford, on board
the Clyde, on the 14th of April, 1832, and arrived on the 30th of
August.

1833
1834

The regiment remained at New South Wales five years; its head-
quarters being established at Paramatta until June, 1833, when they
were removed to Sydney; but returned to Paramatta in June, 1834;
where they remained upwards of twenty months.

1835

On the decease of General the Earl of Chatham the colonelcy of


the King's Own was conferred on Lieut.-General John Hodgson, by
commission dated the 30th of September, 1835.

1836
1837

In March, 1836, the head-quarters were again removed to


Sydney; and in August of the following year two divisions embarked
for the East Indies. One division landed at Madras on the 30th of
September, 1837; the head-quarters arrived on the 7th of October,
and were stationed at Fort St. George.

1838

The third and last division embarked from New South Wales on
the 26th of December, 1837, and arrived at Madras on the 9th of
April, 1838.
1839

Thus, after serving a period of nearly one hundred and sixty years,
in every quarter of the globe, this celebrated corps, which has so
often triumphed over foreign enemies in fields of conflict, has been
appointed to guard the colonial possessions of its country in the
distant clime of India, where it has remained to the beginning of
1839, which brings this record to a conclusion.

1839
Fourth (or King's Own) Regiment of Foot.
[To face page 141.
FOOTNOTES:
[6] Piercy Kirke held the commission of captain-lieutenant of the
Earl of Oxford's troop in the royal regiment of horse guards, at
the time he was appointed lieut.-colonel of this regiment, and for
several months afterwards.
[7] The first Tangier regiment was raised in 1661, and is now the
second, or queen's royal regiment of foot.
[8] The expense of equipping the regiment was estimated at the
following rates.
Clothing. Appointments.
£. s. d. £. s. d.
Coat and breeches 1 16 0 Waist belts 0 4 6
Serjeant's ditto 4 10 0 Swords 0 4 6
Hats 0 7 0 Pikemen's Swords 0 5 0
Serjeant's ditto 0 15 0 Grenadier hangers 0 6 6
Grenadier caps 0 9 6 Serjeant's Swords 0 10 0
Neckcloths 0 1 0 Collars or Bandaliers 0 5 6
Serjeant's ditto 0 2 0 Cartouch boxes 0 2 6
Shirts 0 3 6 Match boxes 0 1 0
Serjeant's shirt 0 6 0 Grenade bags 0 6 0
Shoes, per pair 0 4 6 Knapsacks 0 1 6
Stockings, per pair 0 2 0
Serjeant's ditto 0 6 0
Sashes for the Pikemen 0 2 6

[9] The usual charge for regimental colours, was from £6 to £10
each.
[10]
James R.
"Our will and pleasure is, That out of such
For £206 5s. 6d. to
Thomas Holford for moneys as shall come into your hands for
Ten Colours for Thethe pay and contingent uses of Our guards
Queen's Regiment ofand garrisons, you pay to Thomas Holford
Foot. the sum of Two Hundred and Six Pounds
Five Shillings and Six Pence, for Ten Colours
made and provided by him for Our dearest Consort, The Queen's
Regiment of Foot, and for so doing this, together with the
acquittance of the said Thomas Holford, shall be your warrant
and discharge.
"Given at Our Court at Windsor this 21st day of August 1686.
"By His Majesty's command,
"To Our Trusty and well-beloved }
Cousin and Councillor Richard }
Earl of Ranelagh, Our Pay- } "W. Blathwayt."
master-General, }
&c. &c. &c. }
[11]
Third troop of life guards; disbanded in 1746.
Queen's horse; now first dragoon guards.
M. G. Warden's horse; disbanded in 1690.
Queen's dragoons; now third light dragoons.
Royals; now first foot.
Queen Dowager's; now second foot.
Queen Consort's; now fourth foot.
[12] The following corps were sent to England on this occasion:—
First troop of life guards; now first regiment of life guards.
Count De Schomberg's horse; now seventh dragoon guards.
Royal Dragoons; now first, or royal dragoons.
The Queen's regiment of foot; now fourth, or King's Own.
Hastings'; now thirteenth foot.
[13] The Earl of Marlborough's force consisted of the following
corps:—
The Queen's regiment; now fourth, or King's Own.
Royal fusiliers; now seventh foot.
Princess Anne's; now eighth foot.
Hastings'; now thirteenth foot.
Hales's, afterwards disbanded.
Sir David Collier's, ditto.
Fitz-patrick's, ditto.
100 men of the Duke of Bolton's, ditto.
200 of the Earl of Monmouth's, ditto.
Lord Torrington's marine regiment, ditto.
Lord Pembroke's, ditto.
[14] On the accession of Queen Anne, the eighth foot, which had
been designated the Princess Anne's regiment from the time of its
formation in 1685, obtained the title of the Queen's regiment, the
Fourth also continued to be distinguished by the same title; and
during this reign two regiments were designated Queen's
regiments.
[15] Vide the Historical Record of the Third Foot, or Buffs.
[16] The embarkation return of the regiment is preserved among
the Harleian MSS. No. 7025.
[17] The six regiments of marines were:—
Colonel Thomas Saunderson's; now thirtieth foot.
Colonel George Villiers'; now thirty-first foot.
Colonel Edward Fox's; now thirty-second foot.
Colonel Harry Mordaunt's; disbanded.
Colonel Henry Holt's; disbanded.
Colonel Viscount Shannon's; disbanded.
The six regiments of foot for sea service were:—
Colonel Ventris Columbine's; now sixth foot.
Colonel Thomas Earl's; now nineteenth foot.
Colonel Gustavus Hamilton's; now twentieth foot.
Colonel Lord Lucas's; now thirty-fourth foot.
Colonel Earl of Donegal's; now thirty-fifth foot.
Colonel Lord Charlemont's; now thirty-sixth foot.
[18] The grenadiers, on their institution in 1678, wore fur caps
with high crowns; these were soon afterwards replaced by leather
caps covered with cloth and ornamented with regimental devices,
which were continued until the adoption of bear skin caps in the
reign of George III.
[19] Boyer's Annals of Queen Anne.
[20] In some accounts this officer's name is stated to be Fish, in
others Fisher.
[21] The following regiments were employed on this expedition,
viz.:—
Kirke's regiment, now second foot.
The
" " fourth foot.
Queen's
Hill's " " eleventh foot.
Desney's " " thirty-sixth foot.
Windress's " " thirty-seventh foot.
Clayton's " disbanded in 1712.
Kane's " " 1713.
Churchill's Marines "
Walton's North American militia, joined the
Vetch's } expedition at Boston.
[22] "The behaviour of the officers in general was very brave, nor
are some regiments unworthy of great praise; viz., Barrell's (King's
Own), Price's, and some others."—General Advertizer.
"The regiments which distinguished themselves were Barrell's
(King's Own) and Ligonier's foot."—Ibid.
[23] "General Barrell's regiment (the King's Own) gained the
greatest reputation imaginable at the late engagement, the best
of the clans having made their strongest efforts to break them,
but without effect; for the old Tangiereenes bravely repulsed
those boasters with a dreadful slaughter, and convinced them
that their broad sword and target are unequal to the musket and
bayonet when in the hands of veterans who are determined to
use them. After the battle there was not a bayonet of this
regiment but was either bloody or bent."
"The battle was so desperate that the soldiers' bayonets were
stained with blood to the muzzles of their musquets."
"There was scarce an officer or soldier of Barrell's (King's Own)
and that part of Munro's (now thirty-seventh) which engaged,
who did not kill one or two men each with their bayonets," &c.—
Particulars of the Battle of Culloden published at the time.
[24] The exact time when the regiment obtained the Lion of
England for its badge has not been ascertained. A tradition has
long existed in the corps that it was conferred by King William
III., in consequence of its being the first corps which joined him
after he landed at Torbay, in November, 1688; but on searching
the details of the events which occurred at that period, it appears
that this was not the first regiment which joined his Majesty; that
only the colonel, lieut.-colonel, a few other officers, and about
thirty soldiers, joined King William; and that the regiment adhered
to King James until he vacated the throne. It is probable,
however, that this distinguished badge was conferred by King
William III. for the attachment which the regiment evinced to his
person and government and to the protestant cause.
[25] Beatson's Naval and Military Memoirs.
[26] Return of regiments in garrison at Minorca, 1756—
Key:
A = Officers
B = Serjeants
C = Corporals
D = Drummers
E = Privates
F = Killed
G = Wounded
H = Died

Strength at the Loss.


commencement of At the
Corps. During
the siege. general
the siege.
assault.
A B C D E F G H F G
Fourth, or King's
Own 25 28 27 18 616 14 68 8 7 7
Twenty-third, or
Royal Welsh
Fusiliers 24 24 26 17 615 19 83 7 9 7
Twenty-fourth
Regiment 25 23 27 16 623 6 61 6 .. 7
Thirty-fourth
Regiment 26 29 29 19 650 12 77 9 1 3
Total 100 104 109 70 2504 51 289 30 17 24

Officers Killed.
Fourth, or King's Own, --Lieut. Whitehead.
Thirty-fourth regiment,--Captain Hobby.
" " Lieut. Armstrong.
Officers Wounded.
Twenty-third regiment, --Lieut. Young.
Twenty-fourth regiment,--Major Godfrey.
" " Lieut. Francis.
Thirty-fourth regiment,--Capt. Sir Hugh Williams.
Engineer,--Major Cunningham.
[27] "Major-General Grant crossed the ford with the Fourth and
fifth regiments, and the Fourth Regiment, passing the ford first,
drove the enemy from an entrenchment and battery, and took
from them three brass field-pieces and a 5½ inch howitzer."—
London Gazette.
[28] London Gazette.
[29] The effectives of the British army in 1803 were as follows:—
On
In Great
In Ireland. Foreign Total.
Britain.
Stations.
Cavalry 10,436 3,466 2,263 16,165
Artillery and engineers 9,000 2,000 3,000 14,000
Foot guards 6,916 .. .. 6,916
Infantry of the line 44,981 21,790 42,951 109,722
Militia 66,189 18,508 .. 84,697
137,522 45,764 48,214 231,500
Yeomanry and volunteers:—
Cavalry 29,000 10,000 .. 39,000
Artillery 7,000 .. .. 7,000
Infantry 290,000 65,000 .. 355,000
General Total 463,522 120,764 48,214 632,500

The above numbers of "Fighting men" are exclusive of the Royal


Navy and Marines.

[30]
A "Horse Guards, 5th September, 1804.
"My dear Lord,
"I have been so extremely occupied since my return from my
tour through the southern district that I have never been able, till
this day, to write to you, and to express to you, in the warmest
manner possible, the thorough satisfaction I experienced at the
appearance and state of discipline of the King's Own regiment,
which does the highest credit to the commanding officer, and
every individual in it. I beg your lordship to convey these
sentiments from me to the regiment, and at the same time to be
assured that I shall, in consequence, recommend to his Majesty
to allow a greater promotion to take place in the King's Own upon
the present occasion, than has been allowed to other regiments,
the fifty-second excepted. I shall therefore be happy to receive
any recommendations that your lordship may think proper to
make."
(Signed) "Frederick."
"To Lieut.-General the Earl of Chatham.

"Lieut.-General the Earl of Chatham has the greatest pleasure


in communicating to the King's Own regiment the distinguished
approbation which his Royal Highness the commander-in-chief
has been pleased to convey to him of their soldierlike appearance
and high state of discipline when his Royal Highness lately saw
them at Shorncliffe camp. Lord Chatham desires to offer his
particular thanks to Lieut.-Colonel Brinley, as well as to the
officers, non-commissioned officers, and privates, for their
conduct and unremitted exertions, so well attested by the
superior appearance of the regiment, and he trusts that a
perseverance in the same exemplary conduct, will ensure to them
a continuance of his Royal Highness's favourable opinion.
"Lord Chatham assures the regiment that it is with the
warmest satisfaction he has seen a corps, whose zeal and whose
bravery it has been his good fortune to witness in the field, attain
that degree of discipline, correctness, and precision, which when
combined must ever render British soldiers invincible."
[31] After dinner Colonel Brinley was addressed by Major Dales as
follows:—
"The King's Own have directed me to inform you that, while
they rejoice at your promotion, they feel much distressed at
parting with an officer whose whole time has been so zealously
and successfully employed for the general welfare of the corps. It
is their intention to beg your acceptance of a small mark of their
universal esteem, and it naturally suggested itself to them that a
SWORD was the most appropriate token; and, while it will keep
alive your attachment to them, opportunities will probably occur
when it will be drawn in defence of the best of Kings and best of
governments."
To which the colonel replied:—"I beg leave to express in the
warmest terms, how much I feel the marked attention showed
me by this very elegant entertainment. I return you a thousand
thanks for the testimony of your attachment, esteem, and regard,
manifested by the proposed present of a superb sword, which I
shall wear with pride, and I hope with honour to the end of my
life. To your assistance alone, during the three years I have had
the honour to command you, am I indebted for enabling me to
bring the King's Own regiment to its present state of perfection;
and I attribute the recent mark of favour which his Majesty has
been graciously pleased to confer on me, to your generous aid."
[32] In 1808 the officers' lace, epaulettes, and buttons, were
directed to be changed from silver to gold.
[33] Lieut.-General Leith was wounded during the action, when
Major-General Pringle assumed the command of the fifth division,
and Lieut.-Colonel Brooke that of the brigade.
[34] Brevet Major John Wynne Fletcher was senior captain of the
regiment, in which he had served most zealously twenty-five
years, and he was sincerely lamented by his brother officers. He
was aide-de-camp to Lieut.-General Sir Henry Warde, K.C.B.,
commander of the forces in the Windward and Leeward Islands,
who followed his remains to the grave, and directed a marble
tablet, with the following inscription, to be placed in the church at
Bridgetown;—
SACRED TO THE MEMORY
of a good Christian, a gallant soldier, and an honest man,
in life beloved and in death lamented.
Near this spot rest the mortal remains of Brevet Major
JOHN WYNNE FLETCHER,
Captain in the Fourth, or the King's Own Regiment of Foot,
And Aide-de-camp to Lieut.-General Sir Henry Warde,
Who departed this life on the 24th of October, 1824,
Aged 39 years.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

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.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookluna.com

You might also like