Computer Programming E Balagurusamy Full Chapter
Computer Programming E Balagurusamy Full Chapter
Balagurusamy
Visit to download the full and correct content document:
https://ebookmass.com/product/computer-programming-e-balagurusamy/
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
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
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:
Preface xiii
Roadmap to the Syllabus xvi
Answers 1.29
Review Questions 1.29
Answers 4.48
Review Questions 4.49
Debugging Exercises 4.51
Programming Exercises 4.51
Answers 7.40
Review Questions 7.40
Debugging Exercises 7.42
Programming Exercise 7.42
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
E Balagurusamy
Publisher’s Note
McGraw Hill Education (India) invites suggestions and comments, all of which can be sent to
[email protected] (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
Go to
Chapter 1: Introduction to Computers and Programming
Chapter 2: Basics of C
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
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
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)
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.
Magnetic Magnetic
Tape Disk
Arithmetic
Unit
Control
Data and results flow
Unit
Control Instructions to units
Instructions to control unit
CPU
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
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.
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.
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
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
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.
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
Protective coating
Dielectric
layers
Laser beams
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
Although C99 is an improved version, still many commonly available compilers do not support all of the
new features incorporated in C99.
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.
Integral Type
Integer Character
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
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.
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:
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:
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.
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
run infinitely.
solution.
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
Feasibility Analysis
Developing code
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();
C=(F-32.0)/1.8;
Testing
The program must be tested with multiple input values so as to ensure that there are no logical errors present
in the code.
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.
Another random document with
no related content on Scribd:
will be sewed by arbitration at an early day. Under the
circumstances the Commission, while continuing its deliberations
in the preparation and orderly arrangement of many valuable maps,
reports, and documents, which have been procured and used in the
course of its labors, does not propose to formulate any decision
for the present of the matters subject to its examination. It
will continue its sessions from time to time, but with the hope
and expectation that a friendly and just settlement of all
pending differences between the nations interested will make
any final decision on its part unnecessary." This hope was
substantially realized a few days later, when a convention
embodying the agreement of the United States and Great Britain
was signed by Secretary Olney and the British Ambassador, Sir
Julian Pauncefote. The agreement was carried to its next stage on
the 2d of February, 1897, when a treaty between Great Britain and
the United States of Venezuela was signed at Washington, which
provided as follows:
{692}
"Article I.
An Arbitral Tribunal shall be immediately appointed to
determine the boundary-line between the Colony of British
Guiana and the United States of Venezuela.
"Article II.
The Tribunal shall consist of five Jurists: two on the part of
Great Britain, nominated by the Members of the Judicial
Committee of Her Majesty's Privy Council, namely, the Right
Honourable Baron Herschell, Knight Grand Cross of the Most
Honourable Order of the Bath, and the Honourable Sir Richard
Henn Collins, Knight, one of the Justices of Her Britannic
Majesty's Supreme Court of Judicature; two on the part of
Venezuela, nominated, one by the President of the United
States of Venezuela, namely, the Honourable Melville Weston
Fuller, Chief Justice of the United States of America, and one
nominated by the Justices of the Supreme Court of the United
States of America, namely, the Honourable David Josiah Brewer,
a Justice of the Supreme Court of the United States of
America; and of a fifth Jurist to be selected by the four
persons so nominated, or in the event of their failure to
agree within three months from the date of the exchange of
ratifications of the present Treaty, to be selected by His
Majesty the King of Sweden and Norway. The Jurist so selected
shall be President of the Tribunal. In case of the death,
absence, or incapacity to serve of any of the four Arbitrators
above named, or in the event of any such Arbitrator omitting
or declining or ceasing to act as such, another Jurist of
repute shall be forthwith substituted in his place. If such
vacancy shall occur among those nominated on the part of Great
Britain, the substitute shall be appointed by the members for
the time being of the Judicial Committee of Her Majesty's
Privy Council, acting by a majority, and if among those
nominated on the part of Venezuela, he shall be appointed by
the Justices of the Supreme Court of the United States, acting
by a majority. If such vacancy shall occur in the case of the
fifth Arbitrator, a substitute shall be selected in the manner
herein provided for with regard to the original appointment.
"Article III.
The Tribunal shall investigate and ascertain the extent of the
territories belonging to, or that might lawfully be claimed
by, the United Netherlands or by the Kingdom of Spain
respectively at the time of the acquisition by Great Britain
of the Colony of British Guiana, and shall determine the
boundary-line between the Colony of British Guiana and the
United States of Venezuela.
"Article IV.
In deciding the matters submitted, the Arbitrators shall
ascertain all facts which they deem necessary to a decision of
the controversy, and shall be governed by the following Rules,
which are agreed upon by the High Contracting Parties as Rules
to be taken as applicable to the case, and by such principles
of international law not inconsistent therewith as the
Arbitrators shall determine to be applicable to the
case:—
Rules.
(a.) Adverse holding or prescription during a period of fifty
years shall make a good title. The Arbitrators may deem
exclusive political control of a district, as well as actual
settlement thereof, sufficient to constitute adverse holding
or to make title by prescription.
Article XIII.
The High Contracting Parties engage to consider the result of
the proceedings of the Tribunal of Arbitration as a full,
perfect, and final settlement of all the questions referred to
the Arbitrators:"
VICTORIA, Queen:
The Diamond Jubilee celebration of her accession to the throne.
VICTORIA.
VIENNA: A. D. 1895-1896.
Anti-Semitic agitation.
VIENNA: A. D. 1897.
Scenes in the Reichsrath.
VIENNA: A. D. 1900.
Census.
VIEQUEZ.
VISAYANS, The.
See (in this volume)
PHILIPPINE ISLANDS: THE NATIVE INHABITANTS.
{694}
WADAI.
WALDECK-ROUSSEAU, M.:
The Ministry of.
WANA:
Inclusion in a new British Indian province.
WAR:
Measures to prevent its occurrence and to mitigate its
barbarities.
WAR BUDGETS:
Military and naval expenditures of the great Powers.
{695}
"TABLE A.
Analysis of the war budget of the United States as agreed to,
or about to be agreed to, by the House of Representatives,
first session Fifty-sixth Congress.
1. ARMY.
Appropriations for the active Army.
Army bill
$117,994,649.10
Military Academy bill
700,151.88
Fortification bill
7,227,461.00
Deficiencies submitted:
December 11, 1900
12,062,223.36
January 21, 1901
5,835,239.50
January 26, 1001
5,300,000.00
Total
23,197,462.36
Pensions
$145,245,230.00
Salaries, Pension Bureau, etc.
3,352,700.00
Record and Pension Office
585,170.00
National Homes for Disabled Volunteer Soldiers
3,074,142.00
State Homes for Disabled Volunteer Soldiers
950,000.00
Back pay and bounty (civil war)
325,000.00
Arrears of pay (Spanish war)
200,000.00
National cemeteries
191,880.00
Artificial limbs and appliances
27,000.00
Headstones and burials
28,000.00
Apache prisoners
2,500.00
Secretary of War, extra clerks (Spanish war)
600,000.00
Auditor for War Department,
extra clerks(Spanish war)
112,580.00
Total.
154,694,292.00
Naval bill
$77,016,635.60
Legislative, executive, and judicial bill:
Office of the Secretary of the Navy
$47,900.00
Office of the Auditor for the Navy
Department 68,080.00
Offices of heads of bureaus, etc.
224,430.00
Maintenance of three-eighths
of Department building
45,990.00
Contingent expenses
12,750.00
Total
$399,150.00
Deficiencies submitted:
December 11, 1900
74,481.09
December 17, 1900
20,000.00
January 21, 1901
2,267,068.55
January 25, 1901
130,000.00
Total
2,491,549.64
3. RECAPITULATION.
Active Army
$152,068,100.84
Active Navy
80,034,335.24
Total
$232,102,436.08
{696}
TABLE B. Analysis of war budgets of various armies.