CP Text
CP Text
Fundamentals and
Programming in
— Reema Thareja |
Computer
Fundamentals and
Programming in
SECOND EDITION
Reema Thareja
Assistant Professor
Department of Computer Science
Shyama Prasad Mukherji College for Women
University of Dethi
OXFORD
UNIVERSITY PRESS
OXFORD
UNIVERSITY PRESS
Published in India by
Oxford University Press
YMCA Library Building. 1 Jai Singh Road, New Delhi 110001, India
© Oxford University
Press 2012. 2016
poe ee
a retrieval system, or transmitted, in any form or by any means, without the
i ifOxford University Press, ited
ISBN-13: 978-0-19-946373-2
ISBN-10; 0-19-946373-5
Keys such as Shift, Ctrl, and Alt are called modifier keys
because they are used to modify the normal function of a
key. For example, Shift + character (lowercase) makes the
Notes and Programming Tips computer display the character in upper case.
Notes highlight important terms and concepts,
and programming tips educate the readers about
common programming errors and how to avoid Programming
Tip:
Strings cannot be
them manipulated with
arithmetic or other
operators available in
C boundaries.
POINTS TO REMEMBER
GUDSSARY
Glossary eee pa nee at rtsayat oeet
cae mereSta
meet owe sree Hataati teat
Includes a list of key terms along with their definitions Come mate nage Snr ene
ane mae owtee© ot paeny Oe
for a quick recapitulation of important terms learned ee
ee anadieaddeed
in all chapters fe ees ore eS
Cans met capes The mee oteat
the Book
CASE STUDY 1: Chapters
9and10
a attire Case Studies
Select chapters on C include case studies that
CASE STUDY 2: Chapter 12
show how C can be used to create programs
demonstrating real-life applications
.4 +
» =
Sa. to Objective
tions Objective Questions
Includes comprehensive exercises at the end of each
chapter to facilitate revision—Answers to these
questions are provided in Appendix F at the end of
the book
EXERCISES
Exercises
Includes plenty of program code-related programs
at the end of relevant chapters, which require the
readers to find the output of a given code, the
functionality of a given loop, or errors in a given
program code
Companion Online Resources
SOOKE
Visit india.oup.com/ores/9780199463732 to access
both teaching and learning solutions online.
Online Resources
The following resources are available to support the
faculty and students using this text:
For Faculty
* PowerPoint presentations
* Solutions manual
* Projects
For Students
* Multiple-choice Questions
* Model Question Papers
* Codes of chapter-wise programming examples
Step 9:Confirmation
© Youwil receivea
confemation omyour
‘Step 4:ViewResources gray = =
© Chik on"Viewat Fear
resources* Step 20;Visitusagain
oa, © Goto indiacup-com
aS © Sign in withOuferdiO
Step 11: Visityourlicensed products Step 12:Download Resources
* Goto “Resources” section © Git onthetitle
. View orine resources
— Resources
© Select resource type
=—-- -
© Oownioad the resource you require
Preface to the Second Edition
Information technology (IT) is the buzzword in the 21st century. It has revolutionized the way we think and irreversibly
changed our everyday existence. Computers form the backbone of information technology affecting all aspects of our
lives, They are not only used for general computing but also for performing tasks such as booking railway and airline
tickets, designing a building, training a player, and practicing landing of an airplane. The use of computers has become so
widespread that almost all electrical and electronic devices such as washing machines and air conditioners have a small
embedded computer within them. Even the smartphones are connected to the Internet.
Learning computers is no longer meant only for students pursuing 4 career in engineering and technology, but is also
mandatory for students of other professions such as journalism, nursing, archacology, and construction and management.
Therefore, a basic knowledge of computers helps one to be more productive and self-sufficient.
Moreover, C is considered to be the mother of all moderm-day computer languages. Almost all popular cross-platform
programming languages and scripting languages, such as C++, Java, Python, Objective-C, Perl, Ruby, PHP, Lua, and
Bash, are implemented in C and borrow syntaxes and functions heavily from C. In the programming language popularity
website, C tops the list followed by C++ and Java.
Thus, knowledge of C provides a solid foundation to learn advanced programming skills such as object-oriented
programming, event-driven programming, multi-thread programming. real-time programming, embedded programming,
network programming, parallel programming, other programming languages, and new and emerging computing
paradigms such as grid-computing and cloud computing.
PEDAGOGICAL FEATURES
The following are the salient features of the book:
Comprehensive coverage Provides comprehensive coverage of important topics ranging from the basics of computers
to C programming and important data structures
Case studies Includes case studies at the end of select chapters on C, which provide practical orientation to the concepts
discussed in the respective chapters.
Complete program codes Contains plenty of program codes that are thoroughly tested and compiled to support the
text
Practical orientation Provides numerous solved examples and chapter-end exercises in the form of objective-type
questions, review exercises, and programming problems that enable the students to check their understanding of the
concepts
Glossary Includes a list of key terms at the end of each chapter that facilitates revision of important topics learned
Tips and Notes Includes programming tips that educate readers about common programming errors and how to avoid
them and notes that highlight important terms and concepts in between the text as sidebars for a quick recapitulation,
Chapter 1 To provide readers a perspective of how computers evolved over the last century, this chapter presents a
section on history of computers, which gives a timeline of the developments in computing technology. The section on
applications of computers covers new applications.
it Preface to the Second Edition
3 The section on secondary storage devices includes latest devices such as Blu-ray disks and external hard
disks, The chapter now also provides section on processor architecture, which focuses on the different components of a
processor, and types of processors.
Chapter 4 This chapter includes new examples to demonstrate the addition and subtraction of hexadecimal and octal
numbers. In addition, the chapter covers codes such as Unicode and 8421 and 2421 BCD codes. The sections on logic
gates and universal gates have been moved to Chapter 5.
Chapter 5 This is a new chapter, which focuses on logic gates that form the basic building blocks of a digital circuit,
and discuses Boolean algebra, which is used to express the output of any circuit implemented using logic gates.
Chapter 6 This chapter strengthens discussion on operating systems by briefly explaining the command interpretation
module of an operating system and CLI vs GUI interface. It discusses the features of Windows 8 and Windows 10 along
with mobile operating systems, In addition, it includes a section outlining the differences between customized and public
domain software.
Chapter 7 To familiarize readers with how applications communicate over a network, this chapter provides a brief
overview of two reference models—OSI! model and TCP/IP model. In addition, it discusses Internet-related concepts
such as IP address, URL, and domain name system (DNS).
Chapter 8 \n order to make the text more coherent, this chapter has been restructured to focus on the program designing
tools that aid in the development of efficient programs. The section on programming languages has been shifted to
chapter 6.
Chapter 9 This chapter includes an annexure, which shows the steps to compile and execute C programs on both Unix/
Linux and Ubuntu platforms,
Chapter 12 This chapter adds a program showing the array representation of sparse matrices. Similarly, it includes a
program to find whether a matrix is symmetric or not.
Chapter 14 \t includes a program to illustrate the dangling pointer problem.
Chapter 15 \t presents three different ways to find the size of a structure, All these different methods have been
exemplified through program codes.
ACKNOWLEDGEMENTS
1 would like to gratefully acknowledge the feedback and suggestions provided by various faculty members for the
improvement of the book. | am obliged to the editorial team at Oxford University Press India for alltheir support towards
revising this book. Suggestions for improving the presentation and contents can be sent to the publishers through their
website www.india.oup.com or to me at reemathareja@ gmail.com.
Reema Thareja
Preface to the First Edition
Computers are so widely used in our day-to-day lives that imagining a life without them has become almost impossible.
They are not only used by professionals but also by children for interactively learning lessons, playing games, and doing
their homework. Applications of the computer and its users are increasing by the day.
Learning computer fundamentals is a stepping stone to having an insight into how these machines work. Once the
reader is aware of the basic terminology that is commonly used in computer science, he/she can then go on to develop
useful computer programs that may help solve a user's problems.
Since computers cannot understand human languages, special programming languages are designed for this purpose.
C is one such programming language. Being the most popular programming language, it is used in several different
software platforms such as system software and application software. A few other programming languages such as C++
and JAVA are also based on C. Hence, mastering the C language is a prerequisite for learning such languages.
ACKNOWLEDGEMENTS
The writing of this textbook was a mammoth task for which a lot of help was required from many people. Fortunately, |
have had the fine support of my family, friends, and fellow members of the teaching staff at the Institute of Information
Technology and Management, Delhi.
My special thanks would always go to my father Shri Janak Raj Thareja, my mother Smt. Usha Thareja, my brother
Pallay, and sisters Kimi and Rashi who were a source of inspiration and divine blessings for me. | am especially thankful
to my son Goransh who has been very patient and cooperative in letting me realize my dreams, My sincere thanks go to
my uncle, Mr B.L. Theraja, for his inspiration and guidance in writing this book.
Finally, | would like to acknowledge the technical assistance provided to me by Ed. Udit Chopra, who helped me in
designing and testing the numerous program codes provided in the book.
Last but not least, my acknowledgements will remain incomplete if | do not thank the editorial team at Oxford
University Press, India, for supporting me wholeheartedly during the publication of my books over the past few years.
Reema Thareja
Brief Contents
Features of the Book iv
Companion Online Resources vi
Preface to the Second Edition vii
Preface to the First Edition x
Detailed Contents xii
12.12 Applications of Arrays 308 14,10 Difference Between Array Name and
Case Study 2: Chapter 12. 313 Pointer 360
14.11 Pointers and Strings 360
13 Strings 317 14.12 Arrays of Pointers 364
13.1 Introduction 3/7
14.13 Pointers and 2D Arrays 365
13.1.1 Reading Strings 318
14.14 Pointers and 3D Arrays 367
13.1.2 Writing Strings 319
14.15 Function Pointers 368
13.13 Summary of Functions Used to Read
14.15.1 Initializing a Function Pointer 368
and Write Characters 320
1415.2 Calling a Function Using a Function
13.2 Suppressing Input 32/
Pointer 368
13.2.1 Using a Scanset 321
14,15.3 Comparing Function Pointers 369
13.3 String Taxonomy 322
14.15.4 Passing a Function Pointeras an
13.4 Operations on Strings 322
Argument to a Function 369
13.4.1 Finding the Length of a
14.16 Array of Function Pointers 369
String 323
14.17 Pointers to Pointers 370
13.4.2 Converting Characters of a String into
14.18 Memory Allocation in C Programs 370
Upper Case 323
14.19 Memory Usage 370
13.4.3 Converting Characters of a String Into
14.20 Dynamic Memory Allocation 37/
Lower Case 324
14.20.1 Memory Allocations Process 371
13.4.4 Concatenating Two Strings to Form a
14.20.2 Allocating a Block of Memory 371
New String 324
14.20.3 Releasing the Used Space 372
13.4.5 Appending a String to Another
String 325
14.204 To Alter the Size ofAllocated
Memory 373
13.4.6 Comparing Two Strings 326
14.21 Drawbacks of Pointers 374
13.4.7 Reversing a String 325
Annexure 3 382
13.4.8 Extracting a Substring from
Left 327
Case Study 3: Chapters 13 and 14 384
13.4.9 Extracting a Substring from Right of 15 Structure, Union, and Enumerated
the String 328 Data Type 386
13.4.10 Extracting a Substring from the 15.1 Introduction 386
Middle of a String 328 15.1.1 Structure Declaration 386
13.4.11 Inserting a String in Another 15.1.2 Typedef Declarations 387
String 329 15.1.3 Initialization of Structures 388
13.4.12 Indexing 330 15.1.4 Accessing the Members ofa
13.4.13 Deleting a String from the Main Structure 388
String 330 15.1.5 Copying and Comparing
13.4.14 Replacing a Pattern with Another Structures 389
Pattern in a String 331 15.1.6 Finding the Size of a Structure 389
13.5 Miscellaneous String and Character 15.2 Nested Structures 392
Functions 33/ 15.3 Arrays of Structures 393
13.5.1 Character Manipulation 15.4 Structures and Functions 395
Functions 331 15.4.1 Passing Individual Members 395
13.5.2 String Manipulation Functions 332 15.4.2 Passing the Entire Structure 395
13.6 Arrays of Strings 337 15.4.3 Passing Structures Through
Pointers 398
M4 Pointers 347
15.5 Self-referential Structures 402
14.1 Understanding the Computer's
15.6 Unions 402
Memory 347
15.6.1 Declaring a Union 402
14.2 Introduction to Pointers 348
15.6.2 Accessing a Member of a
14.3 Declaring Pointer Variables 348
Union 403
14.4 Pointer Expressions and Pointer
15.6.3 Initializing Unions 403
Arithmetic 350
15.7 Arrays of Union Variables 404
14.5 Null Pointers 354
15.8 Unions Inside Structures 404
14.6 Generic Pointers 354
15.9 Structures Inside Unions 404
14.7 Passing Arguments to Function Using
15.10 Enumerated Data Type 405
Pointers 354
15.101 enum Variables 406
14.8 Pointers and Arrays 358
15.10.2 Using the Typedef Keyword 406
14.9 Passing an Array to a Function 359
Detailed Contents eit
1 Introduction to Computers
6 Computer Software
FA Computer Networks and the Internet
TAKEAWAYS
* Characteristicsof computers
* Digital computers
* Stored program concept
and say that the age of the student is 23 years, then the
COMPUTER outcome is information,
These days, computers have become a crucial part of
A computer, in simple terms, can be defined as an our everyday lives, and we need computers just like we
electronic device that is designed to accept data, perform need televisions, telephones, or other electronic devices at
the required mathematical and logical operations at high home. Computers are basically meant to solve problems
speed, and output the result, quickly and accurately, The important characteristics
We all have seen computers in our homes, schools, and of a computer (refer to Figure 1.1) are discussed in the
colleges. In fact, in today’s scenario, we find computers in following text.
most aspects of our duily lives. For some of us, it is hard to
even imagine a world without them,
In the past, computers were extremely large in size
and often required an entire room for installation. These
computers consumed enormous amounts of power and
were too expensive to be used for commercial applications.
Therefore, they were used only for limited tasks, such
as computing trajectories for astronomical or military
applications, However, with technological advancements,
the size of computers became smaller and their energy
requirements reduced immensely. This opened the way for
adoption of computers for commercial purposes.
These days, computers have become so prevalent in
the market that all interactive devices such as cellular
phones, global positioning system (GPS) units, portable
organizers, automated teller machines (ATMs), and gas
pumps, work with computers.
Figure 1.1 Characteristics of computers
id the incorrect data/program is responsible. This clearly computers also reduces manpower requirements and leads
means that the output generated by a computer depends on toan elegant and efficient way of performing various tasks.
the given instructions and input data, If the input data is Hence, computers save time, energy, and money, When
wrong, then the output will also be erroneous. In computer compared to other systems, computers can do more work
terminology, this is known as garbage-in, garbage-out in lesser time. For example, using the conventional postal
(GIGO). system to send an important document takes at least two to
three days, whereas the same information when sent using
Automation Besides being very fast and accurate, the Internet (e-mail) will be delivered instantaneously,
computers are automatable devices that can perform a
task without any user intervention. The user just needs to
assign the task to the computer, after which it automati- STORED PROGRAM CONCEPT
cally controls different devices attached to it and executes
the program instructions. All digital computers are based on the principle of stored
Diligence Unlike humans, computers never get tired of a program concept,which was introduced by Sir John von
repetitive task. It can continually work for hours without Neumann in the late 1940s. The following are the key
creating errors. Even if a large number of executions need characteristic features of this concept:
to be executed, each and every execution requires the same * Before any data is processed, instructions are read into
duration, and is executed with the same accuracy. memory.
Versatile Versatility is the quality of being flexible. Today, + Instructions are stored in the computer's memory for
execution.
computers are used in our daily life in different fields. For
* Instructions are stored in binary form (using binary
example, they are used as personal computers (PCs) for numbers—only Os and Is),
home use, for business-oriented tasks, weather forecasting,
+ Processing starts with the first instruction in the program,
space exploration, teaching, railways, banking, medicine,
which is copied into a control unit circuit. The control
and so on, indicating that computers can perform different unit executes the instructions.
tasks simultaneously. On the PC that you use at home,
you may play a game, compose and send e-mails, listen
+ Instructions written by the users are performed
sequentially until there is a break in the current flow.
to music, etc. Therefore, computers are versatile devices
as they can perform multiple tasks of different nature at * Input/Output and processing operations are performed
simultaneously, While data is being read/written, the
the same time.
central processing unit (CPU) executes another program
Memory Similar to humans, computers also have in the memory that is ready for execution,
memory. Just the way we cannot store everything in our
memory and need secondary media, such as a notebook,
to record certain important things, computers also have
internal or primary memory (storage space) as well as
external or secondary memory. While the internal memory
of computers is very expensive and limited in size, the
secondary storage is cheaper and of bigger capacity.
The computer stores a large amount of data and John W. Mauchly, an American physicist, and J.
programs in the secondary storage space. The stored Presper Eckert, an American engineer, further contributed
data and programs can be retrieved and used whenever to the stored program concept to make digital computers
required, Secondary memory is the key for data storage. much more flexible and powerful. As a result, engineers
Some examples of secondary devices include floppy disks, in England built the first stored-program computer,
optical disks (CDs and DVDs), hard disk drives (HDDs), Manchester Mark I, in the year 1949, They were shortly
and pen drives. followed by the Americans who designed EDVAC in the
When data and programs have to be used, they are very same year.
copied from the secondary memory into the internal Today, a CPU chip can handle billions of instructions
memory, often known as random access memory (RAM). per second. It executes instructions provided both the data
The concept of computer memory is discussed in detail in and instructions are valid. In case either one of them or
Chapter 3. both are not valid, the computer stops the processing of
instructions.
No 1Q Although the trend today is to make computers
intelligent by inducing artificial intelligence (AI) in them,
they still do not have any decision-making abilities of their
1.3.1 Types of Stored Program Computers
own. They need guidance to perform various tasks. A computer with a Von Neumann architecture stores data
Economical Today, computers are considered as short- and instructions in the same memory. There is a serial
term investments for achieving long-term gains. Using machine in which data and instructions are selected one
Introduction to Computers
®)
peaches address
Read/Write Data
Figure 1.2 Von Neumann architecture (a) Shared memory for instructions and data (b) Separate
memories for instructions and data
at a time. Data and instructions are transferred to and China. It was used by the Babylonians even in 300 BC and
from memory through a shared data bus. Since there is a is still in use today (in the Far East).
single bus to carry data and instructions, process execution
1822: English mathematician Charles Babbage designed
becomes slower.
a steam-driven calculating machine that could compute
Later Harvard University proposed a stored program
tables of numbers. Though the project failed as he could
concept in which there was a separate memory to store
not complete the construction of the engine, it laid the
data and instructions, Instructions are selected serially
foundation for the first computer.
from the instruction memory and executed in the processor.
When an instruction needs data, it is selected from the data 1890: Herman Hollerith, an American inventor, designed
memory, Since there are separate memories, execution a punched card system to calculate the 1880 census,
becomes faster, The system completed the task in three years saving the
US government $5 million. Later Herman established a
company that we today know as IBM.
HISTORY OF COMPUTERS 1936: British mathematician Alan Turing introduced
4 universal machine called the Turing machine capable
Early computers were designed not for entertainment but of computing anything that is computuble, The central
for solving number-crunching problems. These computers concept of the modern computer is based on this machine.
were punch-card based computers that took up entire rooms,
1941: John Vincent Atanasoff, a Bulgarian-American
‘Today, our smurtphones have much more computing power
physicist, and his graduate student, Clifford Berry, at lowa
than that was available in those early computers,
State College designed Atanasoff—Berry computer (ABC)
In this section, we will read about history ofcomputers
that could solve 29 equations simultaneously. It was the
way back from the invention of abacus and take a look at
first time a computer could store information in its main
the remarkable achievements in computing technology till
memory.
the current time,
1943-1944: John W. Mauchly and J. Presper Eckert
Timeline of Developments built the Electronic Numerical Integrator and Calculator
(ENIAC), which is considered as the grandfather of digital
300 BC: The abacus was an early aid for mathematical computers. It filled a 20 x 40 feet room and had 18,000
computations and was designed to aid human’s memory vacuum tubes.
while performing calculations. A skilled abacus operator
can add and subtract with the same speed asthat ofa person 1946: Mauchly and Presper designed the UNIVAC,
performing the same calculation using a hand calculator. which was the first commercial computer for business and
The invention of abacus is often wrongly attributed to government applications.
86 Computer Fundamentals and Programming in C
: William Shockley, John Bardeen, and Walter 1986: Compaq introduced Deskpro 386 in the market,
Brattain of Bell Laboratories invented the transistor. Soon which was a 32-bit architecture machine that provides
vacuum tubes in computers were replaced by transistors. speed comparable to mainframes.
1953: Grace Hopper developed the first computer 1990: Tim Berners-Lee invented World Wide Web with
language COBOL. HTML as its publishing language.
1954: The FORTRAN programming language was 1993: The Pentium microprocessor introduced the use of
developed. graphics and music on PCs.
1958: Jack Kilby of Texas Instruments and Robert 1994: PC games became popular.
Noyce at Fairchild Semiconductor Corporation separately
1996: Sergey Brin and Larry Page developed the Google
invented integrated circuit, which is commonly known as search engine at Stanford University.
the computer chip.
1999: The term Wi-Fi was introduced when users started
1964: Douglas Engelbart developed a prototype of the
connecting to the Internet without wires.
modern computer, with a mouse and a graphical user
interface (GUI). This was a remarkable achievement 2001: Apple introduced Mac OS X operating system,
as it shifted computers from a specialized machine for which had protected memory architecture and pre-emptive
scientists and mathematicians to general public. multi-tasking, among other benefits, To stay competitive,
1969: Unix operating system was developed at Bell Labs. Microsoft launched Windows XP.
It was written in the C programming language and was 2003: The first 64-bit processor, AMD's Athlon 64, was
designed to be portable across multiple platforms, Soon it brought into the consumer market,
became the operating system of choice among mainframes
at large companies and government entities. 2004: Mozilla released Firefox 1.0 and in the same year
Facebook, a social networking site, was launched.
1970: DRAM chip was introduced by Intel.
2005: YouTube, a video sharing service, was launched. In
1971: Alan Shugart with his team in IBM invented the same year, Google acquired Android, a Linux-based
the floppy disk which allowed data to be shared among mobile phone operating system.
computers.
2006: Apple introduced MacBook Pro, its first Intel-
1973: Robert Metcalfe, a research member at Xerox, based, dual-core mobile computer.
developed Ethernet for connecting multiple computers
and other hardware. 2007: Apple released iPhone, which brought many
computer functions in the smartphone.
1974-1977: Personal computers started =becoming
popular, 2009: Microsoft launched Windows 7 in which users
1975: Paul Allen and Bill Gates started writing software for could pin applications to the taskbar.
the Altair 8800 using the new BASIC language. On Apnil 4. 2010: Apple launched iPad, which revived the tablet
they both formed their own software company, Microsoft. computer segment.
1976: Steve Jobs and Steve Wozniak started Apple 2011: Google introduced Chromebook, a laptop that runs
Computers and developed Apple I, the first computer with on the Google Chrome operating system.
a single-circuit board.
2015: Apple released the Apple Watch. In the same year,
1977: Apple Il was launched that offered colour graphics Microsoft launched Windows 10.
and incorporated an audio cassette drive for storage.
After reading these interesting developments in
1978: WordStar, a word processor application, was computing technology, let us also understand the evolution
released by MicroPro International. of computers through different generations.
1979: VisiCalc. the first computerized spreadsheet
program for personal computers, was unveiled. First Generation (1942-1955)
1981: The first IBM personal computer was introduced Hardware Technology First generation computers were
that used Microsoft's MS-DOS operating system. The manufactured using thousands of vacuum tubes (see
term PC was popularized. Figure 1.3); a vacuum tube is a device made of fragile glass.
1983: The first laptop was introduced. Moreover, Apple Memory Electromagnetic relay was used as primary
introduced Lisa as the first personal computer with a GUI memory and punched cards were used to store data and
with drop-down menus and icons. instructions.
1985: Microsoft announced Windows as a new operating Software Programming was done in machine
system, or assembly language.
Introduction to Computers Cc
Used for Scientific applications * They consumed 1/10th the power consumed by
generation computers
Examples ENIAC, EDVAC, EDSAC, UNIVAC 1, IBM 701 * Bulky in size and required a complete room for its
Highlights installation
* They were the fastest calculating device of those times + Dissipated less heat than first generation computers but
still required air-conditioned rooms
* Computers were too bulky and required a complete
* Costly
room for storage
* Highly unreliable as vacuum tubes emitted a large * Difficult to use
amount of heat and burnt frequently
Required air-conditioned rooms for installation
Costly
Difficult to use
Required constant’ maintenance because vacuum
tubes used filaments that had limited life time. até
Therefore, these computers were prone to frequent
hardware failures
o*
Bulky in size and required a complete room for Highlights Faster, smaller, cheaper, powerful, reliable,
installation and easier to use than the previous generation computers
* Dissipated less heat than second generation computers
but still required air-conditioned rooms
* Costly
* Easier to use and upgrade
ts
on asingle
LSI circuits contained 30,000 componen chip
Memory Semiconductor memory is used as primary
and VLSI technology had about one million electronic memory: large capacity magnetic disks are used as built-in
componen ts
on asingle chip. secondary memory. Magnetic tapes and floppy disks were
used as portable storage devices, which have now been
Memory Semiconductor memory was used as primary replaced by optical disks and USB flash drives.
memory, large capacity magnetic disks were used as built-
Software Technology Programming is done in high-level
in secondary memory. Magnetic tapes and floppy disks
programming languages such as Java, Python, and C#
were used as portable storage devices Graphical User Interface (GUI)-based operating systems
Software Technology Programming was done in such as Windows, Unix, Linux, Ubuntu, and Apple Mac
high level programming language such as C and C++ are being used. These operating systems are more powerful
Graphical User Interface (GUI) based operating system and user friendly than the ones available in the previous
(c.g. Windows) was introduced. It had icons and menus generations.
among other features to allow computers to be used as Used for Scientific, commercial, interactive online,
a general purpose machine by all users. UNIX was also
multimedia (graphics, audio, video), and network applications
introduced as an open source operating system. Apple Mac
OS and MS DOS were also released during this period. All Examples 1BM_ notebooks, Pentium PCs, SUM
these operating systems had multi-processing and multi- workstations, IBM SP/2, Param supercomputer
programming capabilities, Highlights
Used for Scientific, commercial. interactive online, and * Faster, smaller, cheaper, powerful, reliable, and easier to
network applications use than the previous generation computers
Examples 1BM PC. Apple Il, TRS-80, VAX 9000, CRAY- * Speed of microprocessors and the size of memory are
1, CRAY-2, CRAY-X/MP growing rapidly
Introduction to Computers
ce
(0 )
* High-end features available on mainframe computers units, etc. Some examples of supercomputers are CRAY=Ty
in the fourth generation are now available on the CRAY-2, Control Data CYBER 205, and ETA A-10,
mucroprocessors
* They consume less power than computers of prior 1.5.2 Mainframe Computers
generations
* Air-conditioned rooms required for mainframes and Mainframe computers are large-scale computers (but
supercomputers but not for microprocessors smaller than supercomputers). These are very expensive and
need a very large clean room with air conditioning, thereby
making them very costly to deploy. As with supercomputers,
mainframes can also support multiple processors. For
example, the IBM $/390 mainframe can support 50,000
users at the same time. Users can access mainframes by
cither using terminals or via PCs. The two types of terminals
that can be used with mainframe systems are as follows:
Dumb Terminals
Dumb terminals consist of only a monitor and a keyboard
(or mouse). They do not have their own CPU and memory
Figure 1.7 ULSI chip and use the mainframe system's CPU and storage devices.
Intelligent Terminals
CLASSIFICATION OF COMPUTERS
In contrast to dumb terminals, intelligent terminals have
Computers can be broadly classified into four categories their own processor and thus can perform some processing
based on their speed, amount of data that they can process, operations. However, just like the dumb terminals, they do
and price (refer to Figure 1.8). These categories are as not have their own storage space. Usually, PCs are used
follows: as intelligent terminals to facilitate data access and other
+ Supercomputers services from the mainframe system.
+ Mainframe computers Mainframe computers are typically used as servers on
+ Minicomputers the World Wide Web. They are also used in organizations
* Microcomputers such as banks, airline companies, and universities. where
a large number of users frequently access the data stored
1.5.1 Supercomputers in their databases, IBM is the major manufacturer of
mainframe computers. Some examples of mainframe
Among the four categories, the supercomputer is the computers include IBM $/390, Control Data CYBER 176,
fastest, most powerful, and most expensive computer. and Amdah! 580.
Supercomputers were first developed in the 1980s to
process large amounts of data and to solve complex 1.5.3 Minicomputers
scientific problems, Supercomputers use parallel
processing technology and can perform more than one As the name suggests, minicomputers are smaller,
trillion calculations in a second. cheaper, and slower than mainframes. They are called
A single supercomputer can support thousands of users at minicomputers because they were the smallest computer
the same time, Such computers are mainly used for weather of their times. Also known as midrange computers, the
forecasting, nuclear energy research, aircraft design, capabilities of minicomputers fall between mainframe and
automotive design, online banking, controlling industrial personal computers.
Classification
of computers
are widely used in business, education, easily be carried from one place to another. They may also
hospitals, government organizations, ctc. While some be placed on the user's lap (thus the name). Hence, laptops
minicomputers can be used only by a single user, others are very useful, especially when going on long journeys.
are specifically designed to handle multiple users Laptops operate on a battery and do not always have to be
simultancously, Usually, single-user minicomputers are plugged in like desktop computers.
used for performing complex design tasks. ‘The memory and storage capacity of a laptop is almost
As with mainframes, minicomputers can also be used equivalent to that of a desktop computer. As with desktop
as servers in a networked environment, and hundreds of computers, laptops also have hard disk drives, USB drives,
PCs can be connected to it, etc, For input, laptops have a built-in keyboard and a
The first minicomputer was introduced by Digital trackball/touchpad, which is used as a pointing device (as
Equipment Corporation (DEC) in the mid-1960s, Other a mouse is used for a desktop PC).
manufacturers of minicomputers include IBM Corporation Today, laptops have the same features and processing
(AS/400 computers), Data General Corporation, and speed as the most powerful PCs. However, a drawback is
Prime Computer. that laptops are generally more expensive than desktop
computers. These computers are very popular among
1.5.4 Microcomputers business travellers.
The Intemet is a network of networks that stocks, finding a job, conducting an auction, marketing
connects computers all over the world. It gives the user and advertising products or services, and providing
access (0 an enormous amount of information, much more customer service. The following are techniques in which
than available in any library. Using e-mail, the user can e-commerce helps users to conduct business transactions.
communicate in seconds with a person who is located Business-to-consumer or B2C In this form of electronic
thousands of miles away. Chat software enables users commerce, business companies deploy their websites
to chat with another person in real-time (irrespective of on the Internet to sell their products and services to the
the physical location of that person), Video conferencing customers. On their websites, they provide features such
tools are becoming popular for conducting mectings with as cutalogues, interactive order processing system, secure
people who are unable to be present at a particular place. electronic payment system, and online customer support.
Digital video or audio composition Computers make
Business-to-business or B2B This type of electronic
audio or video composition and editing very simple. This
commerce involves business transactions performed
has drastically reduced the cost of equipment to compose between business partners (customers are not involved).
music or make a film. Graphics engineers use computers For example, companies use computers and networks (in
for developing short or full-length films and creating 3-D
the form of extranets) to order raw materials from their
models and special effects in science fiction and action
suppliers. Companies can also use extranets to supply
movies,
their products to their dealers.
Desktop publishing Desktop publishing software enables
Consumer-to-consumer or C2C This type of electronic
us to create page layouts for entire books.
commerce enables customers to carry business transactions
After discussing how computers are used in today’s among themselves. For example, on auction websites,
scenario, let us now have a look at the different areas a customer sells his/her product which is purchased by
where computers are being widely utilized. another customer.
special programs that compare the sequence of molecules Doctors sitting in hospitals can monitor their t
in DNA of a healthy person with that ofthe patient's. These sitting in their homes by using computer-based systems.
analyses help them to identify what is missing in a patient As soon as warning signs of serious illnesses are spotted,
and to determine drugs that can make the molecules in they alert the concerned doctor quickly.
DNA of the patient look similar to that of a healthy person.
For example, one of the drugs to treat AIDS was designed Geographic Information System and
using bioinformatics techniques.
Remote Sensing
Health care A geographic information system (GIS) is a computer-
based tool for mapping and analysing earth’s features.
Last few years have seen a massive growth of computers
It integrates database operations and statistical
and smartphone users. Like in our daily lives, computers
analysis to be used with maps. GIS manages location-
have also become 4 necessary device in the health care
based information and provides tools for display and
industry, The following are areas in which computers are
analysis of statistics such as population count, types of
extensively used in the health care industry.
vegetation, and economic development opportunities.
Storing records To begin with, computers are first and Such type of information helps to predict outcomes and
foremost used to store the medical records of patients. plan strategies.
Earlier, patient records were kept on paper, with separate Remote sensing is the science of taking measurements
records dealing with different medical issues from separate of the earth using sensors. on airplanes or satellites. These
healthcare organizations. With time, the number of sensors collect data in the form of images, which are then
prescriptions, medical reports, etc., grow in volume making analysed to derive useful information.
it difficult to maintain and analyse. Use of computers to The key feature of remote sensing is that it acquires
store patient records has been a game-changer in terms of information about an object without making physical
improving the efficiency and accuracy of the entire process. contact with it, Remote sensing is a sub-field of geography,
Now, the entire medical history of patients is easily which can be applied in the following areas to collect data
accessible, Since the records are electronically stored, they of dangerous or inaccessible areas for the following:
can be easily shared between different doctors (in same
* Monitoring deforestation in areas like the Amazon
or different healthcare organizations) who are treating
Basin
the same patient. Besides saving paper and enhancing * Studying features of glaciers in Arctic and Antarctic
efficiency, use of computers also saves patients’ money by regions
reducing duplication of tests and procedures.
Analysing the depth of coastal and ocean areas
Surgical procedures Computers are used for certain Studying land usage in agriculture
surgical procedures. They enable the surgeon to use Examining the health of indigenous plants and crops
computer to control and move surgical instruments in Determining the prospect for minerals
the patient's body for a variety of surgical procedures. In CUS
ewLocating and measuring intensity of earthquakes (after
such surgeries, a small incision is made, and then a small they had occurred) by comparing the relative intensity
surgical tool with an attached camera is placed inside the and precise timings of seismograms collected from
patient's body. This reduces the riskofcomplications from different locations
a larger surgical wound, and minimizes damage done to
the patient's body. In such a scenario, computers are not Meteorology
only used to drive the tools but also used to relay images
from inside the patient's body out to the doctors. Metcorology is the study of the atmosphere, This branch of
Computers also help to determine the cause of an science observes variables of Earth’s atmosphere such as
affliction or illness. For example, computers can combine temperature, air pressure, water vapour, and the gradients
ultrasonography and imaging in fields like cardiology to and interactions of each variable, and how they change
check the functionality of the heart. In case of a serious over time, Meteorology has applications in many diverse
ailment, the causes can be detected in less time and fields such as the military, energy production, transport,
treatment can be started at the earliest thereby saving a agriculture, and construction. Some of the applications
numberof lives. include the following:
Today, tablets and computers are being used in surgical Weather forecasting It includes application of science
consultations and videoconferencing between doctors. and technology to predict the state of the atmosphere
Better diagnosis and treatment Computers help (temperature, precipitation, etc.) for a future time and a
physicians make better diagnoses and recommend given location, Weather forecasting is done by collecting
treatments. Moreover, computers can be used to compare quantitative data about the current state of the atmosphere
expected results with actual results in order to help and analysing the atmospheric processes to project how
physicians make better decisions. the atmosphere will evolve.
{4 Computer Fundamentals and Programming in C
forecasts are especially made to generate explanation. However, they find it interesting to learn
warnings regarding heavy rainfall, snowfall, etc. They are through interacting with an animation of the algorithm
also important to agriculturists and also to commodity
traders within stock markets, Temperature forecasts
are used by utility companies to estimate demand over
coming days. Edutainment
isthecombination ofeducation with
entertainment.
Aviation meteorology Aviation meteorology studies the
impact of weather on air traffic management. It helps Legal System
cabin crews to understand the implications of weather on
their flight plan as well as their aircraft, Computers are used by lawyers to shorten the time required
to conduct legal precedent and case research. Lawyers use
Agricultural meteorology Agricultural meteorology computers to look through millions of individual cases and
deals with the study of effects of weather and climate on tind whether similar or parallel cases have been approved,
plant distribution, crop yield, water-use efficiency, plant denied, criticized, or overruled in the past. This enables
and animal development. the lawyers to formulate strategies based on past case
Nuclear meteorology Nuclear meteorology studies decisions. Moreover. computers are also used to keep
the distribution of radioactive aerosols and gases in the track of appointments and prepare legal documents and
atmosphere. briefs in time for filling cases,
Astronauts are trained using computer-simulated problems humans cannot work, For example, in high t
that could be encountered during launch, in space, or upon high pressure conditions or in processes that demand very
return to earth. high levels of accuracy. The main distinguishing feature
between a robot and other automated machines is that @
Astronomy robot can be programmed to carry out a complex task and
then reprogrammed to carry out another complex tasks.
Spacecrafts are usually monitored using computers that
not only keep a continuous record of the voyage and Decision Support Systems
of the speed, direction, fuel, and temperature, but also
suggest corrective action if the vehicle makes a mistake. Computers help managers to analyse their organization's
The remote stations on the carth compare all these data to understand the present scenario of their business,
quantities with the desired values, and in case these values view the trends in the market, and predict the future of their
need to be modified to enhance the performance of the products. Managers also use decision support systems to
spacecraft, signals are immediately sent that set in motion analyse market research data, to size up the competition,
the mechanics to rectify the situation. With the help of and to plan effective strategies for penetrating their
computers, all this is done within a fraction of a second. markets.
A computer is a powerful teaching aid and can act as Expert systems are used to automate the decision-making
another teacher in theclassroom, Teachers use computers to process in a specific area, such as analysing the credit
develop instructional material. Teachers may use pictures, histories for loan approval and diagnosing a patient's
graphs, and graphical presentations to casily illustrate condition for prescribing an appropriate treatment. Expert
an otherwise difficult concept. Moreover, teachers at all systems analyse the available data in depth to recommend
levels can use computers to administer assignments and a course of action. A medical expert system might provide
keep track of grades. Students can also give exams online
the most likely diagnosis of patient's condition.
and get instant results. To create an expert system, an extensive amount of
human expertise in a specific area is collected and stored
in a database, also known as a knowledge base. A software
Industry and Engineering
called an interface engine analyses the data available
Computers are found in all kinds of industries, such in the knowledge base and selects the most appropriate
as thermal power plants, oil refineries, and chemical response.
industries, for process control, computer-aided designing Adding more to it, in today’s scenario, computers are
(CAD), and computer-aided manufacturing (CAM). used to find jobs on the Internet, read news and articles
Computerized process control (with or without human online, find your batchmates, send and receive greetings
intervention) is used to enhance efficiency in applications pertaining to different occasions, etc.
such as production of various chemical products, oil
refining, paper manufacture, and rolling and cutting steel
to customer requirements. BASIC ORGANIZATION OF
In CAD, computers and graphics-oriented software are
integrated for automating the design and drafting process.
A COMPUTER
It helps an engincer to design a 3D machine part, analyse
A computer is an electronic device that performs five
its characteristics, and then subject it to simulated stresses. major operations:
In case a part fails the stress test, its specifications can be
modified on the computer and retested. The final design * Accepting data or instructions (input)
specifications are released for production only when the * Storing data
engineer is satisfied that the part meets strength and other * Processing data
quality considerations. * Displaying results (output)
The CAM phase begins when the CAD phase is * Controlling and coordinating all operations inside a
complete. In this phase, the metal or other materials are computer
manufactured while complying with their specifications. In this section, we will discuss all these functions and
For this computer controlled manufacturing, tools are used see how one unit of a computer interacts with another to
to produce high quality products. perform these operations. Refer to Figure 1.11, which
shows the interaction between the different units of a
Robotics computer system.
Robots are computer-controlled machines mainly used in Input This is the process of entering data and instructions
the manufacturing process in extreme conditions where (also known as programs) into the computer system, The
{(16 } Computer Fundamentals and Programming in C
Data and
é; R Input Storage Output Results
cru
Control unit
'
aga Flow of data and instructions
— Control exercised by control unit
data and instructions can be entered by using different only in binary form and the result of processing is also in
input devices such as keyboard, mouse, scanner, and binary form, the result cannot be directly given to the user.
trackball. Note that computers understand binary language, The output devices, therefore, convert the results available
which consists of only two symbols (0 and 1), so it is the in binary codes into a human-readable language before
responsibility of the input devices to convert the input data displaying it to the user.
into binary codes. Control The control unit (CU) is the central nervous
Storage Storage is the process of saving data and system of the entire computer system. It manages and
instructions permanently in the computer so that they can controls all the components of the computer system. It
be used for processing, The computer storage space not is the CU that decides the manner in which instructions
only stores the data and programs that operate on that data will be executed and operations performed. It takes care
but also stores the intermediate results and the final results of the step-by-step processing of all operations that are
of processing, performed in the computer.
A computer has two types of storage areas: Note that the CPU is a combination of the arithmetic
logic unit (ALU) and the CU. The CPU is better known
Primary storage Primary storage, also known as the main as the brain of the computer system because the entire
memory, is the storage area that is directly accessible by processing of data is done in the ALU, and the CU activates
the CPU at very high speeds. It isused to store the data and and monitors the operations of other units (such as input,
purts of programs, the intermediate results of processing, output, and storage) of the computer system.
and the recently generated results of jobs that are currently
being worked on by the computer. Primary storage space Processing The process of performing operations on the
is very expensive and therefore limited in capacity. data as per the instructions specified by the user (program)
Another drawback of main memory is that it is volatile is called processing. Data and instructions are taken from
in nature; that is, as soon as the computer is switched off, the primary memory and transferred to the ALU, which
the information stored gets erased. Hence, it cannot be performs all sorts of calculations. The intermediate results
used as a permanent storage of useful data and programs of processing may be stored in the main memory, as they
for future use. An example of primary storage is random might be required again. When the processing completes,
access memory (RAM). the final result is then transferred to the main memory.
Hence, the data may move from main memory to the ALU
Secondary storage Also known as auxiliary memory, multiple times before the processing is over.
this memory is just the opposite of primary memory, It
overcomes all the drawbacks of the primary storage area.
It is cheaper, non-volatile, and used to permanently store
data and programs of those jobs thal are not being currently
executed by the CPU. Secondary memory supplements
the limited storage capacity of the primary memory. An
example is the magnetic disk used to store data, such as C
and D drives, for future use. LAB SESSION—INSIDE THE
Output Output is the process of giving the result of data COMPUTER
processing to the outside world (external to the computer
system). The results are given through output devices such As a part ofthis chapter, the instructor must show the parts
as monitor, and printer. Since the computer accepts data of the computer to the students, as illustrated inFigure 1.12.
PS/2 Keyboard USK Serial! Serial? Graphics Secondary ethernet Sound card
The following are some of the major parts of the These days, many computers come with a built-in sound
computer: chip, which makes it unnecessary to buy a separate card
unless a higher quality of sound is needed,
CPU The CPU is the brain of the computer. It performs
all calculations and controls the devices connected to Modem A modem (modulator-demodulator) is a device
the computer system. The faster the CPU, the quicker that enables the computer to use a telephone line to
programs can process the instructions. communicate and connect to the Internet,
RAM A fast CPU is of no use if the computer does not Network card A network card is used to connect the
have sufficient RAM. As discussed earlier, RAM is the computer cither to other computers or to the Internet (in
computer's memory which stores information used by case you are using a fast Internet connection such as cable
applications that are currently being executed by the or DSL).
CPU. More memory means more applications can be
Fans There are one or more fans inside the computer to
executed at the same time without degrading the system's
performance. keep the air moving and the computer cool.
Hard disk drive (HDD) The HDD of the computer is Cables There are multiple wires inside the computer
the secondary memory of the computer system where that are flat, ribbon-like cables. They are used to provide
information is stored permanently. All types of data, power and communication to the various parts inside the
computer.
documents, and programs are stored on the hard disk.
The larger the hard disk, the more the amount of data that
can be stored on the drive. Though the size of the HDD
does not affect the speed of execution of the program, it MOTHERBOARD
does affect the speed at which the user can access his/
her files. The motherboard, also known as the mainboard or the
parent board (refer Figure 1.13), is the primary component
Video card The video card is a board that plugs into
of a computer. It is used to connect all the components
the motherboard of the computer and generates images
of the computer. The motherboard is a printed circuit that
for display. Many video cards these days have their own
has connectors for expansion cards, memory modules, the
RAM and processor to enhance the speed of the graphics
processor, etc.
display, Many computers come with an in-built video chip.
In such a computer, a separate video card is used only if
the computer has to be used for high-end multimedia work 1.9.1 Characteristics of a Motherboard
or to play video games, A motherboard can be classified depending on the
Soundcard As with video cards, sound cards are expansion following characteristics:
boards that are used to enable a computer to manipulate * Form factor
sound. For example, sound cards allow the users to plug in * Chipset
speakers and a microphone. Some sound cards also provide * Type of processor socket used
the jacks for hooking your computer up to a common stereo. * Input-Output connectors
18 Computer Fundamentals and Programming in C
Input-Output connectors
Jumpers Disk drive and floppy drive connectors Case fan power supply
connector
Form factor Form factor refers to the motherboard's of the computer (such as the processor and memory). In
geometry, dimensions, arrangement, and clectrical order to enhance the computer's upgradeability, one must
requirements. The industry has defined a few standards choose a motherboard that has the latest chipset integrated
for the form factors, so that they can be used in different in it, Some chipsets may include a graphics or audio chip,
brands of cases, which makes it unnecessary to install a separate graphics
card or sound card. However, in case you need very high
Integrated components Some of the motherboard’s
components are integrated into its printed circuitry. These quality of audio and visual capabilities, then you must
include the following: disable the graphics/audio chip in the BIOS setup and
install high-quality expansion cards in the appropriate slots.
* The chipset is a circuit that controls the majority of the
computer's resources such as the bus interface with the CMOS clock and battery The real-time clock (or RTC)
processor, cache memory, RAM, and expansion cards. is 4 circuit that is used to synchronize the computer's
* CMOS clock and battery signals. When the computer is switched off, the power
+ BIOS supply stops providing electricity to the motherboard.
* System bus and expansion bus You must have observed that when we turn on the system,
it always displays the correct time. This is because an
In addition to these, the latest motherboards also have
electronic circuit, called the complementary metal-
a number of onboard multimedia and networking devices oxide semiconductor (CMOS) chip, saves some system
(which can be disabled), such as integrated network
information, such as the time, date, and other essential
card, integrated graphics card, integrated sound card, and system settings,
upgraded hard drive controllers.
The CMOS chip is powered by a battery located on the
Chipset The chipset is an electronic circuit that basically motherboard. Information on the hardware installed in the
coordinates data transfers between the different components computer (such as the number of tracks or sectors on cach
Introduction to Computers
USB VGA
hard drive) is stored in the CMOS chip. Since the CMOS it and to improve the heat transfer. The fan vents hot air
chip is quite slow, some systems prefer to copy the CMOS from the case and lets fresh air come in from outside.
chip's content into the RAM, which is a comparatively RAM connectors RAM is the primary storage area that
faster storage. This process of copying data into RAM is stores data while the computer is running. However, its
better known as memory shadow. contents are erased when the computer is turned off or
Have you noticed that, at times, the system time gets restarted, While the hard disk can store data permanently,
reset automatically, or the clock runs late’? This indicates we still need RAM because it is extremely fast when
that you need to change the battery. compared to mass storage devices such as hard drives.
BIOS The basic inpuV/output system (BIOS) is an interface Therefore, the fast processor accesses data from RAM
between the operating system and the motherboard. and not from the hard disk. The data is transferred from
The BIOS is stored in the read-only memory (ROM), the hard disk to the RAM, from where it is used by the
which cannot be rewritten. The BIOS uses data stored processor. RAM is available in the form of modules that
in the CMOS chip to know about the system's hardware plug into motherboard connectors.
configuration, Expansion slots Expansion slots are compartments into
‘To configure the BIOS, the user can use an interface which expansion cards can be inserted. Such curds render
known as B/OS setup. which can be accessed when the new features or enhance the computer's performance. For
computer is booting. To enter BIOS setup, the user must example, the AGP slot (also known as Accelerated Graphic
press the DEL key. Fl and F2 keys can also be used. Port) is a fast port used for graphics cards,
Processor socket The processor (also called the micro- 1/0 connectors The motherboard has a number of input~
processor) is the brain of the computer, The processor is output sockets (Figure 1.14) on its rear panel, some of
characterized by its speed or frequency, which is the rate at which include:
which it executes instructions. For example, an 800-MHz
* A serial port to connect some old peripherals
processor can perform 800 million operations per second.
A parallel port to connect old printers
The slot on the motherboard into which the processor is
USB ports to connect more recent peripherals such as
inserted is called the processor socket or slot. Irrespective mouse and pen drive.
of whether you use a slot or a socket, you must gently
RJ45 connector (also known as LAN or Ethernet port)
insert the processor, so that none of its pins are bent (it has
to connect the computer to a network. It corresponds to
hundreds of them). Usually, a concept called zero insertion
a network card integrated into the motherboard.
force (ZIP) is used. The ZIF sockets allow the processor to
Video graphics array (VGA) connector fo connect &
be inserted very gently and casily.
monitor. This connector interfaces with the built-in
When the computer is on, the processor is working
graphics card.
and it releases heat, which must be dissipated to keep the
Audio plugs that include the line in, line out, and
circuits from melting. Therefore, the processor is generally
microphone to connect sound speakers, hi-fi system, or
mounted on a cooler that is made of metal (such as copper microphone, This connector interfaces with the built-in
or aluminum), which conducts heat well. In addition to the
sound card.
cooler, there is also a fan to improve air circulation around
POINTS TO REMEMBER
* Modern are based y
computers-da of
on the principle
. A computer is anelectronic machine that accepts data
the stored program concept, which was introduced by
and instructions and performs computations on the
data based on those instructions. Sir John von Neumann in the late 1940s.
. Computers are used in allinteractive devices, such as * The speed of the computer is usually given in
nanoseco and picoseco
nds nds.
cellular telephones, GPS units, portable organizers,
ATM s,
and gas pumps.
G) Computer Fundamentals and Programming in C
© The term computer generation refers to the different of integrated circuits built
computers, with thousands
advancements of new computer technology. With on to a single silicon chip.
each new generation of computers, the circuitry has © Fifth-generation computers are manufactured using
become smaller and more advanced than that in its integrated chips (ICs) built with ultra-large scale
previous generation, integration (ULSI) technology.
© First-generation computers used a very large number © The CPU is a combination of the ALU and the CU. The
of vacuum tubes for circuitry and magnetic drums for CPU is known as the brain of the computer system.
memory. * The CU is the central nervous system of the entire
* Second-generation computers were manufactured computer system. It manages and controls all the
using transistors rather than vacuum tubes. components of the computer system.
* The development of the integrated circuit was the * The motherboard, also known as the mainboard or
hallmark of the third generation ofcomputers. the parent board, is the primary component of a
¢ The microprocessor started the fourth generation of computer.
| GLOSSARY
Tee "Kcomputer is an electronic machine thattakes computers all over the world.
instructions and performs computations based on those Memory shadow The process ofcopying data from CMOS
instructions. into RAM.
Expert systems Expert systems arecustom-written computer Program Aset of instructions executed by the computer.
programs that are ‘expert’ ina particular problem area, and Robotics Computers programmed to look, listen, and
embody a human expert’s knowledge, experience, and react to other sensory stimuli.
problem-solving strategies. They are being used in many Semiconductor devices Semiconductor devices are
areas such as medicine, chemistry, geology, meteorology, and electronic components that make use of the electronic
computer systems. properties of semiconductor materials (such as silicon
Garbage-in, garbage-out |f input data is wrong, then the and germanium). The conductivity of such devices can be
output will also be erroneous. controlled by introducing an electric field, by exposure to
making such
GUI A GUI is a type of user interface that enables users to light, and even pressure and heat, thereby
Interact with programs in more ways than typing. A GUI! devices excellent sensors.
offers graphical icons and visual indicators to display the Storage The process of saving data and instructions
Information and actions available toa user. The actions are permanently in the computer so that it can be used for
performed by direct manipulation ofthe graphical elements. processing.
Input The process of entering data and instructions into Stylus Astylus isan electronic pen that looks like a small
the computer system. ballpoint pen.
Integrated circuit Also called a chip or microchip, an IC Transistor A transistor is a semiconductor device that is
is a semiconductor wafer on which thousa millions used to amplify and switch electronic signals. Although
ornds
of tiny resistors, capacitors, and transistors are fabricated. some transistors are packaged individually, others are
it can be used as an amplifier, oscillator, timer, counter, usually found embedded in ICs.
computer memory, or microprocessor. Vacuum tube A vacuum tube is a device used to amplify
InternetIt is a network of networks that connects electronic signals.
EXERCISES
Fill in the Blanks 4. The speed of computers is expressed in or
1, Aprogram is the
based on 5. Raw facts or figures are called
2. Computers operate on
calculations in a second.
6. is an example of primary memory.
3. Computers can perform
and______ are examples offirst-generation 6. The brain of the computer is the
computing devices. (a) control unit (b) ALU
. Second-generation computers were first developed for {e) CPU (d) All of these
the industry.
3 packages allow easy manipulation and analysis State True or False
of data organized in rows and columns.
1. Computers work on the GIGO concept.
|. CRAY-1, CRAY-2, Control Data CYBER 205, and ETA A-10
are -
2. Lnanosecond = 1x10"™ seconds,
3. Floppy disks and hard disks are examples of primary
enables the computer to use a telephone line memory.
to communicate
and connect to the Internet.
4. First-generation computers used a very large number of
connector is used to connect a monitor. transistors.
hs concept was introduced by Sir John von
5. First-generation computers could be programmed only
Neumann
in the late 1940s.
in binary language.
. Android Jellybean, Windows, and iOS are all examples of
ALGOL is used in the third generation of computers,
popular operating systems used in and
. Fifth-generation computers are based on Al.
f is an interface between the operating system Network computers have more processing power,
memory, and storage than a desktop computer.
and the motherboard.
. RAM stores the data and parts of program, the
Multiple-choice Questions intermediate results of processing, and the recently
generated resultsofjobs that are currently being worked
1, Which was the first commercial computer delivered to a
on by the computer.
business client?
10. Aserial port is used to connect old printers,
(a) UNIVAC (b) ENIAC
{c) EDSAC (d) Noneof these Review Questions
. Which technology was used to manufacture second- 1. Define a computer.
generation computers? 2. Differentiate between data and Information,
(a) Vacuum tubes (b) Transistors 3. Differentiate between primary memory and secondary
(c) ICs {d) None of these memory.
. Time sharing operating systems were used in which 4. Write a short note on the characteristics of a computer.
generationof computers? 5. Computers work on the garbage-in, garbage-out
(a) First {b) Second concept. Comment.
(c) Third (d) Fourth 6. Explain the evolution of computers. Further, state how
. Choose the computer languages that are specially computers in one generation are better than their
designed for the fifth generationofcomputers. predecessors.
. Broadly classify computers based on their speed, the
(a) ALGOL ({b) SNOBOL amount ofdata that they can hold, and price.
(c) Lise {d) Prolog Discuss the variants of microcomputers that are widely
. Web TV is an exampleof used today,
(a) supercomputer {b) minicomputer . Explain the areas in which computers are being applied
(c) network Computer (d) laptop to carry out routine and highly-specialized tasks,
put and Output Devices
and the
an inverted T-type fashion between the typing
r on the
INPUT DEVICES numeric keys, and are used to move the curso
addit ion to the arrow keys,
screen in small increments. In
keys) , such as:
An input device is used to feed data and instr
uctions into there are other cursor keys (or navigational
uter
‘a computer, In the absence of an input device, a comp + Home and End to move the cursor to the begin
ning and
on,
would have only been a display device, In this secti end of the current line, respectively
es,
we will read about some of the widely used input devic * Page Up and Page Down to move the curso
r up and
into diffe rent group s. ly.
Figure 2.1 categorizes input devices down by one screen at a time, respective
existing
+ Insert to enter a character between two
2.1.1 Keyboard characters
ion
ters. + Delete to delete a character at the cursor posit
The keyboard is the main input device for compu
Computer keyboards look very similar to the keybo ards Other common control keys on the keyboard include
Print Screen,
of typewriters, with some additional keys, as show n in Control (Ctrl), Alternate (Alt), Exeape (Esc),
Windows
Figure 2.2. Pause, the Windows or Start key (Microsoft
s
Using a keyboard, the user can type & document, use logo), and a shortcut key. The shortcut key is used to acces
right mous e butto n.
keystroke shortcuts, access menus, play games
, and the options available by pressing the
perform numerous other tasks. Most keybo ards have The Esc key cancels the selected option, and the Pause
between 80 and 110 keys, which include the following: key suspends a command/process in progress. Finally, the
n as an
bet. Print Screen key captures everything on the scree
Typing keys These include the letters of the alpha image. The image can be pasted into any docu ment .
RTY for
The layout of the keyboard is known as QWE
its first six letters. The QWERTY pattern has been a
were
standard right from the time computer keyboards
introduced.
Numeric keys These include a set of keys, arranged in the
data
same configuration found on calculators to speed up
entry of numbers. When the Num Lock key is set to ON,
~,
the user can type numbers, dot, or input the symbols /, *,
and +. When the Num Lock key is set to OFF, the numer ic
Inside the Keyboard
keys can be used to move the cursor on the screen,
Function keys These are used by applications and A keyboard is like a miniature computer that has its own
operating systems to input specific commands, They processor and circuitry to carry information to and from
are often placed on the top of the keyboard in a single that processor. The circuitry has a key matrix, which is
row. Function keys can be programmed so that their a grid of circuits underneath the keys. Each circuit is
functionality varies from one program to another, broken at a point below each key. When a key is pressed,
it corresponds to pressing a switch, thereby completing
Control keys These are used to handle control of the
the circuit,
cursor and the screen. Four arrow keys are arranged in
Input and Output Devices Gs
Input devices
OMR
MICR
Mouse
The mouse is an input device that was invented by Douglas
Engelbart in 1963. It is the key input device used in a
graphical user interface (GUI). It can be used to handle the
Figure 2.2 Keyboard pointer easily on the screen to perform various functions
such as opening a program or file. With the mouse, the users
Source: digital art/FreeDigitalPhotos.net
no longer need to memorize commands, which was earlier
a necessity when working with text-based command line
environments like MS-DOS. A mouse is shown in Figure 2.3,
Barcode Reader
A barcode reader (also price scanner or POS scanner) is
a handheld input device that is used to capture and read
information stored in a barcode. It consists of a scanner,
a decoder, and a cable used to connect the reader to a
computer, The function of the barcode reader is to capture
and translate the barcode into numerals and/or letters. It
is connected to a computer for further processing of the
captured information, This connection is achieved through
a serial port, keyboard port, or an interface device called
awedge. Figure 2.10 Flatbed image scanner
Abarcode reader works by directing a beamof light across Source: Mile Atanasov/Shutterstock
the barcode and measuring the amount of light reflected
back. The dark bars reflect less light when compared to the Some scanners can be connected to the computer using
amount of light reflected by the white spaces between those a small computer system interface (SCSI). Some major
bars. The scanner converts this light energy into electrical manufacturers of scanners are Epson, Hewlett-Packard,
energy, The decoder then converts these signals into data Microtek, and Relisys, The basic types of image scanners
and sends it to the computer for processing. are flatbed, hand, film, and drum scanners.
These days, barcode readers are widely used in The scanners that we see in our colleges or offices are
following areas: flatbed scanners. In this type, the object to be scanned is
placed on a glass pane and an opaque cover is lowered over
* Generate bills in supermarkets and retail stores
it. A sensor and light move along the pane, reflecting off
* Take stock of inventory in retail stores
the image placed on the glass. The cover is used to prevent
* Check out books from a library other light from interfering, and the image becomes visible
* Track manufacturing and shipping movement
to the detector.
* Keep track of employee login
A hand image scanner has to be manually moved across
* Identify hospital patients the object or image to be scanned. The scanner produces
* Tabulate the results of direct mail marketing returns
light from green light emitting diodes (LEDs), which
* Tag honeybees used in research
highlight and scan the image onto a computer for further
Advantages processing. However, these days, 3D image scanners have
* Barcode readers are inexpensive. become the most popular form of hand scanners, as they
* They are portable. are able to compensate for jerky hand movements during
* They are handy and easy to use. scanning.
Input and Output Devices @
Film scanners are usually used in photography and In OCR processing, the analysis of the scanned i
slides. The slide or negative film is first inserted in strips is done to detect light and dark areas so as to identify each
of six or less frames into the film scanner, and then moved letter or numeral. When a character is recognized, it is
across a lens and sensor to capture the image. converted into an ASCII code.
While handheld and film scanners use charge coupled OCR has facilitated users to store text documents as
device (CCD) arrays, drum scanners. on the other hand, text files (rather than as images, as in case of scanners).
use photo multiplier tubes. Drum scanners are mounted Hence, the text files occupy much less storage space and
on an acrylic cylinder that rotates while passing the object can be easily edited. These days, OCR is widely used in
in front of precision optics, which in tum transfers the the following areas:
image information to the photo multiplier tubes, Most * Digitize and preserve documents in libraries
drum scanners use three matched PMTs that are capable * Process checks and credit card slips
of detecting red, blue, and green light. The light of the + Sort letters for speeding up mail delivery
object being scanned is separated into red, blue, and green Letus takeareal-world example to understand the power
beams. Drum scanners are very expensive and are often
of OCR. The police department usually has all the criminal
used for high-end applications of film.
records stored in large file cabinets. Seanning millions of
Advantages pages to find a particular record is not only tedious and
* Any printed or handwritten document can be scanned error-prone but also an expensive process. However, if
and stored in a computer for further processing. OCR is used to convert the pages into computer-readable
* The scanned and stored document will never deteriorate text, the police can casily search through the entire
in quality with time. The document can be displayed history in a few seconds. OCR technology can be easily
and printed whenever required. understood from Figure 2.11.
* There is no fear of loss of documents. The user can scan Advantages
important documents and store them permanently in the + Printed documents can be converted into text files.
computer. + Advanced OCR can recognize handwritten text and
Disadvantages convert it into computer-readable text files.
* Scanners are usually costlier than other input devices. Disadvantages
* The documents that are scanned and stored as images + OCR cannot recognize all types of fonts.
have a higher size as compared to other equivalent text
+ Documents that are poorly typed or have strikeover
files. cannot be recognized.
* Text documents are scanned and stored as images. + Very old documents when passed through OCR may not
Therefore, they occupy more space and are also convert into anexact copy of the text file. This is because
uneditable because computers cannot interpret
some characters may not have been recognized properly.
individual characters and numbers in the image.
In such cases, the user has to manually edit the file.
Optical Character Recognition (OCR) Device Optical Mark Recognition (OMR) Device
Optical character recognition is the process of converting Optical mark recognition is the process of electronically
printed materials into text or word processing files that can extracting data from marked fields, such as checkboxes
be easily edited and stored. The steps involved in OCR and fill-in fields, on printed forms. The optical mark reader,
include: as shown in Figure 2.12, is fed with an OMR sheet that has
* Scanning the text character by character pen or pencil marks in pre-defined positions to indicate
+ Analysing the scanned image to translate the character each selected response (¢.g., answers for multiple-choice
images into character codes (¢.g., ASCII) questions in an entrance examination).
Printed
documents:
Magnetic
ink character recognition
Video input devices are used to capture video from the
outside world into the computer. Here, the term video
Figure 2.13 A cheque containing magnetic ink characters means moving picture along with sound (as in television).
printed on it As we have sound cards to convert analog audio signals
= W
Input and Output Devices (9 i
a Sound card
4 Speakers
The user speaks in The sound card converts analog ‘The sound card converts digital data stored
the microphone signals into digital data sothat itcan in the computer into analog signals and
be stored in thecomputer sends ittothe speakers sothat users may
hearthe sound
into digital data and vice versa, we also have video cards * They can be used to record memorable moments in
to convert analog video signals to digital data fo store it one’s life.
in the computer (and vice versa). Digital camera and web * They can also be used for security purposes,
camera are popular examples of video input devices.
Disadvantages
A digital camera as shown in Figure 2.15(a) is a * Audio input devices are not effective in noisy places,
handheld and easily portable device used to capture + With audio input devices, it is difficult to clearly
images or videos. The digital camera digitizes image or distinguish between two similar sounding words such
video (converts them into Is and 0s) and stores them on
as ‘sea’ and ‘see’.
a memory card. The data can then be transferred to the * Videos and images captured using video input devices
computer using a cable that connects the computer to the have very big file sizes, and they must be compressed
digital camera, Once the images or videos are transferred before being stored on the computer.
to the computer, they can be easily edited, printed, or
transmitted (c.g., through e-mails),
As with digital cameras, web cameras (also called OUTPUT DEVICES
webcams) too capture videos that can be transferred
via the Internet in real-time, Web cameras are widely Any device that outputs/gives information from a computer
used for videoconferencing. They are not very costly, can be called an output device. Basically, output devices
and this is one reason why they are so widely used for are electromechanical devices that accept digital data (in
security and privacy purposes. Webcams are also used the form of 0s and 1s) from the computer and convert them
4s security cameras, since PC-connected cameras can be into human-understandable language.
used to watch for movement and sound, recording both Since these days all computers are multimedia-enabled,
when they are detected, These recordings can then be the information from computers is usually output in cither
saved in the computer and used to detect or investigate visual or auditory format. Monitors and speakers are two
theft or any other crime. A web camera is shown in widely used output devices. These devices provide instant
Figure 2.15(b). feedback to the user's input. For example, monitors
display characters as they are typed. Similarly, speakers
Advantages play a song instantly when the user selects one from a
* Audio devices can be used by people who are visually playlist. Other examples of output devices include printers,
impaired. plotters, and projectors.
* Audio input devices are best used in situations where In this section, we will discuss these output devices.
users want to avoid input through keyboard or mouse. However, before going into their details, let us classify the
+ Video input devices are very useful for applications output devices based on whether they give a hard copy or
such as videoconferencing, a soft copy output (refer Figure 2.16).
Hard
copy devices
Projector Speaker
* Soft copy cannot be used by people who do not have a glass tube. The ray is a stream of electrons that come
computer. out from a heated cathode into the vacuum, While
* Scarching for data in a soft copy is easy and fast. electrons are negative, the anode, on the other hand, is
* Electronic distribution of material as soft copy is positive, so it attracts the electrons coming out of the
cheaper, It can be done easily and quickly. cathode. That is, the focusing anode focuses the stream
of electrons to form a tight beam that is then accelerated
Monitors by an accelerating anode. This tight, high-speed beam of
The monitor is a soft copy output device used to display electrons flies through the vacuum in the tube and hits
video and graphics information generated by the computer the flat screen at the other end of the tube, This screen is
through the video card. Computer monitors are similar to coated with phosphor, which glows when struck by the
television screens but they display information at a much beam, thereby displaying a picture, which the user sees
higher quality, The monitor is connected to cither the VGA on the monitor,
or the digital video interface (DVI) port on the video card
(on the motherboard or separately purchased).
Monitors come in three variants—cathode ray
tube (CRT), liquid crystal display (LCD), and plasma Note that, colour CRT monitors contain three electron
(refer Figure 2,17), While CRT monitors look much guns (one each for red, blue, and green).
like traditional televisions and are very huge in size, ach pixel ordot on the screen has three phosphors (red,
LCD monitors on the other hand are thinner, offering blue, and green). When the beam from these guns is
equivalent graphics quality. However, these days, LCD focused on the phosphors, they light up. Byvarying the
monitors are replacing CRT monitors as they are cheaper intensities ofthe beam, the user can obtain different
and occupy less space on the desk. Most monitors have colours.
a size range of 15’ to 21’ or more (where size is defined
as a diagonal measurement from one corner of the screen
to the other). Advantages
CRT monitor CRT monitors work by firing charged * CRT monitors provide images of good quality (bright as
well as clear).
electrons at a phosphorus film (refer Figure 2.18). When
electrons hit the phosphor-coated screen, they glow, * CRT monitors are cheapest when compared to LCD and
thereby enabling the user to see the output. plasma monitors.
In a CRT, the cathode (negative terminal) is a heated * The images are clear even when you try to view it from
filament that is placed in a vacuum created inside a an angle.
Input and Output Devices GI
9 |
to allow users to talk and listen at the same time, using
the same device. Headsets are widely used in call centers
and other telephone-intensive jobs, and for personal use
on the computer to facilitate comfortable simultancou
conversation and typing. Figure 2.22 shows the various
audio devices used with computers,
Although every computer has a built-in speaker, an
Figure 2.21 Projector external speaker disables this lower-fidelity built-in
Source: olegbush/Shutterstock speaker. Speakers available in the market have a wide
Input and Output Devices 33
HB 6
information. Colour printers can also be set to print only
in monochrome. These printers are more expensive, so if
the users do not have a specific need for colour and usually
take a lot of printouts, they will find a black-and-white
printer cheaper to operate.
2.2.2 Hard Copy Devices Memory Most printers have a small amount of memory
(for example, | MB), which can be expanded by the user.
Hard copy output devices are those that produce a physical
Having more memory enhances the speed of printing.
form of output. For example, the content of a file printed
Printers can be broadly classified into two groups:
on paper is a form of hard copy output. The features of
impact and non-impact printers as shown in Figure 2.23.
hard copy output include
* Acomputer is not needed to sce the output Impact Printer
Editing and incorporating the edits in the hard copy is These printers print characters by striking an inked ribbon
difficult against the paper. Examples of impact printers include dot
* Hard copy output can be easily distributed to people matrix printers, daisy wheel printers, and most types of
who do not have a computer line printers
* Searching for data in a hard copy is a tiring and difficult
job. Advantages
* Distribution of hard copy is not only costly but slower * These printers enable the user to produce carbon copies.
as well * They are cheap.
Disadvantages
Printers + Impact printers are slow
A printer is a device that takes the text and graphics * They offer poor print quality, especially in the case of
information obtained from a computer and prints it on graphics.
a paper, Printers are available in the market in various * They can be extremely noisy
sizes, speeds, sophistication, and costs, Usually, more * They can print only using the standard font
expensive printers are used for higher-resolution colour
printing. The qualities of printers that are of interest to Non-impact printer
users include
Non-impact printers are much quieter than impact printers,
Colour Colour printouts are needed for presentations, as their printing heads do not strike the paper. They offer
maps, and other pages where colour is part of the better print quality, faster printing, and the ability to create
Impact printers
Prints that contain sophisticated graphics. Non-impact The speed of dot matrix printers varies in the range of
printers use cither solid or liquid cartridge-based ink, 50-500 cps (characters per second).
which is cither sprayed, dripped,orclectrostatically drawn
Advantages
onto the page. The main types of non-impact printers are
* The dot matrix printer can produce carbon copies.
inkjet, laser, and thermal printers.
* It offers the lowest printing cost per page.
Advantages * It is widely used for bulk printing where the quality of
* Non-impact printers produce prints of good quality, and the print is not of much importance.
hence render sophisticated graphics. + Itis inexpensive
re noiseless. * When the ink is about to be exhausted, the printout
re fast gradually fades rather than suddenly stopping partway
* They can print text in different fonts. through a job.
Disadvantages * Itcan use continuous paper rather than individual sheets,
+ These printers are expensive making them useful for data logging.
* The ink cartridges used by them are also costly Disadvantages
In this section, we will read about the different types of + This type of printer creates a lot of noise when the pins
the printers. strike the ribbon against the paper.
* Itcan only print lower resolution graphics, with limited
Dot matrix printer A dot matrix printer (shown in
quality
Figure 2.24) prints characters and images of all types
* Itis very slow
as a pattern of dots (hence the name). This printer has a
printhead (or hammer) that consists of pins representing * It has poor print quality
the character or image. The printhead runs back and forth, Daisy wheel printer Daisy wheel printers use an impact
or in an up-and-down motion on the page and prints by printing technology to generate high quality output
striking an ink-soaked cloth ribbon against the paper, comparable to typewriters, and are three times ter
much like the print mechanism of a typewriter However, today, daisy wheel technology is found only in
some electronic typewriters,
The printhead of a daisy wheel printer is a circular
wheel, about 3 inches in diameter with arms or spokes.
The shape of the printer wheel resembles the petals of
a daisy flower, and hence its name. The characters are
embossed at the outer ends of the arms.
To print a character, the wheel is rotated in such a way
that the character to be printed is positioned just in front
of the printer ribbon. The spoke containing the required
character is then hit by a hammer, thereby striking the
ribbon to leave an impression on the paper placed behind
the ribbon. The movement of all these parts is controlled
Figure 2.24 Dot matrix printer
by a microprocessor in the printer.
The key benefit of using a daisy wheel printer is that
Source: burnel1/Shutterstock the print quality is high, as the exact shape of the character
hits the ribbon to leave an impression on the paper.
From the 1970s to 1990s, dot matrix impact printers
were the most common type of printers used with PCs. Line printer A line printer is a high-speed impact printer
Several dot matrix printer manufacturers implemented in which one typed line is printed at a time. The speed
colour printing through a multi-colour ribbon. Colour was of a line printer usually varies from 600 to 1200 lines
obtained through a multi-pass composite printing process per minute, or approximately 10-20 pages per minute.
In cach pass, the printhead struck a different section of the Because of their high speed, line printers are widely
ribbon (one primary colour), However, because of poor used in data centers and in industrial environments, Band
colour quality and increased operating expense, colour printer is a commonly used variant of line printers.
dot matrix printers could never replace their monochrome
counterparts, Moreover, the black ink section would Band printer A band printer (loop printer), is an impact
gradually contaminate the other three colours (RGB), printer with a printing mechanism that uses a metal loop
thereby changing the consistency of printouts over the life or band to produce typed characters, The set of characters
of the ribbon. The colour dot matrix printer was therefore are permanently embossed on the band, and this set cannot
suitable only for abstract illustrations and pie charts, but be changed unless the band is replaced. The band itself
not for photo-realistic reproduction revolves around hammers that push the paper against the
Input and Output Devices &
ribbon, allowing the desired character to be produced on inkjet printers have to be changed more frequently,
the paper. the special coated paper required to produce high quality
The main advantage of using a band printer is its output is very expensive. Hence, the cost per page of
high speed. This type of printer can print 2000 lines per inkjet printers becomes ten times more than laser printers.
minute, and is, therefore. perfect for high volume printing Therefore, inkjet printers are not well suited for high
in businesses, schools, and other organizations. Band volume print jobs.
printers are normally attached to mainframes and used for Laser printer A laser printer, shown in Figure 2.26,
industrial printing.
is a non-impact printer that works at very high speeds
However, band printers cannot be used for any graphics and produces high-quality text and graphics. It uses
printing, as the characters are predetermined and cannot the technology used in photocopier machines. When a
be changed unless the band is changed. Band printers were
document is sent to the printer, the following steps take
very popular in the 1970s and 1980s; however, today, laser place:
printers have replaced band printers.
+ A laser beam ‘draws’ the document on a drum (which
is coated with a photo-conductive material) using
electrical charges.
Band printers are often confused with band printing. * After the drum is charged, it is rolled in a toner (a dry
Band printing istheprocess ofsending output toa powder type of ink).
printer and isnot associated with this type ofprinters. * The toner sticks to the charged image on the drum,
* The toner is transferred onto a piece of paper and fused
Inkjet printer Inkjct printers, shown in Figure 2.25, came to the paper with heat and pressure.
in the market in the 1980s, but it was only in the 1990s that * After the document is printed, the electrical charge is
their prices reduced enough to bring the technology to the removed from the drum and the excess toner is collected.
high street. Inkjet printers have made rapid technological
advances in recent years. The colour inkjet printers have
succeeded in making colour printing an affordable option
even for home users.
POINTS TO REMEMBER
* An input device is used to feed data and instructions The sound card is a hardware unit that converts
into the computer. analog signals generated through the microphone
© Keyboard is an electro-mechanical device, which is into digital data, so that it can be stored in the
used to input alphanumeric data into the computer. computer.
A pointing input device enables the users to easily Video input devices are used to capture video from
control the movement of the pointer, It is connected the outside world into the computer.
to the serial or USB port on the system unit. * Any device that outputs/gives information from a
Mouse is an input device, which enable users to control computer can be called an output device, Basically,
the movement of the pointer in graphical user interface output devices are electromechanical devices that
A joystick is a cursor control device widely used in accept digital data from the computer and convert
computer games and CAD/CAM applications. them into human understandable language.
A stylus is a pen-shaped input device used to enter * The monitor is a soft copy output device used to
information or write on the touchscreen of a phone. display video and graphics information generated by
A touchscreen is a display screen that can identify the the computer through the video card. It is connected
occurrence and position of a touch inside the display to either the VGA or the DVI port on the video card
region. (which is on the motherboard or separately
A barcode reader is a handheld input device used to purchased).
capture and read information stored in a barcode. A projector is a device that takes an image from a
A scanner is a device that captures images, printed video source and projects it on a screen or another
text, and handwriting, from different sources such as surface,
photographic prints, posters, and magazines, and * Dot matrix printer is an impact printer, which prints
converts them into digital images for editing and characters and images as a pattern of dots.
display on computers. * Laser printer is a non-impact printer, which uses a
© Audio devices are used to either capture or create laser beam to produce an image on a negatively-
sound, Microphones and CD players are examples of charged cylindrical drum.
two widely used audio devices.
Input and Output Devices 37
GLOSSARY
impact printer A printer that works by striking an inked extracting data from marked fields, such as checkboxes
ribbon against the paper and fill-in fields, on printed forms
Input device A device that is used to feed data and Outputdevice Adevice
thatisused to present information
instructions into the computer from the computer to the user
Optical character recognition The process of converting Pointing device A device that enables the users to easily
printed materials into text or word processing files that control the movement of the pointer to select items on
can be easily edited and stored a display screen, to select commands from the command
Optical device A device that uses light as a source of input menu, to draw graphics, etc
for detecting or recognizing different objects Printer Adevice that takes the text and graphics information
Optical mark recognition The process of electronically obtained from a computer and prints it on paper
EXERCISES
Fill in the Blanks 3. Select the printer that uses impact printer technology
1, _____ is used to feed data and instructions into the from the following options
computer. (a) Daisy wheel (b) Laser
2 captures everything on the screen as an {c) Band (d) Inkjet
image. 4. Select the pointing devices from the following options:
3, The movement of an optical mouse is detected using
(a) Keyboard (b) Barcode reader
ae WAVES,
{c) Joystick (d) Touchscreen
4, ___ is used to enter information or write on the
5. Which type of screen is used in gaming devices, clocks,
touchscreen of a phone.
watches, calculators, and telephones?
5. A barcode reader is connected to the computer through
aL port. (a) LCD (b) Plasma
6 sttechnology is used for electronically extracting ({c) CRT (d) All of these
data from marked fields.
7. ____ converts analog signals generated through a State True or False
microphone into digital data 1, Home and End keys move the cursor to the previous and
8, ______s capture videos that can be transferred via the next page, respectively.
Internet in real-time 2. Pointing devices can be connected to the USB port of a
9. allow the users to talk and listen at the same computer.
time. 3, The movement of the cordless mouse is detected using
10, The resolution of a printer means laser technology.
4. OCR is used to verify the legitimacy or originality of
Multiple-choice Questions paper documents.
1, Which keys are used by applications and operating 5. The monitor is a soft copy output device.
systems to perform specific commands? 6. Non-impact printers create characters by striking an
(a) Typing keys (b) Arrow keys inked ribbon against the paper.
7. A laser printer uses the same technology used in
() Control keys (d) Function keys
photocopier machines.
2, Select the optical devices from the following options
8. A plotter is used to print vector graphics
(a) MICR (b) Barcode reader
9. A mouse cannot be used with a laptop computer.
(c) Scanner (d) All of these
38 ‘Computer Fundamentals and Programming in C
10, Soft copy output devices are those that produce a 11 Under which situation, will you prefer to use an inkjet
physical form of output. printer over a laser printer?
12 How is a plotter different from a printer?
Review Questions 13. Explain the variants of plotters.
1, How does a keyboard work? 14 What are input devices? Discuss the different types of
2. Explain the working of different types of mouse. input devices in detail.
3, How is OCR technology better than an ordinary image 15. Give a detailed note on different output devices.
scanner? 16. How is a touchpad better than a trackball?
4, How does MICR technology help to detect fraud in 17, Which pointing input device would you prefer to use,
cheque payments? mouse or trackball? Justify your answer.
5, Web cameras can be used to check security in a bank 18. List the applications of touchscreen
Comment 19. What are optical input devices? Where are they used
6. How are projectors used to display information to a and for what purpose?
user? 20, Differentiate between a soft copy and a hard copy
7. How are headsets better than speakers and headphones? output
8. Differentiate between impact and non-impact printers. 21 Which factors will you consider while purchasing a
9. Can characters of different fonts be printed with a band monitor for your personal computer? After considering
printer? the factors, which monitor will you buy?
10. Why is a line printer preferred over a dot matrix printer? 22 What is a data projector? How is it different from a
if you have an image to be printed, which out of the two computer screen?
will you use and why?
Computer Memory and
“Processors
TAKEAWAYS
* Sequential access © Magnetic tapes * Memory cards
* Random access © Floppy disks © Mass storage devices
* Processor registers © Hard disks * Processor architecture
* Cache memory © Optical drives * Pipelining
© Primary memory © USB flash drives * Parallel processing
* Secondary memory
in nature. In this section, we will read about the different while reading a bit, the transistor checks for a charge if
types of RAM and ROM available in the market the capacitor. Ifacharge is present, then the reading is 1;
if not, the reading is 0.
3.6.1 Random Access Memory (RAM) However, the problem with DRAM is that the capacitor
leaks energy very quickly and can hold the charge for
RAM is a volatile storage area within the computer that only a fraction of a second. Therefore, a refresh process
is typically used to store data temporarily, so that it can is required to maintain the charge in the capacitor so that
be promptly accessed by the processor. The information it can retain the information. This refreshing process is
stored in the RAM is basically loaded from the computer's carried out multiple times in a second and requires that all
hard disk, and includes data related to the operating cells be accessed, even if the information is not needed.
system and applications that are currently being executed However, the advantage of DRAM over SRAM is that
by the processor. it is cheap, can hold more data per chip, and generates less
RAM is considered random access because any memory heat than SRAM. DRAM is widely used to build the main
cell can be directly accessed if its address is known. When memory. The following are the different types of DRAM:
the RAM gets full, the computer system operates at a slow
Synchronous DRAM (SDRAM) SDRAM synchronizes
speed. When multiple applications are being cxecuted
itself with the clock speed of the microprocessor to enable
simultaneously and the RAM gets fully occupied by
faster access lo memory
the application's data, it is searched to identify memory
portions that have not been utilized. The contents of those Enhanced SDRAM (ESDRAM) This version of SDRAM,
locations are then copied onto the hard drive. This action though not widely used, includes a small SRAM cache to
frees up RAM space and enables the system to load other reduce delays in data access and speed up operations,
pieces of required data. Double data rate SDRAM (DDR) DDR allows data
These the applications’ and operating system's transfers on both the rising and falling edges of the clock
demand for system RAM has drastically increased. For cycle, which doubles the data throughput, DDR SDRAM
example, in the year 2000, a personal computer (PC) had chips are available in capacities of 128MB to 1GB
only 128 MB of RAM, but today PCs have 1-2 GB of RAM Although DDR memory is very common, the technology
installed, and may include graphics cards with their own is becoming outdated and is being replaced by DDR2,
additional $12 MB or more of RAM. As discussed carlicr,
there are two types of RAM—static RAM (SRAM) and DOR2 These chips are the next generationofDDR SDRAM
dynamic RAM (DRAM). memory. It can hold 256 MB to 2GB of memory and can
Operate at higher bus speeds. Although DDR2 has twice
StaticRAM This is a type of RAM that holds data without the latency (data access delays) of DDR, it delivers data at
an external refresh as long as it is powered. This is in twice the speed, thereby performing at the same level.
striking contrast with the DRAM which must be refreshed
multiple times in a second to hold its data contents. SRAM Rambus DRAM (RDRAM) It is a proprietary, protocol-
is made of D flip-flops in which the memory cells flip-flop based, high-speed memory technology developed by
between 0 and | without the use of capacitors. Therefore, Rambus Inc. RDRAM can operate at extremely high
there is no need for an extemal refresh process to be frequencies as compared to other types of DRAMs.
carried out Synchronous link dynamic RAM (SLDRAM) This version
The limitation of SRAM is that it occupies more space of SDRAM, not used widely, was basically designed as a
and is more expensive than DRAM, While each transistor on royalty-free, open-industry standard design alternative to
a DRAM chip can store one bit of information, the SRAM RDRAM
chip, on the other hand, requires four to six transistors to
store a bit, This means that a DRAM chip can hold at least 3.6.2 Read-only Memory (ROM)
four times as much data as an SRAM chip of the same size,
thereby making SRAM much more expensive. ROM refers to computer memory chips containing
permanent or semi-permanent data. Unlike RAM, ROM is
However, SRAM is faster, more reliable than DRAM,
non-volatile; that is, the data is retained in it even after the
and is often used as cache memory. SRAM chips are
also used in . houschold appliances, and handheld computer is tumed off.
Most computers store critical programs like the basic
electronic devices.
inpuVoutput system (BIOS) in ROM, which is used to boot
Dynamic RAM This is the most common type of memory up the computer when it is tumed on. The BIOS consists
used in personal computers, workstations, and servers of a few kilobytes of code that tells the computer what to
today. A DRAM chip contains millions of tiny memory do when it starts up, such as running hardware diagnostics
cells. Each cell is made up of a transistor and a capacitor, and loading the operating system into the RAM, Morcover,
and can contain | bit of information—0 or 1. To store ROMs are used extensively in calculators and peripheral
a bit of information in a DRAM chip, a tiny amount of devices such as laser printers, whose fonts are often stored
power is put into the cell to charge the capacitor. Hence, in ROMs.
42 Computer Fundamentals and Programming in C
Originally, ROMs were read-only. So, in order to 3.6.3 Finding Required Data from Main
update the programs stored in them, the ROM chip had to
Memory
be removed and physically replaced by another that had
4 newer version of the program. However, today ROM The main memory is organized as a matrix of bits, as
chips are not literally read-only, as updates to the chip shown in Figure 3.2. A matrix of bits means a combination
are possible. The process of updating a ROM chip is a of rows and columns that stores a bit. The main memory,
bit slower, as memory must be erased in large portions which holds the user’s data and programs for execution by
before it can be rewritten. Rewritable ROM chips include the CPU, is directly or
PROMs, EPROMs, and EEPROMs. indirectly connected to
the processor via a bus
Programmable read-only memory (PROM) It is also
called one-time programmable ROM, and can be written
There are two buses, an
to or programmed using a special device called a PROM address bus and a data
bus. The CPU first sends
programmer. The PROM programmer uses high voltages
a number through the
to permanently destroy or create internal links (fuses or
address bus,
anti-fuses) within the chip. The working of a PROM is
similar to that of a CD-ROM recorder, which enables the This number denotes
the memory address
users to burn programs onto blank CDs, The recorded
or the burnt data can be read multiple times. Therefore, of the desired location
programming a PROM is also called burning, just like
of data. Then it reads
burning a CD-R, and is comparable in terms of its
or writes the data itself
using the data bus. Figure 3.2 Bit matrix
flexibility.
Erasable programmable read-only memory (EPROM) It
is a type of ROM that can be erased and re-programmed. ED SECONDARY STORAGE DEVICES
The EPROM can be crased by exposing the chip to strong
ultraviolet light, typically for 10 minutes or longer, and Secondary storage (also known as external memory or
can then be rewritten with a process that again needs the auxiliary storage) differs from main memory in that it is
application of a higher voltage. Repeated exposure to not directly accessible by the CPU. The secondary storage
ultraviolet light wears out the chip. The EPROM is much devices hold data even when the computer is switched off.
more useful than PROM and can be compared with a An example of such a device is the hard disk.
reusable CD-RW. The computer usually uses its input/output channels to
Electrically erasable programmable read-only memory access data from the secondary storage devices to transfer
(EEPROM) Itis based on a semiconductor structure similar the data to an intermediate area in the main memory.
to the EPROM, but allows the entire or selected contents Secondary storage devices are non-volatile in nature,
to be electrically crased, then rewritten electrically, so that cheaper than the primary memory, and thus can be used
they need not be removed from the computer (or camera, to store huge amounts of data, While the CPU can read
MP3 player, ctc,). The process of writing an EEPROM is the data stored in the main memory in nanoseconds, the
also known as flashing. data from the secondary storage devices can be accessed
The flash memory is also a type of EEPROM in which in milliseconds.
the contents can be erased under software control. This is The secondary storage devices are basically formatted
the most flexible type of ROM, and is widely used to store according to a file system that organizes the data into files
BIOS programs. It is primarily used in memory cards, and directories. The file system also provides additional
USB flash drives, MP3 players, personal digital assistants information to describe the owner of a certain file, the
(PDAs), laptop computers, digital audio players, digital access lime, the access permissions, and other information.
cameras, and mobile phones. The EEPROM blurs the
difference between read only and read—write. However, the 3.7.1 Offline Storage
EEPROM is rewritten only once a year or so, compared to
Offline storage devices are those on which data is
real read-write memory (RAM), where rewriting is often
recorded and then physically removed or disconnected
done many times per second.
(off the computer, hence the name). Such devices include
magnetic tapes, floppy disks, optical disks, flash memory
devices, and external hard disks, In order to access data
(a) By applying write protection,
some types of from an offline storage device, it must first be connected
reprogrammable ROMs may temporarily become to a computer.
read only memory. Offline storage devices are widely used to store a
(b) In practice, both RAM and ROM support random backup of important data. For example, if the original
access of memory. data gets destroyed in case of a disaster, the data can be
Computer Memory and Processors 43
recovered from the offline devices, which are usually ofasupply reel, a take-up reel, a R/W head, and an eras€
stored in another distant place. Moreover, offline storage head. When the user has to edit/rewrite the pre-recorded
also provides security of critical data, as these devices are data on a tape, the previously recorded data is erased by
physically inaccessible by a computer, and therefore data the erase head and the new data is recorded. The process
confidentiality or integrity cannot be affected by malicious of recording data is much similar to that of recording on an
software. audio tape or audio cassette
Usage A magnetic tape can store large amounts of
EX) macnetic tapes information and is therefore used in the regular backing
up of hard disks.
Magnetic tapes (shown in
Figure 3.3) are mass storage Advantages
devices capable of backing * Amagnetic tape is compact in size, light in weight, and
up and = retaining =large can store large amounts of data. Therefore, tapes are
volumes of data. A magnetic
easily portable and can be used to transfer data from
tape, which resembles an one computer to another.
audio tape, is a thin stnp of Magnetic tapes are economical. The cost of storing
plastic coated with magnetic characters is very less as compared to other storage
recording material, These
devices.
storage devices are basically
Copying of data on a magnetic tape is easy and fast
used as sequential ac Magnetic tapes can be used for long-term data storage
Figure 3.3 Magnetictape secondary storage devices. and retrieval
Magnetic tapes are available in the form of cassettes, * Tape drives use less power.
reels, and cartridges, with recls being most widely used.
* Tape drives can easily be stored offsite, allowing data
Reels that are used with mini and mainframe computers are to survive even if the computer itself is destroyed or
1/2 inch wide and 2400 feet long. Such a tape can store stolen.
1600 characters per inch of the tape length. This means that
about 50 books could be stored on just one reel of tape.
Disadvantages
Storage capacity of magnetic tape
Data recording density * Length of the tape * Data stored
on the tape can be accessed only sequentially.
* As compared to other storage devices, data on a tape is
Here, data recording density is the amount of data that
accessed at very slow speeds because of serial access,
can be stored on a given length of tape. It is measured * Special hardware is required to read the data stored on
in bytes per inch (bpi), and usually varies from 800 to
tapes, and most standard PCs available today do not
77,000 bpi. For example, a tape of length 2400 feet with come with such hardware.
1000 bpi as its storage density has a storage capacity of + With advancements in technology, hard drives are
2400 * 12 * 1000 = 2,88,00,000 = 28 « 10° =28MB. becoming cheaper than tapes and are therefore being
However, as of now, magnetic tapes with stora: increasingly used for backups.
capacity of up to 35 trillion bytes (terabytes) of data are
Magnetic tapes are casily susceptible to degradation due
easily available in the market to heat, humidity, dust, mishandling, electromagnetic
Data representation On a magnetic tape, data is recorded surfaces, and ordinary wear.
in the form of tiny non-magnetized and magnetized spots, * Magnetic tapes are best suited for full-system restores
where the presence of a spot represents | and its absence and not for restoring of individual files. This is because
represents 0. This means that data is stored in the form of finding and restoring individual files can be a long,
0s and 1s. For example, ‘A’ is stored as 1011 on the tape. slow, and cumbersome process,
Data on a tape is represented using the EBCDIC standard.
However, the data stored on a tape can be accessed only in
a sequential fashion, Unlike magnetic disks, flash drive
EX) Fiopry pisks
optical drives, and floppy drives, magnetic tapes do not Floppy disks (shown in Figure 3.4) are data storage devices
support random access of data.
that consist of a thin magnetic storage medium encased in
On a tape, the data is stored in terms of records, with
a square plastic shell lined with fabric that removes dust
individual records separated by a gap known as the inter- particles. The storage capacity of floppy disks is very
record gap. \n addition, when records are short, they may
limited as compared to CDs and flash drives, Although
be grouped to form blocks. The data stored in the form of
floppy drives are very cheap, they are much slower than
blocks will then have inter-block spacing other data storage devices. Moreover, floppy disks must be
Magnetic tape drive A tape drive is used to read and handled with utmost care as they are vulnerable to damage
write data on a magnetic tape. The tape drive units consist from mishandling. For example, data stored on a floppy disk
44 Computer Fundamentals and Programming in C
can be lost if the disk padding bytes are written on these, which are discarded by
is bended, removed the floppy disk controller.
while in use, or Moreover, each data sector has a header that stores the
exposed to excessive sector location on the disk. An error checking code is also
temperature, dust, or written into the sector headers and at the end of the user
smoke. data, so that the diskette controller can detect errors when
Floppy disks were reading the data.
widely used from the
Storage capacity All 3.5 inch floppy disks are double-
mid-1970s till 2000
sided. They have 80 sectors, 18 sectors/track, and can
to distribute software,
store 512 bytes/sector.
transfer data, and
create backups. Today, Therefore the storage capacity of afloppy disk
Figure 3.4 Floppy disk however, their use has 2 *« 80 * 18 © 512 bytes
become very limited 14,74,560 bytes = 147 MB
Source: Photodisc/OUP Picture Bank
as they have been
superseded by
drives, external hard drives, optical disks, and memory cards.
flash
ERT Hard visks
The mechanism of a floppy disk involves two motors.
While one motor in the drive rotates the diskette at a The hard drive is a part of the computer that stores all the
programs and files, so if the drive is damaged for some
regulated speed, the second motor moves the magnetic
reason, all the data stored on the computer is lost. The hard
R/W head (or heads, if a double-sided drive) along the
disk provides relatively quick access to large amounts of
surface of the disk. To read/write data on the disk media,
data stored on an clectromagnetically charged surface or a
there must be physical contact between the R/W head and
set of surfaces. Today, PCs come with hard disks that can
the disk media. Figure 3.5 shows the internal parts of a
store gigabytes of data.
floppy disk.
A hard disk is basically a set of disks, stacked
Reading/Writing data In order to write data on a floppy together like phonograph records, that has data recorded
disk, current is passed through a coil in the head. The electromagnetically in concentric circles known as
magnetic field of the coil magnetizes spots on the disk tracks
as it rotates. The change in magnetization encodes the A single hard disk includes several platters (or disks)
digital data, that are covered with a magnetic recording medium.
Similarly, to read data from the floppy disk, a small Each platter requires two read/write (R/W) heads, one for
amount of current is induced in the head coil to detect each side. Note that in the figure, all the R/W heads are
the magnetization on the disk. The floppy drive controller attached to a single access arm and so they cannot move
separates the data from the stream of pulses coming from independently. The parts of the hard disk are shown in
the floppy drive, decodes the data, tests for errors, and Figure 3.6,
sends the data on to the host computer system.
Tracks and sectors A blank floppy disk has a pattem of Rw
magnetized tracks, cach broken into sectors. The tracks Arm head Sector
on the floppy drive have some spaces between the tracks Spindle
where no data is written, Similarly, there are spaces Track
between the sectors and at the end of the track to allow Platter
for slight speed variations in the disk drive. Usually some [ff
Cylinder
Shell/Housing b 0&
Magnetic disk (
Shell/Housing
k)Nt fh
Af 0
a aA
SE So
Paper ring
Figure 3.5 Components of a floppy disk Figure 3.6 Schematic diagram of a hard disk
Computer Memory and Processors 45
The R/W head can pivot back and forth over the platters disk drive makes it susceptible to head crash. Head crash
to read or write data on them. Data is actually stored on the can also occur if dust settles into the hard drive, thereby
surface of a platter in sectors and tracks (refer Figure 3.7). resulting in bouncing of the arm when the disk operates.
While the tracks are concentric, sectors on the other hand During a head crash, the fragile magnetic recording medium
are pic-shaped wedges on a track. Thus, a track is divided gets ruined, resulting in loss of the data stored in it. Laptop
into a number of segments (also called sectors) that can users must very carefully move their laptops as moving it
store a fixed number of bytes—for example, 256 or 512 abruptly when it is switched on can lead to head crash.
The tracks are numbered consecutively from outermost to The performance of a hard disk depends on its access
innermost, starting from zero, The number of tracks on time, which is the time required to read or write on the
a disk can vary from 40 on some low capacity disks to disk. Access time is a combination of the following three
several thousands on high capacity disks components:
Seek time This is the time taken to position the R/W head
A sector over the appropriate cylinder (usually around 8 ms on an
average). Seck time varies depending on the position of
the access arm when the R/W command is received. Its
value will be maximum when the access arm is positioned
over the innermost track while the data that has to be
accessed is stored on the outermost track. Similarly, it will
be zero if the access arm is already positioned over the
desired track. On an average, the seck time varies from 10
to 100 milliseconds.
a a A track Rotational delay This is the time taken fo bring the target
sector to rotate under the R/W head. Assuming that the
Figure 3.7 Cross-section of a cylinder hard disk has 7200 rpm, or 120 rotations per second, a
single rotation is done in approximately 8 ms. The average
Moreover, cach platter has the same number of tracks, rotational delay is around 4 ms.
and a track location that cuts across all platters is
called a cylinder. In simple terminology, a cylinder is Transfer time The time to transfer data or read/write to a
vertically formed by tracks. For example, track 2 on disk is called the transfer rate.
platter 0 plus track 2 on platter 1, plus track 2 on platter Thus, the overall time required to access data = seck
n is cylinder 2. The number of cylinders of a disk drive time + rotational delay + transfer time.
is equal to the number of tracks on a single platter of The sum of the seck time and the rotational delay is
the disk also known as disk latency. Disk latency is the time taken
When the computer is turned on, the platters in the hard to initiate a transfer.
disk drive immediately begin to spin. While the platters
in a desktop computer hard disk drive rotate 7200 times
per minute, on the other hand, the hard drives in laptop
The key tousing the hard drive effectively is to
computers usually make $400 rotations per minute (rpm).
minimize
disklatency. Ideally,
thiscan bedone by
You must have heard the steady hum of your hard drive.
defragmentation, which moves related data to physically
Even when you are not retrieving from or writing anything
proximate areas on the disk. Some computer operating
to the hard disk, the platters spin. However, the arm with
systems perform defragmentation automatically,
the R/W head moves only when you run 4 program or
open, save, or delete a file, The arm can move back and
forth across the surface of the platter as many as 50 times To access data from a hard disk, a disk address has to be
in a second. specified. The disk address represents the physical location
of a record on the disk, and comprises the following
components:
* Sector number
Atypical hard disk drive has two electric motors—a disk * Track number
motor to spin the disks and an actuator (motor) toposition * Surface number (when data is recorded on both sides of
the R/W head assembly across the spinning disks. the disk)
The storage capacity of a disk with multiple recording
The R/W head does not actually touch the platters, instead surfaces can be calculated as:
just barely skims above them, supported by a cushion of Storage capacity = No. of recording surfaces * No. of
moving air that is generated by the spinning of the platters. tracks per surface * No. of sectors
The rapid motion of the platters and heads inside the hard per track * No. of bytes per sector
46 Computer Fundamentals and Programming in C
* They can store large amounts of data. If required, the External hard disks are also called removable hard disks.
users can have multiple disks
* The cost of data storage is very low. With advancement
in technology, the cost of magnetic disks has reduced
and the capacity of data they can store has constantly OPTICAL DRIVES
increased.
Data transfer rate of magnetic disks is much higher than Optical storage refers to storing data on an optically
that of the magnetic tapes. readable medium by making marks in a pattern that can
be read using a beam of laser light precisely focused on a
Disadvantages spinning disk. Optical storage devices are the most widely
used and reliable storage devices, The most popular
* They must be stored in a dust-free environment optical storage devices are CD-ROM, DVD-ROM,
* They are larger in size and heavier in weight when CD-Recordable, CD-Rewritable, ete
compared to flash drives and optical disks. Today, every computer contains a CD-ROM drive.
A single CD can hold a large amount of data, including
software, movies, and songs. While some optical storage
EREB EXTERNAL HARD DISKS media is read-only, others are read- and write-enabled
An optical storage media consists of a flat, round,
As the name suggests, an external hard disk (sce Figure portable metal disk, which is usually 0.75 inches in
3.8) is a drive that is located outside the computer case diameter and less than sith of an inch thick. The disk is
in its own enclosure, It is used in addition to internal coated with a thin metal, plastic, or other material that is
hard drives to store data. It has become quite popular highly reflective.
because of its portability and high-storage capacity. It The optical disk stores information in the form of pits
is connected to the computer system with a high-speed and lands (shown in Figure 3.9). Pits are tiny reflective
interface cable, usually with plug-and-play interfaces bumps created with a laser beam and lands are flat areas
such as USB or FireWire, and may also contain a fan for separating the pits. While a land reflects the laser light and
cooling. While with USB connections, data can move at is read as binary digit |, a pit on the other hand absorbs the
arate of 12 to 480 Mbps (megabits per second), FireWire light and is read as binary digit 0.
Computer Memory and Processors 47
0000000000 10000000000 10000000000, rates (or speeds) ranging from 48X to 75X, or more. Here;
a 48X drive has a data transfer rate of 7200 kbps (i.c., 48 *
150 =7200) or 7.2 Mbps.
3.12.2 DVD-ROM
Digital video disk or digital versatile disk (DVD) is an
extremely high-capacity optical disk with storage capacity
ranging from 4.7GB to 17GB. DVDs are widely used to
store large databases, movies, music, complex software, ctc
Figure 3.9 Pits and lands Most of the DVD-ROMs are double-sided disks,
as they can store data on both the sides of the disk
Similar to magnetic disks, optical disks also have tracks Although 4 DVD-ROM resembles a CD-ROM in size
that are divided into sectors, but the shape of these sectors and shape, it stores information in different manner. A
is different from that of magnetic disks. Different types of DVD-ROM drive is compatible with CD-ROM drives
optical storage devices are explained in this section. and can therefore read CDs
A standard DVD can store seven times more data than
3.12.1 CD-ROM a CD because of its multi-layer storage technique and the
fact that the size of its pits and tracks is smaller. When
Compact disk read only memory (CD-ROM), shown data is recorded on a DVD, the laser starts on the inside of
in Figure 3.10, is a type of optical disk that uses laser the disk and moves outward, The laser beam has a smaller
technology to read and write data onto the disk. A single wavelength and can be focused on two different layers
CD-ROM can store a large amount of data, but once the on the disk. Data can be recorded on cach of the layers,
information is stored on it, it becomes permanent and thereby doubling the storage capacity of the disk.
cannot be altered. This means that the stored information In a double-sided DVD-ROM, two such disks are stuck
can only be read for processing, hence the name. back-to-back to allow recording on both sides, However,
such DVD-ROMs must be handled very carefully, as
both sides have data stored on them and this data can be
damaged accidentally due to mishandling
3.12.3 CD-R
Compact disk recordable (CD-R) is a blank disk that can be
used to store information. For example, users can use it to
store their databases, software, projects, assignments, etc
The process of writing data on the optical disk is called
Figure 3.10 CO-ROM burning. CD-R can be used in any CD-ROM drive and
Source: \talianphoto/Shutterstock/OUP Picture Bank is functionally equivalent to a pre-recorded CD-ROM.
However, once data is written on the CD-R, it cannot be
CDs are easily portable from one computer to another and changed. Moreover, the user can continue to store data
are therefore used to transfer data from one computer to on other parts of the disk until it is full. However, cach
another (similar to a floppy disk). The storage capacity part of a CD-R can be written only once and can be read
of a CD-ROM varies from 650 MB to 1GB, which is many times.
1000 times greater than that of afloppy disk. Nowadays, Today, many utility programs are available in the
most software products (such as Microsoft Office, market to write data on CD-Rs, but the most popular and
Windows operating system, and so on) are available on commonly used software for PCs is Nero Burning ROM.
CD-ROMs. CD-Rs are widely used to backup critical data, However,
to record information on a CD-R, the user must have a CD
CD-ROM drive The CD-ROM drive is used to read the writer. A CD writer or recorder (or simply CD-R drive)
information stored in a CD-ROM. The data transfer rate can also read information from a CD. The speed of these
of the first CD-ROM drive was 150 kbps (kilobytes per drives is up to 48X or more, and they are more expensive
second), and is denoted as X. The data transfer rate of a than ordinary CD-ROM drives.
CD-ROM is much slower than that of a typical hard disk
drive, which reads data at a rate of S—15 mbps (megabytes
per second), The speeds of all CD-ROM drives are
3.12.4 CD-RW
calculated relative to the first CD-ROM drive's speed. For Compact disk rewritable (CD-RW) is a new generation of
example, the CD-ROM drives used today have transfer erasable optical disks. The user can write and overwrite
48 Computer Fundamentals and Programming in C
Brand and product promotion The casy availability of recommended when repairing a virus-contaminaléd
inexpensive flash drives has motivated companies to use host computer as there is a risk of infecting the USB
them for promotional and marketing purposes, particularly flash drive itself
within techni and computer-industry circles. USB * Flash drives are very small devices that can casily be
flash drives may be given away for free, sold at less than misplaced, left behind, or otherwise lost. This can at
wholesale price, or included as a bonus with another times be a serious problem, especially if the data is
purchased product. Usually, such drives are stamped with sensitive.
4 company’s logo, as a form of advertising. The drive may * The cost per unit of storage of a flash drive is higher
cither be empty or preloaded with graphics, documentation, than that of hard disks.
web links, Flash animation or other multimedia, and free
or demonstration software. ERTB memory carps
Backup Many users (especially involved in business)
use flash drives as a backup medium. However, one must A memory card (sometimes
remember that it is casy lose them and easy for people called aflash memory card ora
without a right to the data to make illicit copies. storage card, shown in Figure
Newer flash drives have much higher estimated 3.12) is a small device that can
lifetimes and are therefore available with warranties store digital files. They are
of five years, or more, Moreover, flash drives have easily portable from one place
experienced an exponential growth in their storage to another. A user can take a
capacity over time (following the Moore's law growth memory card, insert it into
curve). Today, flash drives of 256 GB are not uncommon. a computer, store files such
This has made them a very good substitute for magnetic Figure 3.12 Memory text documents, pictures,
disks, card audio files, and video file
and then remove the card and
Source: \tya Akinshin/
Advantages take it to another computer
Shutterstock/OUP Picture
Bank
where it can be again inserted
* Data stored on flash drives is impervious to damages
to copy the files onto the local
due to scratches and dust. disk of that computer,
* Flash drives are mechanically very robust and Technically, a memory card uses flash memory, which
computers these days come with a USB port, so they enables the users to add/delete files multiple times.
can be easily used to transfer data from one computer
Initially, when flash cards were first introduced in the
to another
market, they were not very large and were incredibly
* Flash drives have higher data capacity than any other
expensive. However, with advancements in technolog’
removable media.
memory cards have become cheaper and smaller in size.
* Compared to hard drives, flash drives use very little
Today, different types of memory cards are available in the
power and have no fragile moving parts
market. These include compact flash memory (which is the
* Flash drives are small and lightweight devices.
largest in size but has the smallest capacity to store data),
* Operating systems can read and write to flash drives
secure digmemory card (SD), miniSD card, microSD card,
without installing device drivers
memory stick, and the multimedia card (MMC). As these
* Specially manufactured flash drives have a tough
cards have evolved, they have become smaller in size and
rubber or metal casing designed to be waterproof and
larger in data capacity
virtually unbreakable. The data stored in these flash
Most of these cards have constantly powered non-
drives does not get destroyed even when submerged
volatile memory, which means that data is retained on thes
in water. Leaving such a drive out to dry completely
cards even when there is no power supply to the computer,
before allowing current to run through it has been and they do not need to be periodically refreshed. Memory
known to salvage the drive, with no further problems cards have no moving parts; therefore, they are unlikely to
in the future. suffer from mechanical difficulties.
Disadvantages Since newer memory cards are smaller, require |
power, have higher storage capacity, are completely
* Flash drives can sustain only a limited number of write silent, are less prone to mechanical failures, allow
and erase cycles before the drive fails. Therefore, flash immediate access to data, and are portable among
drives are usually not a good option to run application a greater number of devices, they are being widely
software or operating systems. used in the production of an increasing number of
* Most flash drives do not have a write-protect mechanism small, lightweight, and low-power devices, Although
to prevent the host computer from writing or modifying memory cards are far better than hard disks, they still
data on the drive. Wnite-protection devices are highly cannot replace them, because memory cards are quite
50 Computer Fundamentals and Programming in C
¢xpensive. For example, a compact flash card with one or more tape drives. As
192 MB capacity typically costs more than a hard drive shown in Figure 3.14, a tape 1
with a capacity of 40GB. library consists of a number of
slots to hold tape cartridges, a
ERER Mass STORAGE DEVICES barcode reader to identify tape
cartridges, and an automated
Mass storage refers to storing enormous amounts of data method called robot for
in a persistent manner, Mass storage devices can store up loading the appropriate tape
to several trillion bytes of data and hence are used to store on one of the tape drives for
large databases, such as the data of customers of a big retail processing. After processing,
chain and library transactions of students in a college. the robot automatically returns
Figure 3.14 Automated
Mass storage devices have the following advantages: the tape to the library.
Tape libraries can store
tape library
ainable transfer speed
* Low cost large amounts of data ranging from 20 terabytes to more
than 411 petabytes of data. They offer a cost-effective
* High data sto: wwe capacity
* Less weight
solution to the problem of storing large volumes of da
* Better tolerance of physical stress caused by shaking or
with the cost per gigabyte being at least 60 per cent less
dropping
than when using most hard drives. In addition, multiple
drives also lead to improved reliability because even when
+ Low power consumption
+ Easily portable one of the drives fail, the unit can still continue to function
with the other devices at a slower speed.
All these features make it convenient to use them with Though tape drives provide systematic access to
mobile phones, laptops, and desktops. Some of the very large quantities of data, the access is slow, varying
commonly used mass storage devices are discussed in this from several seconds to several minutes. A tape library
section. is commonly used for data backups as the final stage of
digital archiving. In organizations, it is extensively used
3.15.1 Disk Array for recording daily transactions or data auditing
A disk array, commonly known as a redundant array of
independent disks (RAID), is a group of one or more 3.15.3 CD-ROM Jukebox
physically independent and high-capacity hard disk
ACD-ROM jukebox, also known as an optical jukebox,
drives, which can be used in place of larger, single disk
an optical disk library, or a robotic drive, is a data storage
drive systems. The benefit of such a system is that it helps
reduce costs, because having several medium-sized hard device that can automatically load and unload optical
disks such as CDs and DVDs to provide terabytes and
disks is cheaper than having a single large hard disk
petabytes of tertiary storage (Figure 3.15). It can have
As shown in Figure 3,13, a disk array contains several
up to 2000 slots for disks and usually has a robot that
disk drive trays to improve speed and increase protection
traverses the slots and drives for loading the appropriate
against loss of data, The storage capacity of a disk armay is
several terabytes
(1 terabyte = | trillion bytes), The disk array
CD-ROM. After processing, the robot automatically
unit allows data to returns it back to the library
CD-ROM jukeboxes are extensively used for creating
be read or written to
any disk in the array.
backups and in disaster recovery situations, They can be
Disk armys are a
used for archiving data
(data is stored on media
vital component of
that will last up to 100
high-performance
years). Such archival
storage systems, and
their importance is
data is usually written
on disks of write once,
continuously growing
read many (WORM)
with the increase in
type so that it can never
demand to access
information for the be erased or changed.
Moreover, jukeboxes
day-to-day operation
are effectively used
Figure 3.13 Disk array of modem businesses.
for archiving data in
systems such as online
3.15.2 Automated Tape Library digital libraries, online
An automated tape library, also known as a fape silo, tape encyclopacdia, and
robot, or tape jukebox, is a storage device that contains online museums Figure 3.15 CD ROM jukebox
Computer Memory and Processors 51
DATA BACKUP
Data backup is the process of making one or more copies accidental deletion of a file, or a natural disaster like an
of data from an online storage device (hard disk) to a earthquake. In such cases, re-creating all the files would
tertiary storage device like a magnetic tape. The copy of take a lot of time, and at times, it might not even be
data acts as an offline storage so that if the system loses possible. Therefore, it is a good practice to take regular
the original data, it can be retrieved from the backup data backups so that the data can be retrieved within a
device and restored in the online storage device. short time. There are two types of data backups, which
The online storage system may lose its data because of can be compared as follows:
a disk crash, a virus attack, a hardware malfunction, an
* It copies allthe data on a teniary device, * Ncopies only newly created files or files
* The process takes from few minutes to hours changed since the last backup.
* Itis an expensive process interms of both * Bnceds fess backup time and storage space.
lime taken and storage space occupied. © Mis faster.
© Ibs slower. * is complex when compared to full
* It is simple. data backup
the variations in speed is that personal or minicomputers architecture is like having two separate processors installed
use a single processor to cxecute instructions, whereas in the same computer. However, since the two processors
mainframes and supercomputers employ multiple processors are actually plugged into the same socket, the connection
to speed up their overall performance. between them is faster. Ideally, such processors must be
twice as powerful as a single-core processor, but in practice,
3.16.7 Pipelining and Parallel Processing their performance is only about one-and-a-half times more.
Computers working on high-end applications, such as
Most of the modern PCs support pipelining, which is a artificial intelligence and weather forecasting, go a step
technique with which the processor can fetch the second further by implementing the concept of massively parallel
instruction before completing the execution of the first processing, that is, large-scale parallel pro ing. Ino
instruction. Initially, a processor had to wait for an multi-core processor, tens or hundreds of processors are
instruction to complete all stages before it could fetch the incorporated in @ single chip. Companies such as IBM,
next instruction, thereby wasting its time. However, with AMD, and Intel have already come out with multi-core
pipelining, processors can operate at a faster pace as they no chips for desktops, laptops, and servers, These multi-core
longer have to wait for one instruction to complete before chips are available as dual core (2 processors per chip),
fetching the next instruction. Such processors that can quad core (4 processors per chip), 8 core, and 16 core.
execute more than one instruction per clock cycle are called
superscalar processors. Instruction execution without
pipelining and with pipelining are shown in Figure 3.20.
Since multi-core processors generate less heat and
With superscalar architecture, processors could
consume less power, they are also called energy-efficient
execute programs faster by replicating components
like ALUs. Replication was the only possible solution ‘OF power-aware processors.
because a single processor was already made to work at
3.16.8 Types of Processors
its maximum limit
The other technique to enhance a computer's A computer is a combination of hardware and software.
performance is to have parallel processing. With this However, companics often argue about the role that
method, multiple processors can be used simultancously hardware and software should play in the design of
to execute a single program or task, In parallel processing, processor architecture, Companies like Intel want the
a complex and large task is divided into smaller tasks in hardware to bear more responsibility than the software
such a way that cach task can be allocated to a processor. so that the software can be simple and casy; companics
Thus, multiple processors work together simultaneously like Apple, on the other hand, want the software to lead.
on the sub-parts of the task assigned to them, Based on these entirely contrasting opinions, there are two
Parallel processing systems need 4 special software to major processor architectures—complex instruction set
determine how the problem will be divided and then, at computer (CISC) and reduced instruction set computer
a later stage, how the sub-solutions will be combined to (RISC)
form the final solution of the problem.
Modern-day PCs implement parallel processing by using Complex Instruction Set Computer
dual-core processors or multi-core processors. Dual-core
Intel's hardware-oriented approach has given rise to CISC
architecture in which more complexities have been added
in the hardware to allow the software to be simpler, In
CISC machines, most of the instructions are implemented
using hardware. The hardware in such machines is capable
of understanding and executing the instructions. For
example, in a CISC machine, when multiplication needs
to be performed, the programmer just has to write the
Instruction | name of the instruction and its operands (¢.g., MUL 2, 3).
The processor will automatically load the data values in
Instruction 2 processor registers, multiply them in the execution unit,
and store the result. The advantages of CISC processors
Instruction 3 include the following
* Programs can be very simple and short,
Instruction 4 * Short programs require less memory space.
* Less effort is required by the translator (discussed
in Chapter 6) to convert the program into machine
(b) Machine cycle (with pipeline) language
Figure 3.20 Instruction execution with and without pipelining * Faster execution of instructions is possible.
Computer Memory and Processors 55
However, on the downside, CISC machines require companies to decide on the efficient use of space on W
additional hardware circuitry to handle instructions. microprocessor.
This adds to the complexity and cost of the processor's Although RISC machines are less complex and less
hardware circuitry. Therefore, CISC processors are more expensive, they place extra demand on programmers to
expensive than RISC processors. implement complex computations by combining simple
instructions. Unlike CISC machines, programs developed
for RISC machines have more lines of code. Therefore,
they require more memory space and more effort from a
Majorityof the PCs use CISC processors.
translator to convert the code into machine language.
* Pipelining is a technique with which the processor can * In parallel processing, multiple processors can be used
fetch the second instruction before completing the simultaneously to execute a single program.
execution of the first instruction.
>
GLOSSARY
Basic input output system (BIOS) Program that tells Offline storage Data storage device on which the data Is
the computer what to do when it starts up, e.g., running recorded and then physically removed or disconnected
hardware diagnostics and loading the operating system (off the computer). For example, magnetic tapes, floppy
into RAM. disks, optical disks, flash memory, and external hard disks.
Cache memory An intermediate form of storage between Optical storage Storing data on an optically readable
the ultra-fast registers and the RAM. medium by making marks in a pattern that can be read
Computer memory An internal storage area in the using a beam of laser light precisely focused on a spinning
computer used to store data and programs either disk. The most popular optical storage devices are
temporarily or permanently. CD-ROM, DVD-ROM, CD-R, and CD-RW.
Data transfer rate The time taken to transfer data or the Primary memory It is also known as main memory or
time taken to read/write to a disk. internal memory; the only type of memory that Is directly
Disk latency The sum of the seek time and the rotational accessed by the CPU, which continuously reads and
delay. It is actually the time taken to initiate a transfer.
executes instructions stored in the primary memory.
DRAM A type of RAM that must be refreshed multiple Programmable read-only memory A type of ROM that
times in a second to retain its data contents. can be programmed using high voltages,
Erasable programmable read only memory A type of Rotational delay The time taken to bring the target sector
ROM that can be erased and re-programmed. The EPROM to rotate under the R/W head
can be erased by exposing the chip to strong ultraviolet Seek time The time taken to position the R/W head over
light. the appropriate cylinder.
Flash memory A type of EEPROM in which the contents SRAM A type of RAM that holds data without an external
can be erased under software control. The most flexible refresh as long as it is powered. It is made of D flip-flops in
type of ROM. which the memory cells flip-flop between 0 and 1 without
Hard disk A set of disks stacked together like phonograph the use of capacitors.
records, which have data recorded electromagnetically in Superscalar processors Processors that can execute more
concentric circles known as tracks, than one instruction per clock cycle.
Instruction set A set of commands that instructs the System clock A small quartz crystal circuit that controls
processor to perform specific tasks. the timing of all operations within the computer system.
EXERCISES
Fill in the Blanks is a one-time programmable ROM
1, The memory holds data and programs that are 8. The flash memory is also a type of
currently being executed by the CPU. 9. Digital cameras and mobile phones have
2. memory is volatile. memory.
3, memory stores data or instructions 10, The number of cylinders of a disk drive is equal to the
permanently. number of
4. are the fastest of all forms of computer data 11. The process of writing data to a optical disk is called
storage.
5. Aprocessor register can store _ bytes. 12. The most popularly used software for writing data on
6, Static RAM is made of CDRsis_
‘Computer Memory and Processors 57
13. Data on a magnetic tape is represented using the (a) MAR (b) program counter
code (c) MBR (d) IR
| are concentric circles and _ are pie- 8. The speed of supercomputers is specified by
shaped wedges on a track.
{a) GHz (b) GIPS
15. The time taken to R/W data to a disk is called
(c) GFLOPS (d) all of these
16.____ unit directs and coordinates the computer
operations.
State True or False
17. Intermediate results during program execution are
1. Primary memory is faster than secondary memory.
stored in
2. Cache memory is made of ORAM
18. stores the address of the data or instruction to
3, L2 caches are built into the motherboard outside the CPU.
be fetched from memory.
4. An SRAM chip can hold more data than a DRAM chip of
19. Aninstruction consistsof and
the same size.
20. The instruction cycle is repeated continuously until
5. EPROM can be erased by exposing the chip to strong
ultraviolet light.
21. Buses in a computer system can carry
a 6. PROM allows its entire or selected contents to be
electrically erased
22. Inan instruction, specifies the computation to
7. Seek time is the time taken to bring the target sector to
be performed.
23. A: is the smallest unit of time in which
rotate under the R/W head.
processing is done.
8. CD-Rs can be written only once and can be read as many
times.
24. The speed of PCs and minicomputers is specified in
OF 9. Operating systems can read and write to flash drives
without installing device drivers
25. Gigais and tera is =
10. Memory cards use flash memory to store data.
26. processors are power-efficient processors
11. The ALU initiates action to execute the instructions,
12. The value stored in the program counter is copied from
Multiple-choice Questions
the MAR
1. The memory used by the CPU to store instructions and
data that are repeatedly required to execute programs 13. The program counter stores the address of the next
to improve overall system performance is instruction to be executed
14. The executing unit provides functions for data transfer.
(a) primary memory (b) auxiliary memory
15. A processor can perform all operations in a single clock
(c) cache memory (d) flash memory tick,
2. Magnetic tapes, floppy disks, optical disks, flash memory,
16. Computers can have at most one clock.
and hard disks are examples of
17. The speed of a mainframe computer is measured in MHz
(a) primary memory (b) auxiliary memory or GHz.
(c) cache memory (d) flash memory 18. Personal computers support pipelining.
3. The time taken to initiate a transfer is called 19. Pipelining needs replication of components
(a) seek time (b) rotational delay 20. Parallel processing can be implemented only on server
(c) data transfer rate (d) disk latency machines.
4. Disk address is specified using 21. In RISC machines, most of the instructions are
(a) sector number (b) track number implemented using hardware.
22. An instruction set can be implemented only using an
(c) surface number (d) all of these
opcode.
5. The memory used in MP3 players, PDAs, laptops, and
digital audio players is Review Questions
(a) primary memory (b) optical memory 1. What do you understand by computer memory?
(c) cache memory (d) flash memory 2. Differentiate between primary memory and secondary
6. The component of the processor that controls the flow memory.
of data through the computer system is 3. Give the characteristics of the memory hierarchy chart.
(a) BIU (b) execution unit 4. What is a BIOS? Which kind of memory is preferred in it,
(c) CU (d) ALU and why?
7. While transferring data from memory into the processor, 5. Differentiate between static RAM and dynamic RAM
the register that is used as an intermediate placeholder 6. Give the organization of computer memory. How does
of the data is the CPU access a memory cell?
58 ‘Computer Fundamentals and Programming in C
7. Explain the working of a magnetic disk. What do you understand by re-programmable ROM
8. How is data stored on optical storage devices? chips?
9. A DVD-ROM can store more data than a CD-ROM of the Discuss the different types of optical storage devices.
same size. Comment. Draw and explain the basic architecture of a processor.
10. What is a USB flash drive? ‘Control unit is the brain of the computer.’ Justify.
11. Write a short note on memory cards What are special-purpose registers?
12. Give the formulas used to calculate the storage capacity Define instruction cycle.
of magnetic disks, floppy disks, and magnetic tapes. Differentiate between pipelining and parallel processing.
Which of these have the highest storage capacity? How can pipelining improve processor performance?
Explain with the help of relevant examples. What are multi-core processors?
13, What is a head crash? How does it occur? Differentiate between RISC and CISC.
14. Briefly discuss the importance of cache memory.
>: _ _ Number Systems and
‘Computer Codes
TAKEAWAYS
* Number systems * BCD © Weighted codes
* Binary number system * ASC © Gray code
* Octal number system * EBCDIC * Unicode
* Hexadecimal number system * Excess code
Here, 123=1* 100+2*10+3*1 Step3: Repeat Step 2 until all the bits have been
or 123=1 10? +2 10'+3 = 10° Step4: Add the end result of each worked power of 2 to
The same concept is applicable to the binary number get the decimal number.
system, the only difference being that wherever 10 is used,
it is replaced by 2 as shown in Table 4.5.
4.3.2 Converting aDecimal Number into
4.3.1 Converting a Binary Number into
Binary Form
Decimal Form
To convert a decimal number into its binary equivalent,
In a binary number, all the columns are powers of 2. simply divide the decimal number by 2 and then write
Table 4.5 shows the five least significant digit place holders. down the remainder, repeat this process until the number
cannot be divided by 2 anymore,
Five leastsignificant
digitplaceholders
Example 4.4
(‘Sixteen's Eight’s Four's Twos One's i"
column | column | column | column | column (LSB) | Convert decimal 13 of (13),q into its binary equivalent.
2 oe || 2 Solution
2,13 |R
21641
Note that, in Table 4.5, all the columns are specified in 2 | 3 | 0 Now write the result starting from the
powers of 2. Hence, in order to convert a binary number
into its decimal equivalent, multiply that place holder value 2 | 1 [| 1 last remainder obtained, Therefore, (13),o =
(power of 2) with the bit, and then add all the products. 10} 1 (1102),
—___——
Example 4.2
Example 4.5
Convert 1101 into a decimal number.
Solution Convert 169 into its binary equivalent.
Use Table 4.5 to form the decimal number. Solution
Decimal number = 1x 27412? +0x2!+1x%2° 21 169|R
=1x8+1x44O0x2+1x1
2) 8i1
=8+4+0+1
=13 2) 4210
2) 210
24 30/1
21 510
i
2] 211 Nowwrite
the result starting from the last
Convert 1010 1001 into adecimal number.
21110 remainder obtained.
Solution
Decimal number = 1 x 2’ +0 x 2°+ 1% 2° +0 2*+1x2° | 0 | 1 Therefore, (169),,
=(1010 1001),.
+0x2?4+0x 2'+1%2°
=1x 128 +0x64+1x32+0x16+1x8+
Ox4+O0x241x1
4.3.3 Adding Two Binary Numbers
=128+0+32+0+8+0+0+1
=169 Adding binary numbers is similar to the addition of
The following steps summarize the procedure to convert a decimal numbers. While performing binary addition,
binary number into a decimal number. start by adding the bits (digits) in one column at a time,
from right to left as we do in the case of adding decimal
Step 1: Start with the least significant bit (LSB) and multiply numbers. However, to perform binary addition, one must
that bit with 2°. Note that any number raised to O is remember the rules of addition.
always 1,
Step 2: Continue working from right to left. Multiply each Rules of Binary Addition
bit with an incremental power of 2 (i.e., 2°, 27, 2°, + 0+0=0 *0+1=1 -1+0=1
2", ete). + 1+1=0, and carry | to the next more significant bit.
62 Computer Fundamentals and Programming in C
Consider the following examples: be used to restructure the subtraction problem into an
addition problem. This is called subtraction by the two's
0001010 1010101
+ 0100100 + 0101010
complement method.
0101110 Liditit Step 1: To subtract two binary numbers using two's
complement, first find the two’s complement of the
number to be subtracted (subtrahend). Two's complement
i Carry iii Carry is calculated in the following two steps:
1011 1010101
+ 0001 + 0101110
+ Complement cach bit of the number, That is, change |
to 0 and 0 to I. The resultant number is said to be in
1100 _10000011
one x complement form.
+ Add 1 to the resultant number in one’s complement
4.3.4 Subtracting Two Binary Numbers form to get the corresponding two ¥complement
Now that you have learnt to perform addition on two Step 2: Add the minuend and subtrahend (which is now in
binary numbers, subtraction will also be an casy task to two's complement form). Take care of the carries in each
perform. As with binary addition, there are certain rules column, and discard any carry bit that extends beyond
to be followed for binary subtraction. These rules can be the number of bits of the original number or the two's
summarized as: complement
* 0-0-0 *1-0=1 *1-1=0
However, an important point to note here is that when
+ 0—1=0, and borrow | from the next more significant bit subtracting binary values it is important to maintain the
same number of bits for cach number (minuend and
subtrahend). For this, you may pad the number with extra
Note that the value borrowed from the next more zeroes to the left of the value
significant bit depends on the base of the number system You should also remember to discard the carry obtained
and is always the decimal equivalent of the base. Hence, after adding the last bits. Observe the following examples,
in the decimal number system, 10 is borrowed, in binary which will help make the concept clear.
2 isborrowed, in octal 8 isborrowed, and in hexadecimal
16 is borrowed, Example 4.6
Consider the following examples Calculate 1011 — 1001 using two's complement method.
00 Solution
1011 10110111 +001 10
Step 1: Find the two's complement of the subtrahend.
- 1001 00110010 0101010
Subtrahend = 1001
0010 10000101 0101100
One’s complement of subtrahend = 0110
MW Two's complement of subtrahend = 0110 + 1 =0111
00 22 22 Step 2: Add the minuend and the two's complement of
104401 $000101 104401 the subtrahend.
—0011000 1011
~ 0101101 +0111 Now discard the carry from the last bit;
1.0010 hence the result = 0010.
2122
062002
libretto Minuend
1o1olid Subtrahend Example 4.7
OOM Difference
Calculate 10110111 — 00110010 using two's complement
4.3.5 Subtracting Two Binary Numbers Using method.
Two's Complement Solution
Though the previously discussed technique of subtracting Step 1: Find the two's complement of the subtrahend
two binary numbers is simple, there is another way to Subtrahend = 00110010
perform subtraction. In this technique, subtraction is One’s complement of subtrahend = 11001101
done through addition, Do you recall having learnt in Two's complement of subtrahend = 11001101 +1
school that a positive number subtracted from another = 11001110
positive number is the same as a negative number added Step 2: Add the minuend and the two's complement of the
to a positive number? This fundamental concept can subtrahend.
Number Systems and Computer Codes (os
10100 00000
11110 000000
1011000
1100011
111010= 101 = 100100010
4.4.1 Converting an Octal Number into
111010
Decimal Form
«101
111010 Try to recall what we did to convert a binary number into
0000000 its decimal equivalent; the same steps can be applied to
11101000 convert an octal number into decimal. The only difference
100100010 is that we will use base 8 insteadof base 2.
64 Computer Fundamentals and Programming in C
Tn order to convert an octal number into its decimal 8 | 12 | 2 Nowwrite the result starting from the last
equivalent, multiply that place holder value (power of 8) 8 | 1 |4 remainder obtained. Therefore, (786),, =
with the digit, and then add all the products
| 0 | 1 (1422),
Example 4.9 ——
Convert (123), into its decimal equivalent
Example 4.12
Solution
Use Table 4.6 to form the decimal number. Convert (9890), into its octal equivalent
Decimal number = 1 = 8? + 2x 8'+3x8° Solution
=1x64+2x8+3x1 8 |9890 | R
=64+16+3
=83
8 | 1236
|2
8 | 154 | 4
8 | 19 | 2 Nowwrite the result starting from the
8| 2 | 3 _ last remainder obtained
Example 4.10 “|
0 12 Therefore, (9890), = (23242),
Convert (10567), into its decimal equivalent
Solution
Decimal number = 1« 8°+0x8'+5x8?+6x8'+7x8° 4.4.3 Converting an Octal Number into Binary
= 14096 +0*512+5*64+6x8+7x1 Form
= 4096 +0 +320+48+7 To convert an octal number into its binary equivalent,
=4471 replace cach octal digit with its binary equivalent,
The following steps summarize the procedure to convert an
octal number into a decimal number.
Example 4.13
Step 1; Start with the least significant digit and multiply
that digit with 8°. Note that any number raised to 0 Convert (63), into its binary equivalent
is always 1,
Solution
Step 2: Continue working from right to left. Multiply each
digit with an incremental power of 8 (i.e., 8°, 8”, 8°, (63), can be converted into its binary equivalent using the
8', etc.) following steps:
Step 3: Repeat Step 2 until all digits have been multiplied Step 1: Write the binary equivalent of 6, which is equal to
Step 4; Add the end result of each worked power of 8 to 110.
get the decimal number. Step 2: Write the binary equivalent of 3, which is equal to
011
Step 3: Merge the two values. Therefore, (63), = (110011),
Let us take another example and convert (175), Into its
4.4.2. Converting a Decimal Number into binary form.
Octal Form Step 1: Write the binary equivalent of 1, which is equal to
001
To convert a decimal number into its octal equivalent,
Step 2: Write the binary equivalent of 7, which is equal to
simply divide the decimal number by 8 and then write 111
down the remainder; repeat this process until it cannot be
Step 3: Write the binary equivalent of 5, which is equal to
divided by 8 anymore.
101
Step 4: Merge thevalues. Therefore,(175), =(001111101),
Example 4.11
4.4.4 Converting a Binary Number into Octal
Convert decimal 786 or (786);o into its octal equivalent
Form
Solution
8 |786 | R To convert a binary number into its octal equivalent, divide
the binary number into groups of bits, where cach group
8 | 98 | 2 consists of exactly three bits (except the last). Convert
Number Systems and Computer Codes 65
Since 2 is less than 8, Since 4 is less than 5, ones. Then, working from right to left, we move to a 16's
we borrow I from the we borrow | from the column, a 256’s column, a 4096's column, a 65,536's
next immediate digit. next immediate digit column, and so on. In programming languages, prefix ‘Ox*
So 9 now becomes 8. So 7 now becomes 6 is used to indicate a hexadecimal number,
Moreover we get 10, Moreover we get 10.
80 now it's not 2 but so now it’s not 4 but 4.5.1 Converting a Hexadecimal Number into
10 +2= 12. 8 is finally 10 +4 = 14. 5 is finally | Decimal Form
subtracted from 12 and subtracted from 14 and
the result is written. the result is written. To convert a hexadecimal number to decimal, multiply the
value in cach position by its hex weight and add each value
Case 2
You can use the same concept while doing octal Example 4.15
subtraction, When we subtract two octal numbers, there
can be two cases:
Convert 0x3128 into its equivalent decimal value.
Solution
Case 1: The digit in the minuend is greater than the digit
in subtrahend. In this case, we just subtract the Decimal number = 3 x 16° + 1x 167 +2 16° +B x 16°
digits and write the result. = 3x 4096 +1 256+2*16+Bx1
12288 +256+ 32+ 11
Case 2: The digit in the minuend is smaller than the digit = 12587
in subtrahend. In this case, borrow | from the
immediate higher place. When a digit is borrowed,
the minuend digit at the current place gets 8 and Example 4.16
4 | is subtracted from the minuend digit at the
immediate higher place Convert hexadecimal 123 into decimal.
Consider the following examples
Solution
98
3108
Decimal number = 1 x 167 + 2% 16'+3 «16°
7654 Arve =1x256+2*16+3x1
= 256 +32+3
2341 =3654
$313 0334 =291
——
4.5.2 Converting a Decimal Number into
G8 HEXADECIMAL NUMBER SYSTEM
Hexadecimal Form
The hexadecimal number system is the base 16 number To convert a decimal number into its hexadecimal
system. It uses sixteen distinct symbols—the symbols 0-9 equivalent, simply divide the decimal number by 16 and
represent values zero to nine, and A, B, C, D, E, F (or af) then write down the remainder, repeat this process until it
represent values 10-15, Figure 4.2 shows numbers from cannot be divided by 16 anymore.
0 to 15 and their values in binary as well as hexadecimal
number systems. Example 4.17
The main problem with binary numbers is that, for larger
values, binary numbers quickly become too unwieldy Convert decimal 1239 into its hexadecimal equivalent
The hexadecimal (base 16) number system overcomes Solution
this problem, as hexadecimal numbers are very compact
Moreover, it is very casy to convert from hexadecimal to 16 11239 | R
binary and vice versa. 16 | 77 | 7 Nowwrite
the result starting
from the last
In the hexadecimal system, just like in the binary, 16 | 4 | D_ remainder obtained. Therefore, (1239),o
octal, and decimal number systems, we start counting
from the first column, which represents the smallest unit, | 0 14 =(407):6
Figure 4.2. Hexadecimal number system and its binary and decimal equivalents
Number Systems and Computer Codes (a
4: Merge the individual values. Thus, (567), = (101 Case 2: The digit in the minuend is smaller than the digit
110 111);. in the subtrahend. In this case, borrow | from
: Divide the binary number into groups of 4 binary the immediate higher place. When a digit is
bits. (Left pad the binary number
with zeroes if there borrowed, the minuend digit at the current place
are not enough bits to be grouped.) Therefore, gets 16 and a | is subtracted from the minuend
0001 0111 0111 digit
atthe immediate higher place.
Convert each group of binary bits into itsequivalent 15 23
hexadecimal number. Thus, we have 1 7 7. D218 16 EM1I7 7728
Merge the octal values to get the final result. Hence, 6A7B EASO FerD Exe
(567)s = (177)is. 2361 3 A87 -9 676 B3AD
471A ABO9 5 9A7 34DF
Example 4.22
WORKING WITH FRACTIONS
Convert (134), into its hexadecimal equivalent.
Solution In general, for a fractional number a, in any number system
Step 1; Write the binary equivalent of 1, which is equal to of base 4, the position values can be written as:
001.
Step 2: Write the binary equivalent of 3, which is equal to
011.
Step 3: Write the binary equivalent of 4, which is equal to The generalized table when used with specific base
systems can be given as in Table 4.7.
100.
Now let us use Table 4.7 to convert the following
Step 4: Merge the individual values. Thus, (134), = (001
numbers of base 6 into decimal.
011 100),.
Step 5: Divide the binary number into groups of 4 binary 1. Convert (101101110), into decimal:
bits, Therefore, (10110.1110))
=1 *28+0x 2+ 1x 2+1%2'4+0%
0000 0101 1100 Peixrterx2+ 1x 2940x294
Step 6: Convert each group of binary bits into its equivalent = 1X 1G+OKR+1 KAHL 2+OK1+
hexadecimal number, Thus, we have 5C. LX U2+ 1K 14+ 118 +0% 1/16
Step 7: Merge the hexadecimal values to get the final =16+0+4+2+0+05+0.25
+0.125+0
result. Hence, (134), = (5C)
x5.
= 22.875
2. Convert (127.35), into decimal:
4.5.7 Adding Two Hexadecimal Numbers (127.35), = 1 * 8 +2%8'+ 7% 8943x8445 x87
You can add two hexadecimal numbers in the same way
= 16442847143 «145% 1164
as you add decimal and octal numbers. When we add two
= 64 + 16 + 7+ 0.375 + 0.078125
hexadecimal numbers, there can be two cases: = 87.453125
Case 1; The sum is less than 16, In this case, we just write 3. Convert (21 F.DE))« into decimal:
the digit obtained after addition. (QQIR.DE),
5=2* 167+ 1* 16'+F * 16°+D x 16" +
Ex 167
Case2: The sum is greater than or equal to 16. In this =2*256+1* 16415 *1413 *16+
case, 16 is subtracted from the sum and the result 14 * 1/256
is written at that position. Moreover, a carry is =S512+ 16+ 15 +0,8125 + 0,0546875
given to the next digit. = 543.8671875
Consider the following examples:
Now that we have converted a fractional binary/octal/
1 111 111 hexadecimal number into its decimal equivalent, let us learn
1A2B 2C4A 5C8D 6E8C how the fractional part of a decimal number can be converted
+2361 +D287 +9676 +B3AD into its equivalent binary/octal/hexadecimal number.
3D8C FEDI F303 12239
Example 4.23
4.5.8 Subtracting Two Hexadecimal Numbers
Convert the decimal number 92.25 into its equivalent binary
When we subtract
two hexadecimal
numbers there can be number.
two cases: Solution
Case 1: The digit in the minuend is greater than the digit Break the number into two parts. The first part consists
of digits
in the subtrahend. In this case, we just subtract the before the decimal point, and the second part contains digits
digits and write the result. after the point. A separate procedure is applied to convert
Number Systems and Computer Codes 69
Convert 4567), to BCD 2.5. Give the BCD equivalent for the decimal number 68.23.
Solution Solution
From Table 4.9, we can write, From Table 4.9, we can write,
{4567)
x =(0100 0101 0110 0111) scoser: {68.23),9
=(0110 1000.0010
0011Jecpes2t
Number Systems and Computer Codes e
4.8.6 Unicode
ASCII, which is the most widely used encoding scheme, is
a 7-bit code that can support only 128 character definitions.
These 128 characters can be used casily for English
characters, numbers, and punctuation symbols but there is
2421 Code negligible or no support for the characters in other languages
of the world. Therefore, organizations started creating their
The 2421 weighted code has weights 2, 4, 2,and 1. In own encoding schemes for other languages’ characters,
this code, a decimal number is represented using 4 bits. thereby defeating the concept of a universal or standard code
The maximum weight in this code is2+4+2+1=9, for information exchange. Moreover, each new scheme was
Therefore, the 2421 code can represent decimal numbers of different length, and programs were supposed todetermine
from 0 to 9, as shown in Table 4,10. which encoding scheme they would be using.
Similarly,
in the 4221 coding. each digit isrepresented The only solution to this problem was to have a new
as a 4-bit group, and cach bit represents 4, 2, 2, and 1, encoding scheme that could unify all the different encoding
instead of 8, 4, 2, and 1. For example,7 in 4241 can be schemes to minimize confusion between the different
written as 1101, because 1 *4+1*2+0*%2+1*1=7. schemes. This led to the development of Unicode, which
can represent characters (including punctuation marks,
4.9.5 Gray Code diacritics, mathematical symbols, technical symbols, and
The gray code is a minimum change code, in which only arrows) as integers. It has several character encoding
one bit in the code changes from one code to the next. It forms such as the following:
is a non-weighted code. These codes are also known as UTF-8 Thisuses only eight bits t encode English characters.
single-distance codes. This format iswidely used inemail and onthe Intemet.
‘The gray code of a number is obtained from its binary UTF-16 This uses 16 bits to encode the most commonly
code, To derive the gray code of a number, the following used characters.A 16-bit Unicode can represent more
steps are used: than 65,000 characters. Moreover, any Unicode character
+ Copy the MSB of the binary code as the MSB of the represented in the UTF-16 form can be converted to the
gray code, UTF-8 form and vice versa without losing information.
* Repetitively add MSB and the bit next to the MSB to UTF-32 This uses 32 bits to encode the characters.
get the correspondingbit for the gray code. A 32-bit Unicode can represent more than 100,000
For example, letuscalculate the gray code of 7. characters.
Decimal
7=Binary 0111
Now gray code of 7 is obtained as follows:
* MSB of gray code 7 is 0 (because MSB of binary 7 is 0)
Now, other bits can be calculated
© O0+1=1
as:
Da ET
Besides representing the characters of different
+ 1+1 =0(discard the carry) languages, UTF also reserves some codes for private
+ L+1=0 (discard the carry) use, which hardware and software vendors can assign
Hence, gray code for 7 = 0100. internally for their own characters and symbols.
74 Computer Fundamentals and Programming in C
Nowadays, Unicode is widely used to represent text for computer processing, as it provides a consistent way of
encoding multilingual characters. This makes it convenient to exchange text files internationally. The growing popularity
of Unicode suggests that it will eventually supplant ASCII as the standard coding scheme.
Table 4.11 illustrates how coding is done in the ASCII, EBCDIC, XS3, 4221, gray, and Unicode coding techniques.
POINTS TO REMEMBER
* Computers are electronic machines that operate using Binary coded decimal (BCD) is a technique of
binary logic. These devices use two different values to encoding decimal numbers. In unpacked BCD
represent the two voltage levels (OV for logic 0 and SV representation, only one decimal digit is
for logic 1). represented per byte. In packed BCD representation,
* The number of unique digits used to form numbers two decimal digits are stored in a single byte.
within a number system is called radix of that system. ASCII is a 7-bit character code that was introduced
Decimal number system has a radix of 10, binary has a by ANS! and is used by personal and workstation
radix of 2, octal has a radix of 8, and hexadecimal has computers.
a radix of 16. EBCDIC is an 8-bit character encoding technique used
To convert a decimal number into its binary/octal/ on IBM mainframe operating systems. It is considered
hexadecimal equivalent, simply divide the decimal to be an obsolete coding system, but Is still used in
number by 2/8/16 and then write down the some equipment to allow for continued use of
remainder, software written many years ago that requires an
To convert a binary/octal/hexadecimal number into EBCDIC communication environment,
its decimal equivalent, multiply the place holder * In the excess-3 coding technique, each decimal
value by the digit, and then add all the products. digit is the 4-bit binary equivalent with 3 (0011)
Signed number representation is required to encode added.
negative numbers in the binary number system. * Gray code is a minimum change code, in which only
* The two’s complement is the most popular method ‘one bit changes from one code to the next.
of representing signed numbers in the binary
number system.
GLOSSARY
Binary number system It is a number system of base 2 Hexadecimal number system It is a number system of
Bit It is short form of ‘binary digit’; smallest possible unit base 16.
of data; can be either 0 or 1. Nibble It is a group of four binary digits.
Byte It is a group of eight bits. Octal number system it is a number system of base 8,
Decimal number system It is a number system of base 10. Word It is a group of 2 bytes.
Number Systems and Computer Codes 75
EXERCISES
Fill in the Blanks 10. Computers can define a word of four bytes.
1, Computers are electronic machines that operate on
logic. Review Questions
2. bits make one word, 1. What is binary language?
3.0-1 =_ -_ 2. Why do computers understand only binary language?
4. Inthe _____ technique, the MSB is used to denote 3. Explain the process of converting a binary number into
the sign of the number. decimal with an example.
5. In , the digit is stored in the lower nibble, and Describe the general procedure to convert a number
the higher nibble is not relevant to the value of the from any base system into its decimal equivalent. Explain
represented number. using examples the conversion of numbers from any
6, ASCII codes can support characters. three base systems to the decimal system.
7, EBCDICisa__ bit character encoding technique. How can two numbers be subtracted only through
8. The hexadecimal number system uses digits from addition? Explain with the help of an example.
to How are signed numbers represented in the binary
9. The octal number system was used in the _ form?
system. Two's complement is the most popular technique to
10, Working from right to left, the colurnns in the hexadecimal represent signed numbers. Justify the statement.
number system are Differentiate between packed and unpacked BCD
representations.
Multiple-choice-Questions How is the 8421 code different from the 4221 code?
1. The code that is easier to use on punched cards is Give the gray code for the decimal number 13
(a) ASCII (b) EBCDIC Convert the following numbers into the decimal number
system.
(c) Excess-3 (d) BCO
2, The code also known as single-distance code is {a) (1011 0101),
(a) ASCIL (b) EBCDIC (b) (5674),
{c) Excess-3 (d) gray code {c) (A1E2),6
3, The coding technique in which the upper nibble is {d) 0000 1001 (unpacked BCD)
padded with 1111 is (e) 1000 0001 (packed BCD)
(a) ASCII (b) EBCoIC Convert the decimal 987654 into octal and hexadecimal
number systems.
(c) Excess-3 (d) gray code
4, 12345 in octal is_ in decimal. Convert 1001 0010 1110 into the hexadecimal number
system.
(a) 5439 (b) 5349 Convert 89CD into the binary number system.
(c) 4593 (d) 4359 Subtract:
5, 98765 in decimal is in hexadecimal
(a) 10101011 -01111
(a) 1¢81D (b) C1810
(b) 11100001 ~ 11110111
(c) 181¢D (d) C0181
{c) 1010101010 ~ 111101
16. Add:
State True or False
1, Abyte is a group of eight bits. (a) 10101011 + 0111111
2, Bits 4 through 7 form the lower nibble. (b) 11100001 + 1121110111
3. l+1=1 {c) 1010101010 + 111101
4. The two's complement method can be used to 17 Multiply:
restructure a subtraction as an addition problem. (a) 10111 x 1011
. The octal number system uses digits from 0 to 8. (b) 1111000 100
au
. The two's complement of a negative number is obtained
(c) 1121101 * 1111
by negating the bits of its positive counterpart.
18. Divide:
7, In packed BCD representation, two decimal digits are
(a) 10121110/1011
stored in a single byte.
8, ASCII digits are examples of unpacked BCD numbers. (b) 1111000/100
9. ASCII supports more number of characters than EBCDIC. (ec) 1121101301/1111
Boolean Algebra and
~~ ‘Logic Gates
TAKEAWAYS
© Boolean algebra © Truth tables © Universal gates
¢ Venn diagrams * Canonical forms * Karnaugh
map (K-Map)
* De Morgan's
law © Logic gates
VENN DIAGRAMS
A Venn diagram can be used to represent Boolean
operations using shaded overlapping regions. In the Venn x
Yi, x wy
diagrams that are presented in this section, there is one
Figure 5.5 Venn diagrams for double negation law
circular region for cach variable, The interior and exterior
of aregion ofa particular variable corresponds to values 1
(truce) and 0 (false), respectively, The Venn diagrams De Morgan’s
Law: x Oy’ =(x Uy)’
corresponding to AND, OR, and NOT operations are To visualize De Morgan's law, for the left-hand side
shown in Figure 5,3. Here, the shaded area indicates the (LHS), shade the area that is neither in x nor in y. Then, for
value | of the operation and the non-shaded area denotes the right-hand side (RHS), shade the area corresponding to
the value 0, x Uy, which is the area in eitherorboth the circles, Finally,
shade the area that is not in the region of x U y. It canbe
seen from Figure 5.6 that it is the same area that we had
shaded for the LHS.
voy vuy 7 Y
Figure 5.3 Venn diagrams for conjunction (AND),
disjunction (OR), and complement (NOT) ay ny
ZY
Yt
avy leayy
The following points can be observed from Figure 5.3: Figure 5.6 Venn diagrams for De Morgan's law
* For the AND operation, the region common to both
circles is shaded to indicate that x 9 y is | when both
variables are 1, The non-shaded area indicates that x Oy
is 0 for the other three combinations of variables x and y.
TRUTH TABLES
* For the OR operation, the regions that lic inside eitheror
A truth table is used to describe a Boolean function of
both the circles are shaded.
n input variables. It lists all possible values of input
* For the NOT operation, the Venn diagram represents combinations of the function and the output that will
complement x’ by shading the region nof inside the be produced based on these input combinations. Such
circle,
a table provides a useful visual tool for defining the
Venn diagrams are useful to understand and visualize the input-output relationship of binary variables in a Boolean
following laws of Boolean algebra. function.
78 Computer Fundamentals and Programming in C
A Boolean function of'n variables has 2" rows of possible term OR’ed with a | is always | and a term AND‘ed with
input combinations, Each row specifies the output of the a 0 will always result in 0.
Boolean function for a different combination. The truth |. A+0=A
tables for the Boolean operators are shown in Table 5.1 If A = 0, then 0 + 0 = 0, which is equal to A
If A = 1, then 1 +0 = 1, which is again equal to A
Lee Truth tables for Boolean operators 2. At+1=1
| AND OR NOT IfA =0, then 0+1=1
\| a [z=A.8 | 4 |B |Z=AsB 4 |Z=a IfA= 1, then 1 +1=1
jo 0 oy) ww 0 on 8 3. A-0=0
}o a oO” me 1 1 0 IfA = 0, then 0-0 =0.
IfA= 1, then 1 0=0.
|i @ om) Wwe 1
WEEE i Gl 1 4. A*1=A
IfA= 0, then 0+ 1 0, which is equal to 4
IfA=1,then ts 1 1, which is again equal to A
A truth table can also be used to represent one or more
Boolean functions, For example, Table 5.2 represents the 5.4.2 idempotency Law
truth table for the Boolean function Z= 4 U(B OC).
The idempotency law states that a term AND’ed with itself’
or OR’ed with itself is equal to that term
Truth tableforBoolean function 2= AU (8) 1. A+A@A
A la c Ipnc |ZuAs(BUq) If A = 0, then 0 + 0 = 0, which is equal to A
0 0 ) ° ° IfA = 1, then | +1 = 1, which is again equal to A (here,
A + B means a true valuc, that is, a non-zero value),
0 0 1 0 o
2. A*A=A
0 1 0 0 o IfA= 0, then 0° 0 0, which is equal to A
0 1 1 1 1
IfA=1,then ls 1, which is again equal to. A
1 0 0 ° 1
1 0 1 0 1 5.4.3 Complement Law
1 1 0 0 i The complement law states that a term AND'ed with its
\ 1 1 1 ! 1 comple-ment always results in 0 and a term OR'ed with
its complement always results in |
|, A+A'=1
23 Basic LAWS OF BOOLEAN ALGEBRA IfA= 0, thenO+1=1
IfAw@ 1, then 1 +01
The laws of Boolean algebra can be divided into two
2. A-A'=0
categories—laws applicable on a single variable and laws IfA=0, then 0-1 0, which is equal to 0,
applicable on multiple variables (Figure 5.7).
IfA=1, then 1-0 0, which is again equal to 0
Truth table to prove the commutative law Truth table to prove the associative law
of the OR operator of the AND operator
A B A+s B+a A B c 4-(8-C) | (A- Bye
0 o 0 0 o 0 o o 0
0 1 1 1 0 0 1 0 0
1 0 1 i 0 1 0 0
1 1 1 1 o ' 1 0 0
1 0 0 o 0
i 0 ! 0 i}
2. A*B=B-A 1 1 0 0 0
Table 5.4 shows the truth table of the Boolean functions, 1 1 1 i 1
which proves this law
=A BU +C)+A CL +B)
1S: Truth table to prove the second distributive law A+ B+A'C=RHS (Since 1+C=1
ie
is, m/ = M,. It is possible tocheck this, (A’ « BY ' = 4+ B.
Multiply each term with the sum of the missing variable and Therefore, in a maxterm, 0 will be represented in the
its complement. Therefore, un-complemented form and I will be represented in the
FIA, B, C)= AB’ (C+ C’) + BC (A+A')+ AC (8 +8") complemented form.
= AB'C
+ AB'C + ABC + A'BC + ABC + ABC
By looking at the truth table, we can say that the XOR
= AB'C + AB'C’ + ABC’ + A’BC’ (Because A+A=A)
function can be represented as the product of the maxterms
or the canonical POS form as follows:
= 101+ 100+110+010
=me+my+m,_+myz F(A, B)= (A +B)» (A' +B’)
Therefore, the canonical SOP form of the given Boolean expres-
The shorthand
notation is as follows:
sion can be given asfollows:
F(A, B, C)= ms + mg + me + mz oFFIA, B, C)= Em(2, 4, 5, 6) FIA, B) = Mo-My or F(A, B) = TIM(0, 3)
Example 5.2
Let us consider some examples of sum terms and maxterms
for a function of three variables A, B, and C: Convert F(A, B, C)= (A+ B')(8 + C’) tothe canonical POS form.
Sum terms 4,4 + 8, B+ C,A' +B, A’ + BY Solution
Maxterms 4+B+C.A+B'+C,
A+ B+ CA +B +O Add each term with the product of the missing variable and
its complement. Therefore,
A maxterm is represented by a symbol M,, where the
subscript / is the decimal equivalent of the maxterm. For FIA, B, C)= [(A+ B')+ (C- CYB + C) +(A A’)
example, consider the truth table of the XOR operation S(AtB'+C-CYB+C
+A A)
given in Table 5.13 and note the corresponding maxterms. Using the distributive
law, we can write
FIA, B, C)= (A+B + CiA+ B+ CVB+C + Al(B+C +A’)
Truthtable ofXORoperation =(A+ B+ CYA+B'+C}A+B+C)(A'+B+C)
= (010)(011)(001){101)
= (Mz(M3)(M,)(Ms)
Therefore, the canonical SOP form of the given Boolean
expression can be given as
FA, B, C)=M,-M,°M, + M, orF(A,8, C)=NM(1, 2, 3, 5)
LOGIC GATES
Only those input combinations for which the function
produces 0 as the output are considered tofind the product We have seen that computers work on binary digits, which
of maxterms. form the heart of digital electronics. In digital electronics,
It should be noted that for My we have written My = We are not concemed about electrical signals; rather,
A+ B and not A’ + B'. This is because any minterm m, we just need to understand the difference between two
is the complement of the corresponding maxterm M,, that States: on (1) and off (0). Moreover, in digital electronics,
Boolean Algebra and Logic Gates 83
operations are performed using logic gates, which are also gate accepts two inputs and retums 0 if both the inputs areTy
known us Boolean gates. These gates work only on the else retums 1. The truth table of the NAND gate is given in
logic that comprises cither a 0 or 1. There are different Table 5.17, The expression involving a NAND operation can
types of Boolean gate ch of which follows a different be written as Input, |Input), or Input, Input)
set of rules. In this section, we will discuss Boolean gates
and sce how Boolean expressions can be represented using Lo eee® Truth table of NAND gate
these gates in digital electronics.
Input, Input, Output
AND gate The AND gate is represented with the> symbol 0 0 1
This gate accepts two inputs and gives an output. The output
will be | if and only if both the inputs are 1, and will be a 0 0 1 1
otherwise. The truth table of the AND gate is given in Table i 0 1
5.14. The expression involving an AND operation can be 1 1 0)
written as Input) © Input, or Input, «Input,
NOR gate The NOR gate is represented using the 2
LELICEB GR Truth table of AND gate symbol. In addition, it is known as the negated OR“or
Input, Input; Output NO OR gate. It is just the opposite of the OR gate, The
0 0 0 NOR gate accepts two inputs and returns | only if both the
inputs are low (0). The truth table of the NOR gate is given
0 1 0 in Table $,18. The expression involving a NOR operation
1 o 0 can be written as Input;—Inputy, or Input; + Input,
1 1 1
Le Eee Truth table of NOR gate
OR gate The OR gate is represented with the } > symbol Input, Input; Output
This gate accepts two inputs and gives an output. The
output will be | if any of the two inputs is 1. That is, 0 ) 1 |
it gives a 0 output only when both the inputs are 0. 0 1 0 |
The truth table of the OR gate is given Table 5.15. The 1 0 0
expression involving an OR operation can be written as 1 1 0 }
Input, \ Input, or Input, + Input).
XOR gate The XOR gate is represented using the —))-
Cee ee Truth table of OR gate symbol. The X in the XOR gate stands for exclusive, This
Input, | Input; Output means that the output from this gate will be | if only one
| 0 0 0 of the inputs is a 1, but not both. Notice in Table 5.19 that
| 0 1 i the output is a 0 if both the inputs are | or 0. In general, the
output of the XOR gate is | when the number of its high
} 1 0 1 inputs is odd. The expression involving an XOR operation
\ I 1 1 can be written as Input; ® Input. This also means that the
output will be 1 if the inputs are different
NOT gate The NOT gate is represented by the -}e- symbol
Unlike the AND and OR gates, the NOT gate accepts just one if eece Truth table of XOR gate
input, The output produced by a NOT gate is just the opposite
of the input given, For example, if the input is | the output is Input, Input, T Output
0, and vice versa. The expression involving a NOT operation 0 0 0
ean be written as NOT Input, or as ~Input, or as Input’ 0 1 1
Table 5.16 shows the truth table of this gate 1 0 I
1 1 °
Truth table of NOT gate
Input Output XNOR gate The XNOR gate is represented using the ~)>
| 0 i symbol. In addition, it is known as the negated XOR or NO
\ 1 r XOR gate and is just the opposite of the XOR gate. The
XNOR gate accepts two inputs and returns | only if both the
NAND gate The NAND gate is represented using the | > inputs are same and a 0 otherwise. The expression involving
symbol. In addition, it is known as the negated AND or NO an XNOR operation can be written as Input, ® Inputy .The
AND gate. It is just the opposite
of the AND gate. The NAND truth table of the XNOR gate is given in Table 5.20.
84 Computer Fundamentals and Programming in C
pe
(b) OR operation of the first parentheses
0 1 0 ]
' o 0 |
\ It t 1 }
(c) NOT operation
i)
LOGIC DIAGRAMS AND BOOLEAN
EXPRESSIONS
(d) OR operation of the second parentheses
A logic diagram is a pictorial representation of a
combination of logic gatestospecify a Boolean expression.
Therefore, we can directly obtain the Boolean expression
by analysing the circuit diagram or vice versa.
Let us first convert a logic circuit diagram to a Boolean
expression. In order to do this, first list the inputs at the
correct place and then process the inputs through the gates
by considering one gate at a time. Write the output of cach
gate, This will give you the resulting Boolean expression (¢) OR operation of the two parentheses
of cach of the gates. For example, consider the logic circuit
diagram given in Figure 5.9. Let us use this diagram to
obtain its cor-responding Boolean expression.
apt A")
A UJ (A' By +
c
(B+)
(f) Redrawn figure with single inputs of each input variahle
dD
wo (Be C+D EY Figure 5.10 Conversion of Boolean expression into logic
& diagram
pp «Dp
(Figure 5.11).
c
Example 5.6
Figure 5.11 Representation of a NOT gate
Represent Y = (A + 8) -C using logic gates.
using a NAND gate
Solution
Ye(A+B)c
AND Gate
Represent Y = (A 8) + (C- D) using logic gates. Figure 5.12 Representation of an AND gate
using a NAND gate
Solution
Y=(A- B)+(C- D) OR Gate
aos AB An OR gate can be implemented using a NAND gate as
shown in Figure 5.13
>>>
Y=(A-B)+(C-D)
cD
Example 5.8
Figure 5.13 Representation of an OR
Represent Y= (A+B) + C- D+ (E> F) using logic gates. gate using a NAND gate
Solution
Conversion of Boolean Expression into Circuit
Y=(A+B)+C- D+E-F)
Diagram using NAND Gates
The following are the steps to convert a given expression
into a circuit dia-gram using only NAND gates:
* Read the expression carefully and draw its corresponding
circuit diagram
* Replace every AND, OR, and NOT gate with its
equivalent NAND gate.
* Redraw the circuit.
Identify and remove double inversions (i.c¢., back-to-
back inverters, if any).
* Redraw the final circuit
GED universat Gates
Example 5.9
Universal gates are those gates that can be used for
implementing any gate such as AND, OR, and NOT. The two Y¥=A+(8-C) has been represented using AND and OR gates
important universal gates are the NAND and NOR gates. Represent it using NAND gates.
86 Computer Fundamentals and Programming in C
c ae
Solution
pp “D-
Yru Mec
A Ree (A Ry+e
Figure 5.14 Representation of a NOT
ee
gate using a NOR gate
OR Gate
The OR gate is a NOR gate followed by a NOT gate
(Figure 5.15)
>
B a >.
Figure 5.15 Representation of an OR
gate using a NOR gate
AND Gate
From the truth tables, we can observe that an AND gate
gives the output as 1 when both inputs are 1, whereas a
NOR gate outputs | only when both inputs are 0. This
Boolean Algebra and Logic Gates 87
GE) simpiFicaTion OF BOOLEAN Locke) Truth table and K-map for four variables
EXPRESSIONS USING KARNAUGH MAP A |B) C | D | Outpuy
# c@: 0) 16 0
Karnaugh map (K-map) is a tool to represent Boolean
functions of up to six variables. It is a pictorial method ooo1 1
to minimize Boolean expressions without using oo1o 0
Boolean algebra theorems and equations, thereby CK Ope we 0
making the process of minimization simpler, faster, o 1 o 0 0
and efficient
An n-variable K-map has 2n cells where cach cell
Omms !
corresponds to an n-variable truth table value. The cells 6) find HY 1 0
in a K-map are arranged in such a way that adjacent cells ol el tae o
correspond to truth rows that differ in position by only one 100 0 0
bit (logical adjacency). i) oy io 1
K-maps can be casily used to represent expressions
€]) (Oi EG Ke 0
that involve two to four variables, expressions with
five to six variables are comparatively difficult but
3 Ga Ha 0
achievable, but expressions with seven or more 45 [el FO FS 0
variables are extremely difficult (if not impossible) to 7 Del tol 1
minimize using a K-map. gt aber OB )
Consider the truth table of two variables and observe 7 el 0
the K-map for this truth table (Table 5.21). A cell of the
K-map contains a | if the output value for 4 and B in the
truth table has a 1 Rules for Minimization
Let us consider the truth tables of three (Table 5.22) and The following are the rules for minimizing an expression
four (Table 5.23) variables and observe the K-map for
using a K-map
these tables,
Rule | Form groups of cells in such a way that a group
should not include a cell with a zero value.
ceeey Truth table and K-map for three variables Rule {1 Groups may be formed either horizontally or
vertically, They cannot be formed diagonally
A|BIC Output ¥
}o 0 0 1 B
}o o 4 : \ pt
a pesos:
a oe |
|o ao S ~~ e oo
1 0; 0
(esd IEA 9 0 1T1]lo]o
ectehk Sie Se : cane |
eae :
(ca
i|
generally
2"cells. 00" 01 ll 10
Example 5.11
oo Ol tt 10
Cae
pated minnie
Example 5.12
Rule VI Groups can be = around the table. For Consider the expression Y= A’: B'-C' +A’: B'.C
example, the leftmost cell in a row can be grouped with +A’. B+ C+A’-B-C and minimize it using aK-map,
the rightmost cell. Similarly, the topmost cell in the table
may be grouped with the bottommost cell in the group.
in the group of 1s, we
see that the output is
independent of the values
of B and C. This is because
there is a 1 when B = 0
as well as when B = 1.
Similarly,
there is a1 when
C =0 as well as when C = 1. However, the output is 1 only
when A =0 or A’ = 1. Therefore,
Y= A’.
Leftmost cell
Example 5.13
Rule Vil The number of groups should be as small as
possible (provided any of the earlier-stated rules are not Consider the expression Y=A’»B'-C+A'-B-C+A+B'-C+
violated). A-8> Cand minimize itusing aK-map.
Boolean Algebra and Logic Gates 89
Consider
the expression Y=A'-B'-C'+A'-B+A-8-C'+A-C
and minimize it using K-map.
Solution
A B's
C +A B+ A+B: C +A>Ccan be expanded
as,
ABU C4+A'B(CHC)4A-B-C+A-C (B48)
AB CHA BS C+A B CHA B CHA CBAC 8.
Hence, the K-map can be drawn as
[[Group wt |
Group Il
POINTS TO REMEMBER
© Computers understand only binary numbers, in which to represent a Boolean function. This helps them to
only the digits0and 1 are used. A complex proposition reduce the number of logic gates for simplification
can be easily stated in terms of binary variables (two and minimization of digital circuits. A canonical form
variables) and binary operators (OR, AND, and NOT). can be either a sum of minterms or a product of
Boolean operators take certain inputs and produce an maxterms.
output based on a predetermined table of results . A logic gate or Boolean gate is an electronic circuit,
{also known as the truth table). A truth table lists all which acts as a basic building block of any digital
possible values of input combinations of the function system.
and the output that will be produced based on these . NAND and NOR gates are known as universal gates
input combinations, because they can be used to implement all other logic
A Venn diagram can be used to represent Boolean gates.
operations using shaded overlapping regions. Karnaugh map (K-map) is a tool to represent Boolean
¢ A variable or a complemented variable is called a functions of upto six variables. A n-variable K-map has
literal. Designers of logical circuits prefer to use a 2" cells where each cell corresponds to an n-variable
standardized form of literals called the canonical form truth table value.
90 Computer Fundamentals and Programming in C
GLOSSARY
Boolean expression A combination of Boolean variables making the process of minimization simpler, faster, and
and Boolean operators. efficient.
Boolean function A function that has one or more input Maxterm A canonical sum (or a canonical product of
variables and generates an output based on these input sums) term.
values, which may be 0 or 1. Minterm A canonical product (or a canonical sum of
K-map A tool to represent Boolean functions of up to six products) term.
variables, which minimizes Boolean expressions without Truth table A table used to describe a Boolean function
using Boolean algebra theorems and equations, thereby of n input variables.
EXERCISES
12 Explain the steps to convert a POS expression into the Implement the expressions given in Question 16 using
canonical POS form with the help of an example. NAND gates
13, Convert F(A, B, C) = (A' + B')(8' + C) to the canonical POS Implement the expressions given in Question 16 using
form. NOR gates.
14. What are logic diagrams? How are they useful? Write a short note on K-maps
15. Draw the logic diagram for the Boolean expression Y = Draw a K-map and simplify the Boolean expression given
(A-B+C -D)+(A'+Dd) by fix, y, 2) = Zm(0, 2, 3, 4, 6, 7)
16. Implement the following expressions using logic gates
(a) Y=(A-8)+(C-D)-E
(b) Y=A4(C+D)-(A-B)
Pm 4
+ Sos >
Computer Software
a”
TAKEAWAYS
© System software © Application software * Command interpreter
* BIOS © Pre-written software * Mobile operating systems
© Operating systems © Customized software * Generations of programming
© Utility software © Productivity software languages
* Translators * Microsoft Office
Computer system
Computer software can be broadly classified into two Differences between system and application
groups, namely application software and system software. software
* Application software is designed for users to solve a System software ] Application software
particular problem. It is generally what we think of when
Itis a collectionof programs —Itisa collection of programs:
we refer to a computer program. Examples of application that cnable users tointeract —_written fora specific application,
software include spreadsheets, database systems, desktop with hardware components — such as a library system,
publishing software, program development software, efficiently. inventory control system, and
games, and web browsers. Simply put, application © 08,
sofiware represents programs that allow users to do
Ktcontrols
and manages the —_It uses the services provided by
something besides merely run the hardware. hardware. the system software to interact
* On the contrary, system sofiware, provides a general with hardware components,
programming environment in which programmers can
Tt is machine-dependent. Itis machine independent,
create specific applications to suit their needs, This
The programmer must Tn most cases, the programmer
environment provides new functions that are not available
understand
the architecture ignores the architecture
ofthe
at the hardware level and performs tasks related to executing of themachine and hardware —machine and hardware details to
the application program. System software represents details to write system write application software,
programs that allow the hardware to run properly. It acts as software.
an interface between the hardware of the computer and the
Itinteractswith the hardware It interacts with the hardware
application software that users need to run on the computer. directly, indirectly through system calls
Figure 6.2 illustrates the relationship between application provided by system software.
sofiware and system software,
Writing
system software isa = Writing application programs ix
Table 6.1 lists the differences between system and complicated task. relatively easy.
application softwares. Examples include compilers Examples include Microsoft
inn Ans ee eee ee
6.2.1 System Software
S stem software is computer software designed to operate BIOS is built into the computer and is the first code run
computer hardware and to provide and maintain a platform by the computer when it is switched on. The key role of
for running application software. Some of the most widely BIOS is to load and start the operating system (OS).
used system software are discussed in this section. When the computer starts, the first function that BIOS
performs is to initialize and identify system devices such
Computer BIOS and Device Drivers as the video display card, keyboard, mouse, hard disk,
CD/DVD drive, and other hardware. In other words, the
Basic Input/Output System (BIOS) and device drivers code in the BIOS chip runs a series of tests called POST,
provide basic functionality to operate and control the which stands for power on self test, to ensure that the
hardware connected to or built into the computer. system devices are working correctly
94 Computer Fundamentals and Programming in C
System profilers can be used to provide detailed the interpreter, on the other hand, translates the instructiony
information about the software installed and hardware into an intermediate form, which it then executes.
attached to the computer. Usually, a compiled program executes faster than
* Anti-virus utilities are used to scan the computer for an interpreted program. However, the big advantage of
viruses, an interpreter is that it docs not need to go through the
* Data compression utilities are used to compress files to compilation stage during which machine instructions are
a smaller size, generated. This process can be time-consuming if the
Cryptographic utilities are used to encrypt and decrypt program is long. Moreover, the interpreter can immediately
fil execute high-level programs,
Launcher applications are used as 4 convenient access In summary, compilers and interpreters both achieve
point for application software similar purposes, but are inherently different in how they
Registry cleaners are used to clean and optimize the achieve that purpose,
Windows registry by deleting old registry keys that are
Assembler Since computers can execute only codes written
no longer in use. in machine language, a special program called assembler i
Network utilities are used to analyse the computer's required to convert the code written in assembly language
network connectivity, configure network settings, and into an equivalent code in machine language, which contains
check data transfer or log events. only 0s and Is. An assembler takes an assembly language
Command line interface (CLI) and graphical user
progmum as an input and gives a code in machine language
interface (GUI) are used to interface the operating
(also called an object code) as output. There is a one-to-one
system with other software. correspondence between the assembly language code and
the machine language code, However, if there is an error,
Translators the assembler gives a list of errors. The object file is created
only when the assembly language code is free from errors.
In this section we shall discuss the functions of translators The object file can be executed as and when required,
which are computer programs used to translate a code
written in one programming language to a code in another
language that the computer understands.
An assembler only translates an assembly program into.
Compiler A compiler is a special type of program that machine language, the result of which is an object
file
transforms source code written in a programming language that can be executed. However, the assembler itself does
(the source language) into machine language comprising not execute the object file.
just two digits, 1 and 0 (the farget Janguage). The resultant
code is known as the object code. The object code is the
one that will be used to create an executable program. Linker
Therefore, a compiler is used to translate the source code A linker, also called /ink editor and binder, is aprogram that
from a high-level programming language to a lower level combines object modules to form an executable program.
language (c.g., assembly language or machine code). Generally, in case of a large program, the programmers
If the source code contains errors, then the compiler will prefer to break the code into smaller modules, as this
not be able to execute its intended task, Errors that limit simplifies the programming task. Eventually, when the
the compiler in understanding a program are called syntax source code of all the modules has been converted into
errors. Syntax errors are similar to spelling mistakes or object code, these modules need to be put together, This
typing mistakes, Another type of error is the logical error, is the job of the linker. Usually, the compiler automatically
which occurs when a program does not function accurately invokes the linker as the last step in compiling a program.
Logical errors are much harder to locate and correct
The work of a compiler is simply to translate human- Loader
readable source code into computer-executable machine
code. It can locate syntax errors in the program (if any), but A loader is a special type of program that is part of an
cannot fix it, Until and unless the syntactical error is rectified, operating system and which copies programs from a storage
the source code cannot be converted into object code. device to the main memory, where they can be executed.
Interpreter Similar to the compiler, the interpreter also Debugger
executes instructions written in a high-level language.
Basically, a program written in a high-level language can Debugging is a necessary step in software development
be executed in any of the two ways— by compiling process. Since itis verycommon for real world applications
the program, and second, by passing the program through to have thousands of lines of code, the possibility of having
an interpreter. errors in them cannot be ruled out. Therefore, identifying
While the compiler translates instructions written in a high- bugs (errors) and removing them as early as possible is
level programming language directly into machine language, very important.
96 Computer Fundamentals and Programming in C
Debugging tools, commonly known as debuggers, ‘CD-ROM and the agreement is wrapped with a plastic
are used to identify coding errors at different stages of
film that isshrunk byheat toform a seal onatight-fitting
software (or program) development. These days, many
package. This bundled software is known as shrink-wrap
programming language packages have a facility for
checking the code for errors while it is being written. software.
A debugger is a program that runs other programs Once the customer buys the software and opens the
allowing users to exercise some degree of control over package, he is bound by the license agreements and
their programs so that they can examine them when things other terms and conditions specified in the document.
go wrong. A debugger helps the programmer to discover However, in recent times, the trend is shifting towards
the following things electronic delivery of software, using the Internet. Thisis
called click-wrap software. Agreements for such software
* Which statement or expression was being executed
are found only on the Internet as a part of the installation
when the error occurred?
process. All inall, click-wrap software is the electronic
* If an error occurred during the execution of a function,
what parameters were passed to it while it was called? equivalent of shrink-wrap software.
What is the value of variables at different lines in the
program? 6.3| Acquiring Computer Software
What is the result of evaluating an expression?
What is the sequence of statements actually executed in When we buy a computer, we ure just purchasing the
a program? hardware. Now, we know that in the absence of required
When a program crashes, debuggers show the position software, the computer is just a useless box. Therefore,
of the error in the program. Many debuggers allow buying a computer is just not enough; to make the
programmers to run programs in a step-by-step mode. computer functional and useful, we need to acquire some
They also allow them to stop on specific points at which software, which can be acquired in three ways as follows:
they can examine the value of certain variables.
6.3.1 Buying pre-written software
6.2.2 Application Software Nowadays, many pre-written software packages are
Application software is a type of computer software that already available in the market, We just need to find
employs the capabilities ofa computer directly to perform a one that best meets our requirements. Here, requirement
user-defined task. This is in contrast with system software, means two things. First, compatibility with the available
which is involved in integrating a computer's capabilities, hardware and the operating system, and second, the list of
but does not directly apply them in the performance of desired features, duration of warranty, cost, etc
tasks that benefit the user
To understand appli jon software better, consider an 6.3.2 Having customized software
analogy where hardware would depict the relationship of If any pre-written software package does not meet the
an electric light bulb (an application) to an electric power individual's or the organization's requirements, then the
generation plant (a system). next option is to have a customized software package.
The power plant merely generates electricity, which is The organization can create a customized software
not by itself of any real use until harnessed through an package cither in-house, if the organization has a
application such as the clectric light, which performs a software development team or outsource it to a different
service that actually benefits the user organization.
Typical examples of software applications are word
processors, spreadsheets, media players, education In-house development of customized software When
software, CAD, CAM, data communication software, customized software is created by the software
statistical and operational research software, ete. Multiple development team in the same organization, the following
applications bundled together as a package are sometimes steps are performed:
referred to as an application suite The development team studies the user's requirements
and plans for the functional modules of the software
keeping in consideration if any pre-written software
Shrink-wrap and click-wrap software meets requirements partially, If there exists such a
Any licensed software, whether system software or software package, then it can be used and enhanced to
application software, comes in a CD-ROM placed inside fully meet user's requirements, otherwise the software
a box, has to be written from scratch.
The software is bundled with a license agreement or The modules planned in the previous step are coded,
tested, and documented. The complete software when
other terms and conditions, which the customer
can
ready is deployed in the user's machine and then
read only after opening the box. The box containing the
software maintenance activities get started.
Computer Software 9o7
Figure
6.5 Menu bar
Spelling&
Save Print grammar Format painter —insert hyperlink —Insert
Excel worksheet ©Zoom —Help
Styles & formatting Font size Italics Align left Align right Bullets Decrease
&Increase indent
After locating the proper drive and folder, enter the file
name in the File name text box at the bottom of the dialog
box and then click the Save button to save the file.
Offers two ways to see how a document will look when it drag the mouse over the text. Once finished with working
is printed: on the selected text, clicking somewhere in the document
* Print Layout view (View —> Print Layout)}—in this deselects the text
view, one is able fo enter text, insert graphics, and work Correcting mistakes The casiest way to correct mistakes
in columns while seeing how the printed document will is to select the text that requires correction and type the
turn out text for replacement. Pressing any key will immediately
Print Preview allows one to view multiple pages of delete the selected text. To correct mistakes that one makes
the document at once, zoom in and out of pages casily, while typing, one of the following methods can be used:
adjust margins, and shrink the document by one page * Using the Backspace or Delete keys
fo prevent a small carryover from appearing on a page * Clicking the Undo button on the Standard toolbar
by itself. To open Print Preview, click the Print Preview
button on the standard toolbar or choose File — Print Copying and moving text The most commonly used
Preview method of moving and copying text is through the use of
the Cut, Copy, and Paste features on the Standard toolbar
The dream of a paperless office may not be a long way from and Menu bar. The user finds it easy to move and copy text
reality. In the meantime, however, we are still expected by using the following methods
to generate a hard-copy of most documents we write.
A few tricks can make all the difference in producing a * Select the text to be copied or to be cut,
printed document that reflects the professional appearance * Click Edit + Copy or Edit > Cut
one would like to convey. There are two ways to print a * Move the cursor to the position where the text is to be
document, depending on how much control one needs: pasted.
* Click Edit —+ Paste.
+ If one needs to specify print settings, choose File
Print from the Menu bar to open the Print dialog box, Figure 6.13 shows the screenshot for copying the
shown in Figure 6.12, which allows one to select a selected text.
printer, choose the number of copies, and specify what
should be printed. Clicking the Options button at the
bottom of the dialog box opens a page where one can
select the print quality and other settings.
* To send a document to the printer immediately, using
the default print options (and without opening a dialog
box), click the Print button on the Standard toolbar.
This is convenient in most of the applications.
command bars. Below the command bars is a strip that Point-and-click formulae Point-and-click
(see Figure 6.
contains the name box and the formula bar. The Excel is a highly reliable method that Excel is known for.
status bar displays information about current selections, The following steps will get one started with this
commands, or operations. The right end of the status bar
displays NUM if the keyboard's Num Lock is on.
Workbooks and worksheets When Excel is launched,
the Excel application window opens with a new Excel
workbook. A workbook is a multi-page Excel document. a
f =
Each page in the workbook is called a worksheet, and the (i. mea
MAS Scum RSL Comput Torat
active worksheet is displayed in the document window, The ae) ” ” 5
f ee ” . ° ©
sheet tabs are used to move to another worksheet and the i © ? ® ”
eee) = ~ *
navigation buttons are used to scroll through the sheet tabs. i$ A 2 ° ”
Se ee
Owes Are @t-h mew -SI ”
a
Ss a3 t J
ae aan sown tennis cere Ae
tis “”
oe tt > Mf =
dine © ” ri e
fives 7 ~ 7 ™
Ga Come * " «
fa) )
Figure 6.20 _ Filling formula operation (a) Before filling (b) After filling
104 Computer Fundamentals and Programming in C
if the series, based on the step value that is specified. For Growth This is selected for a series that increases
instance, if one cell contains the number 10, or the date geometrically or exponentially. For instance, multiplying
02/14/07, the user can use Excel to utilize these values each successive cell value by the preceding cell value is
to fill the other cells and automatically add 2 to each growth.
successive cell value, or seven days to cach succeeding
Date This is used for dates to be incremented. In addition,
cell date.
the date interval to be used is selected in the Date Unit
Excel will even fill the cells based on the series of area. The choices are Day, Weekday, Month, and Year.
values in successive cells, Let's say a user selects three
cells, with successive values of 3, 6, and 9, and three more AutoFill This is used for formulae or other series types. It
blank cells after them. Excel can recognize the series and determines what series type to use based on the cells selected
automatically fill the three selected blank cells with 12, This option is the same as filling by dragging the fill handle,
15, and 18 (the next values in the series where n =n + 3). For linear or growth series types, the trend box is
For using the AutoFill feature, the starting fill value is checked or a step value and/or stop value is filled, based
selected based on one of following three approaches: on the following
* One cell: A single cell is selected if the user needs to Trend This box is checked if a range of cells with
fill cells based on the contents of one cell, which will progressive values is selected. el will determine what
increase according to a step value that is specified. the trend is and fill the blank cells accordingly.
ies of cells: A set of adjoining cells containing a Step value The valuc that should be used in incrementing
series of values is selected for using those values to the Linear or Growth series of values is entered here.
continue in other blank cells.
Formula cell: A cell containing a formula is chosen if Stop value This is an optional field which specifies the
the user wants to fill other cells with the formula. maximum value to be reached in the series.
Now, the rest of the cells in the fill series are selected. The Formatting numbers Excel lets the user present numbers in
destination cell must be adjacent to the target cell. Edit —+ a variety of formats. Formatting is used to identify numbers
Fill —+ Series is chosen to display the Series dialog box as Currency or percents and to make numbers casier to read
This is shown in Figure 6.21 by aligning decimal points in a column. Formatting can be
Next the series category under the Type heading is effected in the selected cells with three tools:
selected. The available choices are as follows: * Formatting toolbar
linear This is chosen for a series that increases linearly + Format Cells dialog box
For example, adding a number to each successive cell * Shortcut menu
value is linear.
When a user formats a number, its appearance changes,
not its numeric value. The default format for numbers,
General, does not display zeros that have no effect on the
©) Om Lite beet tone a value of the number. For example, ifone enters 10.50, 10.5
Be) Vere Tal cme Ree hme OF has the same numeric value, so Excel does not display the
. c extra or trailing zero.
eck Hicks compe Using the Formatting toolbar To format cells with the
4 4 toolbar, select the cells and then click a button to apply
ic— — one of the formats shown in Table 6.2.
Using the Format Cells dialog box Excel has more heading should be right-aligned or centred. Labels fF
numeric formats, which can be selected from the Format text columns should be left-aligned or centred,
Cells dialog box. Select the cells to be formatted. Then
open the dialog box by clicking Format — Cells from Rotating text The rotation tools are used to orient text
the Menu bar. The format cells dialog box has separate vertically or to rotate text to a specific orientation. These
pages for Number, Alignment, Font, Border, Patterns, and steps guide the user through the process:
Protection, as shown in Figure 6.22 * Select the cell containing the words to be rotated, select
Format — Cells, and click the Alignment tab in the Format
Cells dialog box. Choose one of the following options:
« To orient text vertically, click the box with the vertical
word “Text” in it
« To rotate text to another orientation, either use the
Degrees spin box or drag the Text indicator in the
rotation tool
+ Click OK to apply the rotation.
Microsoft Lxcel -Book? textbox. Click on OK to choose the selected function and
return to the Formula Palette
(BD) Ele Edt Yew Insert Format Tools Qeta These steps summarize the method to use Excel
ae ae SY iMimo- BE- functions:
* Activate the cell where the result of the function needs
AVERAGE to appear,
ir 69 BS 78 * Click the = button on the formula bar.
HYPERLINK 77 es 67 + Choose a function from the Function box drop-down
60 77 63 list; or, if the function does not appear on the list, choose
72 70 73 lore Functions to open the Insert Function dialog box
so 89 74
Choose a category and the specific function. Click OK
to return to the Formula Palette.
+ In the Formula Palette, select the Number | text box.
That is, select the cells to include in the argument.
Figure 6.23 List of functions in the formula palette of * Click the OK button to complete the entry
Microsoft Excel
Working with statistical tables Excel includes a fistful
of complex statistical functions, However, the most used
hacer baatBead functions are everyday statistics such as average, min,
De ee ee ee
max, and the following
* Count—retums the number of numbers in a selected
range
* Median—another kind of average, which is used to
calculate the value in the middle of the range
* Mode—returns the value that occurs most frequently
Using COUNT, MEDIAN, and MODE: The COUNT
function indicates the numbers of cells that are present in
a selected range. If the user has a small worksheet, this can
Figure 6.24 Function arguments in the formula palette of
Microsoft Excel
be casily counted but its difficult for large worksheets, and
the problem is compounded when some cells in a column
are blank.
AVERAGE returns a value called the arithmetic
Search
tor0faretan mean—the total of all the values in a range divided by
[epee en ae ees « the number of values in the range. When we talk about
averages—bowling scores, test grades, speed on several
typing tests—we are referring to the arithmetic mean
However, there are two other types of averages:
MEDIAN and MODE. MEDIAN indicates which value is
the middle value in a range, and MODE refers to the value
that occurs most frequently
Charts Charts are graphical representations of numeric
teetaonttsfuertaans data. Charts make it casier for users to compare and
understand numbers, and so are a popular way to present
numerical data. Every chart tells a story. Stories can be
Figure 6.25 Searching for a function in Microsoft Excel
simple, such as conveying the information ‘See how
our sales have increased" or complex, such as indicating
Palette. As with any formula, the results of the function are “This is how our overhead costs relate to the price of our
displayed in the active cell. The function itself is displayed product’. Whether simple or complex, the story should
in the formula bar when the cell is active be readily understandable. If one cannot immediately
Ifthe required function is not listed in the Function box, understand what a chart means, then it is not a well
More Functions at the bottom of the list is chosen to open presented chart. Charts are constructed with data points,
the Insert Function dialog box, as shown in Figure 6.25. which are individual numbers in a worksheet.
One can search for a function or select a function Understanding chart types Excel! comes with a wide
category. Depending on the category selected, the variety of charts capable of graphically representing most
corresponding list of the functions will be displayed in the standard types of data analysis, and even some more exotic
Computer Software 107
numeric interpolations. The type 20 28 The bars give added substance to the chart. In the Hii€
of data being used and presented chart, what the reader notices is the trend up or down in
determines the type of chart each line and the gaps between the lines, The bar chart not
to be used to plot the data on. only makes the data seem more substantial, it also makes
Excel has charts in the following 22 the differences between the destinations even clearer, The
30
categories: horizontal line is called the x-axis, and the vertical line is
* Pie charts; These work best Figure 6.26 Pie chart the y-axis.
for displaying how much each * Specialty charts: Excel includes a number of charts
part contributes to a total value (see Figure 6.26), suitable for presenting scientific, statistical, and
series charts: More than one data series can be charted financial data. Scatter charts are used to present
in a series chart. This lets one compare the data points experimental results, Surface and contour charts are
in the series, such as January vs February, or the sale of good for presenting 3D and 2D changes in data. Radar
Reynolds pens vs Flair pens. There are several types of charts show data values in relation to a single metric
serics charts, A user can give the same set of data a very Stock charts present values from three to five series
different look by simply changing the chart type. of data, including open, high, low, close, and volume
Line and area charts: These show data points connected trading information.
with lines, indicating upward or downward trends in
Creatinga chart The easiest way to create a chart is by
value, as shown in Figure 6.27.
using the chart wizard. Begin the chart creation process
95 by selecting the data to be used in the chart. With the
90 #89 expectation of the chart's title, everything else that
8s 285 appears in the chart should be selected somewhere in the
80 78 worksheet
75 275
7 * When the text and number are selected, click the chart
wizard button on the Standard toolbar
com 2 1 In the first step of the chart wizard, choose a chart type
100
AD 8 be
all in the Chart Type list box
@80 SS 678 75 Ramesh * In the second step, shown in Figure 6.29, the user has
40 * Mohan the opportunity to make sure the range ected on the
20 Data Range tab is correct. Choose Rows or Columns
0 in the Series In option group. The preview changes
¥ ¢ > ¢ to reflect the range and series arrangement specified.
yy £ $ ¢
- < Click Next, or click the Series tab to make additional
¢ changes,
Figure 6.27 Line and area charts + In the third step, the tabs shown in Figure 6,30 are used
to change options for various aspects of the chart
The series chart shown in the second figure is a line
« Titles: Enter titles for the chart and axes
chart showing the relationship between marks obtained by
two students in different subjects, Line charts are available
‘ u
in a 2D version (as shown) or in a 3D version, which is
sometimes called a ribbon chart. An area chart is a line
chart with the area below the line filled
* Column and bar charts; These compare values across
categories, with results presented vertically in column
charts and horizontally in bar charts. Figure 6.28 shows
the same information presented as a bar chart sateretecel
Figure 6.28 Column and bar charts Figure 6.29 Chart wizard in Microsoft Excel
108 ) Computer Fundamentals and Programming in C
——————
POINTERS
he or more database administrators who control cach same time calls for efficient utilization of the system’s
function, as well as provide other users with various levels resources by the operating system.
of administration rights. + Memory management: Finding vacant spaces in the
From a technical point of view, DBMSs can differ primary memory. loading the appropriate data and
widely based on the way they organize the underlying data programs in the located space, executing them, and
in the database. A DBMS can be relational, network, flat, removing them from the memory is all done by the
or hierarchical, The internal organization of the data can operating system.
affect the speed and flexibility with which the information + File management: The OS allows users to create, copy,
can be extracted. delete, and rename files.
Information from a database is extracted in the form + Security management: The OS protects stored information
of a query, which is a stylized question. Consider the from malicious users. It ensures that the data and files
following query: stored cannot be accessed by unauthorized users.
SELECT ALL FROM STUDENTS WHERE MARKS > 96
The query requests all records from the table STUDENTS 6.8.1 Types of Operating Systems
that have marks greater than 90. The set of rules for Based on the usage and requirements, operating systems
constructing queries is known as query language. The can be classified into different categories, as shown in
most commonly used query language is structured query Figure 6.33.
language (SQL).
Batch processing operating system This is an OS that
The information from a database can be presented allows very limited or no interaction between the user and
to the users in a variety of formats. For example, many
processor during the execution of work. Data and programs
DBMSs include a report writer program that outputs the
that need to be processed are bundled and collected as a
data in the form ofareport. Many DBMSs also include a
*batch’ and executed together.
graphics component to display the information in the form
Batch processing operating systems perform very well
of graphs and charts, DBMS facilitates its users to control
when a large amount of data has to be processed, and
data access, enforce data integrity, manage concurrency,
cither the data or the processing is similar in nature, Batch
and restore the database from backups.
processing is performed automatically without any user
intervention,
OPERATING SYSTEMS For example, an organization uses batch processing to
automate its payrolls. The process would identify each
An operating system is a collection of system programs employee, calculate his/her monthly salary (with tax
deductions), and print the corresponding pay slip. Batch
that control the operations of the computer system, An
processing is useful for this purpose since these procedures
operating system has the following main objectives.
are repeated for every employee each month.
* Manages the computer hardware: The OS controls and
efficiently utilizes hardware components such as CPU, Single-user single-tasking operating system As the name
memory, and I/O devices. indicates, this operating system allows only one program
* Provides a user interface: The OS enables users to easily to execute at a time. It is designed to manage the computer
interact with the computer hardware. For example, the to enable a single user to do a single job effectively at any
Windows operating system displays icons, using which point of time. The Palm OS for Palm handheld computers
the users can interact with the system. is an example of a modern single-user, single-tasking
* Process management: The OS enables a user to operating system.
execute more than one job at the same time to enhance Single-user multitasking operating system This
productivity. Multiple processes being executed at the operating system allows a single user to perform several
Command line interface (CLI) is a way by which users typing the complete command without any mistake to
i interact with a program by typing commands at the perform the same operation.
prompt. Such an interface makes use of only the keyboard + GUls case the task of transferring data from one
to issue commands. Although CLI has been widely application to another. However, the two applications
replaced by GUI, many computer users still prefer CLI must be running the same GUI. For example, we can
because of the following advantages: casily incorporate a pic chart created in MS-Excel into a
* They provide a more concise and powerful means to document created using MS-Word.
control a program or operating system. + GUI gives users an immediate visual feedback of the
* Programs with CLI can be casily automated through effect of user's action, For example, when a file is
scripting deleted, the icon of that file immediately disappears,
* This interface is very valuable for some type of thereby notifying the user that the file has been removed
operations. For example, if we have to rename 100 files from its current location
in Windows that is based on GUI, then it will take a long
time but with CLI the same operation can be performed
in a few seconds. 6.9 | Popular Operating Systems
* When sharing resources over the network, CLI is
widely used as some networking devices can only be MS-DOS, Windows family of operating systems, Unix,
manipulated using a command line interface. Linux, and Mac OS X are some of examples of commonly
* ACL is stable in the sense that once a user has learned used operating systems. Each operating system has
to execute commands, the procedure will never change as specific characteristics. Here, we will discuss the features
compared to GUI, Even ifnew commands are introduced, of MS-DOS, Windows family of operating systems, Unix,
the original ones will always remain the same. and Linux.
the programs and data are stored. The command.com had highly improved user interface along with new
module of the MS-DOS command mode interprets the multitasking capabilities. Later, in March 1992,
command and executes it, As compared to the operating version 3.1 was released, which offered the operating
systems of today, MS-DOS has relatively a very small system a facelift. In July 1993, Windows NT was released
number of commands and became the first operating system to be designed for
The following are some of the frequently used a professional platform.
commands: In August 1995, Windows 95 was released, meant to
* CD to change the current directory replace Windows 3.1. This operating system provided
* COPY to copy a file support for pre-emptive multi-tasking and offered a
* DEL to delete a file consumer solution with significant changes to the user
* DIR to list directory contents interface, It was the first operating system by Microsoft
* EDIT to start an editor to create or edit text files that used the plug-and-play system. Windows 95
* FORMAT to format a disk revolutionized the desktop platform and achieved mass
* HELP to display information about a command popularity
* MKDIR to create a new directory Later, Windows 98 was released in June 1998. However,
* RD to remove a directory it was criticized for being slower and less reliable than its
* REN to rename a file predecessor. Hence, many of these issues were addressed a
* TYPE to display contents of a file on the screen year later with the release of Windows 98 Second Edition.
In February 2000, Microsoft brought out another
MS-DOS is basically a single-user single-tasking professional operating system known as Windows 2000,
operating em, Therefore, at a given instant of time, the consumer version of which was released as Windows
only one user can use it to perform only one task. Another ME in September of that year.
drawback of MS-DOS is that it does not have a built-in October 2001 witnessed the release of Windows XP,
support for networking. Moreover, MS-DOS is a 16- which was based on the NT keel and managed to retain
bit operating system, Therefore, it can send, receive, or the extreme functionality of its home-based predecessors.
process only 16 bits of data at a time. It is unable to take XP became very popular among the masses and was
advantage of the 32-bit or 64-bit processors available in available in two different editions, home and professional
the market today. All these factors consequently led to Windows XP was succeeded by Windows Vista, which
the decline in the popularity of MS-DOS. Its last version, included several new features with an emphasis on
MS-DOS 6.22, was released in 1994. Although users do security
not use MS-DOS today, its command shell (now called Windows 7, which is meant for use on PCs such as
Windows command line) is still popular among users. desktops, laptops, notebooks, tablet PCs and media centre
PC, was released in October 2009. It offers a range of new
6.9.2. Windows
features and is compatible with applications and hardware
The Windows operating system has been developed supported by Windows Vista.
by Microsoft. When designing this operating system, Windows 8 was released by Microsoft in 2012 and was
Microsoft has taken two separate approaches in which one specifically designed to be used on PCs and tablets. The
is suited for home users and the other is intended for the first differentiating feature of Windows 8 was its Start
IT professionals. The home edition supports more user sereen that is the first screen displayed after a user logs
functionalities and multimedia features but has limited into Windows 8 (see Figure 6.37). The Start screen is the
support for security and networking. The professional main interface that is used to launch programs, search for
edition, on the other hand, is well suited for server files, and browse the web. Programs that are designed for
environment, has limited multimedia features but offers the Start screen interface are called apps.
enhanced networking capability and security. Windows 8 contains tiles that represent different
The first version of Windows (version 1.0) which was programs that can be launched by simply clicking on the
released in November 1985 was not very popular as it tile. The tiles also contain information widgets that are
lacked functionality compared to the Apple operating used to display real-time information directly on the Start
system. After two years, version 2.0 was rele which screen. For example, users can quickly see the data related
achieved slightly more popularity than its predecessor. to weather, e-mail, articles, etc
Then, in January 1988, version 2.03 was released which While a square tile is used to quickly launch an
offered a totally different look that resulted in Apple application, the rectangle tile is used to display real-time
filing a lawsuit against Microsoft with accusations of information, The Start screen has a number of pag
infringement. where cach page has different tiles. If there is no pla
In 1990, version 3.0 was released which became the for a tile on one page, then it can be added to other pages.
first edition to reach commercial success by selling two Users can move the tiles from one page to another and
million copies within the first six months, Windows 3.0 organize them in categories.
14 Computer Fundamentals and Programming in C
Wuthenticates the user by verifying the username and computer with Linux can easily be connected to another
password, and then starts a program called the shell. The computer to form a client-server model. Moreover, Linux
shell is a command line interpreter (CLI). It interprets is known to perform tasks such as network backup faster
the commands typed by the user and executes them with than any other operating system.
the help of the kernel. The commands are nothing but Flexibility Linux is a flexible operating system as it
programs, and when they terminate, the shell displays
can be used for high-performance server applications,
another prompt (which is a % symbol). desktop applications, and embedded systems, The user
Let us take an example to see how the shell and kernel has the option to install only the needed components for a
work together to execute the mands typed by the user.
particular use.
When the user types rm myfile (which means removing
the file myfile), the shell searches the file containing the Compatibility Linux is a Unix-based operating system
program rm, and then uses s m calls to request the and is therefore compatible with it. This means that it can
kernel to execute the program rm on myfile run all common Unix software packages and can process
all common file formats.
Files and processes Everything in UNIX is cither
considered to be a file or a process. A process is a program Fast and easy to install Linux comes with user-friendly
under execution and a file is a collection of data, Users can installation.
create their own files using a text editor. Example of files Better use of hard disk Linux uses its resources well,
include a document, the text of a program written in some even when the hard disk is almost full
high-level programming language, a directory containing
information about its contents which may contain other Multitasking Linux is 4 multitasking operating system,
directories (subdirectorics), and ordinary files. so it can execute several jobs simultaneously.
The advantages of using the UNIX operating system Security Linux is a secure operating system as it supports
are as follows: many options for file ownership and permissions.
* Itis flexible and can be casily installed on different types In summary, Linux is a popular operating system used by
of computers (such as supercomputers, microcomputers, home and office users. It is mainly used for high-performance
mainframes, and so on). business and in web servers, Moreover, Linux can be installed
* Itis far more stable than Windows and thus requires less on a wide variety of computers ranging from mobile phones,
maintenance tablet computers, routers, and video game consoles, to
* It offers more ecurity features than the Windows desktop computers, mainframes, and supercomputers. Today,
operating system. Linux is the most popular server operating system, and runs
* The processing power of UNIX is greater than that of the ten fastest supercomputers in the world,
Windows.
* It is the most widely used operating system for web
servers. Almost 90 percent of the web servers have GRUP mosite opERATING SYSTEMS
UNIX installed on them.
In the past, mobile phones were seen as devices that
could be used for making phone calls and for sending
6.9.4 Linux text messages. With passage of time, mobile phones have
Linux is a very powerful, free, open-source operating evolved into smartphones that are much closer to handheld
system based on UNIX. It was originally created by Linus computers. Besides making calls and sending text
Torvalds with the assistance of developers from around messages, smartphones allow users to send emails, play
the globe. Users can download Linux for free from the games, watch the news, make video calls, and much more.
Internet and also make changes to it. The advantages of Like computers, smartphones also have an operating
Linux include the following system to support advance functions that were once
low cost Linux is available for free on the Internet, so supported by only computers. While some operating
systems are open source software others are proprietary.
users need not spend huge amounts of money to obtain
licenses. Moreover, users can also edit its source code to
develop a customized operating system
Stability Linux is a stable operating system. It rarely An open source OS lays no restrictions on what you can
freezes or slows down and has continuous up-times of download on it, or who can develop apps for it.Itis
hundreds of days or more. entirely customizable.
Performance Linux gives very high performance on various A mobile operating system (or mobile OS) is a set of
networks. Itcan handle large numbersofusers simultaneously data and programs that is specifically designed to run
Networking Linux is widely used in networks as it on mobile devices such as smartphones, PDAs, tablet
provides a strong support for network functionality. Any computers, wearable devices, and other handheld devices.
Computer Software 67
The mobile OS is an operating system (system software), with or without touchscreens. Microsoft had
which provides a platform on which other applications Windows Phone 7 in 2010. Its colourful and user-friendly
can run. It manages all the hardware and optimizes the interface has made it in demand all over the world. Window
efficiency of the application software in the device. Phone is recognizable from its tile-based interface dubbed
For example, it manages mobile multimedia functions, Metro, which features removable and interchangeable
Internet connectivity, Bluetooth, Wi-Fi, camera, music squares sections on the home screen, each with its own
player, voice recorder, etc., in a mobile device. purpose and function.
Some commonly used mobile operating systems are the Windows Phone has a pre-installed mobile-optimized
iOS, Android, Windows Phone, and so on. version of the Internet Explorer for accessing the web, and
In this section we will discuss some popular mobile a program called Exchange that provides secure corporate
operating systems. e-mail accounts.
Android Android is Google's operating system which is
used on mobile devices. Android devices can install arange PROGRAMMING LANGUAGES
of apps from Google Play, which is an official app market.
These days, Android is being used on mobile devices A programming language is a language specifically
manufactured by leading smartphone manufacturers such designed to express computations that can be performed
as Samsung, HTC, Motorola, and many others. Currently, using the computer. Programming languages are used to
Android is one of the top operating systems. create programs that control the behaviour ofasystem, to
Android OS is an open source operating system powered express algorithms, or asa mode of human communication.
by the Linux kernel. Users can use this OS to develop apps Usually, programming languages have a vocabulary
as it poses very little restriction on its licensing. Android of syntax and semantics for instructing a computer to
also allows its users to customize multiple home screens perform specific tasks. The term programming language
with useful widgets and apps that give a quicker, casier usually refers to high-level languages, such as BASIC, C,
access to the content and functions that they use frequently. C++, COBOL, FORTRAN, Ada, and Pascal, to name a
Android is a multitasking OS in which users can close few. Each of these languages has a unique set of keywords
programs by simply swiping them away. Users can (words that it understands) and a special syntax for
download a wide range of apps from the Android Market. organizing program instructions,
While high-level programming languages are casy
for humans to read and understand, the computer only
understands the machine language, which consists of only
numbers. Each different type of central processing unit
(CPU) has its own unique machine language.
In between the machine languages and high-level
languages, there is another type of language known as the
BlackBerry OS [1 is a proprictary mobile OS developed
assembly language. Assembly languages are similar to
by BlackBerry Limited to be used on BlackBerry mobile
machine languages, but they are much easier to program
devices. The BlackBerry OS is popular amongst corporate
in, because they allow a programmer to substitute names
users as it offers synchronization with business software
for numbers.
when used with the BlackBerry Enterprise Server.
However, irrespective of the language used by the
iPhone OS It is developed by Apple to be used on its programmer, the programs that are written using any
iPhone devices. It is popularly referred as iOS and is programming language has to be converted into the machine
supported by Apple devices such as iPhone, iPad, iPad 2 language so that the computer can understand it. There are
and iPod Touch, The iOS is also proprietary software and two ways to do this: compilingor interpreting the program,
can be used only on Apple’s own manufactured devices. The question of which language is best depends on the
It was introduced on 29 June 2007 when the first iPhone following factors:
was developed and the latest version being used is the * The type of computer on which the program has to be
iOS 6. Unlike Android, the main focus of iOS has been on executed
performance rather than appearance. * The type of program
The Apple iOS is a multi-touch, multitasking operating
* The expertise of the programmer
system. It comes with the Safari web browser for Internet
use, an iPod application for playing music and Apple's Forexample, FORTRAN is particularly a good language
Mail for managing emails. Users can download different for processing numerical data, but it does not lend itself
applications currently available on the App Store directly very well to organizing large programs. Pascal can be used
on their mobile device. for writing well-structured and readable programs, but it is
not as flexible as the C programming language. C++ goes
Windows Mobile Windows Mobile is Microsoft's mobile one step ahead of C by incorporating powerful object-
OS which is used in smartphones and mobile devices oriented features, but it is complex and difficult to learn.
ag Computer Fundamentals and Programming in C
assembly language less portable, as the code written to be Although 3GLs relieve the programmer of demandiig
executed on one machine will not run on machines from a details, they do not provide the flexibility available in low-
different or sometimes even the same manufacturer. level languages. However, a few high-level languages
No doubt, the code written in assembly language will such as C and FORTH combine some of the flexibility
be very efficient in terms of execution time and main of assembly languages with the power of high-level
memory usage, as the language is also closely connected languages, but these languages are not well suited to the
to the machine language beginning programmer.
Programs written in assembly language require a While some high-level languages were specifically
translator, often known as an assembler, to convert them designed to serve a specific purpose (such as controlling
into machine language. This is because the computer will industrial robots or creating graphics), other languages
understand only the language of Is and Os. It will not were flexible and were considered to be general-purpose
understand mnemonics such as ADD, CMP, SUB and so on. languages, Most of the programmers preferred to use
The following instructions are a part of assembly general-purpose high-level languages such as BASIC,
language code to illustrate addition of two numbers. FORTRAN, PASCAL, COBOL, C++, or Java to write the
code for their applications
MOV AX,4 Stores the value 4 in the Ax Again, a translator is needed to translate the instructions
register of CPU written in a high-level language into computer-executable
MOV 8X,6 Stores the value 6 in the 8X machine language. Such translators are commonly known
register of CPU as interpreters and compilers. Bach high-level language has
ADD AX,BX Add the contents of AX and BX many compilers, and there is one for each type of computer.
registers. Store the result in AX register For example, the machine language, generated by one
Although assembly languages are much better to work computer's C compiler is not the same as the machine
with as compared to machine languages, they still require language of some other computer, Therefore, it is necessary
the programmer to think on the machine's level. Even to have a C compiler for each type of computer on which
today, some programmers still use assembly language to the C program has to be executed.
write parts of applications where speed of execution is The 3GLs make it easier to write and debug a program
critical, like video games, but most programmers today and give the programmer more time to think about its
have switched to third generation programming languages overall logic. The programs written in such languages
(3GLs) or fourth generation programming languages are portable between machines. For example, a program
(4GLs) to do the same. written in standard C can be compiled and executed on
any computer that has a standard C compiler,
6.12.3 Third Generation: High-level Language
A3GLis arefinement of the 2GL. The 2GLs brought logical 6.12.4 Fourth Generation: Very High-level
structure to software. The third generation was introduced Language
to make the languages more programmer-friendly
With cach generation, programming languages have become
The 3GLs spurred the great increase in data processing
easier to use and more like natural languages, However,
that occurred in the 1960s and 1970s. In these languages, 4GLs are a little different from their prior generation
the program statements are not closely related to the
because they are basically non-procedural. When writing
internal characteristics of the computer and are therefore
code using a procedural language, the programmer has to
ofien referred to as high-level languages. tell the computer how a task is done—add this, compare
Generally, a statement written in a high-level
that, do this if the condition is true, and so on, in a very
programming language will expand into several machine
specific step-by-step manner, In striking contrast, while
language instructions. This is in contrast to assembly
using a non-procedural language, the programmers define
languages, where one statement normally generates
only what they want the computer to do, without supplying
one machine language instruction, The 3GLs made
all the details of how it has to be done.
programming easier, efficient, and less error-prone. Although there is no standard rule that defines what a
High-level languages fall somewhere between natural
fourth generation language is, certain characteristics of
languages and machine languages. The 3GL includes such a language include the following
languages such as FORTRAN and COBOL, which made it
possible for scientists and businesspeople to write programs + The code comprising instructions are written in English-
using familiar terms instead of obscure machine instructions, like sentences.
The first widespread use of high-level languages in the * They are non-procedural, so users concentrate on the
carly 1960s changed programming into something quite *what’ instead of the "how" aspect of the task
different from what it had been. Programs were written * The code is easier to maintain.
in an English-like manner, making them more convenient * The4GLcode enhances the productivity of programmers,
to use and giving the programmer more time to address a as they have to type fewer lines of code to get something
client’s problems. done. It is said that a programmer becomes 10 times
120 Computer Fundamentals and Programming in C
more producti when he or she writes the code using a SGLs are widely used in artificial intelligence (Al)
4GL than a 3GL. research. Typical examples of SGLs include programming
A typical example of a 4GL is the query language in logic (Prolog), official production system, version 5
that allows 4 user to request information from a database (OPSS), and Mercury
with precisely worded English-like sentences. A query Another aspect of a SGL is that it contains visual tools
language is used as a database user interface and hides the to help in developing a program. A good example of aSGL
specific details of the database from the user. For example, is visual basic (VB)
when working with structured query language (SQL), the Hence, taking a forward leap from the 4GLs, 5GLs are
programmer just needs to remember a few rules of syntax designed to make the computer solve a given problem
and /ogic, but it is much casier to learn than COBOL or C. without the programmer, While working with a 4GL, the
Let us take an example in which a report has to be programmer has to write specific code to perform a task,
generated that displays the total number of students but with SGL, the programmer only needs to worry about
enrolled in cach class and in cach semester in a school. what problems need to be solved and what conditions need
Using a 4GL, the request would look similar to this: to be met, without worrying about how to implement a
routine or algorithm to solve them.
TABLE FILE ENROLLMENT Generally, SGLs were built upon list programming
SUM STUDENTS BY SEMESTER BY CLASS (Lisp), many originating on the Lisp machine, such as
Hence, we can sce that a 4GL is much simpler to learn ICAD. There are many frame languages, such as KL-ONE.
and work with, The same code, if written in theC language In the 1990s, SGLs were considered to be the wave of
or any other 3GL, would require multiple lines of code to the future, and some predicted that they would replace all
do the same task. other languages for system development (except the low-
4GLs are still evolving, which makes it difficult to level languages). In 1982-93, Japan had invested much
define or standardize them. The only downside of a 4GL research and money into their fifth generation computer
is that it does not make efficient use of the machine's systems project, hoping to design a massive computer
resources, However, the benefit of executing a program network of machines using these tools. However, when
fast and easily far outweighs the extra costs of running it larger programs were built, the flaws of the approach
became more apparent. Researchers began to observe
that, starting from a set of constraints defining a particular
6.12.5 Fifth Generation Programming problem, deriving an efficient algorithm to solve is very
Language difficult .All these things could not be automated and still
The SGLs are centered on solving problems using require the insight of a programmer.
constraints given to the program, rather than using an However, today, the SGLs are back as a possible
algorithm written by a programmer, Most constraint-based level of computer language. Software vendors across the
and logical programming languages and some declarative globe currently claim that their software meets the visual
languages form a part of the fifth generation languages. programming requirements of the SGL concept.
POINTS TO REMEMBER
* Acomputer has two parts—hardware, which does all the * Acompiler is a special type of program that transforms
physical work computers are known for, and software, source code written in a programming language (the
which tells the hardware what to do and how to do it. source language) into machine language comprising
Computer software is written by computer of just two digits, 1 and 0 (the target language). The
programmers using a programming language. resultant code is known as the object code.
Application software is designed to solve a particular * The interpreter takes one statement of high-level
problem for users. language code, translates it into the machine level code,
System software represents programs that allow the executes it, and then takes the next statement and
hardware to run properly. System software acts as an repeats the process until the entire program is translated,
interface between the hardware of the computer and * Anassembler takes an assembly language program as
the application software that users need to run on the input and gives a code in machine language (also
computer. called object code) as output.
The key role of BIOS is to load and start the operating A linker is a program that combines object modules to
system, The code in the BIOS chip runs a series of tests form an executable program.
called POST to ensure that the system devices are A loader is a special type of program that copies
working correctly, BIOS is stored on a ROM chip built programs from a storage device to main memory,
into the system. where they can be executed,
Utility software is used to analyse, configure, optimize, * Software can be acquired in three ways—(a) by
and maintain the computer system. buying pre-written software, or (b) by developing a
Computer Software 121
customized software, or (c) by downloading public While high-level programming languages are easy for
domain software, the humans to read and understand, the computer
Microsoft Office is a suite of inter-related applications actually understands the machine language, which
for the Microsoft Windows and Mac OS X operating consists of only numbers.
systems. The popular applications include Microsoft * The second generation of programming languages
Word, Microsoft Excel, and Microsoft PowerPoint. includes the assembly language. Assembly languages
An operating system is a collection of system programs are symbolic programming languages that use symbolic
that control the operations of the computer system. notation to represent machine language instructions.
MS-DOS, Windows family of operating systems, Unix, An assembly language statement consists of a label,
Linux, and Mac OS X are some of examples of an operation code, and one or more operands. Labels
commonly used operating systems. are used to identify and refer instructions in the
The command interpretation module or command program. The operation code (opcode) is a mnemonic
interpreter of the operating system provides a set of that specifies the operation that has to be performed,
commands that users can execute. such as move, add, subtract, or compare, The operand
The user interface of command interpreter can be specifies the register or the location in the main
broadly classified into two groups—CLI and GUI memory, where the data to be processed is located,
A mobile operating system (or mobile OS) is a set of © 3GLs fall between natural languages and machine
data and programs that is specifically designed to run languages. They include languages such as FORTRAN
on mobile devices such as smartphones, PDAs, tablet and COBOL, which made it possible for scientists and
computers, wearable devices, and other handheld businesspeople to write programs using familiar terms
devices. Some commonly used mobile operating instead of obscure machine instructions.
systems are the iOS, Android, and Windows Phone. * While working with 4GLs, the programmers define
Programming languages are used to create programs only what they want the computer to do, without
that contro! the behaviour of a system, to express supplying all the details of how it has to be done.
algorithms, or as a mode of human communication. © SGLs are centred on solving problems using constraints
Every programming language has a vocabulary of given to the program, rather than using an algorithm
syntax and semantics for instructing a computer to written by a programmer. They are widely used in Al
perform specific tasks. research.
GLOSSARY
Application software Software that employs the by typing commands at the prompt
capabilities of a computer directly to perform a user- Freeware Public domain software available on the
defined task Internet which can be easily downloaded
Compiler Software that transforms source code written Graphical user interface Graphical user interface (GU)) Is
in a programming language into machine language a type of user interface that enables users to interact with
comprising of just two digits, 1 and 0 programs in more ways than typing. A GU/ offers graphical
Linker Software that combines object modules to form an icons and visual indicators to display the information and
executable program actions available to a user. The actions are performed by
Loader Software that copies programs from a storage direct manipulation of the graphical elements.
device to the main memory, where they can be executed Translator A computer program, which translates a code
Productivity software Software that is used to attain written in one programming language to a code in another
something productive, especially in the office or at home, language that the computer understands
as opposed to game or entertainment software Turnkey solution When the user orders both hardware
Program A set of instructions arranged in a sequence to and software from the same vendor, the vendor develops
guide a computer to find a solution for the given problem software on the chosen hardware and delivers the
System software Software that acts as an interface combination of hardware and software to the user. This is
between the hardware of the computer and the application called a turnkey solution or an end-to-end solution,
software that users need to run on the computer Proprietary software A software owned by a company
Command line interface Command line interface (CLI) is or an individual. The owner almost always imposes major
@ type of interface in which users interact with a program restrictions on its use and distribution.
022 ‘Computer Fundamentals
and Programming in C
EXERCISES
Fill in the Blanks Which of the following languages does not need any
1, ______ instructs the hardware what to do and how to translator?
do it. (a) Machine language —(b) 3GL
2. The hardware needs a _ _ to instruct what has to be (c) Assembly language (d) 4GL
done. Choose the odd one out from the following
The process of writing a program iscalled (a) Compiler (b) Interpreter
is used to write computer software.
{c) Assembler (d) Linker
___ transforms source code into binary language.
Which one of the following is a utility software?
Aww allows a computer to interact with additional
(a) Word processor (b) Anti virus
hardware devices such as printers, scanners, and video
cards, (c) Desktop publishing tool {d) Compiler
7. helps in coordinating system resources and POST is performed by the
allows other programs to execute. (a) operating system (b) assembler
8. provides a platform for running application {c) BIOS (d) linker
software. Printer, monitor, keyboard, and mouse are examples of
9. can be used to encrypt and decrypt files.
(a) operating system (b) computer hardware
10. is a software package that enables its users to
(c) firmware (d) device drivers
create, edit, print, and save documents for future
retrieval and reference
Windows Vista, Linux, and UNIX are examples of
11. ____ is used by architects and engineers to create {a) operating systems (b) computer hardware
architectural drawings (c) firmware (d) device drivers
12, ___ is used to design newsletters, advertisements, 10. Which among the following is an excellent analytical
books, and other types of documents. tool?
13. is used to store, edit, and extract data from a (a) Microsoft Word (b) Microsoft Excel
database (c) Microsoft Access (d) Microsoft PowerPoint
14, Information from a database is extracted in the form Which interface makes use of the graphical components
ofa to allow users to easily interact with the computer
15, Adobe Photoshop is an example of software system?
16. Command interpreter is the interface between the
(a) CPU (b) CLI
andthe
{c) GUI (d) CUl
17 ls a good language for processing numerical
12 Which of the following versions of Windows operating
data
system introduced live tiles?
18, Assembly language statement consists of 3
, and one or more
{a) Windows 7 (b) Windows 8
19. is used to convert assembly-level program into {c) Windows 8.1 {d) Windows 10
machine language. 13. To which generation does COBOL belong?
20. __and are used to translate the instructions {a) First generation (b) Second generation
written in high-level language into computer-executable (c) Third generation (d) Fourth generation
machine language. 14 Which generation language concentrates on the ‘what’
instead of the ‘how’ aspect of the task?
Multiple-choice Questions (a) First generation (b) Second generation
1, BIOS is stored in
(c) Third generation (d) Fourth generation
(a) RAM (b) ROM 15. Choose the 5GLs from the following
(c) hard disk (d) none of these {a) Prolog (b) OPSS
2. Which of the following languages should not be used for
organizing large programs?
(c) Mercury (d) All of these
(a) (b) C++ State True or False
(c) COBOL (d) FORTRAN 1 Computer hardware does all the physicalwork computers
3. Which of the following languages is a symbolic language? are known for.
(a) Machine language (b) The computer hardware cannot think and make decisions
(c) Assembly language {d) All of these on its own.
Computer Software 123
3. The term software refers to a set of instructions arranged Explain the role of the operating system.
in a sequence to guide a computer to find a solution for Give some examples of computer software.
the given problem. Differentiate between source code and object code.
4. A word processor is an example of an educational Why are compilers and interpreters used? |s there any
software. difference between a compiler and an interpreter?
5. Desktop publishing system is a system software. What is application software? Give examples.
6. BIOS defines the firmware interface. What is BIOS?
7. Pascal cannot be used for writing well-structured What do you understand by utility software? Is it a
programs. mandatory software for users?
8. Assembly language isalow-level programming language. Differentiate between syntax errors and logical errors.
9. Microsoft Excel is an example of a word processor Can a program written in a high-level language execute
10. Microsoft PowerPoint is used to create multimedia without a linker?
presentations and slide shows Write a short note on graphics software.
11. Microsoft Access can be used as a front-end as well as Give the significance of multimedia software in today’s
back-end application. scenario.
12. Multimedia software is used to create and edit digital What do you understand by DBMS?
images and illustrations. How is application software different from system
13, Microsoft DOS isa non-graphical command line operating software?
system Give a brief description of the Microsoft Office package.
14, iOS is an open source operating system. Write a short note on the different operating systems.
15. C and Pascal can be used for writing well-structured and Classify the operating systems based on their capabilities.
readable programs,
Define the term programming language. Give certain
16. Code written in machine language is highly portable examples of such languages.
State the factors that a user would consider to choose a
Review Questions particular programming language.
1, Broadly classify the computer system into two parts. In What is machine language? Do we still use it?
addition, make a comparison between a human body
Write a short note on assembly languages.
and the computer system, thereby explaining which part Code written in machine language is efficient and fast to
performs what function
execute. Comment
Differentiate between computer hardware and software. How is a third generation programming language better
Define programming. than its predecessors?
Define source code. Explain the significance of an assembler, interpreter, and
What is booting? compiler.
What criteria
Ayrawn are used to select the language in which a 4GL code enhances the productivity of the programmers
program will be written? Justify.
7
=
Computer Networks
the Internet
TAKEAWAYS
* Network topologies © Wireless networks * Internet protocol address
© Types of networks © Data transmissionmode © Domain name system
* Connecting media * OS! model Uniform resource locator
* Connecting devices © TCP/IP model Internet services
* Computer networks © Internet
Facilitating Communication on the other hand, uses radio waves for communication
and eliminates the need for wi
Using a network, users can communicate efficiently LANs are the preferred networks because they have
and casily through clectronic mail (c-mail) and instant higher data transfer rates, smaller geographic range, and
messaging, thereby allowing the exchange of important there is no need for leased telecommunication lines,
messages in a speedy manner without wasting paper.
However, on the downside, the problems associated 7.2.2 Wide Area Network
with computer networks are as follows:
As indicated by the name, WANs (Figure 7.2) span
* If the server fails, the application cannot be accessed
a large geographic area such as a city, country, or even
and can lead to data loss.
intercontinental distances, using a communication channel
If the server is hacked, it can lead to misuse of data.
that combines many types of media such as telephone lines,
When the number of computers and computing devices
cables, and air waves. A WAN often uses transmission
exceed the permissible number, the performance and
facilities provided by common carriers, such as telephone
efficiency of the system can decrease considerably
Network management is a difficult and tedious job. companies. It can be created by linking LANs together,
TYPES OF NETWORKS
am
These days, different types of networks are widely used,
both in homes and in businesses. These networks are
categorized based on their scale and scope, preferences for oo. wan on
networking industries, and their design and implementation
issues. In this section, we shall discuss these network types
———
that include local area network (LAN), wide area network
(WAN), metropolitan area network (MAN), campus area
network or corporate area network (CAN), and personal
area network (PAN). Figure 7.2 Wide area network
Of these, LAN and WAN are the original categories
of area networks, and the others have gradually emerged The Internet is the largest WAN, spanning the Earth, A
over many years as a result of advancement in technology WAN is a geographically dispersed collection of LANs.
A LAN can be easily connected to a WAN by using a
7.2.1 Local Area Network special network device called router. WANs and LANs
can be casily distinguished from each other in several
LAN was first invented for communication between two
important ways. Most WANs (such as the Internet) are
computers. However, later, with growth in technology, it
not owned by any one individual or organization, but
was used to connect computers and devices in a limited
geographical area such as homes, schools, computer rather exist under collective or distributed ownership and
management, WANs generally utilize different and much
laboratories, office buildings, or a closely positioned group more expensive networking equipment than LANs,
of buildings (Figure 7.1), Owing to the limited scope and
The Internet is a public WAN, but organizations can
cost of operation, LANs are typically owned, controlled,
also form private WANs, which are basically two or more
and managed by a single person or organization.
LANs connected to each other. For example, a company
A LAN can be one of two types—wired or wireless.
with offices in Delhi, Kolkata, Chennai, and Mumbai
While awired LAN may use the ethernet cable to physically
might have a LAN set up at each office. These individual
connect all computers on the network, the wireless L.
LANs can be connected through leased telephone lines to
case communication, thereby forming a WAN
The wireless technologies that connect computers and 7.5.3 Infrared Communication
other devices to form a network include terrestrial
microwave, communication satellites, cellular systems, Infrared light is widely used by TV and video cassette
and infrared systems. recorder (VCR) remote controls. In computers, infrared
technology enables computing devices to communicate via
7.5.1 Terrestrial Microwaves short-range wireless signals. Infrared signals are used to
transfer digital data. Infrared communication has become
Terrestrial microwaves use earth-based transmitters and an alternative to cables and provides a point-to-point, low-
receivers. Microwave antennas are usually placed on the cost way to connect computers with cach other or with other
top of buildings, towers, hills, and mountain peaks, and devices and appliances. Moreover, cellular phones are also
resemble satellite dishes. Terrestrial microwaves use the equipped with infrared ports to enable them to be connected
low-gigahertz range, which limits all communications to a computer for dial-up networking connections. Note
to the line-of-sight. Two relay stations are separated that infrared signals can only be transmitted within small
by approximately 40km. A_ terrestrial microwave distances (not more than 10 metres face-to-face) without
communication setup is shown in Figure 7.8. any object in the line of transmission.
NETWORKING DEVICES
Computer networking devices are communication devices
that enable the users tocreate a network. These devices are
also known as network equipment, intermediate systems
(IS) or interworking unit (IWU), In this section, we will
read about commonly used networking devices,
7.6.1 Hub
Figure 7.8 Terrestrial microwave communication
A hub (shown in Figure 7.10) is a device to which different
devices are connected so that they can communicate with
7.5.2 Satellite Communication each other. Every computer on the network is directly
In satellite communication (depicted in Figure 7.9), connected with the hub. When data packets arrive at a hub,
signals are transferred between the sender and the receiver itbroadcasts them toall thedevices connected toit.Hence,
using a satellite that is stationed in space, typically 35,400 every device picks the message but only the destined
km (for geosynchronous satellites) above the equator. device processes the packet and all other computers just
In this process, the signal, which is basically a beam of discard them.
modulated microwaves, is sent towards the satellite. The A hub is not an intelligent device; its main function is
satellite amplifies the received signal and transmits it back to amplify the signal and broadcast them to all the devices
to the receiver's antenna present on the earth's surface. connected to it.
Computer Networks and the Internet G29
é
the traffic on other network segments. Bridges can be
programmed to reject packets from particular networks,
Pri However, bridges do not normally allow connection of
networks with different architectures.
Figure 7.10 Hub
7.6.5 Router
7.6.2 Repeater
A router (shown in Figure 7.12) is an intelligent device
Network repeaters are electronic devices that regenerate that routes data to destination computers. It is basically
incoming electrical, wireless, or optical signals. Without a used to connect two logically and physically different
repeater, the data can only span a limited distance before networks, two LANs, two WANs, and a LAN with WAN,
the quality of the signal degrades. Repeaters attempt to
preserve signal integrity by removing unwanted noise from Network |
the incoming signal, restoring the weak/distorted signal, f=
thereby extending the distance over which data can safely a
travel.
A repeater connects two segments of the network cable.
a g[| 2
It regenerates the signals before sending it to the other
segments, but this regeneration requires a small amount
of time, This can cause a propagation delay, which can
affect network communication, especially when there are
several repeaters in a row, To avoid such a long delay,
many network architectures limit the number of repeaters
that can be used in a row.
7.6.3 Switch a a a
r= a F-
A switch is a device that can be used in all places where
a hub is used, However, it is much better than the hub at) all aL)
because a switch has a switching table within it. The a 8 gl g @
switching table stores the address of every computer Network 2 Network 3 Network4
or device connected to it and sends the data only to the Figure 7.12 Router
destined device rather than broadcast the data to all the
devices connected to it, Therefore, the switch is considered
The routers use special software known as routing
to be an intelligent device as it selects the devices among
table that stores the addresses of devices connected to the
many devices connected to it to forward the data.
network. The major task of the router is to route the data
packets between two networks on the best possible path for
7.6.4 Bridge fast data transmission. For this, it reads the information in
A bridge is a device that connects two or more LANs cach packet to know where the packet has to be sent. If the
(refer Figure 7.11). When a bridge receives data from one packet is destined for an immediate network it has access
LAN to forward it to another LAN, it first regencrates to, it will forward the packet to the appropriate network
{or amplifies) the signals and then forwards the data to so that it can reach the destination device. However, if
the other LAN. Amplification ensures that the devices the packet is destined for another network, the router will
forward the packet to another router.
Figure 7.13 shows four networks connected with the
help of two routers. If a packet reaches RouterA to be sent
on a device on Network 2, Router A simply forwards that
packet to Network 2 so that it can reach the destination
Figure 7.11 Bridge device. However, if the packet is meant for a device on
30 Computer Fundamentals and Programming in C
Nc ig and the star—bus networks. However, the exact + Step I: A computer's wireless adapter receives user’s
configuration of a hybrid network depends on the needs data and translates it into a radio signal.
and structure of the organization where it is deployed. * Step 2: The radio signal is then transmitted through the
Consider an example of a hybrid network: an antenna.
organization has two departments where one department + Step 3: A wireless router receives the radio signal and
has connected its computers using the bus topology and decodes it.
the other department is using the ring topology. Now, the * Step 4: The router sends the decoded data to the Internet
networks of the two departments can be connected by a through a physical and wired connection.
central hub, thereby using the star topology. At the receiver's site, the same set of process takes
place but in reverse. The router receives the data from
8 ’ e the Internet through a wired connection. It translates data
=
into radio signals and transmits it to the sender's wireless
Pa@ ‘ adapter. If many computers are present cach with their
@
own wireless adapter, then all these computers can use a
single router to connect to the Internet. However, if the
7) @ router fails or if too many users access high-bandwidth
Figure 7.18 Hybrid topology applications at the same time, then users may cither
suffer from clectromagnetic interference or may get
disconnected.
WIRELESS NETWORKS
Wi-Fi Hotspots
A wireless network uses any of the wireless media to
connect computers on a network. Cellular phone networks An area with an accessible wireless network is called a Wi-Fi
and Wi-Fi local networks are examples of wireless hotspot. Wi-Fi hotspots that we often use at a public space
networks, Wireless LANs use high-frequency radio such ascafes and airports may be either free or may demand
signals, infrared light beams, or lasers to communicate asmuall fee for use. To use a Wi-Fi hotspot, users must have a
with remote computers. For longer distances, wireless wireless adapter that plugs into the PC card slot or universal
communication is also done through cellular telephone serial bus (USB) port. However, many new laptops and
technology, microwave transmission, or by satellites. desktops come with built-in wireless transmitters, Even the
Wireless networks enable laptop computers or other mobile devices are Wi-Fi-enabled to allow users to access
portable devices to connect to the LAN. They are also the wireless network from any location.
preferred in older buildings where it may be difficult or Once the wireless adapter is installed, the computer
impossible to install additional cables. in a Wi-Fi hotspot will automatically discover existing
A wireless network is a cost-effective means to access networks. It will then inform the user about the existing
the Internet. When we take our laptop cither at hotels, network and seek permission to connect to it,
airports, or other public places and access the Internet, we
are actually working through a wireless network. Bluetooth
Wi-Fi Bluetooth is a wireless technology for exchanging data by
using low-power radio communication. It is often used to
Wi-Fi is a wireless networking technology which provides link phones, wireless headsets, computers, and other devices
wireless Internet and network connections. WiFi Alliance, over short distances, typically up to 30 feet (10 metres).
which owns the Wi-Fi registered trademark, is a global, Bluetooth operates in 2.4 Hz of frequency range and allows
non-profit organization that helps to ensure standards and devices to communicate at less than 1 Mbps. Though some
interoperability for Wi-Fi networks. Wi-Fi networks use consider it to be a good replacement to Wi-Fi networks,
the Ethernet protocol. Bluetooth networking is not only slower but also limited in
range, and supports fewer devices.
Wireless Access Point Today, Bluctooth is commonly used in the following
applications:
A wireless access point (WAP) is a device that allows
wireless devices to connect to a wired network using * It is used in devices such as baby monitors, garage-
Wi-Fi, The access point in such a scenario can be a door openers, GPS receivers, bar code scanners, traffic
router, To understand the importance of a WAP, let us first control devices, medical equipment, modems, watches,
understand how a Wi-Fi network operates. Like walkie- and the new generation cordless phones. These devices
talkies, cell phones, radios, and televisions, a wireless come with in-built support for Bluctooth or a Bluctooth
network uses radio waves for a two-way communication dongle can be used to make a device ready for data
in the following manner. exchange using Bluetooth.
Computer Networks and the Internet
Data transmission
mode
-DOBGOOOO
Data for the first character
Opponano
Data for the second character
elalelsieieiel|»
Header
ojo
Advantages
* There is lower overhead as there is no need to send
START and STOP bits for every single character.
* It enjoys higher throughput because of the lower
overhead.
Disadvantages
* The sending and the receiving devices must have a
buffer area to assemble the blocks of data.
+ It is more complex than asynchronous mode of
transmission. The 7 layers of OS
* The hardware required is more expensive ‘Transmit User
+ For error-free transmission, the clocks of the receiving Dy
and sending devices must be synchronized. CK FJ Application layer
ee =) Presentation layer
Session yer
OPEN SYSTEM
MabepeeLoe
=| ‘Transport layer
concerned with the syntax and semantics of the data to be message and the network accepts only smaller siZ@
transmitted. Generally, the user's programs do not exchange messages), and sends them to the network layer.
data in binary format but as names, addresses, dates, + The transport layer at the destination station reassembles
messages, pictures, ctc. Moreover, different computers store the smaller units in the right sequence to form the
data in different formats. To enable communication among message.
these computers, the presentation layer translates data into a * It provides reliable delivery of messages
standard format to be sent on the network. * Thetransport layeratthe receiver sends acknowledgment
The second function of presentation layer is data to the sender when it receives the message.
compression, which is done to reduce the number of bits to * The transport layer at the receiver informs the sender
be sent over the network. The third function provided by to temporarily stop sending messages when no message
this layer issecurity. For this, it implements authentication, buffers are vailable at the receiver.
data encryption, and decryption functions to prevent * It performs data multiplexing
malicious users from accessing and interpreting the data. + Ifthere is an error in the message received, the transport
layer asks the sender to re-send that data,
there is a long sequence of characters in the address bar, directory. Anything following the question mark (?) in a
This is the URL. This means that to access any page on the URL is a pair of variable(s) and its value(s). In the URL,
Internet, we need to provide its URL q?computer*20fundamentals means that q is a variable
The file on the Internet that we want to access can be a name, and computer%20fundamentals is the value of q
web page, an audio file, video file, or image with extensions Since blank spaces are not allowed in a URL, blank space
him, .php, .mp4, .avi, .jpg. .bmp, .gif, .asp, .cgi, .xml, ete has been written as %20. Spaces can also be written as
The syntax for a URL is as follows: a +(plus) sign. In the query, the user is trying to search
Protocol://domain-name/path computer fundamentals on Google.
where protocol specifies the name of the protocol to be These values are sent by the user's computer to Google's
used to access the file resource. Commonly used protocols server. Google will find relevant pages and will display the
are http, https, ftp, telnet, news, gopher, mailto, etc. This result on the user's screen. Similarly, when we log in to our
field specifies how to connect. email account, we supply two values to the server—username
Domain name identifies the name of the website. This and password. In such a situation, multiple variables are
means that the domain field identifies where to connect separated with an ampersand (&) sign as shown here:
Path is a hierarchical description that indicates the location http://www.gmail.com/config/passwd
of the file. It indicates to the web server what to connect cgi?uverree&pes2ejmd3
For example, when we just write hitp://www.google In the URL, there are two different variables u with
com, http is the protocol, www.google.com is the domain value erree and p with value s2ejmd3
name, and by default, the home page which is saved as
index.htm is displayed to the user. Refer to Figure 7.29
which shows another sample URL. A domain name is not the same as URL because it is just
If we provide the URL as, http://www.cxample.com/
a small part ofthe entire URL.
Studenv/ABC.TXT, then http is used to fetch the file
AB,.TXT from Student directory stored in the computer on
which the website www.cxample.com is hosted.
There are 1PV5is an experimental protocol for Unix-based systems
‘Types of URLs basically two
and was never released to be used by the general
types of URLs as
public.All odd-numbered versions are developed for
shown in Figure
7.30, While an
experimental purposes.
Absolute URL, Relative URL absolute URL
some involve guest experts or celebrities to talk to other users on the Internet that are using the hypertext transfer
online people who want to join the chat protocol (HTTP)". On the web, all the documents are
formatted in a special markup language called hypertext
7.16.4 Internet Conferencing markup language (HTML), which supports links to other
The evolution of the Internet has changed the way in which documents, graphics, audio, and/or video This
feature enables the users to jump from one document to
css houses arrange conferences among the concerned
These days, organizations are increasingly another simply by clicking on hotspots. One must have
switching to the Internet conferencing to reduce the extra noted that when the cursor is positioned on a hotspot,
costs involved in travelling and making telephone calls,
also known as hyperlink, the cursor changes to resemble
a hand. When the hyperlink is clicked, the user is taken to
thereby resulting in better time management and enhanced
another location.
productivity
In simple terminology, the world wide web is a part of
Internet conferencing is quite similar to traditional
the Internet that allows easy navigation through the use
teleconferencing. The difference is that, during an Internet
of GUIs and hypertext links between different addr
conference call, the participants will sit in their respective
WWW was created in 1989 by Tim Berners-Lee.
offices while being connected to each other through the
Internet. Many Internet conferencing software packages
The web, in casy terms, is the user part of the Internet
allow as many as 25 online participants to participate in
Users make use of the Web to communicate and ace
information for business and recreational purposes. There
the web meeting.
are several applications called web browsers that make
Today, there are a number of software packages
it easy to access the web. Some popular web browsers
available on the Internet that can be casily downloaded
to host a conference call at little or no cost. To start an
are Mozilla Firefox, Opera, Google Chrome, Netscape
Navigator, and Microsoft's Internet Explorer.
Internet conference call, the users need a computer with
Many a times, we think that the Internet and the world
an Internet connection, related software, a webcam, and
wide web are the same, but this notion is not correct. The
a microphone (to see and hear what the remote or distant
Intemet and the web work together. While the Internet
participants are saying). During the conference, users can
provides the underlying structure, the web, on the other
share information, files, video, and audio clips
hand, utilizes that structure to offer content, documents,
multimedia, cte. For example, the Internet is like the
7.16.5 Electronic Newspaper highway, and the web is like a truck that uses that highway
An online newspaper, shown in Figure 7.32, also known to get from place to place.
as a web newspaper or an electronic newspaper, is a
newspaper on the Intemet, which is either published
separately or as an online version of a printed periodical
Hypertext isa method of instant cross-referencing.On
websites, certain words or phrases appear ina different
colour than the rest, and are often underlined. When
such words or phrases are selected, the users are
transferred
to the site or page that isrelevant
to this
word
or phrase. Sometimes
there are buttons, images, or
portions
of images that are ‘clickable’.
throughout the store until he or she locates the products information about our body parts and not enough
that are needed. Even after selecting all the products, the specific hits about kidney
customer has to wait in long queues to get the billing done. * If required, use two or more keywords: However, write
In striking contrast, online shopping is very convenient the most important keywords first. For example, if
With online shopping, a shopper logs onto the Internet, information is required about the functions of kidneys
visits the store's website, and selects the products. then write both the words in the same order,
Once all the products have been selected, the user can * Write correct spellings of the keyword: Wrong spellings
click the option to calculate the invoice and pay for the can give unexpected results. For example, if information
purchase using their debivecredit card. Figure 7.33 shows on hear is required, spelling the word as beer will give
an electronics shopping cart used by an online shopping entirely different results,
portal, + Use more than one search engine: Bach search engine
gives different results. This is because different search
engines look through different websites on the Internet
to create their databases. When searching using a
particular search engine, only a small proportion of the
total sites available is considered. Therefore, searching
POINTS TO REMEMBER
* A computer network, simply known as a network, is a * OS! model simplifies the entire process of network
collection of computers and devices interconnected communication (by dividing it into logical smaller
to facilitate sharing of resources, information, and pieces) and makes network designs more extensible
electronic documents and among interconnected as new services can easily be added in a layered
devices, architecture than in a monolithic one.
The three primary physical components of a computer * Transmission Control Protocol (TCP) is a protocol that
network are connecting media, network devices, and works at the transport layer and is used with the IP
network topologies. protocol, which is used to send data packets between
The wireless technologies that connect computers sender and receiver devices.
and other devices to form a network include terrestrial © The Internet is a global network that connects billions
microwave, communication satellites, cellular of computers all over of the world.
systems, and infrared systems. * Internet protocol address is a unique address allotted
The topology of a network refers to the schematic to computing devices such as computers, routers,
description of the arrangement of a network. That is, printers, scanners, modems, smartphones, tablets,
it refers to the actual geometric layout of computers and so on that are connected to the internet.
and other devices connected to the network. * Domain name system (DNS) is a service that
Wireless LANs use high frequency radio signals, automatically converts domain names into IP addresses,
infrared light beams, or lasers to communicate with * While an absolute uniform resource locator (URL)
remote computers. specifies the complete URL containing all three fields—
Wi-Fi is a wireless networking technology which protocol, domain, and path, relative URLs, on the other
provides wireless internet and network connections. hand, contain only one field—the domain name.
Bluetooth is a wireless technology for exchanging data . Electronic mail (email) means the transmission of
by using low-power radio communication. messages over communication networks.
Transmission of data through a communication * Internet chat allows two or more online users to come
channel between two machines can take place in together to talk using an instant messenger.
different ways depending on the direction of the data * With online newspaper, users can read the full
flow, number of bits sent simultaneously, and coverage of breaking news in a timely manner.
synchronization between the sending and the * Online shopping means buying goods and/or services
receiving devices, from merchants who sell on the Internet.
GLOSSARY
Bridge A device that connects two or more LANs. When a the message typed by the other person appears on the
bridge receives data from one LAN to forward to another, user's screen.
it first regenerates (or amplifies) the signals and then Client program A program that requests information
forwards the data. from another computer on the network, The client
Browser It is a software that enables the users to access program accesses and displays the retrieved information
the web. to the user. For example, the web browser is a client
Bus topology It is a network topology in which each program that accesses and displays web pages.
computer or server is connected to a single cable and all Computer network it is a collection of computers and
the nodes share the same communication channel. devices interconnected to facilitate sharing of resources,
CAN itstands for campus area network and interconnects information, and electronic documents among
LANs within a limited geographical area. CAN is almost interconnected devices.
entirely owned by the campus of an enterprise, university, Download To make a copy of a file from another computer to
government, military base, etc. your computer, Forexample,
the user may copy a song from
Chat An internet service that enables users to another computer on the Internet to his or hercomputer.
communicate with other people in real-time. The user E-mail It is a communications system designed to enable
types message using his or her keyboard. The message the users to send and receive electronic messages across
then appears on the screen of the other person. Similarly, a network.
146 Computer Fundamentals and Programming in C
| FTP Short form of file transfer protocol. It is basically Mesh topology It is a topology in which each node is
@ program that enables users to transfer files from one connected to every other node on the network using a
computer to another. separate physical link.
Gateway It is a device which connects two or more Network Two or more computers or computing devices
dissimilar networks that use entirely different protocols. when connected with each other to share information
Gopher A program that organizes information on the and/or resources forms a network
Internet by using a system of menus. Items in the menus Network topology The schematic description of the
can be linked to other documents, or to other information arrangement of a network.
services, Newsgroup An Internet service in which readers can
Host Any computer on a network. post messages or articles for other people to read.
HTML HTML stands for hypertext markup language and Other people can also reply to articles that they read on
is used to create hypertext documents for use on the web. a Newsgroup. It enables people with similar interests to
HTTP it stands for hyper text transfer protocol. It is a communicate with each other.
protocol that defines a set of rules to exchange documents Node Each computer connected to a network is called
on the web. anode.
Hub It is a network device that connects devices to PAN It stands for personal area network and is designed
enable them to communicate with each other. for communication between devices such as mobile
Hybrid topology It is a topology that uses a combination computers, cell phones, and PDAs that are close to one
of any two or more topologies in such a way that the person. The scope or the reach of a PAN is a few metres
resulting network does not exhibit one of the standard (less than 10 metres).
topologies. Ping It is a message sent to check if a server is running.
Hypertext itis a hypertext document is one that includes Protocol A set of standardized rules that should be
links to other documents on the web. followed to exchange information among computers.
Internet The Internet is a network of networks. It There are different types of protocols for different kinds
connects several networks all around the world to enable of communication. For example, HTTP specifies the rules
them to exchange information with each other. For this for exchanging information on the WWW. FTP defines the
purpose, all the computers on the internet use a common tules to copy files from one computer to another across
set of rules (protocol) for communication. Therefore, a network.
the Internet uses a set of protocols called transmission Repeater A network device that regenerates incoming
control protocol/internet protocol (TCP/IP). electrical, wireless, or optical signals. Without a repeater,
Internet service provider A commercial service that sells the data can only span a limited distance before the
access to the Internet to individuals. Users connect to the quality of the signal degrades.
ISP through a modem, While some ISPs only offer a basic Ring topology A topology in which all the nodes are
connection to the Internet, others, on the other hand, connected to each other in the shape of a closed loop, so
sell a variety of value-added services such as discussion that every node is connected directly to two other nodes,
forums, tech support, software libraries, news, weather ‘one on either side of it.
reports, stock prices, plane reservations, and even
Router An intelligent network device that routes data to
electronic shopping malls.
destination computers. It is basically used to connect two
LAN It stands for local area network and connects devices logically and physically different networks, two LANs, two
ina limited geographical area. Owing to their limited scope WANs, and a LAN with a WAN,
and cost of operation, LANs are typically owned, controlled,
Server A program that provides information or services
and managed by a single person or organization.
to other programs. For example, the web browser is a
Link A word, picture, or other area of a web page that client that uses services like e-mail from the server,
users can click on to move to another spot in the same
Star topology A topology in which each node is
document or to another document. Links (words) may
connected to a central hub (or server) with a point-to-
be underlined and usually appear in a contrasting text
point connection.
colour. When the user clicks on the link, the colour of the
text changes. Switch It is a switch is an intelligent network device that
sends the data to the destined device.
MAN It stands for metropolitan area network and
interconnects computers and other devices in a Upload It is just the opposite of download and means
geographic area or region larger than that covered by transferring a file, picture, document, and/or audio/video
even a large LAN but smaller than the area covered by clip fromm one’s computer to some other computer,
a WAN. URL Auniform resource locator (URL) specifies the addresses
Computer Networks and the Internet 147
for webpages. That is, a URL uniquely identifies a webpage. wireless devices to connect to a wired network using Wi-Fi
URLs have three parts: Protocol name, server name, and a Webpage It is a document on the web that can contain
directory path. For example, consider the URL http://wings. text, pictures, movies, sounds, or links to other pages.
avkids.com/SPIT/index.html, Here, “http://" is the name of Website It is a collection of web pages on the web having
the protocol, ‘wings.avkids.com’ is the server's name, and ‘/ to do with a particular topic or organization.
SPIT/index.htm’ is the location of the file on the server.
Wi-Fi It stands for wireless fidelity and usually means a
WAN It stands for wide area network and spans a
form of wireless data communication.
large geographical area such as a city, country, or even
intercontinental distances, using a communications Wi-Fi hotspot It is an area with an accessible wireless
channel that combines many types of media such as network
telephone lines, cables, and air waves. World Wide Web An interconnected set of hypertext
documents located throughout the Internet.
Wireless access point (WAP) It is a device that allows
EXERCISES
Fill in the Blanks 20 __ layer acts as a translator between the application
LA cable is a highly preferred connecting media program and the network format.
for cable television systems.
2. The ___ of the fibre optic cable causes light to travel Multiple-choice Questions
in a controlled path along the entire length of the glass 1. Which mode of data transmission is used in point-of-sale
core terminals?
3. The geosynchronous satellites are positioned at a (a) Simplex (b) Half-duplex
distance of___ kms above the equator. (c) Full-duplex (d) Serial
4, The ____ mode of data transmission is utilized in web 2. Which connection can be thought of as a two-lane bridge?
browsing.
(a) Synchronous (b) Half-duplex
5S. Ina connection, n bits are simultaneously
transmitted over the communication channel (c) Full-duplex {d) Parallet
3. Which mode of transmission is best suited for connecting
6, START and STOP bits are sent in mode of
transmission
input devices, printers, modems, fax machines, etc., to
the computer?
7. In synchronous transmission, the sender and the receiver
are synchronized using 3 _ (a) Synchronous (b) Asynchronous
8. The___ refers to the actual geometric layout of (c) Full-duplex {d) Parallel
computing devices connected to the network 4, in which topology do the nodes share the same
9. In the topology, each node is connected to a communication channel?
central hub. (a) Ring (b) Star
10. A mesh network of n nodes requires physical (c) Bus (d) Mesh
links. 5. Which topology is best suited for a network that does
11, LANs are based on technology. not have a hub?
12. Bluetooth PANs are also called (a) Ring (b) Star
13. Router uses special software known as
(c) Bus (d) Mesh
14, The _ is a network of networks.
6. In which topology has every node an equal chance to
15. The WWW was created by transmit data?
16. Wi-Fi networks use the protocol.
{a) Ring {b) Star
17. is a device that allows wireless devices to connect
to a wired network using Wi-Fi
(c) Bus (d) Mesh
18, Bluetooth operates in of frequency range and 7. Which device is used to connect a LAN to a WAN?
allows devices to communicate at less than _ (a) Hub (b) Switch
19 is an example of application layer (c) Bridge (d) Router
148 ‘Computer Fundamentals
and Programming in C
The underlying technology of WAN may include which of 13. The Internet and the world wide web are the same.
the following? 4 A server is a program that provides information or
(a) Frame Relay (b) X.25 services to other programs.
(c) ATM (d) Ail of these 15. Cellular phone network is an example of wireless
networks.
Which of the following acts as the liaison for the
computer to send and receive data on the LAN? 16 Router is an example of WAP.
17 Bluetooth technology can be used to connect devices in
(a) Hub (b) Gateway
a range of 100 meters.
{c) Bridge (d) NIC
18 Session layer is responsible for data compression.
10. A program that requests information from another
19 Error and flow control are done by both transport and
computer on the network is known as__
data link layer.
(a) hub (b) server
(c) client ({d) host Review Questions
13, HTTP, WWW, FTP, TELNET, and SMTP are used in which Define the term network. Give its key advantages.
layer of OSI? What do you understand by the term connecting media?
(a) Physical {b) Network ilustrate it in detail with respect to wired networks.
(c) Application {(d) Presentation Why are fibre optic cables better than twisted-pair and
122 Which layer decides the optimal route for data coaxial cables?
transmission? Write a short note on wireless network technologies.
(a) Physical (b) Network wpWhatare the limitations of using infrared communication?
Differentiate among simplex, half-duplex, and full-duplex
(c) Session {d) Data Link
modes of data transmission.
13, IP, ARP, RARP, ICMP protocols are used in the _
layer of TCP/IP model How is parallel transmission better than serial
transmission? Is there any consideration for transmitting
(a) Application (b) Transport
the data in parallel?
(c) Internet {d) Network Access Explain the synchronous and asynchronous modes of
data transmission.
State True or False What is topology? Discuss key topologies used to forma
1 Twisted-pair cables are free from noise and other network,
electrical interference. Differentiate between a MAN and a WAN
The satellite amplifies the received signal before Write a short note on the different types of area
transmitting it back to the earth-based antenna. networks.
Infrared signals can be transmitted within small distances Which device will you prefer to form a network—hub or
not more than 10 metres without any object in the line a switch? Justify your answer.
of transmission.
Explain the role of repeaters. How are they helpful?
in duplex mode, there must be two communication
How can a bridge help in controlling traffic on network
channels between the sender and the receiver.
segments?
in a computer, binary data flows from one unit to another
in what situation must the network have a gateway?
using parallel mode.
What is NIC?
Bus topology requires less cable length than star
Write an essay on the Internet and its services,
topology.
Why [s online shopping not very popular among the
Each node in a star topology acts as a signal repeater,
masses?
In ring topology, every node is connected to every other
What are the layers in OS! model? Write the utility of
node on the network.
each layer.
The Internet is the largest PAN
Write a brief note on TCP/IP Model.
Hub broadcasts a message to every device on the
Differentiate between static and dynamic IP address
network.
What do you understand by the term URL?
11 Bridge ts an intelligent network device.
Explain the significance of DNS
12 A gateway provides security to the network
ry
oy
re beDesigning Efficient Programs
TAKEAWAYS
© Programming paradigms © Flowcharts © Testing
* Design of efficient programs © Pseudocodes * Debugging
* Algorithms © Typesof errors
has meaningful names and has clear documentation is that the program accessing this list need not contaiiy
to identify the task performed by it. Morcover. procedures for performing tasks; rather, it uses the
a correctly written structured program is self- routines provided in the object. In other words, instead
documenting and can be casily understood by another of sorting the list as in the procedural paradigm, the
programmer, program asks the list to sort itself. Therefore, we can
More emphasis is given on the code and the least conclude that the object-oriented paradigm is task-based
importance is given to the data (as it considers operations) as well as data-based (as
these operations are grouped with the relevant data).
Disadvantages The striking features of OOP include the following:
* Not data-centred Programs are data centred.
* Global data is shared and therefore may get inadvertently Programs are divided in terms of objects and not
modified procedures.
* Main focus is on functions * Functions that operate on data are tied together with the
data.
8.1.4 Object-oriented Programming (OOP) * Data is hidden and not accessible by external functions.
* New data and functions can be casily added as and when
With the increase in required.
size and complexity of * Follows a bottom-up approach for problem solving.
programs, there wasaneed
In the forthcoming chapters, we are going to study C
for a new programming
programming language which supports both procedural as
Object 2 paradigm that could help
well as structured programming.
to develop maintainable
programs. To implement
this, the flaws in previous
paradigms had to be 3 EXAMPLE OF A STRUCTURED
corrected. Consequently, PROGRAM
OOP was developed. It
treats data as a critical Imagine that your institute wants to create a program to
clement in the program manage the names and addresses of a list of students. For
Objects of a program development and restricts this, you would need to break down the program into the
interact by sending its flow freely around following modules:
messages to each other the system. We have
+ Enter new names and addresses
Figure 8.4 Object-oriented seen that monolithic, * Modify existing entries
paradigm procedural, and structured * Sort entries
programming paradigms + Print the list
are task-based as they focus on the actions the program
should accomplish. However, the object-oriented Now, each of these modules can be further broken
puradigm is task-based and data-based. In this paradigm, down into smaller modules. For example, the first module
all the relevant data and tasks are grouped together in can be subdivided into modules such as follows
entities known as objects (refer to Fig. 8.4). For cxample, * Prompt the user to enter new data
consider a list of numbers. The procedural or structured * Read the existing list from the disk
programming paradigm considers this list as merely a * Add the name and address to the existing list
collection of data. Any program that accesses this list * Save the updated list to the disk
must have some procedures or functions to process this Similarly, ‘Modify existing entries’ can be further
list. For example, to find the largest number or to sort divided into modules such as follows:
the numbers in the list, we need specific procedures or
functions to do the task, Therefore, the list is a passive + Read the existing list from disk
entity as it is maintained by a controlling program rather * Modify one or more entries
than having the responsibility of maintaining itself * Save the updated list to disk
However, in the object-oriented paradigm, the list and Observe that the two sub-modules—‘Read the
the associated operations are treated as one entity known existing list from disk’ and ‘Save the updated list to
as an object. In this approach, the list is considered an disk’ are common to both the modules. Hence, once
object consisting of the list, along with a collection of these sub-modules are written, they can be used in
routines for manipulating the list. In the list object, there both the modules, which require the same tasks to be
may be routines for adding a number to the list, deleting performed. The structured programming method results
a number from the list, sorting the list, etc. The major in a hierarchical or layered program structure, which is
difference between OOP and traditional approaches depicted in Figure 8.5
152 Computer Fundamentals and Programming in C
original design or an extra piece of code, required to fix Step 1: Input first number as A
an unforeseen problem. As a general rule, if the cost of the Step 2: Input second number as B
maintenance phase exceeds 25% of the prior phase’s cost, Step 3: Set Sum = A+B
then it clearly indicates that the overall quality of at least
Step 4: Print Sum
one prior phase is poor. In such cases, it is better to re-build
Step 5: End
the software (or some modules) before the maintenance
cost shoots out of control.
Figure 8.7 Algorithm to add two numbers
(EZ proGRAM DESIGN TOOLS:
ALGORITHMS, FLOWCHARTS, A condition in this context
may evaluate cither to a true value or a false value
is any statement that
Example 8.2 ——
8.4.2 FLOWCHARTS
Write an algorithm to find whether a number is even or odd.
Solution A flowchart is a graphical or symbolic representation of
Step 1: Input number as A a process. It is basically used to design and document
virtually complex processes to help the viewers to visualize
Step 2: IFAX2*0 the logic of the process, so that they can gain a better
Print “Even”
understanding of the process and find flaws, bottlenecks,
ELSE and other less obvious features within it
Print “Odd” When designing a flowchart, each step in the process
[END OF IF) is depicted by a different symbol and is associated with
Step 3: End
a short description. The symbols in the flowchart (refer
Figure 8.10) are linked together with arrows to show the
flow of logic in the process.
Example 8.4
The symbols used in a flowchart include the following
Write an algorithm to print the grade obtained by a student + Start and end symbols are also known as the terminal
using the following rules: symbols and are represented as
circles, ovals, or rounded
Marks | Grade ingles. Terminal symbols are always the first and
the last symbols in a flowchart
Above 75 ° * Arrows depict the flow of control of the program. They
60-75 A illustrate the exact sequence in which the instructions
50-60 8 are executed.
Generic processing step, also called as an activity,
40-50 c
is represented using a rectangle. Activities include
\ Less than 40 D instructions such as add a to b, save the result
Therefore, a processing symbol represents arithmetic
Solution
and data movement instructions. When more than
Step 1: Enter the marks obtained as M one process has to be executed simultaneously, they
Step 2: IF M> 75 can be placed in the same processing box. However,
Print
Designing Efficient Programs 155
Solution
i ‘Start or end Input/Output
symbol symbol
Example 8.6
Limitations
+ Drawing flowcharts is a laborious and a time-consuming
activity. Just imagine the effort required to draw a
flowchart of a program having 50,000 statements in it!
* Many a times, the flowchart of a complex program
becomes complex and clumsy
* At times, a little bit of alteration in the solution may
require complete redrawing of the flowchart
Example * The essentials of what is done may get lost in the
technical details of how it is done.
Draw a flowchart to determine the largest of three numbers. * There are no well-defined standards that limit the details
that must be incorporated into a flowchart
Solution
8.4.3 Pseudocodes
Pscudocode is a compact and informal high-level
description of an algorithm that uses the structural
conventions of a programming language. It facilitates
designers to focus on the logic of the algorithm without
getting bogged down by the details of language syntax
An ideal pseudocode must be complete, describing the
entire logic of the algorithm, so that it can be translated
straightaway into a programming language.
It is basically meant for human reading rather than
machine reading, so it omits the details that are not essential
for humans. Such details include variable declarations,
system-specific code, and subroutines.
Pseudocodes are an outline of aprogram that can easily
be converted into programming statements, They consist
of short English phrases that explain specific tasks within
4 program's algorithm. They should not include keywords
in any specific computer language.
The sole purpose of pseudocodes is to enhance
human understandability of the solution. They are
commonly used in textbooks and scientific publications
for documenting algorithms, and for sketching out the
program structure before the actual coding is done. This
helps even non-programmers to understand the logic of
Advantages the designed solution. There are no standards defined for
writing a pscudocode, because a pseudocode is not an
* They are very good communication tools to explain the executable program. Flowcharts can be considered as
logic of a system to all concemed. They help to analyse graphical alternatives to pseudocodes, but require more
the problem in a more effective manner. Space on paper.
Designing Efficient Programs 657
TYPES OF ERRORS
je8.11
While writing programs, very often we get errors in our
Write a pseudocode to calculate the weekly wages of an programs. These errors if not removed will cither give
employee. The pay depends on wages per hour and the erroncous output or will not let the compiler to compile
number of hours worked. Moreover, if the employee has the program. These errors are broadly classified under four
worked for more than 30 hours, then he or she gets twice groups as shown in Figure 8.11.
the wages per hour, for every extra hour that he or she has
worked, ‘Types
oferrors
Solution
1. Read hours worked Run-time Compile-time
Linker Logical
2. Read wages per hour emer errors erfors = errors
3. Set overtime charges to 0
4. Set overtime hrs to 0 Figure 8.11 Types of Errors
5. IF hours worked > 30 then
a. Calculate overtime hrs = hours worked - Run-time Errors As the name suggests, run-time errors occur
30 when the program is being run executed. Such errors occur
b. Calculate overtime charges = overtime when the program performs some illegal operations like
hrs = (2 = wages per hour) * dividing a number by zero
c. Set hours worked = hours worked - * opening a file that already exists
overtime hrs * lack of free memory space
ENDIF
* finding square or logarithm of negative numbers
6 Calculate salary = (hours worked « wages
per hour) + overtime charges Run-time errors may terminate program execution,
7. Display salary so the code must be written in such a way that it handles
5. End all sorts of unexpected errors rather terminating it
Variables: hours worked, wages per hour, unexpectedly.
overtime charges, overtime hrs, salary Compile-time Errors Again us the name implies, compile-
time errors occur at the time of compilation of the program.
Such errors can be further classified as follows:
Example 8.12 Syntax Errors Syntax errors are generated when rules of a
programming language are violated.
Write a pseudocode to read the marks of 10 students. If
Semantic Errors Semantic errors are those errors which
marks is greater than 50, the student passes, else the student
may comply with rules of the programming language but
fails. Count the number of students passing and failing.
are not meaningful to the compiler.
Solution
Logical Errors Logical errors are errors in the program
1. Set pass to 0 code that result in unexpected and undesirable output
158 Computer Fundamentals and Programming in C
Which is obviously not correct. Such errors are not Cause Elimination In this approach, a list of all possible
detected by the compiler, and programmers must check causes of an error is developed. Then relevant tests are
their code line by line or use a debugger to locate and carried out to eliminate each of them. If some tests indicate
rectify the errors. Logical errors occur due to incorrect that a particular cause may be responsible for an error then
statements, the data are refined to isolate the error.
Linker Errors These errors occur when the linker is not
able to find the function definition for a given prototype Example 8.13
33 TESTING AND DEBUGGING solution, implement it in C and then test our program.
APPROACHES
Marks Grade
Testing is an vity that is performed to verify correct Above 75 ° |
behaviour of a program. It is specifically carried out with 60-75 A |
an intent to find errors. Ideally testing should be conducted
at all stages of program development. However, in the 50-60 8
implementation stage, the following three types of tests 40-50 c
can be conducted
tessthan4O 0D
Unit Tests Unit testing is applied only on a single unit
or module to ensure whether it exhibits the expected Problem Statement To develop an automa
behaviour. accepts marks of a student and generates his/her gi
Integration Tests These tests are a logical extension of Requirements Analysis Ask the users to enlist the rules
unit tests. In this test, two units that have already been for assigning grades. These rules are
tested are combined into a component and the interface Design In this phase, write an algorithm that gives a
between them is tested. The guiding principle is to test solution to the problem
combinations of pieces and then gradually expanding the
component to include other modules as well, This process Step 1: Enter the marks obtained as M
is repeated until all the modules are tested together. The Step 2: If M > 75 then print "0"
main focus of integration testing is to identify errors that Step 3: If M >= 60 and M < 75 then print "A"
occur when the units are combined. Step If M >= 50 and M < 60 then print “B"
Step 5: If M >= 40 and M < 50 then print "Cc"
System Tests tem testing checks the entire system. For
else
example, if our program code consists of three modules print "Dp"
then cach of the module is tested individually using unit Step 6: End
tests and then system test is applied to test this entire
system as one system implementation Write the C program to implement the
Debugging, on the other hand, is an activity that proposed algorithm.
includes execution testing and code correction. The main #include <stdio.h>
aim of debugging is locating errors in the program code. #include <conio.h>
Once the errors are located, they are then isolated and int main()
fixed to produce an error-free code. Different approaches { int marks;
applied for debugging a code includes: char grade;
clrscr();
Brute-Force Method In this technique, a printout of
printf("\n Enter the marks of the student
CPU registers and relevant memory locations is taken,
scanf("Xd", &marks);
studied, and documented. It is the least efficient way of if (marks<O || marks >100)
debugging a program and is generally done when all the
{ printf("\n Not Possible");
other methods fail.
exit(1);
Backtracking Method It is a popular technique that }
is widely used to debug small applications. It works if (marks>=75)
by locating the first symptom of error and then tracing grade = ‘0’;
backward across the entire source code until the real else if(marks>=60 && marks<75)
cause of error is detected. However, the main drawback grade = ‘A’;
of this approach is that with increase in number of source else if(marks>=50 && marks<60)
code lines, the possible backward paths become too large grade = ‘B’;
to manage. else if(marks>=40 && marks<50)
Designing Efficient Programs 159
POINTS TO REMEMBER
Programs written using monolithic programming * After the code is tested and the software or the
languages such as assembly language and BASIC program has been approved by the users, it is then
consist of global data and sequential code. installed or deployed in the production environment.
In procedural languages, a program is divided into * Maintenance and enhancements are ongoing
subroutines that can access global data. activities that are done to cope with newly discovered
Structured programming employs a top-down problems of new requirements,
approach in which the overall program structure is * The different tools which are available to design
broken down into separate modules, solution(s) of a given problem are: algorithms,
Object-oriented programming treats data as a critical flowcharts, and pseudocodes,
element in the program development and restricts its Algorithms give the logic of the program, that is, a
flow freely around the system. step-by-step description of how to arrive at a solution,
The entire program or software (collection of programs) They are implemented using programming languages.
development process is divided into a number of * A flowchart is a diagrammatic representation that
phases, where each phase performs a well-defined task. iMlustrates the sequence of steps that must be performed
During requirements analysis, users’ expectations are to solve a problem. They are usually drawn in the early
gathered to know why the program/software has to stages of formulating computer solutions, They facilitate
be built, communication between programmers and users.
In the design phase, a plan of action is made. * Pseudocode is a compact and informal high-level
In the implementation phase, the designed algorithms description of an algorithm that uses the structural
are converted into program code using any of the conventions of an algorithm. It facilitates the designers
high-level languages. to focus on the logic of the algorithm without getting
In the testing phase, all the modules are tested bogged down by the details of language syntax.
together to ensure that the overall system works well
as a whole product.
GLOSSARY
Algorithm A formally defined procedure for performing Debugging An activity that includes execution testing and
some calculation. It provides a blueprint to writing a code correction. The mainaim of debugging is to locate
program that solves a particular problem. errors in the program code.
Compile-time errors These are errors that occur at the Flowchart A flowchart is a graphical or symbolic
time of compilation of the program representation of a process.
160 Computer Fundamentals and Programming in C
EXERCISES
Fill in the Blanks (a) Rule-based (b) Constraint-based
1 and statements are used to change the (c) Structured (d) Object-oriented
sequence of execution of instructions. 3. Which type of programming does not support
2 paradigm supports bottom-up approach of subroutines?
problem-solving, (a) Monolithic (b) Structured
3, FORTRAN and COBOL are two popular
(c) Rule-based (d) Object-oriented
programming languages.
4, C and Pascal belong to which type of programming
4 _ is a formally defined procedure for performing language?
some calculation.
{a) Monolithic (b) Structured
5; statements are used when the outcome of the
process depends on some condition, {c) Logic-oriented (d)} Object-oriented
6. Repetition can be implemented using constructs such as 5. Which paradigm holds data as a priority?
s , and _ {a) Monolithic (b) Structured
7, The___ symbol is always the first and the last symbol (c) Logic-oriented (d) Object-oriented
in a flowchart 6, Which among the following is an ongoing activity in
8. is a form of structured English that describes software development?
algorithms (a) Requirements analysis (b) Implementation
9 is used to express algorithms and as a mode of (c) User training (d) Maintenance
human communication.
7. The functionality, capability, performance, availability of
10, Inthe _ phase, a plan of actions is made hardware and software components are all analysed in
11. Algorithms and flowcharts are designed in the which phase?
phase.
{a) Requirements analysis (b) Design
12. Inthe ___ phase, designed algorithms are converted
(c) implementation (d) Testing
into program code.
13, User’s expectations are gathered in the _ phase 8. in which phase are algorithms, flowcharts, and
pseudocodes prepared?
14 errors may terminate program execution.
15. Debugging is an activity that includes __ and (a) Requirements analysis (b) Design
(c) implementation (d) Testing
9. Algorithms shouldbe
Multiple-choice Questions (a) precise (b) unambiguous
1, Which programming paradigm utilizes invariant (c) clear (d) all of these
relationships to solve a problem? 10. To check whether a given number is even or odd, you will
(a) Rule-based (c) Structured use which type of control structure?
(b) Constraint-based (d) Object-oriented (a) Sequence (b) Decision
2. Which is the preferred paradigm for designing a (c) Repetition (d) All of these
knowledge base? 11. Which one of the following is a graphical or symbolic
Designing Efficient Programs. 16!
representation of a process? 15. In the deployment phase, all the modules are tested
(a) Algorithm (b) Flowchart together to ensure that the overall system works well as
(c) Pseudocode (d) Program a whole product.
12. In a flowchart, which symbol is represented using a 16. Maintenance is an ongoing activity.
rectangle? 17. Algorithms are implemented using a programming
language.
(a) Terminal (b) Decision
18. Logical errors are detected by the compiler.
(c) Activity (d) Input/Output
13, Which of the following details are omitted in
Review Questions
pseudocodes? What do you understand by the term ‘programming
(a) Variable declaration (b) System specific code paradigm’?
(c) Subroutines (d) All of these Discuss any three programming paradigms in detail
14, Trying to open a file that already exists, will result in How is structured programming better than monolithic
which type of error? programming?
(a) Run time {b) Compile time Describe the special characteristics of monolithic
(c) Linker error (d) Logical error programming.
15. Which of the following errors is generated when rules of Explain how functional abstraction is achieved in
4 programming language are violated? structured programming.
(a) Syntax error (b) Semantic error
Which programming paradigm is data-based and why?
What are the advantages of modularization?
(c) Linker error (d) Logical error
Briefly explain the phases in software development
project
State True or False
Define an algorithm. How is it useful in the context of
1, In monolithic paradigm, global data can be accessed and
software development?
modified from any part of the program.
Explain sequence, repetition, and decision statements?
Monolithic programs have two modules.
In addition, give the keywords used in each type of
, Monolithic programs are easy to debug and maintain statement
. Structured programming is based on modularization.
With the help of an example explain the use of a flowchart.
Object-oriented programming supports modularization How is a flowchart different from an algorithm? Do we
Structured programming heavily uses goto statements.
need to have both of them for developing a program?
Modules enhance the programmer's productivity. What do you understand by the term pseudocode?
A structured program takes more time to be written than
Snauauwun Differentiate between algorithm and pseudocodes.
other programs.
Testing is an unavoidable phase in software development
9. An algorithm solves a problem in a finite number of
life cycle. Comment.
steps What are the different types of errors which frequently
10, Repetition means that each step of the algorithm is occur in programs?
executed in the specified order. Differentiate between syntax and semantic errors,
11, Terminal symbol depicts the flow of control of the
Differentiate between unit test, integration test, and
program. system test
12, Labelled connectors are square in shape.
19. What are the different techniques for debugging a
13, Flowcharts are drawn in the early stages of formulating computer program?
computer solutions.
20. Suppose you are given a problem to find all composite
14, The main focus of pseudocodes is on the details of the
numbers in range provided by users. Perform all the
language syntax. phases of software development on this problem
PART II
PROGRAMMING
INC
Introduction to C
Decision Control and Looping Statements
Functions
Arrays
Strings
Pointers
Files
Preprocessor Directives
TAKEAWAYS
* Writing a C program © Identifiers © Operators
* Compiling and executing C programs « Basic data types * Operator precedence chart
* CTokens © Variables and constants © Type conversion and typecasting
* Keywords * Input/Output statements
cw
9.1.3 Uses of C
Figure 9.1 Taxonomy of C language
C isa very simple language that is widely used by software
professionals around the globe. The uses of C language
9.1.2 Characteristics of C can be summarized as follows:
C is 4 robust language whose rich set of built-in functions * C language is primarily used for system programming.
and operators can be used to write complex programs. The The portability, efficiency, the ability to access specific
C compiler combines the features of assembly languages hardware addresses, and low runtime demand on system
and high-level languages, which makes it best suited for resources make it a good choice for implementing
writing system software as well as business packages. Some operating systems and embedded system applications.
basic characteristics of Clanguage that define the language * C has been so widely accepted by professionals
and have led to its popularity as a programming language that compilers, libraries, and interpreters of other
are listed below, In this book, we will learn all these aspects. programming languages are often written in C
For portability and convenience reasons, C is sometimes
* Cis ahigh-level programming language, which enables used as an intermediate language for implementation
the programmer to concentrate on the problem at hand of other languages. Examples of compilers which use
and not worry about the machine code on which the C this way are BitC, Gambit, the Glasgow Haskell
program would be run. Compiler, Squeak, and Vala.
Small size—C has only 32 keywords. This makes it * Basically, C was designed as a programming language
relatively casy to leam as compared to other languages. and was not meant to be used as a compiler target
+ C makes extensive use of function calls. language. Therefore, although C can be used as an
* C is well suited for structured programming. In this intermediate language it is not an ideal option. This led
programming approach, C enables users to think of to the development of C-based intermediate languages
a problem in terms of functions/modules where the such as C
collection of all the modules makes up a complete * Cis widely used to implement end-user applications.
program, This feature facilitates case in program
debugging, testing, and maintenance.
Unlike PASCAL it supports loose typing (as a character 83 structure OF AC PROGRAM
can be treated as an integer and vice versa).
Structured language as the code can be organized as a A C program is composed of preprocessor commands,
collection of one or more functions a global declaration section, and one or more functions
Stable language. ANSI C was created in 1983 and since (Figure 9.2),
then it has not been revised. The preprocessor directives contain special
* Quick language as a well written C program is likely instructions that indicate how to prepare the program for
to be as quick as or quicker than a program written compilation. One of the most important and commonly
in any other language. Since C programs make use of used preprocessor commands is include which tells the
operators and data types, they are fast and efficient. For compiler that to execute the program, some information is
example, a program written to increment a value from needed from the specified header file.
Introduction to C 167
Preprocessor directives on the tasks that have to be performed, and cach function
can have any number of statements arranged according to
specific meaningful sequence.
The message is quoted The -o is for the output file name. If you leave out the
Programming
Marbepgmeten *
:
because in C atext(also known -o then the file name a.out is used.
igs as a string or a sequence of This command is used to compile your C program. If
bale ol will characters) is always put there are any mistakes in the program then the compiler
iaiahs 4 between inverted commas. will tell you the mistake you have made and on which line
Bs ‘\n’ is an escape sequence and you made it. In case of errors you need to re-open your
error,
represents a newline character, € file and correct those mistakes. However, if everything
It is used to print the message is right then no error(s) will be reported and the compiler
on a new line on the screen. Like the newline character, will create an .exe file for your program. This .exe file can
the other escape sequences supported by C language are be directly run by typing
shown in Table 9.1, *hello.exe’ for Windows and ‘./hello’ for UNIX/
Linux operating system.
Table 9.1 Escape sequences When you run the .exe file, the output of the program
will be displayed on sercen, That is,
Escape Purpose Escape Purpose
sequence sequence Welcome to the world of C
Files in a C program
Library Library
tiles files
Library
les
C TOKENS
Tokens are the basic building blocks in C language. You
may think of a token as the smallest individual unit in a C
program, This means that a program is constructed using Figure 9.8 White space characters in C
a combination of these tokens, There are six main types of
tokens in C. They are shown in Figure 9.7 XE) kevworps
Like every computer language, C has a set of reserved
Tokens in C words often known as keywords that cannot be used as
an identifier. All keywords are basically a sequence of
Keywords
characters that have a fixed meaning. By convention all
keywords must be written in lowercase (small) letters.
Variables
Table 9.2 shows the list of keywords in C
When you read this book, the meaning and utility of
each keyword will become automatically clear to you
‘Constants
9.10.1 Rules for Forming Identifier Names Data type |Keyword | Sizein | Range | Use
used bytes
Some rules have to be followed while forming identifier
names. They are as follows Character char I =128 to 127 Tostore
characters
+ Identifiers cannot include any special characters or
punctuation marks (like #, $, *, ?, ., etc.) except the Imeger int 2 27680 To store
underscore ‘_’. 32767 integer
* There cannot be two successive underscores. numbers
* Keywords cannot be used as identifiers. Floating float 4 34E-3810 To store
* The case of alphabetic characters that form the identifier point S34E+38 floating
name is significant, For example, ‘FIRST’ is different point
from ‘first’ and ‘First’. numbers
* Identifiers must begin with a letter or an underscore.
Double double 8 L7E-W08to To store
However, use of underscore as the first character must L7E+308 — big floating
be avoided because several point
Hibsctatendl has compiler-defined identifiers number;
in the standard C library
pee is have underscore as their first Valucless: vor 0 Valueless: -
printf: thet an error character. Hence, inadvertently
3 duplicated names may cause The char data type is of one byte and is used to store
will be generated. $ * single characters. Note that C does not provide any data
definition conflicts
* Identifiers can be of any reasonable length. They should type for storing text, This is because text is made up of
not contain more than 31 characters. They can actually individual characters.
be longer than 31, but the compiler looks at only the first You will be surprised to see that the range of char is given
31 characters of the name. as —128 to 127. char is supposed to store characters not
numbers, so why this range? The answer is that, in memory
Although it is a good practice to use meaningful
characters are stored in their ASCII codes. For example, the
identifier names, it is not compulsory. Good identifiers are
descriptive but short. To cut short the identifier, you may
character ‘A’ has the ASCII code 65. In memory we will
not store ‘A’ but 65 (in binary number format).
use abbreviations. C allows identifiers (names) to be up to
In addition, C also supports four modifiers—two sign
63 characters long. If a name is longer than 63 characters,
specifiers (signed and unsigned) and two size specifiers
then only the first 31 characters are used.
(short and long).
As a general practice, if the identifier is a little long.
Table 9.4 shows the variants of basic data types. As can
then you may use an underscore to separate the parts of the
name or you may use capital letters for each part. be seen from the table, we have unsigned char and signed
Examples of valid identifiers include: char. Do we have negative characters? No, then why do
we have such data types? The answer is that we use signed
roll_number, marks, name, emp_number, and unsigned char to ensure portability of programs that
basic_pay, HRA, DA, dept_code, DeptCode, store non-character data as char.
RollNo, EMP_NO While the smaller data types take less memory, the
Examples of invalid identifiers include:
larger types incur a performance penalty. Although the
data type we use for our variables does not have a big
23_student, Xmarks, @name, #emp_number, impact on the speed or memory usage of the application,
basic.pay, -HRA, (DA), &dept_code, auto we should always try to use int unless there is a special
need to use any other data type
Last but not the least the void type holds no value. It is
primarily used in three cases:
Cis a case-sensitive language. Therefore rno, Rno, RNo,
* To specify the retum type of a function (when the
RNO are considered as different identifiers.
function returns no value)
Introduction to C 173
Table 9.4 Detailed list of data types mantissa and exponents. According to the IEEE format,
Datatype | Size in bytes Range a floating point value in its binary form is known as a
normalized form. \n the normalized form, the exponent
|char 1 128 to 127 is adjusted in such a way that the binary point in the
|unsigned char 1 Ow 255 mantissa always lies to the right of the most significant
non-zero digit
|signed char 1 =128 0 127
|int 2 -32768 to 32767 Example
9.1
int
| } |056«2=1,1291
signed short int 2 32768 10 32767
|Thus, the binary equivalent of $.52 =101.0101
Jong int 4 2147483648 to 2147483647 The normalized form of this binary number ix obtained by
adjusting the exponent until the decimal point is to the right of
unsigned long 4 0 to 4294967295
int
the most significant |
Therefore, the normalized binary equivalent = 1.010101
signed long int 4 2147483648 to 2147483647
float 4 34E-38 10 3.4E438
Moreover, the IEEE format for storing floating point
double 5 L-7E-308 to 1.7E+308 numbers uses @ sign bit, mantissa, and the exponent
long double 10348-4932 wo 1.144932 (Figure 9.9). The sign bit denotes the sign of the value, If
the value is positive, the sign bit contains 0 and in case the
value is negative it stores |
* To specify the parameters of the function (when the
function accepts no arguments from the caller)
* To create generic pointers, We will read about generic Sign bit Exponent Mantissa
pointers in the chapter on Pointers. Figure 9.9 |EEE format for storing floating point numbers
We will discuss the void data type in detail in the
coming chapters. Generally, exponent is an int value stored in
unsigned binary format after adding a positive bias. In
other words, because exponents are stored in an unsigned
form, the exponent is biased by half its possible value. For
Unsigned int/char keeps the sign bit free andmakes type float, the bias is 127; for type double, it is 1023. You
the entire word available for storage of the non-negative can compute the actual exponent value by subtracting the
numbers. bias value from the exponent value. Finally, the normalized
Sign bit is the leftmost bit of a memory word which is binary equivalent is stored in such a way that lower byte
used to determine the sign of the content stored in that is stored at higher memory address. For example, ABCD is
word, When itis0, the value Ispositive and when itis1, actually stored as DCBA.
the value is negative.
CRED variates
9.11.1 How are Float and Double Stored?
A variable is defined as a meaningful name given to a
In computer memory, float and double values are stored data storage location in computer memory, When using a
in mantissa and exponent forms where the exponent variable, we actually refer to address of the memory where
represents power of 2 (not 10). The number of bytes used the data is stored. C language supports two basic kinds of
to represent a floating point number generally depends on variables—numeric and character.
the precision of the value, While float is used to declare
single-precision values, double is used to represent
double-precision values.
9.12.1 Numeric Variables
Floating-point numbers use the IEEE (Institute of Numeric variables can be used to store cither integer
Electrical and Electronics Engineers) format to represent values or floating point values. While an integer value is a
ai Computer Fundamentals and Programming in C
le number without a fraction part or decimal point, a + When a variable is declared in the definition of function
floating point value can have a decimal point. parameters it is known as a formal parameter (we will
Numeric variables may also be associated with study this in the chapter on Functions).
modifiers, such as short, long, signed, and unsigned. The * When the variable is declared outside all functions, it is
difference between signed and unsigned numeric variables known as a global variable.
is that signed variables can be cither negative or positive
but unsigned variables can only be positive. Therefore, by
using an unsigned variable we can increase the maximum
positive range. When we do not specify the signed/
unsigned modifier, C language automatically takes it as
a signed variable. To declare an unsigned variable, the 9.12.4 Initializing Variables
unsigned modifier must be explicitly added during the While declaring variables, we can also initialize them with
declaration of the variable. some value. For example,
int emp_num = 7;
9.12.2 Character Variables float salary = 2156.35;
Character variables are just single characters enclosed char grade = ‘A’;
within single quotes, These characters could be any double balance_amount = 100000000;
character from the ASCII character set—letters (‘a’, ‘A’),
The initializer applies only to the variable defined
numerals (‘2’), or special characters (‘8’). In C, a number
immediately before it, Therefore, the statement
that is given in single quotes is not the same as a number
without them, This is because 2 is treated as an integer int count, flag = 1;
value but ‘2’ is a considered character not an integer.
initializes the variable flag and not count. If you want both
the variables to be declared in a single statement then write,
9.12.3 Declaring Variables
int count = 0, flag = 1;
Each variable to be used in the program must be
declared, To declare a variable, specify the data type When variables are declared but not initialized they
of the variable followed by its name. The data type usually contain garbage values (there are exceptions to
indicates the kind of values that the variable will store. this that we will study later).
Variable names should always be meaningful and must
reflect the purpose of their usage in the program. The
memory location of the variable is of importance to the
CONSTANTS
compiler only and not to the programmer. Programmers
Constants are identifiers whose values do not change.
must only be concerned with accessing data through
While values of variables can be changed at any time,
their symbolic names, In C, variable declaration always
values of constants can never be changed. Constants are
ends with a semicolon, for example:
used to define fixed values like mathematical constant pi
int emp_num; or the charge on an electron so that their value does not get
float salary; changed in the program even by mistake.
char grade; A constant is an explicit data value specified by the
double balance_amount; programmer, The value of the constant is known to the
unsigned short int acc_no; compiler at the compile time. C allows the programmer
to specify constants of integer type, floating point type,
In C variables can be declared at any place in the character type, and string type (Figure 9.10).
program but two things must be kept in mind. First,
variables should be declared before using them. Second,
‘Constants
in aC program
variables should be declared closest to their first point of
use to make the source code casier to maintain.
C allows multiple variables of the same type to be
declared in one statement. So the following statement is Floating Character Suing
legal in C.
type point type type type
float temp_in_celsius, temp_in_farenheit;
Figure 9.10 Constants in C
In C variables are declared at three basic places as
follows: 9.13.1 Integer Constants
+ When a variable is declared inside a function it is known A constant of integer type consists of a sequence of digits.
as a local variable. For example, 1, 34. 567, 8907 are valid integer constants.
Introduction to C 175
A literal integer like 1234 is of type int by default. For a A floating point number may also be expressed Ti
Jong integer constant the literal is succeeded with either *L’ scientific notation. In this notation, the mantissa is either
or ‘1’ (like 1234567L). Similarly, an unsigned int literal 4 floating point number or an integer and exponent is an
is written with a ‘U’ or ‘u’ suffix (e.g. 12U), Therefore, integer with an optional plus or minus sign. Therefore, the
1234L, 12341, 1234U, 1234u, 1234LU, 1234u) are all valid numbers given below are valid floating point numbers
integer constants.
O0.Se2 14E-2 1.2e+¢3 2.1E-3 -5,.6e-2
Integer literals can be expressed in decimal, octal, or
hexadecimal notation. By default an integer is expressed in Thus, we see that scientific notation is used to express
decimal notation, Decimal integers consist of a set of digits, numbers that are either very small or very large, For example,
0 through 9, preceded by an optional - or + sign. Examples
120000000 = 1.2E8 and -0.000000025 = -2,.5E-8
of decimal integer constants include: 123, ~123, +123, and 0.
While writing integer constants, embedded spaces,
commas, and non-<digit characters are not allowed. Therefore, 9.13.3 Character Constants
integer constants given below are totally invalid in C A character constant consists of a single character enclosed
123 456 in single quotes. For example, ‘a’ and ‘@’ are character
12,34,567 constants, In computers, characters are stored using machine's
$123 character set using ASCII codes. All escape sequences
mentioned in Table 9.1 are also character constants.
An integer constant preceded by a zero (0) is an octal
number, Octal integers consist of a set of digits, 0 through
7. Examples of octal integers include 9.13.4 String Constants
012 «0 01234 A string constant is a sequence of characters enclosed
in double quotes. So “a” is not the same as ‘a’, The
Similarly, an integer constant is expressed in
characters comprising the string constant are stored in
hexadecimal notation if it is preceded with Ox or Ox.
successive memory locations. When a string constant
Hexadecimal numbers contain digits from 0-9 and is encountered in a C program, the compiler records the
letters A through F, which represent numbers 10 through
address of the first character and appends a null character
15. For example, decimal 72 is equivalent to 0110 in octal
(*\0") to the string to mark the end of the string. Thus,
notation and 0x48 in hexadecimal notation. Examples of
length of a string constant is equal to number of characters
hexadecimal integers are 0X12, Ox7F, OxABCD, OX1A38. in the string plus | (for the null character), Therefore, the
Not length of string literal "hello" is 6.
In C, a decimal integer constant istreated as an unsigned
long if its magnitude exceeds that of signed long. An 9.13.5 Declaring Constants
octal or hexadecimal integer that exceeds the limit ofint To declare a constant, precede the normal variable
is taken to be unsigned. If even this limit isexceeded,it declaration with const keyword and assign it a value. For
is taken as long; and in case this limit isexceeded,itis example,
treated as unsigned long.
const float pi = 3.14;
9.13.2 Floating Point Constants The const keyword specifies that the value of pi cannot
change.
Integer numbers are inadequate to express numbers that
However, another way to designate a constant is
have a fractional part. A floating point constant consists
to use the pre-processor command define. Like other
of an integer part, a decimal! point, a fractional part, and preprocessor commands, define is preceded with a #
an exponent field containing an e or E (e means exponent) symbol. Although #define statements can be placed
followed by an integer where the fraction part and integer
anywhere in a C program, it is always recommended
part are a sequence of digits. However, it is not necessary
that these statements be placed at the beginning of the
that every floating point constant must contain all these
program to make them casy to find and modify at a later
parts, Some floating point numbers may have certain parts stage. Look at the example given below which defines the
missing. Some valid examples of floating point numbers value ofpiusing define
are: 0,02, -0.23, 123.456, +0.34 123, 0.9, -0.7,
40.8 etc. define pi 3.14159
A literal like 0.07 is treated as of type double by default #define service tax 0.12
To make it a float type literal, you must specify it using
In these examples, the value of pi will never change
suffix F or #. Consider some valid floating point literals
but service tax may change, Whenever the value of the
given below. (Note that suffix L is for long double.)
service tax is altered, it needs to be corrected only in the
0.02F 0.34f 3.141592654L 0.002146 2.146E-3 define statement
6 Computer Fundamentals and Programming in C
9.14.3 printf()
‘Text stream Binary stream The printf function (stands for print formatting) is used
to display information required by the user and also
Figure 9.11 Streams in C prints the values of the variables. For this, the printf
function takes data values, converts them to a text stream
In a text stream, sequence of characters is divided using formatting specifications in the control string and
into lines with each line being terminated with a new- passes the resulting text stream to the standard output.
line character (\n). On the other hand, a binary stream The control string may contain zero or more conversion
contains data yalues using their memory representation. specifications, textual data, and control characters to be
We can do input/output from the keyboard/monitor or displayed (Figure 9.13).
from any file but in this chapter we will assume that the Each data value to be formatted into the text stream
source of data is the keyboard and destination of the data is described using a separate conversion specification in
is the monitor (Figure 9.12). File handling, i.e., handling the control string. The specification in the control string
input and output via C programs, will be discussed later as describes the data values type, size and specific format
a separate chapter. information as shown in Figure 9.13.
Introduction to C 177
Control string
Length modifiers can be explained as given in Table 9.6. printf(“\n Result: Xd Xe Xf", 12, ‘a’, 2.3);
Result:12 a 2.3
Table 9.6 Length modifiers for print #() printf(“\n Result: Xd\t%e\txf", 12, ‘a’, 2.3);
{ Length | Description Result:12 a 2.3
printf(“\n Result: Xd\tXc\tx6.2°", 12, ‘a’,
h When the argument isa short int orunsigned short 245.37154);
int Result:12 a 245.37
1 ‘When the argument isa long int orunsigned long int printf(“\n Result: XSd \t Xx \t Xx”, 234,
(used for integer specifiers) 234, 234);
Result: 234 EA OxEA
L ‘When the argument isa long double (used for
floating
point specitiers)
print#("\n The number is X6d", 12);
The number is 12
printf("\n The number is X24", 1234);
Type specifiers are used to define the type and the The number is 1234
interpretation of the value of the corresponding argument printf(“\n The number is X6d”, 1234);
(Table 9.7). The number is 1234
Programming Tip: printf("\n The number is
|
Table 9.7 Type specifiers for print#()
Not placing a comma %-6d", 1234);
Qualifying input after the format The number is 1234__
| c For single characters string in a read or // 2 _ indicates
write statement isa 2 white spaces
| d——_Forinteger vatues compiler error. printf("\n The number is
f For floating
point numbers
NoGd”, 1234);
The number is 001234
I! E,e Floating point numbers inexponential format printf(“\n The price of this item is X09.2f
rupees”, 123.456);
Ga Floating point numbers inthe shorter of¢ format
The price of this item is 000123.45 rupees
o For octal numbers printf(“\n This is \’so\’ beautiful”);
This is ‘so’ beautiful
* For a sequence of (string of) characters
printf("\n This is \"so\" beautiful”);
u For unsigned integer values This is “so” beautiful
printf("\n This is \\ so beautiful ”);
Xx For hexadecimal values
This is \ so beautiful
printf(“\n a = [X-+7.2f| b = X007.2f ¢ =
Note that if the user specifies a wrong specifier then %-0+8.2f", 1.2, 1.2, 1.2);
unpredictable things will be seen on the screen and the a= +1.20 b = 0001.20 c = 1.20
error might propagate to other values in the print#() list.
The most simple printf statement is (Note that in this example, - means left justify, + means
display the sign, 7 specifies the width, and 2 specifies the
printf ("Welcome to the world of C language”); precision.)
When executed, the function prompts the message printf(“\n %7.4f \n %7.2f \n X-7.2f \n Xf
enclosed in the quotation to be displayed on the screen \n %10.2e \n X11.4e \n %-10.2e \n Xe”,
98.7654, 98.7654, 98.7654, 98.7654,
98.7654, 98.7654, 98.7654, 98.7654);
The minimum field width and precision specifiers are 98.7654
usually constants. However, they may also be provided 98.77
by arguments to print (). This is done by using the * 98.77
modifier as shown in the printf statement below. 98.7654
9.88e+01
print#("%*.*#", 10, 4, 1234.34);
9.8765e+01
Here, the minimum field width is 10, the precision is 4, 9.88e+01
and the valueto be displayed is 1234.34. 9.876540e+01
char ch = ‘A’;
Example 9.2 printf(“\n %c \m X3c \n XSc", ch, ch, ch);
a
printf(“\n Result: Xd%cXf", 12, ‘a’, 2.3);
A
Result:12a2.3
A
Introduction to C 179
char str[] = “Good Morning”; Type specifies the type of data that has to be read. It als6
Progrevaning Tip: printf("\n Xs", str); indicates how this data is expected to be read from the
Placing an address printf("\n X20s", str); user. The type specifiers for scanf function are same as
Operator with printf("\n X20.10s”, str); given for printf() function in Tuble 9.7.
aleosorbitet printf("\n X%.7s", str); The scan function ignores any blank spaces, tabs, and
Pranté statement
will nte("\n X-20.108", newlines entered by the user. The function simply returns
eth run-time str);
the number of input ficlds successfully scanned and stored.
printf(“\n X7s", str); We will not discuss functions in detial in this chapter. So
Good Morning understanding scanf function in depth will be a bit difficult
Good Morning here, but for now just understand that the scanf function is
Good Morni used to store values in memory locations associated with
Good Mo variables. For this, the function should have the address of
Good Morni the variables, The address of the variable is denoted by an
Good Morning *&’ sign followed by the name of the variable.
(Note that in the last print# statement the complete string
“Good Morning” is printed. This is because if data needs
more space than specified, then print function overrides Whenever data is read from the keyboard, there
the width specified by the user.) is always a return character from a previous read
operation. So we should always code at least one white
space character inthe conversion specification in order
9.14.4 scanf() to flush that white space character. For example, to
The scanf() function stands for scan formatting and is read two or more data values together in a single scanf
used to read formatted data from the keyboard. The scanf statement, we must insert a white space between two
function takes a text stream from the keyboard, extracts fields asshown below:
and formats data from the stream according to a format scanf("%d Xc", 81, &ch);
contro! string and then stores the data in specified program
variables, The syntax of the scanf() function can be Now let us quickly summarize the rules to use a scanf
given as: function in our C programs.
scanf("control string", argl, arg2, arg3, Rule 1: The scanf function works until
<argn);
(a) the maximum number of characters has been
The control string specifies the type and format of the processed,
data that has to be obtained from the keyboard and stored (b) a white space character is encountered, or
in the memory locations pointed by arguments arg, (c) an error is detected.
arg2,.., argn, i.c¢,, the arguments are actually the variable
addresses where cach piece of data is to be stored. Rule 2: Every variable that has to be processed must have
The prototype of the control string can be given as a conversion specification associated with it. Therefore,
the following scanf statement will generate an error as
X[*] [width] [modifier]type num3 has no conversion specification associated with it
Here * is an optional argument that suppresses scanf(“%d 0", &numi, &num2, &num3);
assignment of the input field, ic., it indicates that data
should be read from the stream but ignored (not stored in Rule 3: There must be a variable address for cach
the memory location) conversion specification. Therefore, the following scan
Width is an optional argument that specifies the maximum statement will generate an error as no variable address is
number of characters to be read. However, fewer characters given for the third conversion specification.
will be read if the scanf function encounters a white space scanf("%d %d Xd", &numi, &num2);
or an inconvertible character because the moment scanf
function encounters a white space character it will stop Remember that the ampersand operator (&) before
processing further. cach variable name specifies the address of that variable
name.
Modifier is an optional argument that can be h, 1, or L
Rule 4: An crror will be generated if the format string is
for the data pointed by the corresponding additional
ended with a white space character,
arguments, Modifier h is used for short int or unsigned
short int, lis used for long int, unsigned long int, Rule 5: The data entered by the user must match the
or double values, Finally, L is used for long double data character specified in the contro! string (except white
values, space or a conversion specification), otherwise an crror
180 Computer Fundamentals and Programming in C
Will be generated and scanf will stop its processing. For Remember that if an attempt is made to read a value
example, ider the following scanf statement. that does not match the expected data type, the scant
function will not read any further and would immediately
scanf("Xd / Xd", &numl, &num2);
retum the values read.
Here, the slash in the control string is neither a white
space character nor a part of conversion specification, so 9.14.5 Examples of printf/scanf
the users must enter data of the form 21/46. Look at the following codes that show how we output
Rule 6: Input data values must be separated by spaces. values of variables of different data types.
Rule 7: Any unread data value will be considered as a part int num;
of the data input in the next call to scant scanf("%d ", &num);
print#("Xd", num);
Rule 8: When the field width specifier is used, it should be
large enough to contain the input data size. The printf function prints an integer value (because
Look at the code given below that shows how we input the type specifier is Xd) pointed by num on the screen.
values in variables of different data types. float salary;
int nui scanf("Xf “, &salary);
scanf("%d ", &num); printf(".2%f", salary);
The scanf function reads an integer value (because The printé function prints the floating point number
the type specifier is %4) into the address or the memory (because the type specifier is ¥f) pointed by salary on
location pointed by num the screen. Here, the control string specifies that only two
digits must be displayed after the decimal point
float salary;
scanf("%f ", &salary);
char ch;
Programming Tip: scanf("%e ", &ch);
The scanf function reads a floating point number Afloat specifier printf("Ke", ch);
(because the type specifier is %#) into the address or the
memory location pointed by salary. cannot beused The printf function prints a
toread an integer single character (because the
char ch; value. type specifier is %c) pointed by
scanf("%e ", &ch); ch on the screen.
The scanf function reads a single character (because char str[10];
the type specifier is %c) into the address or the memory scanf("%s “, str);
location pointed by ch
The printf function prints a strir or a sequence of
char str[10]; characters (because the type specific: is Xs) pointed by str
scanf("%s ", str); on the sereen.
The scanf function reads a string or a sequence of scanf("X%2d %5d", Snum1, &num2);
characters (because the type
Goseers specifier is ¥s) into the address The scanf statement will read two integer numbers.
walbe ila ¥ or the memory location pointed The first integer number will have two digits while the
the rie by str. Note that in case of second can have a maximum of 5 digits.
a pies reading strings, we do not use Look at the following code which combines all the
lanintioeald y the &sign in the scanf function. print statements in one single statement
caret
commas.
This will be discussed in the int num;
chapter on Strings. float frum;
Look at the following code which combines reading of char ch;
variables of different data types in one single statement char str[10];
int num;
double dnum;
float frum; short snum;
char ch; long int num;
printf("\n Enter the values : (");
char str[10];
scanf ("Xd Xf Xe Xs", &num, &fnum, &ch, str); scanf("%d Xf %c Xs Ke Xhd X1d", &num, &fnum,
&ch, str, &dnum, &snum, &lnum);
Look at the scanf statement given below for the same printf("\n num = Xd \n fnum = %.2# \n ch =
code, The statement ignores the character variable and %c \n str = %s \n dnum = %e \n snum = X%hd
does not store it (as it is preceded by *) \n lnum = Xid", num, fnum, ch, str, dnum,
scanf("Ad Sf X*c Xs", Snum, &fnum, &ch, str); snum, num);
Introduction to C 18!
9.15.1 Arithmetic Operators From the above observation, we can conclude two
things. If op1 and op2 are inte; and the quotient is not
Consider three variables declared as, an integer, then we have two cases:
int a=9, be3, result; * If opi and op2 have the same sign, then op1/op2 is the
largest integer less than the true quotient.
We will use these variables to explain arithmetic
* If opi and op2 have opposite signs, then op1/op2 is the
operators, Table 9.8 shows the arithmetic operators, their
smallest integer greater than the true quotient
syntax, and usage in C language.
Note that it is not possible to divide any number by zero.
Table 9.8 Arithmetic operators Thisis an illegal operation that results in a run-time division-
Operation Operator | Syntax | Comment | Result by-zero exception, thereby terminating the program.
Except for modulus operator, all other arithmetic
|Multiply . ath reultsaeb 27 oper ors can accept a mix of integer and floating point
|Divide 1 a/b resulta 3 numbers. If both operands are integers, the result will
be an inte; ger. If one or both operands are floating point
Addition + a+b resukeaeb 2 numbers, then the result will be a floating point number.
Subtraction - a-b 6
All the arithmetic operators bind from left to right. As
in mathematics the multiplication, division, and modulus
_ Modulus % a%b resut=a%b 0 operators have higher precedence over the addition and
subtraction operators, i.c., if an arithmetic expression
In Table 9.8, a and b (on which the operator is applied) consists of amix of operators, then multiplication, division,
are called operands. Arithmetic operators can be applied and modulus will be carried out first in a left to right order,
to any integer or floating-point number. The addition, before any addition and subtraction could be performed.
subtraction, multiplication, and division (+, -, *,/) For example,
operators perform the usual arithmetic operations in C 3+4°7
programs, so you are already familiar with these operators. =3+ 28
However, the operator % must be new to you. The = 31
modulus operator (%) finds the remainder of an integer
division, This operator can be applied only to integer 6. Write a program to perform addition, subtraction,
operands and cannot be used on float or double operands. division, integer division, multiplication, and modulo
Therefore, the code given below generates a compiler division on two integer numbers,
error, @include <stdio.h>
#include <conio.h>
Hinclude <stdio.h>
int main()
#include <conio.h>
int main() {
{
float c = 20.0; int numi, num2;
int add_res=0, sub_res=O0, mul _res=0,
printf("\n Result = %f", ¢ % 5);
/* WRONG. Modulus operator is being applied to idiv_res=0, modiv_res=0;
float fdiv_res=0.0;
a float operand */
clrscr();
printf("\n Enter the first number : “);
return 0;
scanf("%d", &num1);
} printf("\n Enter the second number ; ");
While performing modulo division, the sign of the scanf("%d", &num2) ;
result is always the sign of the first operand (the dividend).
Therefore, add_res = numl + num2;
sub_res = num] ~ num2;
16% 3-1 -16%3=
16% -3 = 1 -16% -3 -1
mul_res = numl * num2;
idiv_res = numl/num2;
When both operands of the division operator (/) are modiv_res = numl%num2;
integers, the division is performed as an integer division. fdiv_res = (float)num1/num2;
Integer division always results in an integer result. So, the printf("\n Xd + %d = Xd", uml, num2, add_res);
184 Computer Fundamentals and Programming inC
9.15.2 Relational Operators Although blank spaces are allowed between an operand
and an operator, nospace is permitted between the
Arelational operator, also known as a comparison operator, components of anoperator (like >=isnot allowed, it
is an operator that compares two values. Expressions should be >=). Therefore, writing x==y Is correct but
that contain relational operators are called relational writing x = = y is not acceptable in C language.
expressions. Relational operators retum truce or false
value, depending on whether the conditional relationship
between the two operands holds or not. 8. Write a program to show the use of relational operators.
For example, to test if x is less than y, relational operator @include <stdio.h>
< is used as x < y. This expression will return true(1) if int main ()
x is less than y; otherwise the value of the expression will {
be false(0) int x=10, y=20;
Relational operators can be used to determine the printf("\n Xd < Xd = Xd", x, y, x<y);
relationships between the operands. These relationships printf("\n %d == = Xd", x, ¥, x**y);
are illustrated in Table 9.9 printf("\n %d I= Sd = Xd", x, y, xlay);
The relational operators are evaluated from left to night. printf("\n %d > Xd = Xd"
The operands of a relational operator must evaluate to a printf("\n %d >= Xd = Xd", x, y, x>=y);
Introduction to C 185
Sure that the result will be false. Similarly, for a logical Therefore, the unaltered value is used for the computation
expression involving logical OR, if the first operand is of the expression in which it occurs.
true, then the second operand is not evaluated as it is for Therefore, an important point to note about unary
sure that the result will be true. increment and decrement operators is that x++ is not same
But this approach has a side effect For example, as ++x. Similarly, x-- is not same as --x. Both x++ and
consider the following expression: ++x increment the value of x by 1. In the former case, the
value of x is returned before it is incremented, whereas,
(x > 9) && (y + 1) in the latter case, the value of x is returned after it is
OR incremented. For example,
(«> 9) Il Yea) int x = 10, y;
y = xe;
In the above logical AND expression if the first operand
is false then the entire expression will not be evaluated and is equivalent to writing
thus the value of y will never be incremented. Same is the
y"x;
case with the logical OR expression. If the first expression
is true then the second will never be evaluated and value
x=xe1;
of y will never be incremented.
whereas,
y = +x;
9.15.5 Unary Operators
Unary operators act on single operands. C language is equivalent to writing
supports three unary operators: unary minus, increment, xex¢2;
and decrement operators. y**;
bit of its first operand with the corresponding bit of its By performing negation of each bit, it actually produces
second operand. If both bits are 1, the corresponding bit in the I’s complement of the given binary value, Bitwise
the result is 1 and 0 otherwise. For example, NOT operator sets the bit to | if it was initially 0 and sets
it to 0 if it was initially 1. For example,
10101010 & 01010101 = 00000000
Table 9.14 Truth table of bitwise XOR If you observe carefully, you will notice that shifting
T T once to the left multiplies the number by 2. Hence,
A B | A*B
multiple shifts of 1 to the left, results in multiplying the
0 0 0 number by 2 over and over again.
On the contrary, when we apply a shift-right operator,
| 0 1 ! every bit in x is shifted to the right by one place. So, the
1 o 1 LSB (Icast significant bit) of x is lost, the MSB of x is set
to 0. For example, if we have x = 0001 1101, then
1 1 0
x >> 1 produces = 0000 1110
Similarly, if we have x = 0001 1101, then
The bitwise XOR operator compares cach bit of its first
operand with the corresponding bit of its second operand x >> 4 produces 0000 0001.
If one of the bits is 1, the corresponding bit in the result is
If you observe carefully, you will notice that shifting
land 0 otherwise, For example, once to the right divides the number by 2. Hence, multiple
10101010 * 01010101 = 11111111 shifts of 1 to the right, results in dividing the number by 2
over and over again.
In aC program, the * operator is used as follows:
int a = 10, b = 20, c=0; 12. Write a program to show use of bitwise operators.
@include <stdio.h>
c = a*b
include <conio.h>
void main()
Bitwise NOT
{
The bitwise NOT, or complement, is a unary operator int a=27, b= 39;
that performs logical negation on each bit of the operand. clrser();
Introduction to C 189
q=ye
= 200
qaye
6
WE
et= ‘Ol
‘f=
oem
10%
‘es qu
es qi
=P
‘g= tut
q=cct
= TIwoy
=F Op
qa
ajdurexsy qu
q=re
qe-e
qaye
qaye Qeet ‘o}
eur
= =
ry‘e=qut
qe>>r
emt
g=
6=et
‘C=
qi
“e=qut
1
Suayee PU OFARLTEL € JO SnFEA Sep WO(Som) WEROKE) YTYS Yo] SnSaNpUe UE sup Ig
INsar aap)
SUISSE PUP
oys aIQeUIEA
suaiser pu
aqeUteA ©
pur Jo
SnfeA
UoIssudys
9171
219
JO
oNgeA BO
Ue (SotIN
jo oy
anger FUNOKE)
wION]
Suyuray
am UOHssoadxS SIGRLEEA Say) OF apsoE Oe SUT eRepu
Aq YNYs
oPQrUTEA
NYBU
oMPeX WUE
ap UE
amp SHEAGNS
©vOIsaidys
Soper SEO
SOEdHNPY
OF Oe
aIQeLRA
pDY
4ynsad
onfeA
Nye
sus
o}
op
SqeUre
apna OnE qe oF
oy
Spqeuse
nso
pur
Ue
oi
oyqeurs 2p
SQPHES
Ye
Wy
IU
HN
01
SUSE
yo
247
PqEUEES
OF
OU
aNPeA
Zo
Ue
yo
GorsaKl
pur
sullese
otp
1ytw2s
SPPY
ae
ONTEA
pO
oI
Gn
ot
ue
o1p
pur
BqeUEA
Aq
sip
anyea
jo
SOpLriCy
ap
snyeA
Jo
sa8ayut
sudisse
©uorssoudys OY)
AATEUCA
oY
FPSOE
PUR
OF
SUTISSe
Aq
94)
Jo
Horssaudy>
aIQELTEA
PU
oNgeA
YOK
sILIOLOYG
ONFWA
30
HIMI9q
94)
oy)
Hug
se
so
eM
WOLHSQudY>
>IQUUEA
PUT
aq)
Snyes
CGIN'Y
MULIOpDYG
2)
JO
PEA
go
UZaMOG
34)
SN
NG
a19eL
$T'6
wuawuiissy
suoyesado
wowsondes , opqenen = s1qenstn
worssaudye
ju(eainby
wopsroudyes
9]qeues
aqeuts
|wowssaudyo
= 9AFEURA
IqeLEN
»Uorsaudes
= ®aqeLEN
opGeUEA
+voto
= ~ajqeuey
vorssandx>
9,qeues
= 2yqeurs
2IqeuE
3puotwandeo
= PGEUTA
aqEUEA
HiNOKe
>>
=
wotssaul way ajeqnura
ksxem
=/
x2
91qeum
uotssand x9
a}qqrtneA
=uowssoud 9}qeuma
wyoyssando opps
uomsandys
= uma
94g
ayworssaxdyo OWE
ayqrtMA
Jun
=<<
=>
= = ~
soyes3dQ
Introduction to C 191
The sizeof operator is a unary operator used to calculate the Operator Associativity |Operator | Associativity
size of data types. This operator can be applied to all data types. 0 left-to-right & left-to-right
When using this operator, the keyword sizeof is followed by ul
a type name, variable, or expression. The operator returns the
size of the variable, data type, or expression in bytes, ic. the =>
sizeof operator is used to determine the amount of memory ++ postfix) right-to-left a left-to-right
space that the variable/expression/data type will take. — (postfix)
When a type name is used, it is enclosed in parentheses, ++ pretix) right-to-left i left-to-right
but in case of variable names and expressions they can be ~(pretix)
specified with or without parentheses. A sizeof expression unary) — (unary)
returns an unsigned value that specifies the space in
bytes required by the data type, variable, or expression.
For example, sizeof(char) returns 1, ic., the size of a
character data type. If we have,
int a = 10; °/% left-to-right && left-to-right
unsigned int result;
result = sizeof(a); = left-to-right r] left-to-right
<< > feft-to-right % right-to-left
Then result = 2, which is the space required to store << left-to-right = right-to-left
the variable a in memory. Since a is an integer, it requires
2 bytes of storage space.
getch(); © BILL e*
Introduction to C 195
an integer value to a floating point variable. Consider the float ‘When afloat type datais
’ subtracted from adouble
code given below in which an integer data type is promoted R type data, then float is
to float, This is known as promotion (when a lower level So le promoted
todouble.
data type is promoted to a higher type). SS
float x; double
int y = 3;
Figure 9.15 Type conversion
x* yi}
Consider the following group of statements:
ees Higher level float f = 3.5;
int i;
double i= f;
Float The statement i = f results in f to be demoted to type
unsigned long int int, i.c., the fractional part of # will be lost and i will
contain 3 (not 3.5). In this case demotion takes place, i.c.,
Jong int
a higher level data type is converted into a lower type
unsigned int Whenever demotion occurs, some information is lost, For
example, in this case the fractional part of the floating
int
Lower point number is lost
sho char level Similarly, if we convert an int to ashort int or a long
int fo int, or int to char, the compiler just drops the extra
Figure 9.14 Conversion hierarchy of data types bits (Figure 9.16)
196 Computer Fundamentals and Programming in C
another type. {
float f_num;
We can also typecast integer values to its character
equivalent (as per ASCH code) and vice versa. Typecasting int i_num;
is also done in arithmetic operations to get correct result. clrscr();
For example, when dividing two integers, the result can
printf("\n Enter any integer: “);
scanf("X%d", &i_num);
be of float type. Also when multiplying two integers the
Introduction to C 197
{
int exam_scorel, activities_scorel, printf("\n Total percentage :
sports_score; total_percent);
int exam_score2, activities _score2, return 0;
activities _score3; }
float exam_total, activities total; Output
float total_percent, exam_percent,
sports_percent, activities_percent; Enter the score obtained in two examinations
clrser( (out of 100): 78 89
printf("\n Enter the score obtained in two Enter the score obtained in sports events
examinations (out of 100): “); (out of 50): 34
scanf("Xd Xd", &exam_scorel, &exam_score2); Enter the score obtained in three activities
printf("\n Enter the score obtained in (out of 20): 19 18 17
Sports events (out of 50): “); * RESULT *
scanf("%d", &sports_ score); Total percent in examintaion: 41.75
printf("\n Enter the score obtained in Total percent in activities : 27
three activities (out of 20): "); Total percent in sports : 13
POINTS TO REMEMBER
© C was developed in the early 1970s by Dennis Ritchie The execution of a C program begins at main()
at Bell Laboratories. function.
* AC program is composed of preprocessor commands, Every word in a C program is either a keyword or an
a global declaration section, and one or more identifier. C has a set of reserved words known as
functions. keywords that cannot be used as an identifier.
* A function is defined as a group of C statements that The basic data types supported by C language are:
are executed together. char, int, float, and double.
198 Computer Fundamentals and Programming in C
* A variable is defined as a meaningful name given to a expressions. Conditional operator is also known as
data storage location in computer memory. When ternary operator as it takes three operands.
using a variable, we actually refer to address of the * The bitwise NOT, or complement, produces the 1's
memory where the data is stored. complement of the given binary value.
© The difference between signed and unsigned numeric * The comma operator evaluates the first expression
variables is that signed variables can be either negative and discards its value, and then evaluates the
or positive but unsigned variables can only be positive. second and returns the value as the result of the
By default, C takes a signed variable. expression.
The statement return 0; returns value 0 to the * sizeof is a unary operator used to calculate the size
operating system to give an indication that no errors of data types. This operator can be applied to all data
were encountered during the execution of the types.
program, While type conversion is done implicitly, typecasting
Modulus operator (%) can be applied only to integer has to be done explicitly by the programmer.
operands and not to float or double operands. Typecasting is done when the value of a higher
The conditional operator or the ternary (?:) is just like data type has to be converted to a lower data
an if-else statement that can be used within type.
GLOSSARY
ANSIC American National Standards Institute's definition Ubrary file The file which comprises of compiled versions
of the C programming language. It is the same as the ISO of commonly used functions that can be linked to an
definition, object file to make an executable program.
Constant A value that cannot be changed. Library function A function whose source code Is stored
C tokens All the permissible characters that C language in an external library file.
supports when combined together form tokens that act as Linker The tool that connects object code and libraries to
the basic building blocks of a program. form a complete, executable program.
Data type Defines the type of values that a data can take. Operator precedence The order in which operators
For example, int, char, float. are applied to operands during the evaluation of an
Escape sequence Control codes that comprise of expression.
combinations of a backslash followed by letters or digits Preprocessor A processor that manipulates the initial
which represent non-printing characters. directives of the source file. The source file contains
Expression A sequence of operators and operands instructions that specify how the source file shall be
that may yield a single value as the result of its processed and compiled.
computation Preprocessor directive Instructions in the source file that
Executable program Program which will run in the specify how the file shall be processed and compiled.
environment of the operating system or within an Program A text file that contains the source code to be
appropriate run time environment. compiled.
Floating-point number Number that comprises a decimal Runtime error A program that is encountered when a
place and exponent. program is executed.
Format specification A string which controls the manner Source code A text file that contains the source code to
in which input or output of values has to be done. be compiled.
identifier The names used to refer to stored data values Statement A simple statement in C language that is
as in case of constants, variables, or functions. followed by a semicolon.
Integer A number that has no fractional part. Syntax error An error or mistake in the source code that
Keyword A word which has a predefined meaning to a C prevents the compiler from converting it into object code.
compiler and therefore must not be used for any other Variable An identifier (and storage) for a data type. The
purpose. value of a variable may change as the program runs,
Introduction to.C 199
EXERCISES
Fill in the Blanks {c) Logical OR (d) Bitwise NOT
1, Cwas developed by Which operator has the lowest precedence?
2. sis. a group of C statements that are executed (a) sizeof (b) unary
together, {c) assignment (d) comma
Execution of the C program begins at Short integer has which conversion character associated
In memory characters are storedas_ with it
. The statement return 0; returns Oto the _
(a) %c (b) %d
_ finds the remainder of an integer division.
(c) %hd (d) %f
___ operator reverses the value of the expression Which of the following is not a character constant?
sizeof isa__
Pnanew operator used to calculate the size
of data types.
(a) & (b) “A”
9, _______ is also known as forced conversion. (c) ** (d) ‘*"
10, The scanf() function returns Which of the following is not a floating point constant?
19, Underscore can be used anywhere in the variable name. 3. Write aprogram to read 10 integers. Display these numbers
20. void is a data type in C by printing three numbers in a line separated by commas,
21, The scanf() function can be used to read only one value 4. Write a program to print the count of even numbers
at a time. between 1 and 200. Also print their sum.
22. All arithmetic operators have same precedence. 5. Write a program to count number of vowels in a text.
23, The modulus operator can be used only with integers. Write a program to read the address of a user. Display
the result by breaking it into multiple lines.
Review Questions 7. Write a program to read two floating point numbers.
1, What are header files? Why are they important? Can we Add these numbers and assign the result to an integer.
write a C program without using any header file? Finally display the value of all the three variables.
What are variables? 8. Write a program to read a floating point number. Display
Explain the difference between declaration and definition. the rightmost digit of the integral part of the number.
. How is memory reserved using a declaration statement?
9. Write a program to calculate simple interest and
What does the data type of a variable signify?
compound interest
. Give the structure of a C program
10. Write a program to calculate salary of an employee,
given his basic pay (to be entered by the user), HRA =
What do you understand by identifiers and keywords?
10% of the basic pay, TA = 5% of basic pay. Define HRA
ON Write a short note on basic data types that the C language
AWEWN
and TA as constants and use them to calculate the salary
supports of the employee.
9. Why do we need signed and unsigned char?
11. Write a program to prepare a grocery bill. For that enter
10, Explain the terms variables and constants. How many the name of the items purchased, quantity in which it is
type of variables are supported by C? purchased, and its price per unit. Then display the bill in
11, Why do we include <stdio.h> in our programs? the following format
12. Write a short note on operators available in C language. eeeeeececerses BIL L seterscevevses
13, Give the operator precedence chart. Item Quantity Price Amount
14, Evaluate the expression: (x > y) + ++a || !c
15, Differentiate between typecasting and type conversion Total Amount to be paid
16. Write short notes on printf and scanf functions.
17, Explain the utility of define and #include statements 12. Write a C program using printf statement to print BYE in
18, Find errors in the following declaration statements. the following format
Int n; B88 yY Y €€EE
float a b; BB vY E
double = a, b; 688 Y EEEE
complex a b; 6 B Yy E
a,b : INTEGER 688 xf EEEE
long int a;b;
Find the output of the following codes.
19. Find error(s) in the following code.
int a= 9; 1, #include <stdio.h>
float y = 2.0; int main()
a=b%a; {
printf("Xd", a); int x=3, yeS, 2=7;
int a, bj
20. Find error(s) in the following scanf statement
scanf("KdXf", &marks, &avg); a=uxr2+y/5-2°y3
b= sex * (y- 3) / 2-24 * ys
Programming Exercises printf("\n a = Xd", a);
1, Write a program to read an integer. Then display the printf("\n b = %d", b);
value of that integer in decimal, octal, and hexadecimal return 0;
notation }
2. Write a program that prints a floating point value in 2. #include <stdio.h>
exponential format with the following specifications: int main()
{
(a) Correct to two decimal places;
int a, b =3;
(b) Correct to four decimal places; and char c = ‘A’;
(c) Correct to eight decimal places. a-=bec;
Introduction to C 201
return 0; char a, b, c;
} printf("\n Enter three characters : ");
27. #include <stdio.h> scanf("%c Xe Sc", &a, &b, &c);
int main() ate; bees coe
{ printf("\n a = Xc b = Xe and d =
int a = -21, b = 3; %c", a, b, Cc);
printf("\n Xd", a/b + 10); return 0;
b= -b; }
printf("\n %d", a/b + 10); 30. #include <stdio.h>
return 0; int main ()
} {
28. #include <stdio.h> int x=10, y=20, res;
int main() res = yer + x05
{ res += tty + +x;
int a; printf("\n x = %d y= %d RESULT
float xd", x,y, res)
printf("\n Enter four digit number: “); return 0;
scanf("%2d", &a); }
printf("\n Enter any floating point 31. Minclude <stdio.h>
number: "); int main ()
scanf("%f", &b); {
printf("\n The numbers are ; Xd int x=10, y=20, res;
and Xf", a, b)5 res = xe+eb;
return 0; printf("\n x = 3d y = %d RESULT = Xd",
} x,y, Pes);
29, include <stdio.h> return 0;
int main()
{
204 Computer Fundamentals and Programming in C
+
ANNEXURE 1
Writing, Compiling, and Executing a C ‘This will print Welcome to the World of Programming
on the screen.
_Program in Unix and Linux
To execute a C program, first make sure that the C compiler
gcc is installed on your machine. This is done by writing $ Writing, Compiling, and Executing a C
whereis ce ot $ which ec command in the command shell. If Program in Ubuntu
ice is present then the complete path of the compiler will be
displayed on screen. In case the compiler is present, follow the Step: Open a text editor to write the C program. You can
steps given below to write and execute the program. choose Vim, or gedit, or any other editor available to you.
Step 1: Open the Vim editor and type the program. For this Step 2: Type the code as shown below and save it in a file
first type the following command in the command shell. (for example, firstprog.c)
that there is no semicolon after the test expression. This is #include <conio.h>
because the condition and statement should be put together int main()
48 a single statement {
#include <stdio.h>
char ch;
int main()
printf("\n Press any key:
scanf("%e", &ch);
{
int x=10; // Initialize the value of x if(isalpha(ch)>0)
if ( x20) // Test the value of x
printf("\n The user has entered a
xt+5 // Increment x if it is > 0 character");
printf("\n x = Xd", x); if (isdigit(ch)>0)
// Print the value of x printf("\n The user has entered a digit”);
return 0; if(isprint(ch)>0)
printf("\n The user has entered a
}
printable character");
Output if(ispunct(ch) 0)
X= 11 printf("\n The user has entered a
In the above code, we take a variable x and initialize it punctuation mark");
to 10, In the test expression we check if the value of x is if(isspace(ch)>0)
greater than 0, If the test expression evaluates to true then printf("\n The user has entered a white
statement block 2;
statement x;
‘Statementx
Test FALSE
SYNTAX OF IF-ELSE-IF STATEMENT Expression
if ( test expression 1) TRUE
statement block x;
}
statement y; ‘Statementy
Consider the following code which shows usage of the Sdefine RATE3 0.30
if-else-if statement
int main()
{
‘The AND operand (&&) is used toform a compound relation double income, taxable income, tax;
expression. In C,the following expression is invalid. clrser();
if (60 < marks < 75) printf("\n Enter the income: “);
The correct way to write is as follows: scanf("R1#", &income) ;
if ((marks 2 60) && (marks < 75)) taxable_income = income - 150000;
if(taxable_income <* 0)
printf("\n NO TAX");
10. Write a program to display the examination result else if(taxable_income >= MIN1 && taxable_
#include <stdio.h> income < MAX1)
int main() tax = (taxable income - MIN1) * RATE1;
{ else if(taxable_income >= MIN2 && taxable_
int marks; income < MAX2)
printf("\n Enter the marks obtained: "); tax = (taxable_income - MIN2) * RATE2;
scanf("Kd", &marks); else
if ( marks >= 75) tax = (taxable income - MIN3) * RATE3;
printf("\n DISTINCTION"); printf("\n TAX = %1f", tax);
else if ( marks >= 60 88 getch();
Programming Tip: marks <75) return 0;
Try
to use the printf("\n FIRST }
most probable DIVISION"); Output
condition first so that else if ( marks >= SO 6&
unnecessary tests marks < 60) Enter the income: 900000
are eliminated and printf(“\n SECOND TAX = 74999.70
the efficiency ofthe DIVISION");
program is improved. else if ( marks >= 40 && 12. Write a program to find the greatest of three numbers.
marks < 50) #include <stdio.h>
printf("\n THIRD DIVISION") ; include <conio.h>
else int main()
printf("\n FAIL"); {
return 0; int numl, num2, num3, bige0;
} clrscr();
Output printf("\n Enter the first number: ");
scanf("X%d", &num1);
Enter the marks obtained: 55
printf("\n Enter the second number: ");
SECOND DIVISION
scanf("Xa", &num2);
11. Write a program to calculate tax, given the following printf("\n Enter the third number: “);
conditions; scanf("X%d", &num3);
if (num1>num2)
if income is less than 1,50,000 then no tax
* iftaxable income is in the range 1,50,001—300,000 then
if (numi>num3)
charge 10% tax printf("\n Xd is greater than Xd and Xd",
* if taxable income is in the range 3,00,001-500,000 then numi, num2, num3);
charge 20% tax
Decision Control and Looping Statements 21
14. Write a program to enter the marks of a student in float D, deno, rootl, root2;
four subjects. Then calculate the total, aggregate, and
clrser();
display the grades obtained by the student printf("\n Enter the values of a, b,
and ¢ :");
#include <stdio.h> scanf("%d %d Xd", Sa, &b, &c);
#include <conio.h> D=(b*b)- (4*a*c);
212 Computer Fundamentals and Programming in C
TRUE
Value |
eC Comparison between the switch We have already seen the syntax of the switch
and if-else construct statement, The switch case statement compares the
value of the variable given in the switch statement with
Generalized switch statement |Generalized if-else statement
the value of cach case statement that follows, When the
switeh(x) { iffexp1) value of the switch and the case statement matches, the
case 1: // do this { statement block of that particular case is executed
case 2: // do this H do this,
Did you notice the keyword default in the syntax of
case 3: // dothis ) the switch case statement? default is also a case that is
tae else iffexp2)
default: //do this {
executed when the value of the variable docs not match
} Wt dothis with any of the values of the case statement, i.c., the
1 default case is executed when no match is found between
else iftexp3) the values of switch and case statements and thus there
{ are no statements to be executed. Although the default
4do this case is optional, it is always recommended to include it as
1 it handles any unexpected cases.
In the syntax of the switch
The power of nested if-else statements lies in the fact Programming Tip: case statement, we have used
that it can evaluate more than one expression in a single C supports decision another keyword break, The
logical structure. Switch statements are mostly used in two control statements break statement must be used at
situations: that can alter the the end of each case because if
+ When there is only one variable to evaluate in the flow of a sequence it is not used, then the case that
expression olinstructions: matched and all the following
* When many conditions are being tested for Asuitchscace cases will be executed. For
When there are many conditions to test, using the if statement is'a example, if the value of switch
multi-way decision statement matched with that of
and else-if constructs becomes a bit complicated and
statement that is a case 2, then all the statements
confusing. Therefore, switch case statements are often
used as an alternative to long if statements that compare simplified version in case 2 as well as rest of the
ofan if-else block cases including default will be
a variable to several integral values (integral values are
that evaluates only executed. The break statement
those values that can be expressed as an integer, such as
the value of a char). Switch statements are also used to one variable. tells the compiler to jump out
handle the input given by the user.
214 Computer Fundamentals and Programming in C
Of the switch case statement and execute the statement And if option was equal to 3 or any other value then
following the switch case construct. Thus, the keyword break — only the default case would have been executed, thereby
is used to break out of the case statements. It indicates the __ printing
end of a case and prevents the program from falling through
In case default
and executing the code in all the rest of the case stateme: S.
Consider the following example of switch statement. To summarize the switch case construct, let us go
through the following rules:
char grade = 'C'
switch(grade) + The control expression that
{ Programming Tip: follows the keyword switch
case ‘0’; cathe le must be of integral type
printf("\n Outstanding”); pearpeomebate te (Le., either an integerorany
break; 3 value that can be converted
case ‘A’: you may tisenested to an integer)
printf("\n Excellent"); a + Each case label should be
break; followed with a constant or
case ‘'B’: Programming Tip: @ constant expression
printf("\n Good"); Default isalso a case + Every case label must
break; that is executed evaluate t0 a unique
case 'C': when the value of constant expression value
printf("\n Satisfactory"); the variable does * Case labels must end with a
breal not match with any colon,
case ‘F*: of the values of case * Two case labels may have
printf("\n Fail"); statements. the same set of actions
breal associated with them,
defaul * The default label is optional and is executed only when
printf("\n Invalid Grade"); the value of the expression does not match with any
break; labelled constant expression. It is recommended to have
} a default case in every switch case stutement
* The default label can be placed anywhere in the switch
Output
statement. But the most appropriate position of default
Satisfactory case is at the end of the switch case statement
* There can be only one default label in a switch statement
16. Write a program to demonstrate the use of switch * C permits nested switch statements, ic, a switch
statement without a break. statement within another switch statement.
#include <stdio.h>
17. Write a program to determine whether an entered
. maint) character is a vowel or not
‘Statementx
#include <stdio.h> }
int main() printf("\n The largest of five numbers
{ entered is: Xd", large);
int i=1; return 0;
while (ic=20) }
{ Output
printf("*");
Enter the number : 29
ite; Enter the number : 15
} Enter the number : 17
return 0; Enter the number : 19
} Enter the number : 25
Output The largest of five numbers entered is: 29
Went wae eeneeenennee
24. Write a program to read the numbers until <1 is
22. Write a program to calculate the sum of numbers from encountered. Also count the negative, positive, and
m ton zeros entered by the user,
{ int main()
int n, m, sum =0; {
clrser( int num;
printf("\n Enter the value of = “5 int negativese0, positives=0, zeros=0
scanf("Xd", &m); elrser();
printf("\n Enter -1 to exit.");
printf("\n Enter the value of n ")3 printf("\n\n Enter any number: “);
scanf("%d", &n); scanf("%d" ,&num) ;
while(me=n) while(num [= -2)
{ {
sum = sum + m; if (num>0)
meme; positives++;
} else if(num<0)
printf("\n SUM = %d", sum); negatives++;
return 0; else
} zeroest+;
‘Statement x
statement y;
TRUE Condition
FALSE
Statement y
some invalid data, One complete execution of the loop avg = (float) sum/n;
takes place before the first comparison is actually done printf("\n The sum of first Xd numbers = Xd",
However, do-while loops are widely used to print a list of n, sum);
options for a menu-driven programs, For example, look at printf("\n The average of first Xd numbers «
the following code %.2*", n, avg);
return 0;
#include <stdio.h>
int main() }
{ Output
int i 1; Enter the value of n: 18
do The sum of first 18 numbers « 171
{ The average of first 18 numbers = 9.00
printf(“\n %d", i);
i-=141; 27. Write a program using a do-while loop to display the
} while(ic10); square and cube of first 7 natural numbers.
return 0; #include <stdio.h>
} #include <conio.h>
What do you think will be the output? The code will int main()
print numbers from 1 to 10. {
int i, n;
26. Write a program to calculate the average of first n clrscr();
numbers.
printf("\n Enter the value of n: “);
#includ tdio.h scanf("%d", &n);
Programming Tip: thay Ode,
Do not forget to place {
printf("\n
i=1;
eainongalberbitha int n, i = 1, sum = 0; do
end of the do-while float avg = 0.0;
statement. {
printf("\n Enter the printf("\n | \t ¥d \t |
value of n: “); \t Xd \t | \t Mid \t |", i,
scanf("%d", &n);
do Pier Shy AIDS
while loop for oat
} while(i<en
implementi
sum = sum + i;
izsi+1; pibapsscleah Lahey PRaNER C=
} while(icen); do-«hile loop for i
posttest loo;ps. } ?
220 Computer Fundamentals and Programming in C
Output numbers++;
28. Write a program to list all the leap years from 1900 to printf("\n Total count of lower case
1920. characters entered = Xd", lowers);
printf("\n Total count of upper case
#include <stdio.h>
characters entered = Xd", uppers);
#include <conio.h>
printf("\n Total count of numbers entered «
int main() Xd", numbers);
{ return 0;
int m=1900, n=2100;
}
clrser();
Output
do Enter any character: 0
Enter another character. Enter * to exit.
if(((m%4 == 0) && (m%100!=0)))|
|(m&400""0)) Enter another character. Enter * to exit.
printf("\n Xd is a leap year",m); Enter another character. Enter * to exit.
m= ml; Enter another character. Enter * to exit.
Jwhile(mexn); Enter another character, Enter * to exit.
return 0; Enter another character, Enter * to exit. sazxonx
}
eatyciseirdtyatn Output Total count of lower case characters entered
you wai =3
body ofthe loopmust 1904 4s 2 leap year Total count of upper case characters entered
getexecuted atleast 198 {5 2 leap year =3
‘once, then
use the 1912 is a leap year
Total count of numbers entered = 0
do-uhile loon. 1916 is a leap year
1920 is a leap year
30. Write a program to read the numbers until —1 is
29, Write a program to read a character until a * is encountered, Also calculate the sum and mean of all
encountered. Also count the number of upper case, positive numbers entered and the sum and mean of all
lower case, and numbers entered. negative numbers entered separately
#include <stdio.h>
@include <stdio.h>
#include <conio.h>
#include <conio.h>
int main() int main()
{ {
char ch; int num;
int lowers = 0, uppers = 0, numbers = 0; int sum_negatives=0, sum_positives
clrser(); int positives = 0, negatives = 0;
float mean_positives = 0.0, mean_negatives =
printf("\n Enter any character: "); 0.0;
scanf("%e, &ch); clrser();
do printf("\n Enter -1 to exit");
printf("\n\n Enter any number: “);
if(ch >='A’ BB ch<='Z') scanf("%d" num) ;
uppers++;
if(ch >='a' && che="z') do
lowers++;
if(ch >="0' 8% ch<="9") {
Decision Control and Looping Statements p21
if (num>0) Output
{ Enter -1 to exit
sum_positives += num; Enter any number: 9
positives++;
Enter any number: 8
} Enter any number: 7
else if(num<0) Enter any number: -6
{ Enter any number: -5
sum_negatives += num; Enter any number: -4
negatives++; Enter any number: -1
} Sum of all positive numbers entered = 24
Mean of all positive numbers entered = 8.00
Sum of all negative numbers entered = -15
printf("\n\n Enter any number: *); Mean of all negative numbers entered = -5.00
scanf("%d",&num) ;
} while(num t= =1);
10.3.3 for Loop
mean_positives « (float)sum_positives/
positives; Like the while and do-while loops, the for loop provides
mean_negatives = (float) sum_negatives/ a mechanism to repeat a task until a particular condition is
negatives; truc. For loop is usually known as a determinate or definite
loop because the programmer knows exactly how many
printf("\n Sum of all positive numbers times the loop will repeat. The number of times the loop
entered = Xd", sum_positives); has to be executed can be determined mathematically by
printf("\n Mean of all positive numbers checking the logic of the loop. The syntax and general
entered = %.2*", mean_positives); form of a for loop is given in Figure 10.8
When a for loop is used, the loop variable is initialized
printf("\n Sum of all negative numbers only once. With every iteration of the loop, the value of the
entered = Xd", sum_negatives); loop variable is updated and the condition is checked, If
printf("\n Mean of all negative numbers the condition is true, then the statement block of the loop
entered = %.2#", mean_negatives); is executed, else the statements comprising the statement
return 0; block of the for loop are skipped and the control jumps
} to the immediate statement following the for loop body.
Initialization
of loop variable
Update the
loop variable
‘Statement y
printf(*X%d", i); {
} for(k=N;k>=i;
return 0; printf(" “
} for(j=1; j<=i; j++)
printf("xd", j);
36, Write a program to print the following pattern printf("\n");
0 }
12 return 0;
345 }
6789
#include <stdio.h> 39. Write a program to print the following pattern
int main() 1
{ 121
int i, j, count=0; $2321
for(iwl;ic=d; ive) 1234321
{ 2345432
printf("\n"); #include <stdio.h>
for(jwljjcwizir+) Sdefine NS
printf("Xd", counte+); int main()
} {
return 0; int 4, J; K,. 23
} for(islj;iceN;ir+)
{
for(keN;k>=i;k--)
37. Write a program to print the following pattem printf(" “);
A for (jel; jcwi; jer)
AB printf("%d", 3);
ABC for(1=j-2;1>0;1--)
ABCD printf("%d", 1);
ABCDE printf("\n");
ABCDEF }
return 0;
#include <stdio.h>
int main() }
{ 40. Write a program to print the following pattern,
char i, j;
for(in65; ic#70; i++)
{
printf(“\n");
for(j=65;J<Wijje+)
printf("%e", 3);
#include <stdio.h>
}
return 0; define N 5
int main()
}
{
38. Write a program to print the following pattern. int i, j, k, counts5, c;
for(isl;ic=Njit+)
{
for(k=1;k<=count;k++)
printf(" “);
for(j=1;j<=i; j++)
printf("X2d", i);
#include <stdio.h>
printf("\n");
tdefine N 5
int main()
ons
{ }
int i, j, ki return 0;
for(i=l;i<=Njit+) }
226 Computer Fundamentals and Programming in C
42. Write a program using for loop to print all the numbers #include <stdio.h>
from m to n, thereby classifying them as even or odd include <conio.h>
int main()
#include <stdio.h>
{
#include <conio.h> int fact = 1, num;
int main()
clrser();
{ printf("\n Enter the number: “)
int i, m, n;
scanf("%d" ,&num) ;
clrser(); if(mum == 0)
printf("\n Enter the value of m: “); fact = 1;
scanf("%d", &m); else
printf(“\n Enter the value n: “);
{
scanf("Xd", &n); for(int i=1; ic=num;it++)
for(iwm;icwn;
ire)
fact = fact * i;
{ }
if(i%2 «= 0) printf("\n Factorial of %d is: Xd", num,
printf("\n Xd is even™,i); fact);
else return 0;
printf("\n Xd is odd", i);
}
}
Output
return 0;
} Enter the number: 5
Output Factorial of 5 is: 120
Enter the value of m: 5
Enter the value of n: 7 45. Write a program to classify a given number as prime
5 is odd or composite
6 is even #include <stdio.h>
7 is odd @include <conio.h>
int main()
43, Write a program using for loop to calculate the
{
average of first 1 natural numbers. int flag = 0, i, num;
#include <stdio.h> clrscr();
#include <conio.h> printf("\n Enter any number: “);
Decision Control and Looping Statements 227
$3. Write a program to enter an octal number. Calculate $5. Write a program to calculate GCD of two numbers.
and display the decimal equivalent of this number. #include <stdio.h>
#include <stdio.h> #include <conio.h>
#include <conio.h> int main()
#include <math.h> {
int numl, num2, temp;
int main() int dividend, divisor, remainder;
{ clrscr();
int decimal_num= 0, remainder, octal_num,
i 0; printf("\n Enter the first number: ");
clrser(); scanf("X%d", &num1);
printf("\n Enter the octal number: printf("\n Enter the second number: ");
scanf("%d", &octal_num); scanf("Xd", &num2);
while(octal_num != 0)
{ if (numi>num2)
remainder = octal_numX10; {
decimal_num ¢= remainder*pow(8,
i); dividend = num1;
octal_num = octal_num/10; divisor = num2;
ive }
} else
printf("\n The decimal equivalent = Xd", {
decimal_num) ; dividend = num2;
return 0; divisor = numl;
}
Output while(divisor)
Enter the octal number; 22 {
The decimal equivalent = 18 remainder = dividend%divisor;
dividend = divisor;
$4, Write a program to enterahexadecimal number. Calculate divisor = remainder;
and display the decimal equivalent of this number. F
ttinclude <stdio.h> printf("\n GCD of Xd and Xd is = Xd", numi,
#include <conio.h> num2, dividend) ;
#include <math.h> return 0;
}
int main() Output
{ Enter the first number: 64
int decimal_num= 0, remainder, hex_num, i
Enter the second number: 14
20; GCD of 64 and 14 is = 2
clrser();
I
printf("\n Enter the hexadecimal number: 56. Write
aprogram to sum the series 1+ +2 +--+
scanf("%d", &hex_num); include <stdio.h>
while(hex_num != 0)
#include <conio.h>
{ int main()
remainder = hex_num%10;
decimal_num += remainder*pow(16,i);
{
hex_num = hex_num/10; int n, i;
float sum=0.0, a;
int
clrscr();
} printf("\n Enter the value of n:
printf("\n The decimal equivalent = Xd",
scanf("%d", &n);
decimal_num);
for(i=l;ic=n;ir+)
return 0;
{ a=(float)1/i;
} sum = sum +3;
Output
}
Enter the hexadecimal number: 39 printf("\n The sum of series 1/1 + 1/2 + ....
The decimal equivalent = 57 + 1/%d = %.2f",n,sum);
230 Computer Fundamentals and Programming in C
return 0; 127 3
} 59. Write a program to sum the series ~ + eel mates
Oui #include <stdio.h> l= 3
so #include <conio.h>
Enter the value of n: 5 include <math.h>
The sum of series 1/1 + 1/2+.... + 1/5 = int main()
2.28 {
int n, NUM, i;
§7 Write a program to sum the series float sum=0.0;
clrscr();
#include <stdio.h>
printf("\n Enter the value of n: ");
#include ¢math b> scanf("%d", &n);
#include <conio.h> forfinasicanjdes)
int main() { - -
{ NUM = pow(i,i);
one Aad sum += (float)NUM/i;
float sume0.0, a; }
clrser(); m %
print#(*\n Enter the value of n: *); spss 1/1 + 4/2 + 27/3 + .... = %.2F",
scanf("%d", &n); rE A
for(iwl;icen;it+)
{ a = (float)1/pow(i,2); }
sum = sum +a; Output
} Enter the value of n:5
printf("\n The sum of series 1/17 + 1/ 2? + —. 1/1 + 4/2 + 27/3 + = 701.00
1/xd? = %.2#",n, sum);
return 0; 60. Write a program to calculate sum of cubes of first n
} numbers,
Output #include <stdio.h>
: Programming Tip: include <conio.h>
Enter the value of n: 5 Itis a logical error to SicAndaeanhhhy
The sum of series 1/1? + 1/ 2? + . 1/5? = 1.46 skip theupdatingof
‘5 loop contro! variable int main()
$8, Write « program to sum the series 44 2...4— in thewhile/do- {
#include <stdio.h> ee peeeta eop ete int i, nj
;
#include <conio.h> an
thetosoupdatewal
statement, intlees
term, sum = 0;;
int main t loop willbecome elrser();
{ Oo an infinite loop. printf("\n Enter the
int n, value of n: ");
a; Sean &n);
float sum=0.0,
clrser(); 2 for(iel;icenjire)
printf("\n Enter the value of n: “); ‘ ,
scanf("%d", &n); cate Se aeas
for(isl;icenj;it+) sum += term;
{ a= (float) i/(i+1); } m , ’ , -
sum = sum 4a; dub ig Vee Ve... = BA", sum);
) return 0;
printf("\n The sum of series 1/2 + 2/3 + }
seeeKd/Md = XF",n,n¢1, sum); Output
petury 0} Enter the value of n:5
} P+ 243+...
= 225
oO 5
we 61. Write a program to calculate sum of squares of first 1
Enter the value of n :5 even numbers.
The sum of series 1/2 + 2/3 + ....5/6 = eases EGA KS
2. 6B14E s
#include <conio.h>
Decision Control and Looping Statements 231
#include <math.h> and the annual interest. Calculate the value Of
int main() investment over a period of time.
{ #include <stdio.h>
int i, nj;
int main()
int term, sum = 0;
{
clrser(); double initVal, futureVal, ROI;
printf("\n Enter the value of n: "); int yrs, i;
scanf("%d", &n); printf("\n Enter the investment value: “);
for(iel;ic=n;
i+)
scanf("%1f", &initval);
{ printf("\n Enter the rate of interest: “);
if(ik2 == 0) scanf("%1f", &ROI);
{ term = pow(i,2); print€("\n Enter the number of years for
sum += term; which investment has to be done: “);
} scanf("Xd", Syrs);
} futureVal=initVal;
printf("\n 2? + 4? + 6? +... = Xd", sum); printf("\n YEAR \t\t VALUE");
return 0; printf("\n "5
} for(iwl;iceyrs;ie+)
Output {
futureVal = futureVal * (1 + ROI/100.0);
Enter the value of n: 5 printf("\n %d \t X1f", 4, futureVal);
2+ 474 68+... = 20 }
return 0;
62. Write a program to find whether the given number is }
an Armstrong number or not
Output
#include <stdio.h>
Enter the investment value: 20000
#include <conio.h>
Enter the rate of interest: 12
#include <math.h>
int main() Enter the number of years for which investment
has to be done: 5
{ YEAR VALUE
int num, sum=0, r, nj
clrser();
printf("\n Enter the number: “);
22400.00
scanf("%d", &num);
25088 .00
nenum;
28098 .56
while(n>0)
31470.38
{ wawne
35246.83
renkl0;
sum += pow(r,3); 64. Write a program to generate calendar of amonth given
nen/10; the start day of the week and the number of days in that
} month.
if (sume=num)
printf("\n Xd is an Armstrong number", num); #include <stdio.h>
else int main()
printf("\n Xd is not an Armstrong number”, {
num) 5 int i, j, startDay, num_of_days;
return 0; printf("\n Enter the starting day of the
} week (1 to 7): ");
scanf("kd", &startOay);
Output printf("\n Enter the number of days in that
Enter the number : 432 month: ");
432 is not an armstrong number scanf("%d", &num_of_days);
printf(" Sun Mon Tue Wed Thurs Fri Sat\n");
63. Write a program using for loop to calculate the value printf ("\n
of an investment, given the initial value of investment for(i=0;icstartDay-
232 Computer Fundamentals and Programming in C
printf(" “);
for(j=1; j<=num_of_days;j++)
while(...) do
{ {
{
if(i>6) if(condition) iF(condition)
break ; break ;
{
printf("\n"); Jwhile¢ ..
i=l;
} Transfers control out Transfers control
else of the loop while out of the do-while
i++; loop
print#("%2d ", 3)
}
return 0; for(...) for(...)
} { {
Output iF (condition)
break ;
Enter the starting day of the week (1 to 7): 5
Enter the number of days in that month : 31
Sun Mon Tue Wed Thurs Fri Sat
1 2 3 4 5 6 7 Transfers control out
of the for loop
}
Transfers control out
TED BREAK AND CONTINUE STATEMENTS of inner for loop
In this section, we discuss break and continue statements. Figure 10.9 break statement
10.5.1 break Statement printf("\n Xd", 4);
i-i+1;
In C, the break statement is used to terminate the execution }
of the nearest enclosing loop in which it appears. We have return 0;
already seen its usage in the }
Programming Tip: switch statement. The break
The break statement statement is widely used with Note that the code is meant to print first 10 numbers
isused toterminate for loop, while loop, and using a while loop, but it will actually print only numbers
the execution ofthe do-while loop. When the from | to 4. As soon as i becomes equal to 5, the break
nearest enclosing compiler encounters a break statement is executed and the control jumps to the
loop
in which it statement, the control passes statement following the while loop.
appears, to the statement
that follows Hence, the break statement is used to exit a loop from
the loop in which the break any point within its body, bypassing its normal termination
statement appears. Its syntax is quite simple, just type expression, When the break statement is encountered
keyword break followed with a semicolon. inside a loop, the loop is immediately terminated, and
program control is passed to the next statement following
break; the loop. Figure 10,9 shows the transfer of control when
In switch statement if the break statement is missing the break statement is encountered.
then every case from the matched case label till the end
of the switch, including the default, is executed. This 10.5.2 continue Statement
example given below shows the manner in which break Like the break statement, the
statement is used to terminate the statement in which it is Ueravenminegs continue statement is used
embedded. When the compiler in the body of a loop. When
#include <stdio.h> ponctseardahionits: the compiler encounters a
int main() oe ek continue statement then
{ joon are: nad tak the rest of the statements in
int i = 1; Fe mF the loop are yekease and the
while(ic=10) control is
unconditionally control is unconditionally
{ iteenbieskaainsg? transferred to the loop-
if (i==5) thecleonaha continuation portion of
break; the nearest enclosing loop.
Decision Control and Looping Statements 233
} Sum+=num;
/* Same program without using break count++;
statement */ }
#include <stdio.h> else
int main() flag=0;
{ // set loop control variable to jump out of
int num, sum=0, flag=1; loop
// flag will be used to exit from the loop }
while(flag-=1) // loop control variable printf("\n SUM = Xd", sum);
{ avg = (float) sum/count;
printf("\n Enter any number. Enter -1 to printf("\n Average = Xf", avg);
stop: "); return 0;
scanf("Xd", &num); }
if(num!=-1) // Same program without using continue
sum+enum; statement
else #include <stdio.h>
flag-0; // to quit the loop int main()
} {
printf("\n SUM = Xd", sum); int num, sum=0, flage1, count«0;
return 0; float avg;
} // flag will be used to exit from the loop
while(flage=1)
Now Iet us sce how we can climinate continue
statement from our programs. Let us first write a program {
printf("\n Enter any number. Enter -1 to stop:
that calculates the average of all non-zero numbers entered
by the user using the continue statement. The second ")3
scanf(“X%d", &num);
program will do the same job but without using continue.
if (num! #0)
#include <stdio.h> {
int main() if(num!=-1)
{ {
int num, sums0, flage1, count=0; sum+«num;
float avg; count++
// flag will be used to exit from the loop }
while(flage*1) else
{ flag*0;
printf("\n Enter any number. Enter -1 to }
stop: }
scanf("%d", &num); printf("\n SUM = Xd", sum);
if (nume=0) avg = (float) sum/count;
continue; // skip the following statements printf("\n Average = Xf", avg);
if (num! =-1) return 0;
{ }
POINTS TO REMEMBER
« C supports conditional type branching and pairsan else statement with the most recent unpaired
unconditional type branching. The conditional if statement in the current block.
branching statements help to jump from one part of Switch case statements are often used as an
the program to another depending on whether a alternative to long if statements that compare a
particular condition is satisfied or not. variable to several integral values. Switch statements
* With nesting of if-else statements, we often are also used to handle the input given by a user,
encounter a problem known as dangling else problem. Default is a case that is executed when the value of
This problem is created when there is no matching the variable does not match with any of the values of
else for every if statement. In such cases, C always Case statements.
236 Computer Fundamentals and Programming in C
* Iterative statements are used to repeat the execution * The break statement is used to terminate the execution
of a list of statements, depending on the value of an of the nearest enclosing loop in which it appears.
integer expression * The continue statement is used to transfer control to
The while/do-while/for loops provide a mechanism the loop-continuation part of the nearest enclosing
to repeat one or more statements while a particular loop.
condition is true. In the do-while loop, the test * The goto statement is used to transfer control to a
condition is tested at the end of the loop while in case specified label. However, the label must reside in the
of for and while loops the test condition is tested same function and can appear before only one
before entering the loop. statement in the same function.
GLOSSARY
Conditional branching Conditional branching statements If statement Simplest form of decision control statement
are used to jump from one part of the program to another de- that is frequently used in decision-making.
pending on whether a particular condition is satisfied or not. If-else-if statement Decision control statement that
Continue statement When the compiler encounters a works in the same way as a normal if statement. It is also
continue statement then the rest of the statements in known as nested if construct
the loop are skipped and the control is unconditionally If-else statement Decision control statement in which
transferred to the loop-continuation portion of the nearest first the test expression is evaluated. If the expression
enclosing loop. is true, if block is executed and else block is skipped.
Dangling else problem Problem encountered with nesting Otherwise, if the expression is false, else block is executed
of if-else statements which is created when there is no and if block is ignored.
matching else for every if statement. Iterative statement Statement used to repeat the
do-while loop A form of iterative statement in which the execution of a list of statements, depending on the value
test condition Is evaluated at the end of the loop. of an integer expression,
for loop The mechanism used to repeat a task until a Nested loop Loops placed inside other loops.
particular condition is true. for loop is usually known as Switch case statement A switch case statement Is a
a determinate or definite loop because the programmer multi-way decision statement that Is a simplified version
knows exactly how many times the loop will repeat. of an if-else block that evaluates only one variable.
Goto statement It is used to transfer control to a specified while loop The mechanism used to repeat one or more
label. statements while a particular condition is true.
EXERCISES
Fill in the Blanks 6. In a counter-controlled loop, __ _. variable
1, Dangling else problem occurs when is used to count the number of times the loop will
2. The switch control expression must be of execute.
10. When we do not know in advance the number of times No two case labels can have the same value.
the loop will be executed, we use a loop. 5. The case labelled constant can be a constant or a
11. The _ ___statement is used to transfer control variable.
to a specified label 6, The if-else statement requires integral values in its
12. statement violates the rules of structured expressions.
programming, 7. There can be only one default case in the switch-case
statement
Multiple-choice Questions 8. The do-while loop checks the test expression and then
1. Which type of statement helps to jump from one part of executes the statements placed within its body.
the program to another depending on whether a 9. In awhile loop, if the body is executed n times, then the
particular condition is satisfied or not? test expression Is executed (n + 1) times.
(a) Conditional branching (b) Loops 10. The number of times the loop control variable is updated
(c) Iterative (d) None of these is equal to the number of times the loop iterates.
2, Astatement block consists of how many statements? 11. In the for loop, the value of the loop control variable
must be less than that of its ending value.
(a) 0 {b) 1
12. It is necessary to have initialization, testing, and updating
(c) n (d) None of these expressions within the for statement
3. Dangling else problem can arise in which of the following
13. In a pre-test loop, the test condition is checked after the
statement(s)?
body of the loop.
(a) Conditional branching (b) Loops 14, Post-test loops get executed at least for one time.
(c) Iterative {d) None of these 15. in awhile loop, the loop control variable is initialized in
4. Which among the following is a multi-way decision the body of the loop.
statement? 16. The loop control variable may be updated before or after
(a) if-else (b) if-else-if the loop iterates
(c) switch (d) do-while loop 17. Counter-controlled loop must be designed as pre-test
5. Case labels must end with which token? loops
18. The do-while loop Isa post-test loop,
(a), (b)
19. The for loop and while loop are pre-test loops.
(c) ; (d) /
20. Every case label must evaluate to a unique constant
6. The default label can be placed at which position in the
expression value
switch statement?
21. Two case labels may have the same set of actions
(a) Beginning {b) End associated with them.
(c) Middle (d) Anywhere 22. The default label can be placed anywhere in the switch
7, The statements in the statement block are encapsulated statement.
withina __? 23. C does not permit nested switch statements.
(a) () (b) 0) 24. When we place a semicolon after the for statement, the
() 0) (d) > compiler will generate an error message
8. Which statement is used to terminate the execution of
the nearest enclosing loop in which it appears? Review Questions
1. What are decision control statements? Explain in detail
(a) break (b) continue
2. Compare the use of if-else construct with that of
(c) default (d) case
conditional operator
9, When the statement is encountered then the 3. Explain the importance of a switch case statement. In
rest of the statements in the loop are skipped.
which situations is a switch case desirable? Also give its
(a) break (b) continue limitations.
(c) default ({d) case 4. How is comma operator useful in a for loop? Explain
with the help of relevant examples.
State True or False 5. Write a short note on goto statement. As a programmer
1, Decision control statements are used to repeat the would you prefer to use this statement? Justify your
execution of a list of statements. answer.
2. The expression in a selection statement can have no side 6. With the help of an example explain the dangling if-
effects. else problem.
3. An expression in an if statement must be enclosed 7. Why floating point numbers should not be used for
within parentheses. equality in expressions?
238 ‘Computer Fundamentals
and Programming in C
8. Explain the usefulness of default statement in switch 20. The following for loops are written to print numbers
case statement. from 1 to 10. Are these loops correct? Justify your
9. Give the points of similarity and differences between a answer.
while loop and a do-while loop.
(a) int i;
10 Distinguish between the break and the continue
for(i=0;i<10;i++)
statements. printf("%d", i);
11 Write a short note on iterative statements that C (b) int i, num;
language supports. for(i=0; 1<10;i++)
12. Enter two integers as dividend and divisor. If the divisor {
is greater than zero then divide the dividend by the num = iel;
divisor, Assign their result to an integer variable rem and printf("Xd", num);
their quotient to a floating point number quo. }
13. When will you prefer to work with a switch statement? (c) int i;
14, What is a null statement? How can it be useful in our for(i=1;i<=10;i++)
programs? {
15 In what situation will you prefer to use for, while, and printf("xd", i);
do while loops? ite
10. Write a program to read an angle from the user and then 23. Write a program to generate the following pattern;
display its quadrant
ii, Write a program that accepts the current date and the
date of birth of the user. Then calculate the age of
the user and display it on the screen, Note that the date
should be displayed in the format specified as dd/mm/
vy. 24. Write a program to generate the following pattern:
12 A class has SO students. Every student is supposed to Severe
give three examinations. Write a program to read the “$ .
marks obtained by each student inall three examinations -$ .
Calculate and display the total marks and average of i at |
each student in the class. ween
13 Write a program in which the control variable is updated
in the statements of the for loop.
25. Write a program to generate the following pattern
4 Write a program which demonstrates the use of goto,
break, and continue statements.
15. Write a program that displays all the numbers from 1 to
100 that are not divisible by 2 as well as by 3.
16. Write a program to calculate parking charges of a vehicle.
Enter the type of vehicle as a character (like ¢ for car, b 26. Write programs to implement the following sequence of
for bus, etc.) and number of hours then calculate charges numbers.
as given below: 1, 8, 27, 64,
* Truck/Bus — 20 Rs per hour -5, -2, 0, 3, 6, 9% 12,
* Car = 10 Rs per hour -2, -4, -6, -8, -10, 12,
* Scooter/ Cycle/ Motor cycle ~ 5 Rs per hour 35/4, 24°20;
17, Modify the above program to calculate the parking 27. Write a program that reads integers until the user wants
charges. Read the hours and minutes when the vehicle to stop. When the user stops entering numbers, display
enters the parking lot. When the vehicle is leaving, enter the largest of all the numbers entered.
its leaving time. Calculate the difference between the 28 Write a program to print the sum of the following series.
two timings to calculate the number of hours and
minutes for which the vehicle was parked. Finally -x¢ x= x? o xt +
calculate the charges based on following rules and then 1 + (1+2) + (14243) +
display the result on the screen. 1-x + x*/2! - x/3! +
{ for (num++num++nume+)
int num = 10; print#("Xd", num);
printf("\n Xd", a>200); return 0;
} }
3 #include <stdio.h> #include <stdio.h>
void main() int main()
{ {
printf ("HELLO"); int num=10;
if (-1) for (;--num;)
printf ("WORLD"); printf(" Xd", num);
} return 0;
4. #include <stdio.h> }
void main()
{ 19. include <stdio.h>
int a = 3; int main()
if(a < 10) {
printf("\n LESS"); int num=10;
if(a < 20) for(; !num;num++)
printf("\n LESS"); printf(" Xd", num);
if(a < 30) return 0;
printf("\n LESS"); }
}
15. #include <stdio.h> 20. #include <stdio.h>
void main() int main()
{ {
int a=10, b=20, c=30, d=40) float PI = 3.14, area;
242 ‘Computer Fundamentals and ProgramminginC
int r = 7;
while(r>=0)
{ 26. #include <stdio.h>
area = PI * rer; void main()
printf("\n Area = Xf", area); {
} int x=-1;
return 0; unsigned int y=1;
} if(x < y)
21 #include <stdio.h> printf("\n SMALL");
void main() else
printf("\n LARGE");
if (ones == 1) Output
printf("I");
Bice i (ones <2) ee oe number (1-3000): é 139
printf ("II");
lee 4* (ones o= 3) An algorithm to calculate
theday ofthe week:
print#(*IIE"); 1. Centuries: Use the centuries table given below to calculate
else if (ones == 4) the century
printf("IVv"); 2. Years: We know that there are 365 days in a year, that is, 52
else if (ones ==5) weeks plus 1 day. Each year starts on the day of the week
printf("Vv"); after that starting the preceding year. Each leap year has one
else if (ones == 6) more day than a common year
printf("VI"); If we know on which day a century starts (from above), and
else if (ones == 7) we add the number of years elapsed since the start of the
printf(“VII"); century, plus the number of leap years that have elapsed since
else if (ones ==8) the start of the century, we get the day of the week on which
printf ("VIII"); the year starts. Where year is the last two digitsofthe year.
else if (ones == 9) 3. Months: Use the months table to find the day of the week a
print#("IXx"); month starts
getch();
) 4. Day of the month: Once we know on which day of the week
the month starts, we simply add the day of the month to find
the final result
} November +| 4
December |6
EXAMPLE I 2. Write a program to find out the day for a given date
Let us calculate the day of April 24, 1982. #include <stdio.h>
1, Find the century value of 1900s from the centuries table: 0 #include <stdlib.h>
#include <conio.h>
2. Last two digits give the value of year: 82
main()
3, Divide the 82 by 4: 82/4 = 20.5 and drop the fractional part {
20 int dd,mm,yy,year,month,day,i,n;
4. Find the value of April in the months table: 6 elrscr();
5. Add all numbers from steps 1-4 tw the day of the month (in printf("\n Enter the date:
this case, 24): 0 + 82 +20 +6424 = 132 scanf ("Xd Xd Xd", &dd, &mm, Byy) ;
6, Divide the result of step 5 by 7 and find the remainder: if( dd>31 || mm>12)
132/7 = 18 remainder 6 {
7, Look up the day's table for the remainder obtained printf(" INVALID INPUT ");
6 = Saturday
getch();
exit(0);
That the values in the century table, months table, and days table
are pre-determined. We will only be using them to calculate the }
year = yy-1900;
day of a particular date
Decision Control and Looping Statements 247
TAKEAWAYS
* Using functions * Function call * Storage classes
* Function declaration © Call-by-value and call-by-reference * Recursive functions
* Function definition * Scope of variables * Tower of Hanoi
ren funci()
Let us analyse the reasons for segmenting a program into
4 fuctions as it is an important aspect of programming
deseccsouce Statement Block;
* Dividing a program into separate well-defined
HO ie z functions facilitates each function to be written and
tested separately. This simplifies the process of getting
faaenioes the total program to work. Figure 11,3 shows that the
main() function calls other functions for dividing the
}
entire code into smaller sections (or functions), This
Figure 11.1 The main() function calls funci() approach is referred to as the top-down approach
* Understanding, coding, and testing multiple separate
From the figure, we can see that main() calls a functions is far easier than doing it for one big function
function named funci(), Therefore, main() is known * Ifa big program has to be developed without the use
as the calling function and funci() is known as the of any function other than main() function, then there
called function, The moment the compiler encounters a will be countless lines in the main() function and
function call, instead of executing the next statement in maintaining this program will be very difficult. A large
the calling function, the control jumps to the statements program size is @ serious issue in micro-computers
that are part of the called function. After the called where memory space is limited.
function is executed, the control is returned back to the + All the libraries in C contain a set of functions that the
calling function. programmers are free to use in their programs. These
Functions 249
void swap
(ot a,intb);
‘Swaps ofinterchanges
thevalue of
integer variables a and b received ax
FUNCTION DEFINITION
arguments. The function returns no
When a function is defined, space is allocated for that
value, therefore the return type is void.
function in the memory. A
void print(void); The function
isused toprint Programming Tip: function definition comprises
information
on screen. The function Itisanerror to place two parts
neither accepts any value as argument a semicolon after cc Pineusai sec Svea
the fi header Pras on header
‘por returnsany value, Therefore, the
return type isvoid and the argument hep * Function body
\ listcontains
void data type. definition. The syntax of a function
definition can be given as
Things to remember about function declaration: return_data_type function_name(data_type
* After the declaration of every function, there should be variablel, data_type variable2,...)
a semicolon, If the semicolon is missing, the compiler
will generate an error message.
Functions 251
statements file stdio.h contains the definition of scanf and printf
functions. We simply include this header file and call these
return(variable) ; functions without worrying about the code to implement
} their functionality
The number of arguments and the order of arguments
in the function header must be same as that given in the
function declaration statement List ofvariables used in function call isknown as actual
Pi Tip: While return_data_type parameter list. The actual parameter list may contain
function_name(data_type variable names, expressions, or constants.
The parameter
variablel, data_type
nee variable2,..) is known as
fu ie Agiigaach the function header, the rest 11.5.1 Points to Remember While Calling
Muse patch: of the portion comprising of Functions
program statements within
The following points are to be kept in mind while calling
{ } is the function body which
functions
contains the code to perform the specific task
The function header is same as function declaration. * Function name and the number and type of arguments in
The only difference between the two is that a function the function call must be same
header is not followed by a semicolon. The list of variables as that given in the function
in the function header is known as the formal parameter A logical e: alae declaration and function header
list, The parameter list may have zero or more parameters begenerated ifthe of the function definition
of any data type. The function body contains instructions arguments in the + Ifthe parameters passed to a
to perform the desired computation in a function. function call are function are more than what
The function definition itself can act as an implicit placed inthewrong it is specified to accept then
function declaration. So the order. the extra arguments will be
Programming
Tip: programmer may skip the discarded.
eae canbe function declaration statement + Ifthe parameters passed to a function are less than what
ined either before) in case the function is defined it is specified to accept then the unmatched arguments
or after main(). will be initialized to some garbage value
before being used.
* Names (and not the types) of variables in function
declaration, function call, and header of function
definition may vary
The argument names in the function declaration and * If the data type of the argument passed does not match
function definition need not be the same. However, with that specified in the function declaration then cither
the data types of the arguments specified in function the unmatched argument will be initialized to some
declaration must match with those given in function garbage value or a compile time error will be generated
definition, + Arguments may be passed in the form of expressions
to the called function, In such cases, arguments are first
evaluated and converted to the type of formal parameter
and then the body of the function gets executed.
FUNCTION CALL + The parameter list must be separated with commas
+ If the return type of the function is not void, then the
The function call statement invokes the function. When value retumed by the called function may be assigned
a function is invoked the compiler jumps to the called to some vanable as shown in the following statement.
function to execute the statements that are part of that
function, Once the called function is executed, the program variable_name = function_
control passes back to the calling function. name(variablel, variable2, ...);
Function call statement has the following syntax Let us now try writing a program using function,
function_name(variable1, variable2, ...); 1. Write a program to add two integers using functions,
When the function declaration is present before the include <stdio.h>
function call, the compiler can check if the correct number // FUNCTION DECLARATION
and type of arguments are used in the function call and the int sum(int a, int b);
returned value, if any, is being used reasonably int main()
int check_relation(int a, int b) There are two ways in which arguments or parameters
{ can be passed to the called function. They include:
if(a==b)
Pirparletpe dha return 0 * Call by value in which values of variables are passed by
the calling function to the called function. The programs
utente else if(a>b)
that we have written so far call functions using call-by-
does notreturn data Pensa
else
value method of passing parameters
CUse Seales ees return -1; * Call by reference in which address of variables are
passed by the calling function to the called function,
}
Output
a is less than b 11.7.1 Call by Value
In the aforegiven program there are multiple return Till now, we had been calling functions and passing
statements, but only one of them will get executed arguments to them using call-by-value method. In the call-
depending upon the condition, The return statement, by-value method, the called function creates new variables
like the break statement, is used to cause a premature to store the value of the arguments passed to it. Therefore,
termination of the function. the called function uses a copy of the actual arguments to
An expression appearing perform its intended task.
Programming Tip: in a return statement is If the called function is supposed to modify the value
A function that does converted to the retum type of the parameters passed to it, then the change will be
not return any value of the function in which reflected only in the called function. In the calling function
cannot be placed on the statement appears. If no no change will be made to the
Programming Tip: :
the right side of the implicit conversion is possible, tls toh value of the variables, This
assignment operator. the return statement is invalid. is because all the changes
Since the retum type of the aes were made to the copy of the
statements inC. variables and not to the actual
function check_relation() is int, so the result either 0, 1,
or ~1 isevaluated as an integer variables
We have mentioned earlier that the variables declared To understand this concept, consider the code given
inside the function cease to exist after the last statement below, The add() function accepts an integer variable
of the function is executed. So how can we return the num and adds 10 to it, In the calling function, the value of
value of sum to the program that adds two integers using a num = 2. In add(), the value of num is modified to 12 but in
function? The answer to this question is that a copy of the the calling function the change is not reflected.
value being returned is made automatically and this copy
#include <stdio.h>
is available to the return point in the program.
void add(int n);
int main()
11.6.1 Using Variable Number of Arguments {
Some functions have a variable number of arguments int num = 2;
and data types that cannot be known at the compile time. printf("\n The value of num before calling
Typical examples of such functions include the print€() the function = Xd", num);
and scanf() functions. ANSI C offers a symbol called add(num) ;
ellipsis to handle such functions. The ellipsis consists of printf("\n The value of num after calling
three periods (...). It can be used as the function = Xd", num);
return 0;
int func(char ch, ...);
The function declaration statement given above states
that func is a function that has an arbitrary number and void add(int n)
type of arguments. However, one must ensure that both {
the function declaration and function definition should use n=n4 10;
the ellipsis symbol. printf("\n The value of num in the called
function = Xd", n);
11.7 PASSING PARAMETERS TO FUNCTIONS
When a function is called, the calling function may have Output
to pass some values to the called function, We have been
doing this in the programming examples given so far. The value of num before calling the function = 2
We will now learn the technicalities involved in passing The value of num in the called function = 12
arguments/parameters to the called function. The value of num after calling the function = 2
254 | Computer Fundamentals and Programming in C
Since the called function uses a copy of num, the value * Values of the variables in the calling function remain
of num in the calling function remains untouched. This unaffected when the arguments are passed using call-
concept can be more clearly understood from Figure 11.5 by-value technique.
Therefore, call-by-value method of passing arguments
2 2 to a function must be used only in two cases:
+ When the called function does not need to modify the
um in the calling function num in the calling function, value of the actual parameter. It simply uses the value of
is known as in the the parameter to perform its task.
called functionn + When you want that the called function should only
temporarily modify the value of the variables and not
rt ed permanently. So although the
Programming Tip: called function may modify
num in the calling function nis modified in the Using call-by-value the value of the variables, these
remains unchanged called function methodofpassing variables remain unchanged in
Figure 11.5 Call-by-value method of argument passing values tspreferred the calling function:
to avoid inadvertent
In the aforegiven program, the called function could changes to variables
of the calling Pros and Cons
not directly modify the value of the argument that was
passed to it. In case the value has to be changed, then the inthe calledfunction. §=The biggest advantage of using
programmer may use the return statement, This is shown the call-by-value technique to
in the following code. pass arguments to the called function is that arguments can
#include <stdio.h> be variables (c.g., x), literals (¢.g., 6), or expressions (¢.g.,
int add (int n); x + 1). The disadvantage is that copying data consume:
int main() additional storage space. In addition, it can take a lot of
{ time to copy, thereby resulting in performance penalty,
int num = 2; especially if the function is called many times.
printf("\n The value of num before calling
the function = Xd", num); 11.7.2 Call by Reference
num «= add(num);
When the calling function passes arguments to the called
printf("\n The value of num after calling
function using call-by-value method, the only way to
the function = Xd", num);
return the modified value of the argument to the caller is
return 0;
explicitly using the return statement, A better option when
a function wants to modify the value of the argument is
to pass arguments using call-by-reference technique. In
int add(int n)
call by reference, we declare the function parameters as
{
nen + 10;
references rather than normal variables, When this is done
any changes made by the function to the arguments it
printf("\n The value of num in the called
receives are visible in the calling function.
function = %d", n);
To indicate that an argument is passed using call by
return nj
reference, an asterisk (*) is placed after the type in the
} parameter list. This way, changes made to the parameter
Output in the called function will then be reflected in the calling
function.
The value of num before calling the function = 2
Hence, in call-by-reference method, a function
The value of num in the called function = 12
receives an implicit reference to the argument, rather
The value of num after calling the function = 12
than a copy of its value. Therefore, the function can
The following points are to be noted while passing modify the value of the variable and that change will be
arguments to a function using the call-by-value method. reflected in the calling function as well. The following
* When ablrguments are passed by value, the called program uses this concept
function creates new variables of the same data type as To understand this concept, consider the code given
the arguments passed to it below
#include <stdio.h>
* The values of the arguments passed by the function are
copied into the newly created variables. void add (int *n);
* Arguments are called by value when the called function int main()
does not need to modify the values of the onginal A
Output
{
int temp;
The value of num before calling the function = 2 temp = *c;
The value of num in the called function = 12 // * operator used to refer to the value
The value of num after calling the function = 12 *c = #4;
*d = temp;
Advantages printf("\n In function (Call By Reference
Method) c = Xd and d = %d", *c, *d);
The advantages of using the call-by-reference technique
of passing arguments are as follows: }
} float sum=0.0;
int Fact(int num) clrser();
{ printf("\n Enter the value of n(");
int f=1, i; scanf("%d",&n);
for(i=num;i>=1;4--) for (i=1;icen;it+)
f = f*i; {
return f;
} NUM = pow(i,i);
Output DENO = Fact(i);
Enter the value of n: 4 sum += (float)NUM/DENO;
Enter the value of r: 2
}
C(n/r): €(4)/(2) = 6.00 printf("\n 1/1! + 4/21 + 27/31 + «2.0
%.2f", sum);
8. Write a program to sum the series WA) + 121+1/31 getch();
+ + nt.
#include <stdio.h>
return 0;
#include <conio.h>
}
int Fact(int n)
int Fact(int);
int main() int f#1, i;
{ for(i=n;i>=1;i--)
int n, f, 4; fafei;
float result=0.0; return f;
clrser();
printf("\n Enter the value of n: 5
}
scanf("Xd", &n); Output
for (i=l; icen;it+) Enter the value of n: 3
{ 1/1! + 4/21 + 27/31 + ....= 7.50
feFact(i);
result += 1/(float)f;
}
printf("\n The sum of the series 1/1! +
GERD scope OF VARIABLES
1/21 + 1/31... = %.1f", result); In C, all constants and variables have a defined scope.
getch(); By scope we mean the accessibility and visibility of the
return 0;
variables at different points in the program. A variable or
} a constant in C has four types of scope; block, function,
int Fact(int num)
program, and file
{
int fel, i;
11.8.1 Block Scope
for(i=numji>=1;i--)
f = fei; We have studied that a statement block is a group of
return f; statements enclosed within opening and closing curly
} brackets { }. If a variable is declared within a statement
block then as soon as the control exits that block, the
Output
variable will cease to exist. Such a variable also known as
Enter the value of n: 2 a local variable is said to have a block scope.
The sum of the series 1/1! + 1/2! + So far we had been using local variables. For example,
1/31... = 1.5 if we declare an integer x
Coenen inside a function, then that
9, Write a program to sum the series—I/I! + 4/2! Santhwaea ta variable is unknown to the rest
27/3! +, f — of the program (i.e., outside
#include <stdio.h> the csi that function).
#include <conio.h> nasties Blocks of statements may
#include <math.h> be placed one after the other in
int Fact(int); a program; such blocks that are placed at the same level are
int main() known as parallel blocks. However, a program may also
{ contain a nested block, like a while loop inside main()
int n, i, NUM, DENO; If an integer x is declared and initialized in main(), and
258 Computer Fundamentals and Programming in C
then re-declared and re-initialized in a while loop, then the function scope is applicable only with goto label names.
integer variable x will occupy different memory slots and This means that the programmer cannot have the same
will be considered as different variables. The following label names inside a function.
code reveals this concept Using goto statements is not recommended as it is not
considered to be a good programming practice. We will
#include <stdio.h>
not discuss the goto statement in detail here but we will
int main()
take a look at an example code that demonstrates the
{ function scope.
int x = 10;
int i=0; int main()
printf("\n The value of x outside the {
while loop is %d", x);
while (i<3)
{ loop: /* A goto label has function
int x * 4; scope */
printf("\n The value of x inside the
while loop is Xd", x);
itt;
goto loop; /* the goto statement */
is no specific rule that states where the global variables variable to have file scope, declare that variable with the
must be declared, it is always recommended to declare static keyword before specifying its data type:
them on top of the program code static int x = 10;
Name Conflict If we have a variable declared in a function A global static variable can be used anywhere from the
that has same name as that of the global variable, then the file in which it is declared but it is not accessible by any
function will use the local variable declared within it and other file, Such variables are useful when the programmer
ignore the global variable. However, the programmer must writes his own header files.
not u mes of global variables as the names of local
variables, as this may lead to confusion and erroncous
result EER} STORAGE classes
Storage class defines the scope (visibility) and lifetime of
variables and/or functions declared within a C program.
Jobal variable is not initialized during its declaration
then it is automatically initialized to zero by default.
In addition to this, the storage class gives the following
information about the variable or the function.
Consider the following program. * The storage class of afunction or a variable determines
the part of memory where storage space will be allocated
#include <stdio.h>
for that variable or function (whether the variable/
int x = 10;
function will be stored in a register or in RAM).
void print();
+ Itspecifies how long the storage allocation will continue
int main()
to exist for that function or variable
{ + It specifies the scope of the variable or function, i.c.,
printf("\n The value of x in the main()
the storage class indicates the part of the C program in
= Xd", x);
which the variable name is visible or the part in which
int x = 2;
it is accessible, In other words, whether the variable/
printf("\n The value of local variable x
function can be referenced throughout the program or
in the main() = Xd", x);
only within the function, block, or source file where it
print(); has been defined.
return 0;
* It specifies whether the variable or function has internal,
} external, or no linkage.
void print()
* It specifies whether the variable will be automatically
{ initialized to zero or to any indeterminate value.
printf("\n The value of x in the print()
= Xd", x); C supports four storage classes: automatic, register,
} external, and static. The general syntax for specifying
the storage class ofa variable can be given as:
Output
<storage_class_specifier> <data type>
The value of x in the main() = 20 <variable name>
The value of local variable x in the main() = 2
The value of x in the print() = 10 11.9.1 auto Storage Class
From the code we sec that local variables overwrite the The auto storage class specifier is used to explicitly declare
value of global variables, In big programs use of global a variable with automatic storage. It is the default storage
variables is not recommended until it is very important to class for variables declared inside a block. For example,
use them because there is a big risk of confusing them with if we wnte
any local variables of the same name.
auto int x;
* All local variables declared within a function belong to Register variables are used when quick access to the
automatic storage class by default variable is needed. It is not always necessary that the
* They should be declared at the start of the program register variable will be stored in the register. Rather, the
block, right after the opening curly bracket { register variable might be stored in a register depending on
Memory for the variable is automatically allocated upon the hardware and implementation restrictions.
entry to a block and freed automatically upon exit from Hence, programmers can only suggest to the compiler
that block. to store those variables in the registers which are used
* The scope of the variable is local to the block in which repeatedly or whose access times are critical. However,
it is declared. These variables may be declared within a for the compiler, it is not an obligation to always accept
nested block, such requests. In case the compiler rejects the request to
{very time the block (in which the automatic variable is store the variable in the register, the variable is treated as
declared) is entered, the variable is initialized with the having the storage class specifier auto.
values declared. Like auto variables, register variables also have
* The auto variables are stored in the primary memory of automatic storage duration. That is, each time a block is
the computer. entered, the register variables defined in that block are
* If auto variables are not initialized at the time of accessible and the moment that block is exited, the variables
declaration, then they contain some garbage value. become no longer accessible for use. Now let us have a look
at the following code that uses a register variable.
The following code uses an auto integer that is local to the
function in which it is defined include <stdio.h>
int exp(int a, int b);
#include <stdio.h>
int main()
void funci()
{
{ int a3, beS, res;
int a10; res = exp(a, b);
printf("\n a = Xd", a); printf("\n Xd to the power of Xd = Xd",
// auto integer local to funci() a, b, res);
} return 0;
void func2()
{
int a=20; int exp(int a, int b)
printf("\n a = Xd", a);
// auto integer local to func2() register int res#1;
} int i;
void main() for(i=1;iceb;
i++)
{ res = res*a;
int a#30;// auto integer local to main() return res;
funct(); }
func2();
printf("\n a = Xd", a); Output
} 3 to the power of 5 = 243
Output
11.9.3 extern Storage Class
a*10
a= 20 A large C program can be broken down into smaller programs.
a= 30 When these smaller programs are compiled, they are joined
together to form a large program. However, these smaller
programs may need to share certain variables for processing.
11.9.2 register Storage Class For such situations C language provides an external storage
When a variable is declared using register as its storage class that is specified using the keyword extern
it is stored in a CPU register instead of RAM. Since The extern storage class is used to give a reference of
the variable is stored in a register, the maximum size of a global vanable that is visible to all the program files.
the variable is equal to the register size. One drawback of Such global variables are declared like any other variable
using a register variable is that they cannot be operated in one of the program files. When there are multiple files
using the unary ‘&' operator because it does not have a in a program and you need to use a particular function or
memory location associated with it, A register variable is variable in a file apart from which it is declared, then use the
declared in the following manner; extern keyword. To declarea variable x as extern write,
register int x; extern int x;
Functions 261
In the program, we have used two files—File1 and Look at the following code which clearly differentiates
File2. File1 has declared a global variable x. File1 also between a static variable and a normal variable.
includes File2 which has a printf function that uses the #include <stdio.h>
external variable x to print its value on the sereen. void print(void);
262 Computer Fundamentals and Programming in C
STORAGE CLASS
F
| auto extern register static
Accessibility Accessible within the function — Accessible within Accessible within the Local: Accessible within
or block in which it is all program files function or block in which the function or block
declared. that are a part of itis declared. in which it isdectared_
the program. Global: Accessible within
the program in which it is
declared,
| Storage Main memory Main memory CPU register Main memory
Existence Exists when the function or Exists throughout Exists when the function Locak: Retains value
block in which it isdeclaredis the executionof of block in which it is between function calls
entered. Ceases to exist when the program. declared is entered. Ceases ar block entries.Global:
the control returns from the to exist when the control Preserves
value in program
function ortheblock inwhich returns from the function files.
itwas declared. of the block in which itwas
declared.
\ Default value Garbage Zero Garbage Zero
10. Write a program to calculate GCD using recursive printf ("\n RESULT = %d", res);
functions. return 0;
#include <stdio.h>
}
int exp_rec(int x, int y)
int GCD(int, int);
int main() {
if( y==0)
{ return 1;
int numl, num2, res;
else
printf("\n Enter the two numbers: "); return (x * exp_rec(x, y-1));
scanf("Xd Xd", &numi, &num2);
res = GCD(num1, num2);
printf("\n GCD of Xd and Xd = Xd", num,
num2, res); 11.10.3 Fibonacci Series
return 0; The Fibonacci series can be given as:
$ 8 13 21 34 55
}
int Funci(int n)
int Facti(int n, int res)
{
return nj;
if (ne=1)
return Func2(n);
return res;
else
int Func2(int x)
return Factl(n-1, n*res);
return Funci(x-1);
}
if(num == @)
return @;
else if(num “= 1)
return 1;
else
return ( Fibonacci (num - 1) + Fibonacci (num - 2))5
}
Observe the series of function calls. When the function
returns, the pending operation in turn calls the function
the amount of information to be stored on the system stack the pending operation involves only multiplication to be
is constant (just the values of n and res need to be stored) performed and does not involve another recursive call
and is independent of the number of recursive calls. to Fact.
On the contrary, a recursive function is said to be
Converting Recursive Functions to Tail tree recursive (or non-linearly recursive) if the pending
Recursive operation makes another recursive call to the function. For
example, the Fibonacci function Fib in which the pending
A non-tail recursive function can be converted into a
operations recursively calls the Fib function.
tail-recursive function by using an auxiliary parameter
as we did in case of the Factorial function. The auxiliary
parameter is used to form the result. When we use such a
parameter, the pending operation is incorporated into the EERE Tower OF HANOI
auxiliary parameter so that the recursive call no longer
has a pending operation, We generally use an auxiliary The tower of Hanoi is one of the main applications of
function while using the auxiliary parameter. This is done recursion, It says, ‘if you can solve n — | cases, then you
to keep the syntax clean and to hide the fact that auxiliary can casily solve the n™ case”
parameters are needed Look at Figure 11.12 which shows three rings mounted
on pole A. The problem is to move all these rings from
A to pole C while maintaining the same order, The
11.11.4 Linear and Tree Recursion
Recursive functions can also be characterized depending
on the way in which recursion grows, ic, in a linear
fashion or forming a tree structure (Figure 11.11)
In simple words, a recursive function is said to be
linearly recursive when the pending operation (if any)
does not make another recursive call to the function.
For example, observe the last line of recursive factorial
a @ ©
function. The factorial function is linearly recursive as Figure 11.12 Tower of Hanoi
Functions 267
a @ else
{
Figure 11.13 Move rings from Ato B move(n-1,source,spare, dest);
move(1,source,dest,spare);
Now that # = 1 rings have been removed from pole A, move(n-1,
spare, dest, source);
the n' ring can be casily moved from the source pole (A) }
to the destination pole (C). Figure 11.14 shows this step. }
Let us look at the Tower of Hanoi problem in detail
using the aforegiven program. Figure 11.16 explains the
working of the program using one, then two, and finally
_ three rings.
= mm =
A B c A B c A B c
(Step 1) (Step 1) (Step2)
= SS] aa ah
A B c A B c A B c
(Step 2) (Step 3) (Step4)
(If there is only one ring, then simply move (If there are two rings, then first move ring | to the spare
the ring from source to the destination.) pole and then move ring 2 from source to the destination,
Finally move ring | from the spare to the destination.)
(=) I oe I a | Ee f=
A B c A B c A B c A B c
(Step 1) (Step2) (Step 3) (Step4)
A
dah eS
B c
OS
A B
oa
c
———
A B c A B
= c
(Step 5) (Step6) (Step 7) (Step8)
(Consider the working with three rings.)
Figure 11.16 Working of Tower of Hanoi with one, two, and three rings
To conclude, one must use recursion only to find The drawbacks/disadvantages of using a recursive
solution to a problem for which no obvious iterative program include the following:
solution is known. To summarize the concept of recursion, * For some programmers and readers, recursion is a
let us briefly discuss the pros and cons of recursion. difficult concept
The advantages of using a recursive program include * Recursion is implemented using system stack. If the
the following stack space on the system is limited, recursion to a
* Recursive solutions often tend to be shorter and simpler deeper level will be difficult to implement
than non-recursive ones. Aborting a recursive process in midstream can be a very
* Code is clearer and easier to use. slow process.
* Recursion works similar to the original formula to solve + Using a recursive function takes more memory and time
a problem. fo execute as compared fo its non-recursive counterpart
* Recursion follows a divide and conquer technique to It is difficult to find bugs, particularly while using global
solve problems. variables,
In some (limited) instances, recursion may be more The advantages of recursion pays off for the extra
efficient overhead involved in terms of time and space required.
POINTS TO REMEMBER
* Every function in a program is supposed to perform a * All the libraries in C contain a set of functions that
well-defined task. The moment the compiler have been prewritten and pre-tested, which the
encounters a function call, the control jumps to the Programmers can use without worrying about the
statements that are part of the called function. After code details. This speeds up program development.
the called function is executed, the control is returned ¢ While function declaration statement identifies a
back to the calling function. function with its name, the list of arguments that it
Functions 269
accepts and the type of data it returns, the function Hence, in this method, a function receives an implicit
definition, on the other hand, consists of a function reference to the argument, rather than a copy of its
header that identifies the function, followed by the value. This allows the function to modify the value of
body of the function containing the executable code the variable and that change will be reflected in the
for that function. calling function as well.
main() is the function that is called by the operating * Scope means the accessibility and visibility of the
system and, therefore, it is supposed to return the variables at different points in the program. A variable
result of its processing to the operating system. or a constant in C has four types of scope: block,
. Placing the function declaration statement prior to its function, program, and file scope.
use enables the compiler to make a check on the Storage class defines the scope (visibility) and life-
arguments used while calling that function time of variables and/or functions declared within aC
* A function having void as its return type cannot return program.
any value. Similarly, a function having void as its The auto storage class is the default storage class for
parameter list cannot accept any value. variables declared inside a block. The scope of the
* When a function is defined, space is allocated for that variable is local to the block in which it is declared,
function in the memory. A function definition comprises When a variable is declared using register as its
of two parts: function header and function body. storage class, it is stored in a CPU register instead of
Call-by-value method passes values of the variables to RAM. Extern is used to give a reference of a global
the called function. Therefore, the called function variable that is visible to all the program files. Static is
uses a copy of the actual arguments to perform its the default storage class for global variables.
intended task. This method is used when the function A recursive function is defined as a function that calls
does not need to modify the values of the original itself to solve a smaller version of its task until a final
variables in the calling function. call is made which does not require a call to itself.
In call-by-reference method, address of the variable is Recursive functions are implemented using system
passed by the calling function to the called function. stack.
GLOSSARY
Argument A value passed to the called function by the Iteration Solving a problem by repeatedly working on
calling function. successive parts of the problem.
Block A sequence of definitions, declarations, and Recursion An algorithmic technique where a function
statements, enclosed within curly brackets. calls itself with a smaller version of the task in order to
Divide and conquer Solving a problem by dividing it into solve that task.
two or more smaller instances. Each of these smaller Recursion termination The point at which base condition
instances is recursively solved, and the solutions are is met and a recursive algorithm stops calling itself and
combined to produce a solution for the original problem. begins to return values.
Formal parameter List of the variables in the function Tail recursion A form of recursion in which the last
header. operation of a function is a recursive call.
EXERCISES
Fill in the Blanks 4, The inputs that the function takes are known as
1 provides an interface to use the function.
2 After the function is executed, the control passes back to 5, main() is called by the
the 6. Function definition consists of _ and s
A function that uses another function is known as the 7. In_ method, address of the variable is passed
by the calling function to the called function.
270 ‘Computer Fundamentals and Programming in C
8. Function scope is applicable only within 7. Extern variables are initialized by default.
9. Function that callsitselfisknownasa function. 8. The default storage class of local variables is extern
10. Recursive functions are implemented using Recursion follows a divide-and-conquer technique to
11. _____ function is defined as a function that calls solve problems.
itself. 10. Local variables overwrite the value of global variables.
12. The function int func(); takes arguments 11. AC function can return only one value.
13, _____ variables can be accessed from alll functions in 12. A function must have at least one argument.
the program. 13. A function can be declared and defined before main()
14, The execution of a program starts at 14. A function can be defined in main()
15. By default, the return type of afunctionis 15. Variable names in the function definition must match
16, Variable declared inside a function is known as with those specified in the function declaration.
16. Specifying variable names in the function declaration is
Multiple-choice Questions optional
1, The function that is invoked is known as 17. main() is a user-defined function.
(a) calling function (b) caller function
(c) called function (d) invoking function Review Questions
2. Function declaration statement identifies a function 1, Define a function. Why are they needed?
with its 2. Explain the concept of making function calls.
(a) name (b) arguments
3. Differentiate between function declaration and function
definition.
(c) datatype of return (d) allofthese
4. Differentiate between formal parameters and actual
value
parameters.
3. Which return type cannot return any value to the caller?
5. How many types of storage classes C language supports?
(a) int (b) float Why do we need different types of such classes?
{c) void {d) double Give the features of each storage class.
4, Memory is allocated for a function when the function is 7. Explain the concept of recursive functions with
(a) declared (b) defined example
(c) called {d) returned 8. Differentiate between an iterative function and a
5, Which keyword allows a variable to have file scope? recursive function. Which one will you prefer to use and
in what circumstances?
(a) auto (b) static
9. What will happen when the actual parameters are less
{c) register (d) extern than formal parameters in a function?
6, The default storage class of global variables is
10. What will happen when data type of a variable in the
(a) auto (b) static function declaration does not match with the
(c) register {d) extern corresponding variable in the function header?
7. Which variable retains its value in-between function 11. What will happen when a function returns a value that
calls? does not match with the return type of the function?
(a) auto (b) static 12. Explain the Tower of Hanoi problem.
(c) register (d) extern 13. Differentiate between call by value and call by reference
8, The default storage class of a local variable is using suitable examples
14. What do you understand by scope of a variable? Explain
(a) auto (b) static
in detail with suitable examples.
(c) register (d) extern
15. Why function declaration statement is placed prior to
function definition?
State True or False
1, The calling function must always pass parameters to the Programming Exercises
called function. 1. Write a program to calculate factorial of a number using
2. Function header is used to identify the function. recursion. Also write a non-recursive function to do the
3. The name of a function is global. same job.
4, No function can be declared within the body of another 2. Write a program using function that calculates the
function hypotenuse of a right-angled triangle.
5, The function call statement invokes the function. 3. Write a function that accepts a number n as input and
6. Auto variables are stored inside CPU registers. returns the average of numbers from 1 to n.
Functions 271
. Write a function to reverse a string using recursion. (a) using recursion (b) without using recursion.
. Write a function is_prime that returns 1 if the argument 26. Write a program to convert the given string “hello world”
Passed to it is a prime number and a 0 otherwise. to “dirow olleh” without using recursion,
. Write a function that accepts an integer between 1 and 27. Write a program to find HCF of two numbers (a) using
12 to represent the month number and displays the recursion (b) without using recursion.
corresponding month of the year (For example if 28. Write a program to calculate x" (a) using recursion
month = 1, then display JANUARY). (b) without using recursion.
Write a function is_leap_year which takes the year as its 29. Write a program to print the Fibonacci series (a) using
argument and checks whether the year is a leap year or recursion (b) without using recursion.
not and then displays an appropriate message on the 30. Write a program using functions to perform calculator
screen. Operations.
Write a program to concatenate two strings using 31. Write a function that converts temperature given in
recursion. Celsius into Fahrenheit
Write a program to read an integer number. Print the 32. Write a function that prints the conversion table of
reverse of this number using recursion Degrees Fahrenheit into Degrees Celsius ranging from
Write a program to swap two variables that are defined 32-212 degrees Celsius.
as global variables. 33. Write a function to draw the following pattern on the
. Write a program to compute F(x, y) where screen
F(x, y) = F(x-y, y) + 2 df y?x
And F(x, y) = 0 if xey
12 Write a program to compute F(n, r) where
F(n, ©) can be recursively defined as
F(n, r) = F(n-31, 7) + F(n-3, r-1)
13. Write a program to compute Lambda(n) for all positive 34. Write a function to print a table of binomial coefficients
values of n where Lambda(n) can be recursively which is given by the formula-
defined as B(m, x) = ml/ (x! (m-x)!) where m > x
Lambda(n) = Lambda(n/2) + 1 if no1 Hint:B(m,0) = 1, B(0,0) = 1 and
AND Lambda(n) = 0 if n #1 B(m,x) = B(m, x-1) * [( m- x # 1)/x]
4. Write a program to compute F(M, N) where 35. Write a program to evaluate
F(M, N) can be recursively defined as f(x) = x - «1/31 + 8/51 - x7/7h +
F(M,N) = 1 if MeO or M?N?2
AND F(M,N) = F(M-1,N) + Find the output of the following codes
F(M-1, N-1) otherwise 1, include <stdio.h>
15. Write a menu driven program to add, subtract, multiply, int func();
and divide two integers using functions. main()
16, Write a program to find the smallest of three integers {
using functions. printf("Ad", func());
v7 Write a program to calculate area of a triangle using printf("%d", func());
function. printf("xd", func());
18 Write a program to find whether a number is divisible by
printf("xd", func());
two or not using functions. return 0;
19. Write a program to illustrate call-by-value technique of }
passing arguments to a function.
int func()
{
20, Write a program to illustrate call-by-reference technique int counter=0
of passing arguments to a function.
return counter;
21 Write a program to swap two integers using call-by-value
}
method of passing arguments to a function.
2. #include <stdio.h>
22. Write a program using function to calculate x to the int func();
power of y, where y can be either negative or positive.
main()
23. Write a program using function to calculate compound {
interest given the principal, rate of interest, and number printf("%d", func());
of years. printf("xd", func());
24, Write a program to swap two integers using call-by- printf("Xd", func());
reference method of passing arguments to a function. printf("Xd", func());
25, Write a program to calculate factorial of a number return 0;
272 ‘Computer Fundamentals and Programming in C
} int func(int a)
int func() {
{ if(a>1)
static int counters0; return func(--a) + 10;
return counter; else
} return 0;
3. #include <stdio.h> }
int func(); #include <stdio.h>
int counter = 5; void func(int);
main() main()
A {
printf(*xd", func()); int a=127;
printf("Xd", func()); printf("Xd", a);
printf(“%d", func()); func(a);
printf("Xd", fune()); return 0;
return 0; }
} void func(int a)
int func() {
{ are;
return counter++; printf("%d", a);
} }
4, #include <stdio.h> #include <stdio.h>
int add(int, int); void func(int);
main() auto int a;
{ main()
int ae2, be3; {
printf("Xd Ad Xd", a, b, add(a, b)); int a*10;
return 0; printf("xd", a);
} func(a);
int add(int a, int b) return 0;
{ }
int ¢; void func(int a)
c = arb {
return; art;
} printf("Xd", a);
5. #include <stdio.h> }
int add(int, int); #include <stdio.h>
main() static int add(int val)
{ (
int a*2, b=3; static int sum;
printf("%d Xd Xd", a, b, add(a, b)); sum += val;
return 0; return sum;
} }
int add(int a, int b) main()
{ {
int c; int i, n=10;
c = arb for(i=0;i<10;i++)
} add(i);
6. #include <stdio.h> printf("\n SUM = Xd", func(0));
int func(int); return 0;
main() }
{ 10. #include <stdio.h>
int a=2; void func(int);
printf("Xd", func(a)); int a=10;
return 0; main()
{
int a=2; static int func()
printf("Xd", a); (
func(a); return a++;
printf("Xd", a); }
return 0; main()
} {
void func(int a) a=10;
printf(*xd", func());
ae20; a *= 10;
} printf("xd", func());
11 #include <stdio.h> return 0;
void func(char); }
main() #include <stdio.h>
{ int prod(int x, int y)
char che2S6; {
fune(ch) return (x*y);
return 0; }
} main()
void func(char a) {
{ int x92, y#3, z;
printf("Xd", a); z= prod(x,prod(x,y));
} printf("Xd", z);
12 #include <stdio.h> return 0;
int }
274 Computer Fundamentals and Programming in C
>
| ANNEXURE2
User Defined Header Files #include “fact.h”
At times programmers may need a function that provides int main()
additional processing capabilities and may want to create a {
separate source code file to contain that function. This would int num, £;
help to segregate the function from rest of the main source clrscr();
printf("\n Enter any number: ");
code, In such a situation, the uxer may create a user-defined
scanf("%d", &num);
header file so that the compiler knows how to call this function.
f = factorial(num);
For example, if we want the factorial function to be
printf("\n FACTORIAL of Xd = Xd",
stored in a user-defined header file, then write the code of the
» #5
factorial function in afile and save it as fact.h. Then in the etek us
main program file, we will include the fact .h file and call the Tata Of
function in the same way as we call other functions. Look at }
the code given below which illustrates this concept
In the above code, a user-defined header file-fact.h has been
seiteee MES) used. The name of the header file has been enclosed within
{ long int #2; quotes to tell the compiler not to look along the standard
for(;num >= 1;num--) library path, but to look in the same path as the source file.
f= f * num; When you compile the file that contains the source code,
return f; that is the file contains main(), the compiler will compile it
} into object code. As long as the C program is syntactically
correct, the object code will be created.
// Contents for the main file The linker will combine the object code and library files,
#include <stdio.h> and create an executable file. It is the header file that links the
#include <conio.h> definition of the function with the implementation.
EEE
TAKEAWAYS
* Array declaration * Operations on 2D arrays * Array implementation of
© Operations on arrays * Two-dimensional arrays sparse matrices
© Linear and binary search * Array length © Application of arrays
© Passing arrays to functions . Multidimensional arrays
€FRB intRopuction data elements have the same data type. The clements of
the array are stored in consecutive memory locations and
are referenced by an index (also known as the subscript).
We will explain the concept of arrays using an analogy
Subscript is an ordinal number which is used to identify an
Take a situation in which we have 20 students in a class
element of the array. Some examples where the concept of
and we have been asked to write a program that reads and
an array can be used include lists of the following:
prints the marks of all these 20 students. In this program,
we will need 20 integer variables with different names, as * Temperatures recorded on every day of the month
shown in Figure 12.1 * Employees in a company
+ Students in a class
Marks! MarksS Marks9 Marks13 Marks 17 * Products sold
* Customers
2 I BE FC SI FAB
element |element |clement |element |clement |clement | element | clement | clement
marks[O] marks{1] marks[2] marks{3} marks{4] marks[S] marks{6] marks{7] marks[8] marks[9]
The above statement declares marks to be an array * C never checks the validity of the array index— neither
containing 10 elements. In C, the array index (also at compile time nor at run time. So even if you declare
known as subscript) starts from zero. This means that an array as
the array marks will contain 10 clements in all. The first
int arr[N];
element will be stored in marks[0], the second clement
in marks(1], and so on. Therefore, the last clement, The C compiler will not raise any error but the result of
i.e., the 10" clement will be stored in marks[9]. Note running such code is totally unpredictable. Even if you
that 0, 1, 2, 3 written declare an array of 10 elements and later on by mistake try
Programming Tip: within square brackets are to access the 11th clement, no error will be generated. But
nan array ofsizen, subscripts/index. In memory, the results will be unpredictable as the memory occupied
thelndexranges#OM) ih. array will be stored as by the (so-called) 11th element may be storing data of
Oton-1, shown in Figure 12.2 another object
Points to Remember
* Note that C does not allow declaring an array whose ACCESSING THE ELEMENTS OF
number of elements is not known at the compile time.
Therefore, the following array declarations are illegal in
AN ARRAY
Pa
For accessing an individual element of the array, the array
int are[]; subscript must be used. For example, to access the fourth
int n, arr{n]; element of the array, we must write are[3], The subscript/
index must be an integral value or an expression that
Generally it is a good programming practice to define evaluates to an integral value,
the size of an array as a symbolic constant as shown in Although storing the related
the following code Programming Tip:
data items in a single array
To access allthe Ws
include <stdio.h> enables the programmers to
define N 100 elementsofthe
2F7Y develop concise and efficient
main() Meas PES ‘ programs, there is no single
{ riage function that can operate on all
int arr(N); ic : the elements of the array, To
access all the clements of the
} array, We must use a loop, That is, we can access all the
clements of the array by varying the value of the subscript
* The size of the array can be specified using an into the array. But note that the subscript must be an
expression. However, the components of the expression integral value or an expression that evaluates to an integral
must be available for evaluation of the expression when value. As shown in Figure 12.2, the first element of the
the program is compiled. Therefore, the following array array marks[10] can be accessed by writing, marks(0)
declarations are valid in C language. Now to process all the elements of the array, we will use a
#include <stdio.h> loop as shown in Figure 12.3
define N 100
main() // Set each element of the array to -1
{
int is10; int 4, marks[10};
int arr(N+10), my_arr[i-5*10}; for(4=0;1<20; i++)
marks[i] = -2;
we ff) 1 2) Gl Oo OS)
1000 1004 1008 1012 1016 1020 1024 1028
Here, 100 is assigned to the fourth element of the array 12.5.1 Traversing an Array
which is specified as marks[3).
We cannot assign one array to another array, even if the Traversing an array means accessing cach and every
two arrays have the same type and size. To copy an array, clement of the array for a specific purpose.
you must copy the value of every clement of the first array If A is an array of homogeneous data elements, then
into the clement of the second array, Figure 12.7 illustrates traversing the data clements can include printing every
the code to copy an array.
clement, counting the total number of elements, or
performing any process on these clements. Since an array
is a linear data structure (because all its elements form
// Copy an array at the individual element level @ sequence), traversing its elements is very simple and
straightforward. The algorithm for array traversal is given
int 4, arr1[10], arr2[10}; in Figure 12.9.
are[1] = {0,1,2,3,4,5,6,7,8,9);
for(1w0;i<lO;iee)
arr2[i] = arri{i};
Step 1: [INITIALIZATION] SET I = lower_bound
Step 2: Repeat Steps 3 to 4 while I< = upper_bound
Figure 12.7 Code to copy an array at the individual Step 3: Apply Process to AI]
element level Step
4: SET Teed
[END OF Loop}
‘Step 5: EXIT
In Figure 12.7, the code accesses cach clement of
the first array and simultancously assigns its value to the Figure 12.9 Algorithm for array traversal
corresponding clement of the second array. Finally, the
index value i is incremented to access the next clement In Step 1, we initialize index i to the lower_bound of
in succession, Therefore, when this code is executed, the array. In Step 2, a while loop is executed. Steps 3 and 4
arr2(0}) = arri[O), arr2(2) © arri(i), arr2[2) « form part of the loop. Step 3 processes the individual array
arri[2), and so on. clement as specified by the array name and index value.
We can also use a loop to assign a pattern of values to Step 4 increments the index value so that the next array
the array elements. For example, if we want to fill an array clement could be processed. The while loop in Step 2 is
with even integers starting (from 0), then we will write the executed until all the elements in the array are processed.
code as shown in Figure 12.8 In other words, the while loop will be executed until £ is
less than or equal to the upper_bound of the array.
// Fill an array with even numbers
Example 12.4
int 4, are[10};
for(i#0;1<10;ie+) Assume that there is an array Marks{ ], such that the index
arr[i) = 4°2; of the array specifies the roll number of the student and the
value of a particular element denotes the marks obtained by
Figure 12.8 Code for filling an array with even numbers the student. For example, if it is given Marks[4] =78, then the
student whose roll number is 4 has obtained 78 marks in the
In the code, we assign to each element a value equal to examination. Now, write an algorithm to:
twice of its index, where index starts from zero. So after (a) Find the total number of students who have secured
executing this code we will have, arr[O] «0, arr[{1} = 2, 80 or more marks.
arr[2] = 4, and so on. {b) Print the roll number and marks of all the students
who have got distinction.
Output MARKS[1} = 88
MARKS[2] = 67
Enter the marks of 10 students:
MARKS[3} = 78
MARKS[0] = 95 MARKS[4) = 81
MARKS[1] = 88 MARKS[S] = 98
MARKS[2] = 67 MARKS[6] = 55
MARKS[3] = 78 MARKS[7} = 45
MARKS[4] = 81 MARKS[8] = 72
MARKS[S] = 98 MARKS[9} = 90
MARKS[6] = 55
MARKS[7] = 45 FREQUENCY HISTOGRAM
MARKS[8] = 72 GROUP O |
MARKS[9] = 90 GROUP 1 |
GROUP 2 |
GROUP FREQUENCY
GROUP 3 |
GROUP 4 |e
GROUP 5 |
GROUP 66 |
GROUP 7 |
GROUP 88 |
Group 99 |
printf(" * "); 12 34 56 78 89
MEDIAN = 56,00
}
getch();
return 0;
} 12.5.2 Inserting an Element in an Array
Output Inserting an element in an array means adding a new data
clement to an already existing array. If the element has to
Enter the marks of 10 students:
be insertion at the end of the existing array, then the task
MARKS[0] = 95
284 Computer Fundamentals and Programming in C
Ofinsertion is quite simple. We just have to add 1 to the (c) Show the memory representation of the array.
upper_bound and assign the value. Here we assume that {d) If a new data element with value 75 has to be inserted,
the memory space allocated for the array is still available. find its position.
For example, if an array is declared to contain 10 elements, {e) Insert the new data element and then show the memory
but currently it is having only 8 elements, then obviously representation of the array.
there is sp to accommodate two more elements. But if
it already has 10 elements, then we will not be able to add Solution
another clement to it (a) Length of the array = number of elements
Figure 12,10 shows an algorithm to insert a new Therefore, length of the array = 10
clement to the end of the array (b) By default, lower_bound = Oand upper_bound = 9
{c)
Step 1: Set upper_bound = upper_bound+1 23 | 34 | 45 | 56 | 67 | 78 | 89 | 90 100|
Step 2: Set A{upper_bound] = VAL
Step 3: EXIT DatalO) tt) (2) 131 it IS) (6) 17) 8) 19)
{d) Since the elements of the array are stored in ascending
Figure 12.10 Algorithm to append a new element to an order, the new data element will be stored after 67, i.e.,
existing array at the 6th location. So, all the array elements from the
6th position will be moved one location towards the
In Step 1, we increment the value of the upper_bound. right to accommodate the new value.
In Step 2, the new value is stored at the position pointed {e)
by upper_bound,
For example, if we have an array that is declared as
[a2 [23 [34 [4s [56 |67 [75 | 78 | 89 [90 |100]
int marks[60); Daal) [1] (2) (3) [41 ES) (6) E71 18) 9} 10)
for(i=n-1;i>=pos;i--) }
arr{it1] = arr[i];
Output
arr[pos] = num;
n+; Enter the number of elements in the array: 5
printf("\n The array after insertion of Enter the array elements: 12345
%d is: “, num); Enter the number to be inserted: 6
286 Computer Fundamentals and Programming in C
kt ieee
#include
<stdio.h>
Data[0]Data[1]_ Dataj2] Data{3]_ Dataj4]_— Data{S] #include <conio.h>
i) int main()
— oa {
| s | wo | a2 | so em] 2 | int i, mn, j, num, are[10];
Data[O} Dataf]} Data[2} Dataf3]_ Datal4} Data] clrser();
d) printf("\n Enter the number of elements
in the array : “);
F("Xd", &n);
EEE EAED cnettrin enter the elements:");
Data[O] Dataf1]_ Dataf2]_ Datal3}_— Dataf4) for(is0;icn;
i++)
© scanf("%d", &arr[i]);
Figure 12.15 Deleting an elemen array
from ant printf("\n Enter the number to be deleted
2 °)5
13. Write a program to delete a number from a given RRR ATSs AODS
location in an array,
for(ieO;ic<n;ie+)
#include <stdio.h>
#include <conio.h> if(arr[i] == num)
int main() {
{ for(j=i; j<n-1; j++)
int i, n, pos, arr[10); arr[j) = arr[je1);
clrser(); ¥
}
printf("\n Enter the size of the array:"); printf("\n The array after deletion is;
scanf("Xd", &n); “
printf("\n Enter the elements of the array : “); for(i=O;icn-1jie+)
for(ieO;icnziee) printf("\t%d", arr[i]);
scanf("Xd", &arr[i)); getch();
printf("\n Enter the position from which return 0;
the number has to be deleted: "); }
scanf("%d", &pos);
Output
for(i= pos; icn-1;i++) Enter the number of elements in the array: 5S
arr(i) = arr [i+1); Enter the elements: 12345
n-=5 Enter the number to be deleted: 3
printf("\n The array after deletion is:” The array after deletion is: 1245
for(i=0;icn;i++)
printf("\n Arr{%d] = Xd", i, arr[i]); 12.5.4 Merging Two Arrays
getch();
return 0; Merging two arrays in a third array means first copying
} the contents of the first array into the third array and then
copying the contents of the second array into the third
Output array. Hence, the merged array contains contents of the
Enter the size of the array: S first array followed by the contents of the second array.
Enter the elements of the array: If the arrays are unsorted then merging the arrays is
12345 very simple as one just needs to copy the contents of
ost Computer Fundamentals and Programming in C
One array into another. But merging is not a trivial task Output
when the two arrays are sorted and the merged array
Enter the number of elements in array 1: 3
also needs to be sorted. Let us first discuss the merge
Enter the elements of the first array
operation on unsorted arrays. This operation is shown in
10 20 30
Figure 12.16.
Enter the number of elements in array 2: 3
Enter the elements of the second array
Amy 1 [9056
[89[77[69/ 15 25 35
The merged array is
Arr[O0] = 10 Are[1] = 20 Arr[2] = 30
Array 2 {45[88[76[99[12[58[81| Are(3] = 15 Are[4] = 25 Arr[5) = 35
Array 3 [90[56[89[77[69[45[sx[7699]12[58[1| If we have two sorted arrays and the resultant merged
Figure 12.16 Merging of two unsorted arrays array also needs to be a sorted one, then the task of merging
the arrays becomes a little difficult. The task of merging
can be explained using Figure 12.17.
15. Write a program to merge two unsorted arrays.
#Hinclude <stdio.h> Array 1- [2030 ]40|30[60
#include <conio.h>
int main() Array 2- [15]22[31]45[56[62]78
{
int arr1({10), arr2(10}, arr3[20}; array 3- [15]20[22]30[31[40]4550]56|60[62[78
int i, nl, n2, m, indexed;
clrser(); Figure 12.17 Merging of two sorted arrays
printf("\n Enter the number of elements
in array 1; “); The figure shows how the merged array is formed using
scanf("%d", &n1); two sorted arrays. Here, we first compare the Ist element
printf("\n Enter the elements of the first ofarray | with the Ist element of array 2, put the smaller
array"); element in the merged array, Since 20 > 15, we put 15 as
for(iw0;icndjire) the first clement in the merged array, We then compare
scanf("Xd", &arri[i)); the 2nd clement of the second array with the Ist clement
of the first array. Since 20 < 22, now 20 is stored as the
printf("\n Enter the number of elements in second clement of the merged array. Next, 2nd clement
array 2: "); of the first array is compared with the 2nd element of
scanf("%d", &n2); the second array. Since 30 > 22, we store 22 as the third
printf("\n Enter the elements of the second element of the merged array. Now, we will compare the
array"); 2nd clement of the first array with 3rd element of the
for(isO;icn2;i++) second array. As 30 < 31, we store 30 as the 4th clement
scanf("%d", &arr2[i)}); of the merged array. This procedure will be repeated until
m = ni¢n2; elements of both the arrays are placed in the right location
for(i=O;icnlj;i++) in the merged array.
{
arr3[index) = arri{i); 16. Write a program to merge two sorted arrays,
index++;
#include <stdio.h>
i
for(i=0;i<n2;i++) #include <conio.h>
int main()
{
arr3[index} = arr2[i}; {
index++;
int arri({10}, arr2(10}, arr3[20];
int i, nl, n2, m, index=0;
} int index_first = 0, index_second = 0;
printf("\n\n The merged array is”);
clrscr();
for(i=0;i<m;i++)
printf({"\n Enter the number of elements in
printf("\t Arr[Xd] = %d", i, arr3[i});
arrayl: “);
getch();
scanf("%d", &n1);
return 0;
printf("\n Enter the elements of the first
array”);
Arrays 289
for(i=0;icnl;is+) Output
scanf("Xd", &arri[i}); Enter the number of elements in arrayl: 3
Enter the elements of the first array
printf("\n Enter the number of elements in
10 20 30
array2 : “);
Enter the number of elements in array2: 3
scanf("%d", &n2);
Enter the elements of the second array
printf("\n Enter the elements of the second
15 25 35
array");
for(iw0;i¢n2;
i++)
The contents of the merged array are
Arc(O] = 10 Arr[1) = 15 Arr[2) = 20
scanf("Xd", &arr2[i]});
Arr(3] = 25 Are[4] = 30 Arr[5] = 35
m= nlen2;
while(index_first < nl && index_second < n2)
{ 12.5.5 Searching for a Value in an Array
if(arr1[index_first ]<arr2[index_second])
Searching means to find whether a particular value is
{
arr3{index] = arri[index_first]; present in the array or not. If the value is present in the array
index_first++; then search is said to be successful and the search process
gives the location of that value in the array, Otherwise,
}
else if the value is not present in the array, the search process
{ displays the appropriate message and in this case search is
arr3[index) = arr2[index_second); said to be unsuccessful
index_second++; There are two popular methods for searching the array
} elements. One is linear search and the second is binary
index++; search, The algorithm that should be used depends entirely
on how the values are organized in the array, For example,
ifthe clements of the array are arranged in ascending order,
/* if elements of the first array are over and then binary search should be used as it is more efficient for
the second array has some elements */ sorted list. We will discuss these two methods in detail in
this section
if(index_first == ni)
Linear Search
{
while(index_second<n2) Linear search, also called sequential search, is a very
{ simple method used for searching an array for a particular
arr3[index) « are2[index_second); value. It works by comparing every element of the array
index_second++; one by one in sequence until a match is found, Linear
index++; search is mostly used to search an unordered list of
clements (array in which data elements are not sorted).
} For example, if an array A[) is declared and initialized as
if elements of the second array are over
and the first array has some elements */
int A[] = (10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching
else if(index_second == n2) means to find whether the value 7 is present in the array
{ or not. If yes, then the search is successful and it returns
while(index_first<n1) the position of occurrence of VAL, Here, POS = 3 (index
{ starting from 0). Figure 12.18 illustrates this concept.
are3(index) = arri[index_first]; Obviously, the best case of linear search is when VAL is
index_first++; equal to the first element of the array. In this case, only one
index++; comparison will be made
} Likewise, the worst case will happen when either VAL is
} not present in the array or it is equal to the last element of
printf("\n\n The contents of the merged the array. In both the cases, n comparisons will be made.
array are” However, the performance of the linear search algorithm
for(i=0;icm;it+) (Figure 12.19) can be improved by using a sorted array.
printf("\n Arr(%d] = Xd", i, arr3fi}); In Step | and Step 2 of the algorithm, we initialize the
getch(); value of POS and I. In Step 3, a while loop is executed that
return 0; would be executed until I is less than N (total number of
elements in the array). In Step 4, a check is made to see if'a
290 Computer Fundamentals and Programming in C
Match is found between the current array element and VAL int main()
Ifa match is found, then the position of the array clement {
is printed else the value of 1 is incremented to match the int arr[10], num, i, n, found = 0, pos = -1;
next clement with VAL. However, if all the array clements clrser();
have been compared with VAL, and no match is found then
it means that VAL is not present in the array print#("\n Enter the number of elements in
ea
the array : “);
scanf("%d", &n);
printf(“\n Enter the elements:");
10 s]2[7[s]4] >| [Js for(inO;icn;it+)
scanf("Xd", Barr[i});
AlO} ALt] A[2] ALS] Al4] ALS] Al6] A[7] ALS] AL9]
eae)
printf("\n Enter the number that has to be
searched : ");
scanf("%d", Snum);
wofs]2[7[3[4]°['[«[s for(i=0;icn;ir+)
AlO} A{1] Al2] A[3] Al4] A{S] Al6] A[7] A[8]} AL9]
{
if(arr[i] == num)
{
found =1;
TOC es ed
posei;
printf("\n %d is found in the array
at position = Xd", num, 4);
ALO} Alt} Al2) AL3] Al4] ALS] Al6] AL7] ALS] AL9]
break;
Camm) )
if (found == 0)
printf("\n Xd does not exist
array", num);
in the
wl s]2P7[3[4[o['[e[s getch();
AlO} ALL] Al2] ALB] ALS] ALS] AL6] AL7] ALS} AL9) return 0;
}
Figure 12.18 Linear search
Output
LINEAR_SEARCH(A, N, VAL) Enter the number of elements in the array: 5
Enter the elements: 12345
Step 1; [INITIALIZE] SET POS « -1 Enter the number that has to be searched: 7
Step (INITIALIZE) SET I2 7 does not exist in the array
Step Repeat Step 4 while Icon
Step 4: IF A[I] = VAL
SET POS «I Binary Search
PRINT POS
Go to Step 6 We have seen that the linear search algorithm is very slow
[END OF IF} If we have an array with | million entries then to search
SET I = Tel
[END OF LOOP) a value from that array, we would need to make | million
Step 5: IF POS = -1 comparisons in the worst case. However, if the array is
PRINT "VALUE IS NOT PRESENT sorted, we have a better and efficient alternative known as
IN THE ARRAY ™ binary search.
[END OF IF} Binary search is a searching algorithm that works
Step 6: EXIT
efficiently with a sorted list. The algorithm finds the
Figure 12.19 Algorithm for linear search position ofa particular element in the array. The mechanism
of binary search can be better understood by using the
analogy of a telephone directory. When we are searching
17. Write a program to implement linear search.
for a particular name in the directory, we will first open
#include <stdio.h> the directory from the middle and then decide whether to
#include <conio.h> look for the name in the first part of the directory or in
Arrays 291
the second part of the directory. Again we will open some (a) If VAL < A[MID], then VAL will be present in the left
page in the middle and the whole process will be repeated segment of the array. So, the value of ENO will be
until we finally find the name. changed as, END = MID - 1
Now let us consider how this mechanism will be applied (b) IfVAL > A[MID], then VAL will be present in the right
to search for a value in a sorted array. Given an array that segment of the array. So, the value of BEG will be
is declared and initialized as changed as, BEG = MID + 1
int A[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Finally, if VAL is not present in the array, then eventually
and the value to be searched is VAL « 9. The algorithm END will be less than BEG. When this happens, the algorithm
(Figure 12.20) will proceed in the following manner. will terminate and the search will be unsuccessful
Figure 12.20 shows the algorithm for binary search.
BEG = 0, END = 10, MID = (0 + 10)/2 «5
In Step 1, we initialize the value of variables—BEG,
Now, VAL = 9 and A[MID] = A[5] = 5 END and POS. In Step 2, a while loop is executed until BEG
A[5] is less than VAL, therefore, we will now search for is less than or equal to END. In Step 3, value of MIO is
the value in the latter half of the array. So, we change the calculated. In Step 4, we check if the value of A[MID] is
values of BEG and MID. equal to VAL (item to be searched in the array). If a match
Now, BEG = MID + 1 = 6, END = 10, MID = (6 + is found then value of POS is printed and the algorithm
10)/2 =16/2 = 8 exits. However, if a match is not found and if the value of
Now, VAL = 9 and A[MID] = A[8] = 8 A[MID] is greater than VAL, then the value of END is modified
A[8) is less than VAL, therefore, we will now search otherwise if A[MID) is less than VAL, then value of BEG is
for the value in the latter half of the array. So, again we altered. In Step 5, if the value of POS = ~1, then it means
change the values of BEG and MID. VAL is not present in the array and an appropriate message
Now, BEG = MID + 1 = 9, END = 10, MID = (9 + is printed on the sereen before the algorithm exits
10)/2=9
Now VAL = 9 and A[MID] = 9. 18. Write a program to implement binary search.
In this algorithm we see that BEG and END are the include <stdio.h>
beginning and ending positions of the segment that we are include <conio.h>
looking to search for the clement. MID is calculated as (BEG int main()
+ END)/2. Initially,
BEG = lower_bound and END = upper.
{
bound. The algorithm will terminate when A[MID] = VAL int arr[10], num, i, n, pos = -1, beg, end,
When the algorithm ends, we will setPOS = MID. POS is the mid, found =0;
position at which the value is present in the array clrser();
However, if VAL is not equal to A[MID), then the values
of BEG, END, and MIO will be changed depending on whether print#("\n Enter the number of elements in
VAL is smaller or greater than A[MID]. the array: “);
292 Computer Fundamentals and Programming in C
{
print#("\n Xd is present in the array is just that the data type of the array clement must match
at position = Xd", num, mid);
with the type of the function parameter. Figure 12.22
founde1;
shows the code to pass an individual array element by
break; passing data value.
} In the example given, only one clement of the array is
else if (arr[mid]}>num)
passed to the called function. This is done by using the
end = mid-1;
index expression. So arr[3] actually evaluates to a single
else
integer value. The called function hardly bothers whether
beg = mid+1;
a normal integer variable is passed to it or an array value
} is passed.
if ( beg > end && found == 0)
printf("\n %d does not exist in the
array", num);
Passing Addresses
getch(); Like ordinary variables, we can pass the address of an
return 0; individual array element by preceding the indexed array
element with the address operator (&), Therefore, to pass
}
the address of the fourth element of the array to the called
Output function, we will write Sarr[3)
Enter the number of elements in the array: 5
Enter the elements: 12345
Enter the number that has to be searched: 7
7 does not exist in the array
main()
GERD PASSING ARRAYS TO FUNCTIONS {
int arr(S] #{1, 2, 3, 4, 5};
Like variables of other data types, we can also pass an fune(are[3});
array to a function, While in some situations, you may
want to pass individual elements of the array, and in other
situations you may want to pass the entire array. In this void func(int *num)
section, we will discuss both these cases. Look at Figure
12.21 which will make the concept easier to understand. printf("%d", *num);
Passing Data Values However, in the called function the value of the array
The individual elements can be passed in the same manner clement must be accessed using the indirection (*)
as we pass variables of any other data type. The condition operator (Figure 12.23)
Arrays 293
Hence, we se that a 2D array is treated as a collection In one-dimensional arrays, we have seen that computer
of ID arrays, To understand this, we can also see the does not keep track of the address of every element in the
representation of a two-dimensional array as shown in array. It stores only the address of the first clement and
Figure 12.27 calculates the addresses of other elements from the base
address (address of the first clement). Same is the case with
marks[0} [rmarkst01 [marks marst2i [marks [marks | a two-dimensional array. Here also, the computer stores
the base address and the address of the other elements is
calculated using the following formula.
marks{1} marks[O] [marist [mack [nach [ranks | Address(A{I}[3]) = BLA + w(M(J - 1) + (I - 1)},
if the array clements are stored in column major order, and
marks[2} marks[O] [marks Jmarks2)[rset [marks Address(A{I}[3]) = B_A + w{N (I - 1) + (3 - 1)},
if the array elements are stored in row major order.
Figure 12.27 Representation of two-dimensional array where, w is the word size, i.c., number of bytes required
marks[3)[5] as individual 1D arrays to store clement, M is the number of rows, N is the number
of columns, I and J are the subscripts of the array element,
Although Figure 12.27 shows a rectangular picture of and B_A is the base address.
4 two-dimensional array, these clements will be actually
stored sequentially in memory. Since computer memory
Example 12.7
is basically one-dimensional, a multidimensional array
cannot be stored in memory as a grid. Consider a 20 x 5 two-dimensional array Marks which has
There are two ways of storing a two-dimensional array base address = 1000 and the word size = 2. Now compute
in memory. The first way is row major order and the second the address of the element Marks[18, 4] assuming that the
is column major order. Let us see how the clements of a elements are stored in row major order.
2D array are stored in row major order. Here, the elements
of the first row are stored before the elements of the second Solution
and third row, i.c., the elements of the array are stored row Address(A(I)(3))
by row where n elements of the first row will occupy the = Base_Address + w{N (I 1) +(Q-1)}
first n locations. This is illustrated in Figure 12.28 Address (Marks(18,4])
= 1000 + 2{5(18 - 1) + (4 - 1) }
= 1000 + 2 { 5(17) + 3}
= 1000 + 2 (88)
(0,0) (0,1) (0,2) (0,3) (1,0) (1.1) C2) 0.3) (2,0) 2.1) 2.2) 23) = 1000 + 176 = 1176
Figure 12.28 Elements of a 3 x 4 2D array in row major order
When we store the clements in a column major order, the 12.7.2 Initializing Two-dimensional Arrays
elements of the first column are stored before the clements
Like in case of other variables, declaring a two-
of the second and third column, i.c., the elements of the
array are stored column by column where m clements of dimensional array only reserves space for the array in the
memory. No values are stored in it. A two-dimensional
the first column will occupy the first m locations. This is
array is initialized in the same way as a one-dimensional
ted in Figure 12,29,
array. For example,
(SSB SBS Saaa' int marks[2][3] = {90, 87, 78, 68, 62, 71};
(0,0) (1,0) (2,0) (3,0) (0.1) 11) (21) G31) (0,2) 12) ¢ 2) The initialization of a two-dimensional array is done
row by row. The above statement can also be written as
Figure 12.29 Elements of a 4 x 3 2D array in column major
order int marks[{2][3)={{90,87,78},{68, 62, 71}};
Arrays 297
The given two-dimensional array has 2 rows and 3 2D array and the second for loop will scan individiial
columns. Here, the elements in the first row are initialized columns for every row in the array.
first and then the elements of the second row are initialized. Look at the programs given below which use two for
Therefore, loops to access the elements of a 2D array
marks[O][0] = 90 marks{0](1] = 87
marks[0]}[2] = 78 marks(1](0) = 68 22. Write a program to print the elements of a2D array.
marks[1][1] = 62 marks{1}(2] = 71
#include <stdio.h>
Therefore, in the aforegiven example, cach row is defined #include <conio.h>
asa one~ mensional array of three elements that are enclosed int main()
in braces, Commas are used to separate the clements in the {
row as well as to separate the elements of two rows. int arr[2][2] = {12, 34, 56,32};
Incase of one-dimensional arrays, if the array is completely int i, 4;
initialized, we may omit the size of the array, Same concept for(isO;ic2;ir+)
can be applied to a two-dimensional armay, except that only {
the size of the first dimension can be omitted. Therefore, the printf("\n");
declaration statement given below is valid. for(j=0;5<2; j++)
int marks{]{3]={{90,87,78),{68, 62, 71}}; printf("xd\t", arr[i}[j]);
}
In order to initialize the entire two-dimensional array to return 0;
zero, simply specify the first value as zero, i.c., simply write }
int marks[2][3] = {0}; Output
If some values are missing in the initializer then it 12 «4
is automatically set to zero. For example, the statement 56 32
given below will initialize the values in the first row but
the elements of the second row will be initialized to zero, 23. Write a program to generate Pascal's triangle.
#include <stdio.h>
int marks[2][3] ={ {50, 60, 70}};
#include <conio.h>
Individual clements of a two-dimensional array can be int main()
initialized using the assignment operator as shown below. {
marks{1][2] = 79; int arr[7}[7]#{0};
int rowe2, col, i, j;
marks{1}[2] = marks(1][1] + 10;
arr[0}[0} = are({1)[0) = are[1}[1) * 1;
In order to input the values from the keyboard, you while(row < 7)
must use the following code. {
for (i=0;1<2;
i++) arr[row}[0} = 1;
for(j0;j<2;
j++)
for(col = 1;col <= row;col++)
scanf("%d", &are[i][3]); arr{row][col] = arr[row-2][col-1] +
arr[row-1}[col);
rowe+;
}
An un-initialized array contains unpredictable contents. for(inO0;i<7;
i++)
{
printf("\n");
12.7.3 Accessing the Elements of for(j=0;j<#i; j++)
Output }
// CALCULATE AVERAGE OF EACH STUDENT
ENTER THE DATA for(i=0;iclO;i++)
{
Enter the sales of 3 items sold by saleman for(j*0;j<3; j++)
0: 23 23 45 avg{i] = (float)total_marks[i]/3.0;
Enter the sales of 3 items sold by salesman }
1: 34 45 63 // CALCULATE CLASS AVERAGE
Enter the sales of 3 items sold by salesman for(i=0;i<l0;i+e)
2: 36 33 43 total_avg += avg[i];
Enter the sales of 3 items sold by salesman class_avg = (float)total_avg/10;
3: 33 52 35 // DISPLAY RESULTS
Arrays 299
{
j OPERATIONS ON TWO- printf("\n");
DIMENSIONAL ARRAYS for(j=0535<3;j++)
printf("\t xd", mat(i)}[j]);
Two-dimensional arrays can be used to implement the }
mathematical concept of matrices. In mathematics, a return 0;
matrix is a grid of numbers, arranged in rows and columns. }
Thus, using two-dimensional arrays, we can perform the
following operations on an m * n matrix. Output
Enter the elements of the matrix
Transpose Transpose of am * n matrix A is given as an * see eeeeeeeeeeneeeeeeneens
m matrix 8 where,
123456789
Bay = Aye The elements of the matrix are
Aeeeeeesereseeseoeseneees
Sum Two matrices that are compatible with cach other 123
can be added together thereby storing the result in the third 456
matrix. Two matrices are said to be compatible when they 739
have the same number of rows and columns, Elements of
the matrices can be added by writing: 28. Write a program to transpose a 3 * 3 matrix,
Cis = Any + Buy #include <stdio.h>
#include <conio.h>
Difference Two matrices that are compatible with each int main()
other can be subtracted thereby storing the result in the
{
third matrix. Two matrices are said to be compatible when int 4, j, mat[(3}[3], transposed_mat(3}(3];
they have the same number of rows and columns. Elements
clrser();
of the matrices can be subtracted by writing: printf("\n Enter the elements of the
Ciy = Any > Buy matrix");
Drintf("\n *eeeeeeeetewewewewenwenen):
Product Two matrices can be multiplied with cach other
for(i=0;i¢3;
i++)
if the number of columns in the first matrix is equal to
the number of rows in the second matrix. Therefore, m * {
for(jn0;j<3;
J++)
fn matrix A can be multiplied with a p * q matrix ifn = p.
Elements of the matrices can be multiplied by writing: {
scanf("xd", &mat(i}[j});
Ciy = E AinBa,y for kel to k <n }
}
27. Write 4 program to read and display a 3 * 3 matrix. printf("\n The elements of the matrix are ");
Printf("\n A#eeeeeeeweeareewereuwanen):
#include <stdio.h>
for(i=O;i<3;i++)
#include <conio.h>
int main()
{
printf("\n");
{
int i, j, mat(3][3]; for(j=055<35j++)
clrscr(); printf("\t Xd", mat(i}[5]);5
}
for(i=0;i<3;i++)
printf("\n Enter the elements of the
matrix "); {
Printf("\n ***eeeeeeeeweenweeewweeeen): for(j=0;5<3;
j++)
transposed_mat{i}[j] = mat[{j][i];
for(i=0;i<3;i++) }
printf("\n The elements of the transposed
matrix are “);
for(j=0;
j<3; j++) Printf("\n s+#eeeneneeenwewerenwenen);
scant ("%d",8mat[i][5])s
} for(i=0;1<3;i++)
printf("\n The elements of the matrix are “);
Print#("\n *##eeeeeeeaseseeeeneeweeen):
printf("\n");
for (i=0;i<3;i++)
For (j=055<3;
j++)
Arrays 301
}
flag = 1; Lo
[«|
Page 1
} Third dimension
if(flag= =1)
return 1; Figure 12.32 Three-dimensional array
G06 Computer Fundamentals and Programming in C
“Ufray. The array has three pages, four rows, and two {
columns. printf("\n\n");
for(j = 033 < 23j++)
A multidimensional array is declared and initialized
similar to one- and two-dimensional arrays.
{
printf("\n");
for(k = O;k < 2;k++)
Din printf("\tarr[%d]
[Xd]
Consider a three-dimensional array defined as int A{2}[2)[3].
[Xa] = Xd", i, 5, ky array[i}{5]}[k]);
}
Calculate the number of elements in the array. Also show
}
the memory representation of the array in row major order
getch();
and column major order. return 0;
}
Output
Enter the elements of the matrix
12345678
The matrix is:
arr(0][O}[0] = 1 arr[O][0][1] = 2
arr[0}[1)[0] = 3 arr[O}[1][1] = 4
arr(1)[0][0] = 5 are[1}(0][1] = 6
arr(1)[1)[0] = 7 are[ij[1][1] = 8
To store the lower triangular matrix efficiently in dimensional matrix and a one-dimensional array can bE
memory, We can use a one-dimensional array which stores done in any one of the following ways:
only the non-zero clements. The mapping between a two- (a) Row wise mapping—here the contents of array A[]
dimensional-matrix and a one-dimensional array can be willbe {4, 1, 5, 1, 2, 9, 3, 1, 4, 2, 2, 5, 1,
done in any one of the following ways: 9, 8, 7}
(a) Row-wise mapping—here the contents of array A{) (b Column wise mapping—here the contents of array
willbe {1, 5, 3, 2, 7, -1, 3, 1, 4, 2, -9, 2, A[] willbe
{4, 5, 1, 1, 9, 2, 3, 4, 1, 2, 5,
-8, 1, 7} 2, 1, 8, 9, 7}
(b) Column-wise mapping—here the contents of array fc Diagonal wise mapping—here the contents of array
A[] willbe
{1, 5, 2, 3, -9, 3, 7, 1, 2, -1, 4, A[] willbe
(5, 9, 4, 5, 8, 4, 1, 3, 2, 1, 7,
-8, 2, 1, 7} 1, 2, 1, 2, 9}
{ for(j=0;j<cols;j++) for(i=0;i<=num_values;i++)
{ { printf(*\n"
scanf("¥d", &mat{i}[j]); for(j=053<35j++)
} printf(" Xd", new_mat(i][4]);
} }
printf("\n The sparse matrix is : \n"); }
for(i=0;icrows;i++)
Output
{
printf("\n"); Enter the number of rows : 2
for(j=0;j<cols;j++) Enter the number of columns : 2
printf(“ad", mat(i}(j}); Enter the elements of array : 1000
The sparse matrix is :
} 10
for(i=0;icrows;i++) oo
{ for(je0;j<cols;
j++) The new matrix is :
{ if(mat[{i}[4]!*0) 2 mod
num_values++; oo1
}
)
sparse_mat(mat, num_values, rows, cols);
getch();
} For better performance,
memory for the new matrix
void sparse_mat(int mat(3](3), int num_values, must be allocated
using dynamic memory allocation
int rows, int cols) which will be discussed later in this book. We may also.
{ int new_mat[(S)[3], 4, 3, temp_index 1; represent the sparse matrix using a linked list.
new_mat(0][0] = rows;
new_mat(0}({1) = cols;
new_mat[0][2] = num_values;
for(iw1;i<cerows;
i++) APPLICATIONS OF ARRAYS
{ for(jw1;j<=cols;
j++)
{ if(mat[i-1][j-1] It» 0) * Arrays are widely used to implement mathematical
{ new_mat[temp_index][0] = i-1; vectors, matrices, and other kinds of rectangular tables
new_mat[temp_index](1] * j-1; * Many databases include one-dimensional arrays whose
new_mat[temp_index}(2] = mat[{i-2] elements are records.
(3-1)5 * Arrays are also used to implement other data structures
temp_index++; such as strings, stacks, queues, heaps, and hash tables.
} We will read about few of these data structures in the
} subsequent chapters.
} * Arrays can be used for sorting elements in ascending or
printf("\n\n The new matrix is : \n"); descending order.
POINTS TO REMEMBER
* Anarray is a collection of similar data elements of the referring to the first byte of that array. The index
same data type. specifies an offset from the beginning of the array to
The elements of the array are stored in consecutive the element being referenced.
memory locations and are referenced by an index * A two-dimensional array is specified using two
(also known as the subscript). Subscript is an ordinal subscripts where first subscript denotes row and the
number which is used to identify an element of the second denotes column. C considers the two-
array, dimensional array as an array of one-dimensional
Declaring an array means specifying three things: data arrays.
type, name, and its size. A multidimensional array is an array of arrays. Like we
The name of the array is a symbolic reference to the have one index in a one-dimensional array, two indices
address of the first byte of the array. Therefore, in a two-dimensional array, in the same way we have
whenever we use the array name, we are actually n indices in an n-dimensional or multidimensional
Arrays 309
array. Conversely, an n-dimensional array is specified the main diagonal have a zero value. This type of
using n indices. sparse matrix is called a lower triangular matrix.
© Sparse matrix is a matrix that has large number of * In the second variant of a sparse matrix, elements
elements with a zero value. There are two types of with a non-zero value can appear only on the diagonal
Sparse matrices. or immediately above or below the diagonal. This
© In the first type of sparse matrix, all elements above type of sparse matrix is called a tridiagonal matrix.
GLOSSARY
Array Collection of similar data elements Matrix A two-dimensional array in which the first index is
Array index Location of an item in an array the row and the second index is the column
Binary search Searching method in which a sorted array One-dimensional array An array with one dimension or
is searched by repeatedly dividing the search interval in one subscript/index
half, Begin with an interval covering the whole array. If the Subscript An ordinal number, which is used to identify an
value of the search key is Jess than the item in the middle element of the array
of the interval, narrow the interval to the lower haif. Sparse matrix A matrix that has relatively few non-zero
Otherwise narrow it to the upper half. Repeatedly check elements
until the value is found or the interval is empty Three-dimensional array An array with three dimensions
k-dimensional array An array with exactly k orthogonal or three subscripts/indices
axes or k dimensions Two-dimensional array An array with two dimensions or
Linear search Searching method in which an array is two subscripts/indices
searched by checking elements one at a time
Upper triangular matrix A matrix Ay forms an upper
Lower triangular matrix A matrix A, forms a lower triangular matrix when Aj = 0 for! >|
triangular matrix when A, = 0 for i<j
EXERCISES
Fill in the Blanks 11. ___ means accessing each element of the array
1 An array isa for a specific purpose
2 Every element in an arrayisaccessed using a_ 12 Performance of the linear search algorithm can be
3 An expression that evaluates to an value improved by using a__
may be used as an index. 13. A multi-dimensional array in simple terms is an
The elements of an array are stored in __
memory locations. 14. arr{3] = 10; initializes the element of the
. An n-dimensional array contains __subscripts array with value 10
. Name of the array acts as a 15. The _ search locates the value by starting at
Declaring an array means specifying the beginning of the array and moving towards its end.
—<; | —
The subscript or the index represents the offset from the Multiple Choice Questions
beginning of the array to 1. If an array is declared as arr[] = {1,3,5,7,9}; then what is
_ is the address of the first element in the the value of sizeof(arr[3})?
array. (a) 2 {(b) 2
10. Length of the array is given by the number of (c) 3 (d) 8
310 ‘Computer Fundamentals
and Programming in C
2. Mf an array is declared as arr{} = (1,3,5,7,9}; then what is 18. Linear search can be used to search a value in any array.
the value of arr[3]? 19. Linear search is recommended for small arrays.
(a) 1 {b) 7 20. A two-dimensional array is nothing but an array of one-
(c) 9 {d) 5 dimensional arrays.
if an array is declared as double arr[S0), how many bytes 21. A two-dimensional array contains data of two different
will be allocated to it? types.
(a) 50 (b) 100 22. A char type variable can be used as a subscript in an
array.
(c) 200 (d) 400 23. By default, the first subscript of the array is zero,
Hf an array is declared as int arr[50}, how many elements
24, A long int value can be used as an array subscript.
can It hold?
25, The maximum number of dimensions that an array can
(a) 49 (b) SO have is 4
{c) 51 (d) 0
. fan array
isdeclared as int arr[5][5], how many elements Review Questions
can it store? 1. Why are arrays needed?
(a) 5 (b) 25 What does array name signify?
{c) 10 (d) 0 How is an array represented in memory?
In linear search, when VAL is equal to the first element How is a two-dimensional array represented in memory?
of the array, which case is it? vPwn
How can one-dimensional and two-dimensional arrays
(a) worst case {b) average case be used for inter-function communication?
6. How are multidimensional arrays useful?
(c) best case (d) amortized case
Given an integer array, arr{], the ith element can be 7. What happens when an array is initialized with
accessed by writing (a) fewer initializers as compared to Its size?
(b) more initializers as compared to its size?
(a) (arr+i) (b) *(i+ arr)
8. Explain sparse matrix.
(c) arr{i) (d) allofthese 9. Why does storing of sparse matrices need extra
consideration? How are sparse matrices stored efficiently
State True or False in the computer's memory?
1 An array is used to refer to multiple memory locations 10. For an array declared as int arr[50}, calculate the address
having the same name of arr{35}, if Base(arr) = 1000 and w=2.
An array need not be declared before being used 11. Consider a 10 * 5 two-dimensional array Marks which
. An array contains elements of the same data type. has base address = 2000 and the number of words per
A loop is used to access all the elements of the array. memory location of the array = 2. Now compute the
All the elements of an array are automatically initialized
vwawn address of the element- Marks[8, 5] assuming that
to zero when the array is declared. the elements are stored in row major order.
. An array stores all its data elements in non-consecutive 12. Given an array, int arr{] = (9, 18, 27, 36, 45, 54, 63, 72,
memory locations. 81, 90, 99}. Trace the steps of binary search algorithm to
To copy an array, you must copy the value of every element find value 90 and 17 in the array.
of the first array into the element of the second array. 13. Which technique of searching an element in the array
Lower bound is the index of the last element of the do you prefer to use and in which situation?
array. 14. Consider a 10 x 10 two-dimensional array which has base
Merged array contains contents of the first array address = 1000 and the number of memory locations per
followed by the contents of the second array. element of the array = 2. Now compute the address of the
Binary search is also called sequential search. element arr[8)[5] assuming that the elements are stored
Linear search is performed on a sorted array. in row major order. Then calculate the same assuming the
Binary search is the best search algorithm for all types of
elements are stored in column major order.
arrays. Programming Exercises
Itis possible to pass an entire array as a function argument 1. Write a program which deletes all duplicate elements in
. arr{i] is equivalent to writing *(arr+i). an array.
Array name is equivalent to the addressof its last element. 2. Write a program that tests the equality of two one-
When an array is passed to a function, C passes the dimensional arrays.
value for each element 3. Write a program that reads an array of 100 integers
. When an array is passed toa function, it is always passed Display all pairs of elements whose sum is 50.
by call-by-reference method
Arrays Sul
Write a program to input an array of 10 numbers and Hint: Array A is lower triangular if A,= 0 for i<j
swap the value of the largest and smallest number. 26. Write a program that reads a square matrix of size n * n.
. Write a program to interchange second element with Write
a function int isSymmetric(int a[][], int n)
the second last element that returns 1 if the matrix is upper triangular.
Write a program that calculates the sum of squares of Hint: Array A is symmetric ifA\= Ay for all values of |and j
the elements. 27. Write a program to calculate XA + YB where A and B are
Write a program to calculate the number of duplicate matrices and X = 2, and Y = 3.
entries in the array. 28. Write a program to read an array of 10 floating point
Write a program to arrange the values of an array in numbers. Display the position of the second largest number,
such a way that even numbers precede the odd numbers. 29. Write a program to enter five single digit numbers in an
. Given a sorted array of integers, write a program to array. Form a number using the array elements.
calculate the sum, mean, variance, and standard 30. Write a program to find whether number 3 is present in
deviation of the numbers in the array. the array arr{J= (1,2,3, 8)
Write a program to compute the sum and mean of the 31 Write a program to read a sorted floating point array.
elements of a two-dimensional array. Update the array to insert a new number.
Write a program that computes the sum of elements that 32 Write a program to read a floating point array, Update
are stored on the main diagonal of a matrix using pointers. the array to delete the number from the specified
Write a program to count the total number of non-zero location.
elements in a two-dimensional array, 33, Modify the linear search program so that it operates on
. Write a program to read and display an array of 10 a sorted array,
floating point numbers using functions. 34, Write a program to build an array of 100 random
. Write a program to read an array of 10 floating point numbers in the range 1 to 100. Perform the following
numbers, Display the mean of these numbers till two operations on the array.
decimal places. (a) Count the number of elements that are completely
15 Write a program to read an array of 10 floating point divisible by 3.
numbers, Display the smallest number and its position
(b) Display the elements of the array by displaying a
in the array,
maximum of ten elements in one line.
16. Write a program to input the elements of a two-
dimensional array. Then from this array make two arrays:
{c) Display only the even elements of the array by
one that stores all odd elements of the two-dimensional
displaying a maximum of ten elements in one line.
array and the other stores all even elements of the array. (d) Count the number of odd elements.
17, Write a program to merge two integer arrays, Also (e) Find the smallest element in the array.
display the merged array in reverse order. (f) Find the position of the largest value in the array,
18. Write a program to transpose a 3 x 3 « 3 matrix. Write a program to read two floating point arrays. Merge
19 Write a program to multiply two m « n matrices. these arrays and display the resultant array.
20.Write a menu driven program to add, subtract, and Write a program to read two sorted floating point arrays.
transpose two matrices. Merge these arrays and display the resultant array.
21 Write a program that reads a matrix and displays the Write a program to read and display a p*q*r array.
sum of its diagonal elements. Write a program to initialize all diagonal elements of a
22, Write a program that reads a matrix and displays the two-dimensional array to zero.
sum of the elements above the main diagonal. Consider an array MARKS([20)(5] which stores the marks
Hint: Calculate sum of elements of arrayA,where for an obtained by 20 students in 5 subjects. Now write a program to
element A, i<j (a) find the average marks obtained in each subject
23, Write a program that reads a matrix and displays the (b) find the average marks obtained by every student
sum of the elements below the main diagonal
(c) find the number of students who have scored
Hint: Calculate sum of elementsof array A ,where for on
below SO in their average
elementAy,1>j
24 Write a program that reads a square matrix of size n = n. (d) display the scores obtained by every student
Write a function int is _Upper_Triangular(int a{)} Find the output of the following codes.
{], int n) that returns 1 if the matrix is upper triangular.
1 #include <stdio.h>
Hint: Array A is upper triangular if Ay= 0 for i > j main()
25. Write a program that reads a square matrix of size n x n. {
Write a function int is_Lower_Triangular(int a[} int i, arr[10];
[], int n) that returns 1 if the matrix is lower triangular. for(i=0;1<10;i+
312 Computer Fundamentals and Programming in C
arr[i*2] = 1; for(i=0;i<10;i++)
for(i=0;ic10;i++) arr2{i) = arri[9-i];
arr[i*2¢1] = -1; for (i=0;1¢10;i++)
for(i=0;i<10;i++) printf("\t Xd", arr2[i)});
printf("\t %d", arr[i]); return 0;
return 0; }
} identify errors, if any, in the following declaration statements.
2. #include <stdio.h> (a) int marks(10);
main() (b) int marks{10, 5};
{
int are[}={0,1,2,0,1,2,0,1,2)}; (e) int marks[10],{5};
printf("\\n %d",arr[3] (d) int marks[{10);
printf("\\n %d",are[are[3]]); (e) int marksf };
printf("\\n %d",are[are[3}+arr[1]]); (f) int marks[10] [5];
printf("\\n 4d", are[are(arr{are[1}})));
(g) int marks[9+1)[6-1);
return 0;
} identify errors, if any, in the following initialization statements.
3. #include <stdio.h> (a) int marks[ | = (0,0,0,0};
main() (b) int marks{2}[3] = (10,20,30,40};
{ (c) int marks[2,3} = (10, 20,30},{40,50,60}};
int arri{]={0,1,2,0,1,2,0,1,2,0);
(d) int marks[{10) = {0};
int 4, arr2[10);
Arrays (313
Pass1: (c) Compare 30 and 19. Since 30 > 19, swapping is done.
29, 27, 19, 30, 52, 54, 63, 87
(a) Compare 30 and 52. Since 30 < 52, then no swapping is
done. | Compare 30 and $2. Since 30 < 52, no swapping is done
3i4 Computer Fundamentals and Programming in C
‘Observe that after the end of the fourth pass, the fourth largest getch();
element is placed at the fourth highest index of the array. Alll the return 0;
other elements are still unsorted. }
Pass 5: Output
(a) Compare 29 and 27. Since 29 > 27. swapping is done Enter the number of elements in the array: 6
27, 29, 19, 30, 52, 54, 63, 87 Enter the elements 27 72 36 63 45 54
(b) Compare 29 and 19, Since 29 > 19, swapping is done. The array sorted in ascending order is:
27, 19, 29, 30. 52, $4, 63, 87 27 36 45 54 63 72
(c) Compare 29 and 30, Since 29 < 30, no swapping is done INSERTION SORT
Observe that after the end of the fifth pass, the fifth largest
Insertion sort is a very simple sorting algorithm, in which the
element is placed at the fifth highest index of the array. All the sorted array (or list) is built one element at a time, We all are
other elements are still unsorted. familiar with this technique of sorting as we usually use it for
ordering a deck of cards while playing bridge
Pass 6: The main idea behind insertion sort is that it inserts each
(a) Compare 27 and 19, Since 27 > 19, swapping is done. item into its proper place in the final list. To save memory,
19, 27, 29, 30, 52, 54, 63, 87 most implementations of the insertion sort algorithm work by
moving the current data element past the already sorted values
(b) Compare 27 and 29. Since 27 < 29, no swapping is done
and repeatedly interchanging it with the preceding value until it
Observe that after the end of the sixth pass, the sixth largest is in its correct place
clement is placed at the sixth largest index of the array. All the
other elements are still unsorted. Technique
Insertion sort works as follows:
Pass 7:
* The array of values to be sorted is divided into two sets,
(a) Compare 19 and 27, Since 19 < 27, no swapping is done One that stores sorted values and the other contains unsorted
Observe that the entire list is sorted now values
1, Write a program to enter n numbers in an array. Redisplay * The sorting algorithm will proceed until there are elements in
the array with elements being sorted in ascending order the unsorted set
* Suppose there are n elements in the array. Initially the element
#include <stdio.h>
with index 0 (assuming LB = 0) is in the sorted set, rest of the
#include <conio.h>
int main() elements are in the unsorted set.
{ * The first element of the unsorted partition has array index | (if
int i, n, temp, j, arr [10]; LB =0)
clrser(); * During each iteration of the algorithm, the first element in the
printf("\n Enter the number of elements in unsorted set is picked up and inserted into the correct position
the array: "); in the sorted set,
scanf("%d", &n);
printf("\n Enter the elements “); Insertion Sort Example
for(i = O;1 < njise) Consider an array of integers given below. Sort the values in the
scanf("Xd", Barr [i]); array using insertion sort
for(i = O31 < n-2jier)
{
for(j = 0;j < n-i-2;je+) 39| 9 [45 [o3 |18 |st [ros]
34] 72|36
{
if(arr [j] > are (j+1}) 39 | 9 145 |63 108 |54 |72 |36
{
temp = arr [Jj]; A{0} is the only element in sorted list
are (j) = arr [j+1); Pass 1
are [j+1]) = temp;
}
}
}
printf("\n The array sorted in ascending
rons
order is: \n");
for(i = O;i < njit+)
printf("\t xd", arr[i]);
getch();
Sort Example
3. Write a program to sort an array using selection sort for(i = kelj;i < njier)
algorithm, {
if(arr[i}< small)
#include <stdio.h>
#include <conio.h>
small « arr{i};
int smallest(int arr[{], int k, int n);
void selection_sort(int arr[{], int n); pos = i;
void main() }
}
return pos;
int arr(10], i, n;
clrser();
void selection_sort(int arr[],int n)
printf("\n Enter the number of elements in
the array: “); {
int k, pos, temp;
scanf("Xd", &n);
for(k = O;k < njke+)
printf("\n Enter the elements of the array”);
for(i = O;i «< nji+e) {
pos = smallest(arr, k, n);
{ temp = arr[k];
scanf("%d", &arr[i])); arr[k] = arr[pos];
} arr[pos] = temp;
selection_sort(arr, n);
printf("\n The sorted array is: \n"); }
for(i = O;i< njitr+) }
printf("%d\t", arr{i}); Output
getch(); Enter the number of elements in the array: 6
} Enter the elements of the array 27 72 36
int smallest(int arr[], int k, int n) 63 45 54
{ The sorted array is:
int pos = k, small=arr{k], i; 27 36 45 54 63 72
TAKEAWAYS
© Reading and writing strings © Operations on strings * Arrays of strings
© Suppressing input © String and character functions
char che";
Here H is a character not a string. The
Like we use subscripts (also In such cases, the compiler creates a character array of
hipaeies Nig known as index) to access the size 10, stores the value "HELLO" in it and finally terminates
soelbsetzi te elements of an array, similarly the value with a null character. Rest of the clements in
character array, subscripts are also used to the array are automatically initialized to NULL. Figure 13.3
hae space tohold access the clements of the shows the memory representation of such a string.
mp EEN character array, The subscript
oe starts with a zero (0). All the
char str[10] = "HELLO";
characters of a string array are
stored in successive memory locations. Figure 13.2 shows
how str[) is stored in memory
str(0} 1000
ste{1] 1001
Figure 13.3 Memory representation of a string
st{2] 1002
Consider the following declaration
stx{3] 1003
char str(3);
sf4} 1004
str = “HELLO”;
str[S} 1005 The above declaration is illegal in C and would generate a
compile time error because of two reasons, First, the array
Figure 13.2 Memory representation of a character array
is initialized with more elements than it can store. Second,
initialization cannot be separated from declaration.
Thus we sce that a string is a sequence of characters. In
Figure 13.2, 1000, 1001, 1002, and so on are the memory
addresses of individual characters. From the figure, we see
that H is stored at memory location 1000 but in reality the An array name cannot be used as the left operand of an
ASCII codes of characters are stored in memory and not assignment operator. Therefore, the following statement
the character itself, i.¢., at address 1000, 72 will be stored isegal in C.
since the ASCII code for H is 72. char str2, stri[]="HI";
char str[] = "HELLO"; str2 = stri;
The aforegiven statement declares a constant string as
we have assigned value to it while declaring the string. 13.1.1 Reading Strings
However, the general form of declaring a string is If we declare a string by writing
char str[size); char str[100];
When we declare the string in this way, we can store size Then str can be read by using three ways
~1 characters in the array because the last character would
be the null character. For example, char mesg{100); can 1. using scanf function
store a maximum of 99 usable characters. 2. using gets() function
Till now we have seen one way of initializing strings. 3. using getchar(), getch() or getche() function
The other way to initialize a string is to initialize it as an repeatedly
array of characters, like
Strings can be read using scanf() by writing
char str[] = (‘H", "LY, *L', ‘0", *\0"Ds
scanf("Xs", str);
In this example, we have explicitly added the null
Although the syntax of scanf() function is well known
character. Further, observe that we have not mentioned the
and casy to use, the main pitfall with this function is that
size of the string (or the character array). Here, the compiler
the function terminates as soon as it finds a blank space.
will automatically calculate the size based on the number
For example, if the user enters Hello World, then str will
of clements initialized. So, in this example 6 memory slots
will be reserved to store the string variable, str. contain only Hello. This is
We can also declare a string with size much larger than
insane with because the moment a blank
a string variable in space is encountered, the string
the number of clements that are initialized. For example,
the scant is terminated by the scanf()
consider the statement below
en aa titee function. You may also specify
char str[10] = "HELLO"; a field width to indicate the
Strings 319
maximum number of characters that can be read in. Remember Astring can be displayed using print¢() by writing
that extra characters are left unconsumed in the input buffer.
printf(*%s", str);
Unlike int(%d), float(X#), and char(%c), %s format
does not require ampersand before the variable name We use the conversion character 's* to output a string.
We may also use width and precision specifications along
with Xs (as discussed in Chapter 2). The width specifies
When scanf() encounters a white space character, the minimum output field width. If the string is short, extra
it terminates reading further and appends a null space is cither left padded or right padded. A negative
character to the string that has been read. The white width left pads short string rather than the default right
space character is left inthe input stream and might be justification. The precision specifies the maximum number
mistakenly read by the next scanf() statement. So in
of characters to be displayed. Ifthe string is long, the extra
order to delete the white space character from the input
characters are truncated. For example,
stream, either use a space in the format string before the print#("%S.3s", str);
next conversion code or FLUSH the input stream by using
The above statement would print only the first three
the fflush function by writing fflush(stdin).
characters in a total field of five characters, Also these
three characters are right justified in the allocated width
The next method of reading a string is by using gets() To make the string left justified, we must use a minus sign.
function, The string can be read by writing For example,
gets(str); print#("%-5.3s", str);
gets() is a simple function that overcomes the drawbacks
of the scanf() function. The gets() function takes the
starting address of the string which will hold the input. The When the field width islessthan thelength ofthestring,
string inputted using gets() is automatically terminated the entire string will beprinted. Also ifthe number of
with a null character characters tobe printed isspecified as zero, then nothing
Last but not the least, strings can also be read by calling is printed on the screen.
the getchar() function repeatedly to read a sequence
of single characters (unless 4 terminating character is The next method of writing a string is by using puts()
entered) and simultancously storing it in a character array function. The string can be displayed by writing
as shown below
puts(str);
i=0;
ch = getchar(); // Get a character
puts() is a simple function that overcomes the drawbacks
while(ch I= '*')
of the printf() function. The puts() function writes a
line of output on the screen, It terminates the line with
{
str{i] = ch; a newline character ("\n"). It returns an EOF (~1) if an
// Store the read character in str
error occurs and returns a positive number on success,
itt; Last but not the least, strings can also be written by
ch = getchar(); // Get another character calling the putchar() function repeatedly to print a
sequence of single characters.
}
str[i] = ‘\0'; is0;
// terminate str with null character while(str[i] != "\0')
Note that in this method, {
putchar(str[i]);
eau you have to deliberately
will be ifa append the characters with a // Print the character on the screen
string Is2 ws null character. The other two ite;
pibtidedtent ot functions automatically do }
. this
Note one interesting point from the given fragment.
13.1.2 Writing Strings
char str = “Hello”;
Strings can be displayed on screen using three ways.
printf("\n Xs", str); // prints Hello
1. using print#() function printf("\n Xs", &str); // prints Hello
printf("\n Xs", &str[2}); // prints llo
2. using puts() function
This is possible because a string isan array of characters.
3. using putchar() function repeatedly
320 Computer Fundamentals and Programming in C
13.1.3 Summary of Functions Used to Read 2. Write a program to print the following pattern.
and Write Characters
Table 13.1 contains a list of functions that are used to read
characters from the keyboard and write characters to the
sereen.
Here sscanf() reads data from str and stores them Length-controlled strings In a length-controlled string,
according to the parameter format into the locations given you need to specify the number of characters in the string
by the additional arguments. Locations pointed by each This count is used by string manipulation functions to
additional argument are filled with their corresponding determine the actual length of the string variable,
type of value specified in the format string
Delimited strings In this format, the string is ended
Consider the example given below
with a delimiter. The delimiter is then used to identify
sscanf(str, "Xd", &num); the end of the string. For example, in English language
every sentence is ended with a full-stop (.). Similarly, in
Here, sscanf takes three arguments. The first is str
C we can use any character such as comma, semicolon,
that contains data to be converted. The second is a string
colon, dash, null character, etc. as the delimiter ofa string,
containing a format specifier that determines how the
However, null character is the most commonly used string
string is converted. Finally, the third is a memory location delimiter in the C language.
to place the result of the conversion. When the sscanf
You must be having some confusion when we use the
function completes successfully, it returns the number of
term string and character array. Basically a string is stored
items successfully read.
in an array of characters. If we are using the null character
Similar to scanf(), sscanf() terminates as soon as it
as the string delimiting character then we treat the part
encounters a space, i.c., it continues to read ll it comes
of the array from the beginning to the null character as
across a blank space
the string and ignore the rest. Figure 13.5 illustrates this
concept
GEER strinc taxonomy
In C, we can store a string either in fixed-length format or char str[10};
gets (str);
in variable-length format as shown in Figure 13.4
If the user enters HELLO, then array of characters can be given
Strings
td Part ofthearray
(xJe[z [x] notofthestring
Although the array has 10 locations, only the first 6 locations
Fixed will be treated as a string.
length length
Figure 13.5 Delimited string
In this algorithm, I is used as an index of the string STR. Figure 13.7 Algorithm to convert characters of a string
To traverse cach and every character of STR we increment into upper case
the value of 1. Once the null character is encountered,
the control jumps out of the while loop and length is
initialized with the value of I. This is because the number There is a library function toupper() that converts a
of characters in the string constitutes its length character into upper case. It is defined in ctype.h
In this algorithm, we first initialize the two counters I Step 1: [INITIALIZE] SET I0 and J«0
and 3 to zero. To concatenate the strings, we have to copy Step 2: Repeat Step 3 while Dest_Str[I] != NULL
the contents of the first string followed by the contents Step 3: SETI+I¢1
of the second string in a third string, new_str. Steps 2 [END OF LOOP]
to 4 copies the contents of the first string in new_str. Step4:Repeat Steps 5 to 7 while Source Str[3] !* NULL
Step Dest_Str[I] = Source Str[3]
Likewise, Steps 6 to 8 copies the contents of the second Step 6: SET I = Ie
string in new_str. After the contents have been copied, a Step 7: SET J = Jel
null character is appended at the end of new_str . [END OF LOOP}
Step 8: SET Dest_Str[J] * NULL
6. Write a program to concatenate two strings. Step 9: EXIT
#include <stdio.h> Figure 13.10 Algorithm to append a string to another string
#include <conio.h>
int main()
{
char stri[100], str2[100], str3[100); There isa library function strcat(s1, s2) that concatenates
int 180, j#0; $2 to $1. Itisdefined instring.h.
clrser();
printf("\n Enter the first string : “);
gets(stri); In this algorithm, we first traverse through the
printf(“\n Enter the second string : destination string to reach its end, reach the position
gets(str2); where a null character is encountered. The characters of
while(stri{i] != ‘\0") the source string are then copied into the destination string
{ starting from that position. Finally, a null character is
str3(j) = strifi}; added to terminate the destination string
itt;
j++; 7. Write 4 program to append a string to another string
}
#include <stdio.h>
ie0;
#include <conio.h>
while(str2[i] != '\0")
int main()
{
str3[j] = str2[i); {
ive; char Dest_Str[{100], Source_Str[50);
int i= 0, j= 0;
i+ clescr();
} printf("\n Enter the source string : ");
ste3(j] = ‘\0';
printf("\n The concatenated string is:"); gets(Source Str);
printf("\n Enter the destination string:
puts(str3);
gets(Dest_Str);
getch(); while(Dest_Str[i] != '\0')
return 0;
ite;
} while(Source Str[j] != ‘\0")
Output {
Dest_Str[i]} = Source Str[j];
Enter the first string : Hello,
ite;
Enter the second string: How are you?
The concatenated string is: Hello, How are you? jets
}
Dest_Str[i] = "\0';
printf("\n After appending, the destination
13.4.5 Appending a String to Another String
string is: *);
Appending one string to another string involves copying puts(Dest_Str);
the contents of the source string at the end of the destination getch();
string. For example, if $1 and $2 are two strings, then return 0;
appending $1 to $2 means we have to add the contents of $1 }
to $2, Here $1 is the source string and $2 is the destination
string. The append operation would leave the source string Output
51 unchanged and destination string $2 = $2 + S1. Figure Enter the source string: How are you?
13.10 shows an algorithm that appends two strings. Enter the destination string: Hi,
326 Computer Fundamentals and Programming in C
then,
Figure 13.14 Algorithm to extract n characters from the
right of a string SUBSTRING(str, 15, 5) = world
Figure 13.15 shows an algorithm that extracts the
In Step 1, we initialize the index variable I to zero and substring from a middle of a string,
J to Length(STR) — N, 80 that J points to the character
from which the string has to be copied in the substring Step 1: [INITIALIZE] Set I= M, J «0
In Step 2, a while loop is executed until the null character Step 2: Repeat Steps 3 to 6 while str[I] !*NULL and NO
in STR is accessed. In Step 3, the ™ character of STR is Step 3: SET substr[)) = str[I)}
Step 4: SeT Ie I+.
copied in the 1"th character of Substr. In Step 4, the value Step 5S: SET} «341
of I and 3 are incremented. In Step 5, Substr is appended Step 6: SETN=N-12
with a null cha i [END OF LOOP}
Step 7: SET substr{3]} = NULL
11. Write a program to extract the last m characters of a Step 8: EXIT
string
Figure 13.15 Algorithm to extract a substring from the
#include <stdio.h> middle of a string
#include <conio.h>
int main() In this algorithm, we initialize a loop counter I to M,
ie., the position from which the characters have to be
{
char str[100], substr[100);
copied. Steps 3 to 6 are repeated until N characters have
int is0, j=0, nj been copied. With every character copied, we decrement
clrscr(); the value of N. The characters of the string are copied
printf("\n Enter the string : "); into a string called substr. At the end a null character is
gets(str); appended to substr to terminate the string
printf("\n Enter the number of characters to 12. Write a program to extract a substring from a given
be copied: "); string
scanf("%d", &n);
j = strlen(str) - n; #include <stdio.h>
while(str(j] != "\o") include <conio.h>
{ int main()
substr[i) = str[j]; {
itt, j++; char str[100], substr[100];
} int ixO, je0, n, m;
Strings 329
Enter the string to be inserted: are 13.4.13 Deleting a String from the Main String
Enter the position at which the string has to
be inserted: 6 The deletion operation deletes a substring from a given
The new string is: How are you? text. We write it as, DELETE(text, position, length).
For example,
DELETE(“ABCDXXXABCD", 4, 3) = “ABCDABCD"
13.4.12 Indexing
Figure 13.18 shows an algorithm to delete a substring
Index operation returns the position in the string where the from a given text
string pattern first occurs, For example,
INDEX("Welcome to the world of programming”,
“world") = 15
Step 1: [INITIALIZE] SET 10 and 3«0
Step 2: Repeat Steps 3 to 6 while text[I] | = NULL
However, if the pattern does not exist in the string. the Step 3: IF Ie,then
Repeat while N>0
INDEX function returns 0. Figure 13.17 shows an algorithm SET I Ted
to find the index of the first occurrence of a string within SET N* N21
a given text [END OFLOOP)
[END OF IF)
Step 4: SET new_str[3] = text[I]
Step 5: SET 2 1
Step 6: SETI «I+.
Step 1: [INITIALIZE] SET I « 0 and [END OF Loop]
MAX © LENGTH(text) - LENGTH(str) +2 Step 7: SET new_str[J] = NULL
Step 2: Repeat Steps 3 to 6 while I <= MAX Step 8: EXIT
Step 3: Repeat Step 4 for K « 0 to Length(str)
Step 4: IF str[K] | = text[Iek], then GOTO step6
[END of inner loop} Figure 13.18 Algorithm to delete a substring from a text
Step 5: SET INDEX « I. Gotosteps8
Step 6: SET I « Iv1 In this algorithm, we first initialize indexes to zero.
[END OF OUTER LOOP) Steps 3 to 6 are repeated until all the characters of the text
Step 7: ‘SET INDEX * «1
Step exrT are scanned. If I is exactly equal to M, the position from
which deletion has to be done, then the index of the text
is incremented and N is decremented. N is the number of
Figure 13.17 Algorithm to find the index of the first
characters that have to be deleted starting from position M.
occurrence of a string within a given text
However, if I is not equal to M, then the characters of the
text are simply copied into new_str.
In this algorithm, MAX is initialized to LENGTH(text) Deletion operation can also be used to delete a string
Length(str) + 1. Take for example, if a text contains- from a given text. To do this, we first find the first index
“Welcome To Programming” and the string contains at which the string occurs in the text. Then we delete N
“World”. In the main text we will look for at the most number of characters from the text, where N is the number
22 - 5 + 1 = 18 characters because afler that there is no of characters in the string
scope left for the string to be present in the text.
14, Write a program to delete a substring from a text
Steps 3 to 6 are repeated until each and every character
of the text has been checked for the occurrence of the include <stdio.h>
string within it, In the inner loop, in Step 3, we check #include <conio.h>
n characters of string with n characters of text to find int main()
ifthe characters are same. If it is not the case, then we {
move to Step 6, where I is incremented. If the string char text[200], str[20], new_text[200]
is found, index is initialized with I clse set to -1. For int iO, j*O, k, n=O, copy_loop=0;
example, if clrser();
printf("\n Enter the main text: ");
TEXT = WELCOME TO THE WORLD
gets(text);
STRING
= COME
printf("\n Enter the string to be deleted: “);
In the first pass of the inner loop, we will compare gets(str);
WORLD with WELC character by character. As soon as E and while(text[i]!="\0")
0 do not match, the control will move to Step 6 and then {
ELCO will be compared with WORLD. In the next pass, COME j=0, k=i;
will be compared with COME. while(text(k]==str[j] 8& str[j]!='\0')
We will write the programming code of indexing {
operation in the operations that follows. ket;
Strings 331
j++ elrser();
} printf("\n Enter the string: “);
if(str[j]=="\0") gets(str);
copy_loop=k; printf("\n Enter the pattern to be replaced:
new_text[n] = text[copy_loop); "3
itt; gets(pat);
copy_loop++; printf("\n Enter the replacing pattern: ");
ners gets(rep_pat);
} while(str[i}!="\o")
new_str[nj="\0'; {
printf("\n The new string is: "); j-0,k=i;
puts(new text); while(str[k]==pat(j] && pat[j]!='\0')
getch(); {
return 0; keey
} iets
Output }
if(pat[j]=="\o')
Enter the main text: Hello, how are you? {
Enter the string to be deleted: , how are you? copy_loop=k;
The new string is: Hello while(rep_pat[rep_index] !='\0")
{
new_str[n] = rep_pat[rep_index];
13.4.14 Replacing a Pattern with Another rep_indexe+;
Pattern in a String net;
Replacement operation is used to replace the pattern P1 by }
pattern P2, This is done by writing, REPLACE (text, }
patterni, pattern2) new_str[n] = str[copy_loop];
For example, ("AAABBBCCC", “BBB”, "X") = AAAXCCC ioe;
("AAABBBCCC”, “X", “YYY")= AAABBBCC. copy_loop++;
In the second example, there is no change as ‘x’ docs nee;
not appear in the text, Figure 13.19 shows an algorithm }
to replace a pattern P1 with another pattern P2 in the text new_str[n]='\0';
printf("\n The new string is: ");
Step 1: [INITIALIZE] SET POS = INDEX(TEXT,P,) puts(new_str);
Step 2: SET TEXT = DELETE(TEXT,POS, LENGTH(P,)) getch();
Step 3: INSERT(TEXT, POS,P,) return 0;
Step 4:EXIT }
Output
Figure 13.19 Algorithm to replace a pattern P; with
another pattern P, in the text Enter the string: How ARE you?
Enter the pattern to be replaced: ARE
The algorithm is very simple, where we first find the Enter the replacing pattern: are
position POS, at which the pattern occurs in the text, then The new string is : How are you?
delete the existing pattern from that position, and insert
a new pattern there, String matching refers to finding
occurrences of a pattern string within another string.
MISCELLANEOUS STRING AND
15. Write a program to replace a pattern with another
pattern in the text
CHARACTER FUNCTIONS
#include <stdio.h> In this section, we will discuss some character and string
#include <conio.h> manipulation functions that are part of header files—
int main() ctype.h, string.h, and stdlib.h.
{
char str[200], pat[20], new_str[200], 13.5.1 Character Manipulation Functions
rep_pat[100};
int ie0, j=0, k, n=0, copy _loop=0,
Table 13.2 illustrates some character functions contained
rep_index=0; in ctype.h.
332 Computer Fundamentals and Programming in C
#include <stdio.h>
Functions in ctype.h
include <string.h>
Function |Usage Example int main()
isalnum(intc) Checks whether character cis isalphat'A"); {
an alphanumeric character
char stri[S0} = "Programming" ;
isalpha(intc) —Checks whether character ¢ is isalphat'z"); char str2{] = "In C";
an alphabetic character strcat(stri, str2);
iscntei(int c) Checks whether character cis scanf(“%d",
printf("\n stri: %s", str1);
a control character Kcpisentrhc), return 0;
bschipit(int ) Checks whether character ¢ isdigit(3), }
isadigit Output
isgraph) Checks whether character isgraphe'!"y;
¢ is a graphic or printing str: Programming In C
character, The function
excludes the white space strncat Function
character
Syntax:
ixprintiinte) — Checks whether character c ——_isprimt("@");
is a printing character. The char *strncat(char *str1, const char *str2,
function includes the white size_t n);
space character
islower(itt c) —Checks whether thecharacter islower("k"): This function appends the string pointed to by str2 to
cis in Jower case the end of the string pointed to by str1 up to n characters
isuppertintc) Checks whether thecharacter isuppert"K"); long. The terminating null character of str is overwritten
cis in upper case Copying stops when n characters are copied or the
ispunet(intc) Checks whether thecharacter ispunct('?"); terminating null character of str2 is copied, A terminating
cis @ punctuation mark null character is appended to str1 before returning to the
taspace(intc) Checks whether thecharacter isxpace(" “); calling function:
cis a while space character
include <stdio.h>
isxdigit(intc) Checks whether the character isxdigit(F");
cis a hexadecimal digit
include <string.h>
tolower(intc) —Converts
thecharacter ¢10 tolower("K")
int main()
lower case returnsk {
touppertinic) —Converts the character ¢10 tolower("k")
char stri[50] = “Programming”;
\ upper case returns K
char str2[] = “In C";
strncat(str1, str2, 2);
printf("\n str1: Xs", str1);
13.5.2 String Manipulation Functions return 0;
}
In this section we will look at some commonly used string
functions present in the string.h and stdlib.h header Output
files, strl: Programming In
strcat Function strchr Function
Syntax: Syntax:
char *strcat(char *str1, const char *str2);
char *strchr(const char *str, int c);
The strcat function
Programming Tip: appends the string pointed The strchr ( ) function searches for the first occurrence
Before using to by str2 to the end of the of the character c (an unsigned char) in the string pointed
string copy and string pointed to by stri. to by the argument str. The function returns a pointer
concatensting The terminating null character pointing to the first matching character, or NULL if no
functions, ensure that of stri is overwritten. The match is found.
the destination string process stops when the #include <stdio.h>
has enough space to terminating null character of #include <string.h>
Hore alitheclemems) +2 is copied. The argument int main()
Sothat memory stri is retuned. Note that {
hapa ali stri should be big enough to char str[50] = “Programming In C";
store the contents of str2. char *pos;
Strings 333
return 0; }
} Output
Output
No character matches in the two strings
The position of first character in str2 that
does not match with that in stri is 15 strtok Function
In Step 1. we initialize
co Progracaming Tip: the index variable I to zero.
atoi(), atof(), and atol{) functions are a partof When accessing In Step 2, a while loop ia
stdlib.h header file. elements ofa executed until all the strings
She De acne in the array are accessed, In
13.6 | ARRAYS OF STRINGS a ‘ae Step 3,ie individual string
the pa is processe:
Till now we have scen that a string isan array of characters.
For example, if we say char name[] = "Mohan", then name
16. Write a program to read and print the names of n
is a string (c! ter array) that has five characters students ofaclass.
Now suppose that there are 20 students in a class and
we need a string that stores names of all the 20 students. Binclude <stdio.h>
How can this be done? Here, we need a string of strings or Sinclude <conio.h>
an array of strings, Such an array of strings would store 20 int main()
individual strings, An array of strings is declared as, {
char names[20)[30];
char names[S][10];
int i, nj;
Here, the first index that specifies the number of strings clrser();
that are needed and the second index specifies the length printf("\n Enter the number of students:
of every individual string. So here, we allocate space for scanf("%d", &n);
20 names where cach name can be 4 maximum of 30 for(isO;icn;ie+)
characters long. The general syntax for declaring a two- {
dimensional array of strings can be given as printf("\n Enter the name of
student Xd: ", i+1);
<data type> <array_name> [row_size][{column_
gets(names(i});
size);
}
Let us see the memory representation of an array of printf("\n Names of the students are:\n");
strings. If we have an array declared as for(i = O;4 < njit+)
puts (names{i]});
char name[S}[10] = {"Ram", “Mohan”, “Shyam”,
getch();
“Hari”, "Gopal"};
return 0;
Then in memory the array is stored as shown in }
Figure 13,20.
Output
} return 0;
for(i = 0;4 < njit+) }
{ Output
for(j = 0;j < n-i-1; J++)
{ Enter * to end
if(stremp(names[j], names[j+1})>0) Enter the text: Hi there
{ The text is: Hi there
strepy(temp, names[j}); The count of characters is: 8
strepy(names[j], names[j+1]);
strepy(names[j+1], temp); 19, Write a program to read a sentence. Then count the
} number of words in the sentence.
Programming Tip: } #include <stdio.h>
Strings cannot be include <conio.h>
manipulated with printf("\n Names of int main()
arithmetic or other the students are: "); {
operators available in for(ieO;icn;is+) char str[200};
C boundaries. puts(names[i}); int ie0, count
getch(); cleser();
return 0; printf("\n Enter the sentence: “);
} gets(str);
Output while(str[{i] t= '\0")
{
Enter the number of students: 3 if(str[i] == ° * BB str[iet] I= ' ')
Enter the name of student 1: Sarthak count++;
Enter the name of student 2: Goransh ite;
Enter the name of student 3: Aditya
}
Names of the students are: Aditya Goransh printf("\n The total count of words is: %d",
Sarthak count+1);
return 0;
18, Write a program to read and print the text until a * is
encountered, Also count the number of characters in }
the text entered, Output
#include <stdio.h> Enter the sentence: How are you
#include <conio.h> The total count of words is: 3
int main()
{ 20. Write a program to read multiple lines of text until
char str[100); a * is entered. Then count the number of characters,
int 190; words, and lines in the text
clrscr(); #include <stdio.h>
printf("\n Enter * to end"); #include <conio.h>
printf("\n Enter the text: "); int main()
scanf("%c", &str[i)});
{
while(str[i] l= **") char str[200);
{ int ieO, word_count = 0, line_count =0,
itt; char_count = 0;
scanf("Xe", &str[i]); clrscr();
} printf("\n Enter a * to end”);
str[i] = *\O'; printf("\n Enter the text: ");
printf("\n The text is: "); scanf("%c", &str[i});
is0; while(str[i] f= ‘*')
while(str(i] != "\o') {
{ ise;
printf("%e", str[i]); scanf("Xe", &str[i]);
itt;
}
} str[i} = ‘\o';
printf("\n The count of characters is: i=0;
wd" ,i)5 while(str[i] I= "\0")
Strings 339
} while(str[i] t= ‘*')
{
Output itt;
Enter the text: How are you? scanf("Xe", &str[i]);
Enter the position from which to start: 2 }
340 Computer Fundamentals and Programming in C
str[i] = *\0’; {
i=0; printf("%c", str[j]});
while(str[i) != ‘\o") jets
{ if(str[j] == '\n')
if(linecount == 1 && i == 0) {
printf("\n Xd\t", linecount); Ao-5
if(str[i] == "\n") linecount++;
{ printf("Xd \t", linecount);
linecount++; }
printf("\n Xd\t", linecount); }
} }
printf("%c", str[i]); else
ine; {
} iss;
return 0; if(str[i] == ‘\n')
} Linecount++;
Output
}
Enter a * to end getch();
bb eeeeedwenees return 0;
Enter the text: }
Hello
how
Outpu
are You?* Enter a * to end
1 Hello Enter the text : Hello
2 how how
3 are you? are you?
24, Write a program to enter a text that contains multiple Enter the line number from which to copy: 1
lines, Display the n lines of text starting from the m™ line Enter the line number till which to copy: 2
#include <stdio.h> Hello 1
#include <conio.h> how 2
int main()
25. Write a program to enter a text. Then enter a pattern
<
char str[ 1000); and count the number of times the pattern is repeated
int i = 0, m, n, linecount = 0; in the text
clrser(); #include <stdio.h>
printf("\n Enter a * to end #include <conio.h>
printf("\n Enter the text: *) int main()
scanf("%c", &str{i}); {
while(str[i}!='*') char str[200], pat(20);
{ ins; int iO, j#0, found-0, k, count=0;
scanf("%c", &str[i}); clrser();
} printf("\n Enter the string: “);
str[i] = ‘\0'; gets(str);
printf("\n Enter the line number from which printf("\n Enter the pattern: ");
to copy gets(pat);
scanf("%d", &@); while(str[i}!="\0')
printf("\n Enter the line number till which {
to copy : “); j=0, k=i;
scanf("Kd", &n); while(str[k]==pat[j] 8% pat[j]!="\0")
iso, {
while(str[i] != '\o*) kets
{ has]
if(linecount == m ) }
{ if(pat[j]=="\0")
j= i5 {
while(n>0)
Strings 341
case 1: case 2:
printf("\n Xs \n", quest[{0]); printf("\n\n CHECK THE CORRECT ANSWERS");
for(i=0;
i<3; i++) printf("\n * om}5
printf("\n Xs", option1[i}); printf("\n Xs \n
printf("\n\n Enter your answer number: Xs" ,quest[0],optioni[correct_ans(0]]);
"i printf("\n\n Xs \n
scanf("Xd", &response[0}); %s" ,quest(1],option2[correct_ans[1]}]);
printf("\n Xs \n", quest[1]); printf("\n\n %s \n
for(i=0;ic3;i++) Xs" ,,quest[2], option3[correct_ans[2}]);
printf("\n Xs", option2[i}); printf("\n\n Xs \n
printf("\n\n Enter your answer number: Xs", quest[3),option4[correct_ans[3}]);
")5 printf("\n\n %s \n
scanf("%d", &response[1}); Xs", quest[(4],optionS[correct_ans[4]]);
printf("\n %s \n", quest[2]); break;
for(iw0;ic3;ie+) case 3:
printf("\n Xs", option3[i)); marks = 0;
printf("\n\n Enter your answer number: for(i = O;1 <= 4;i++)
scanf("Xd", &response[2]); {
printf("\n %s \n", quest[3]); if(correct_ans{i +1 == response[i})
for(i0;1<3;
i++) marks++;
printf("\n %s", option4[i]); }
printf("\n\n Enter your answer number: printf("\n Out of 5 you score Xd", marks);
scanf("Xd", &response[3]); break;
printf("\n Xs \n", quest[4]); }
for(in0;1<3;
i++) )while(option!=4);
printf("\n Xs", optionS[i}); getch();
printf("\n\n Enter your answer number: a) return 0;
scanf("Xd", &response[4]);
break;
POINTS TO REMEMBER
© Astring is a null-terminated character array. using putchar() function repeatedly.
* A string is terminated with a null character (\0’) to in printf(), the width specifies the minimum output
signify the end of the character array. field width, If the string is short, extra space is either
* A string is a character array in which individual left padded or right padded. The precision specifies
characters can be accessed using a subscript that the maximum number of characters to be displayed,
starts from zero, A negative width left pads short string rather than the
All the characters of a string array are stored in default right justification. If the string is long, the extra
successive memory locations. characters are truncated.
Strings can be read by using three ways—using scanf() The number of characters in the string constitutes the
function, using gets() function, or using getchar() length of the string.
function repeatedly. Appending one string to another string involves
scanf function terminates as soon as it finds a blank copying the contents of the source string at the end of
space, the destination string.
© gets() takes the starting address of the string which To extract a substring from a given string requires
will hold the input. The string inputted using gets() is information about three things—the main string, the
automatically terminated with a null character. position of the first character of the substring in the
© Strings can also be read by calling getchar() repeatedly given string, and length of the substring.
to read a sequence of single characters (unless a index operation returns the position In the string
terminating character is entered). where the string pattern first occurs.
Strings can be displayed on the screen using three Replacement operation is used to replace the pattern
ways—using printf() function, using puts() function or Pi by another pattern P2_
GLOSSARY
Scanset It is used to define a set of characters which may String matching Finding occurrences of a pattern string
be read and assigned to a string. It is defined by placing within another string.
the characters inside square brackets preceded with a %. String taxonomy A string can be stored either in fixed-
String An array of characters terminated by a null character. length or in variable-length format.
EXERCISES
17. Write a program to insert a sub-string in the middle of a 38. Write a program to read a short story. Display the n lines
given string of story starting from the m™ line.
18 Write a program to input an array of strings. Then 39, Write a program to read a short story. Rewrite the story
reverse the string in the format shown below. by printing the line number before the starting of each
“HAPPY BIRTHDAY TO YOU" should be displayed as "YOU line.
TO BIRTHDAY HAPPY”. 40. Write a program to display a list of candidates. Prompt
19. Write a program to append a given string in the following 100 users to cast their vote. Finally display the winner in
format. the elections.
“GOOD MORNING MORNING GOOD” Write a program to delete the last character of a string
20 Write a program to input a text of at least two paragraphs. Write a program to delete the first character of a string
Interchange the first and second paragraphs and then Write a program to insert a new name in the string array
re-display the text on screen. STUD{][], assuming that names are sorted alphabetically.
21 Write a program to input text of atleast two paragraphs. Write a program to delete a name in the string array
Construct an array PAR such that PAR[i] contains the STUD{)[], assuming that names are sorted alphabetically.
location of the i" paragraph in TEXT. 45. inaclass there are 20 students. Each student is supposed
22 Write a program to find the length of "GOOD MORNING”. to appear in three tests and two quizzes throughout the
23. (a) Write a program to convert the given string “GOOD year. Make an array that stores the names of all these 20
MORNING" to “good morning”. students. Make five arrays that store marks of three
subjects as well as scores of two quizzes for all the
(b) Write a program to convert the given string “hello
students. Calculate the average and total marks of each
world” to “HELLO WORLD”.
student. Display the result
24 Write a program to concatenate two given strings “Good
Morning” and “World”, Display the resultant string.
Find the output of the following codes.
25. Write a program to append two given strings “Good
1 main()
Morning” and “World”. Display the resultant string
{
26 Write a program to check whether the two given strings char stri[]= {°H','I'};
“Good Morning” and “GOOD MORNING” are same.
char str2{] = {'H’, ‘I’, *\0")};
27. Write a program to convert the given string “hello if(stremp(stri, str2) == 0)
world” to “dirow olleh” peintf("\n The strings are equal");
28. Write a menu driven program that demonstrates the else
use of string functions present in the string.h header printf("\n Strings are not equal")
file, }
29. Write a menu driven program that demonstrates the 2. main()
use of character handling functions present in the {
ctype.h header file. char str[]= "Programming in C";
30. Write a program to extract the string “od Mo” from the int 4;
given string “Good Morning”. while(str[i]!="\0')
31 Write a program to insert “University” in the given string {
“Oxford Press” so that the string should read as “Oxford if (1X2==0)
University Press”. printf("%e", str[i});
32 Write a program to delete “University” from the given itt;
string “Oxford University Press” so that the string should }
read as “Oxford Press”. }
33. Write a menu driven program to read a string, display 3 main()
the string, merge two strings, copy n characters from the {
m'" position, calculate the length of the string. char str[]="GGOD MORNING" ;
34 Write a program to copy the last n characters of a printf("\n %20.10s", str);
character array in another character array. Also convert printf("\n Xs", str[0});
the lower case letters into upper case letters while printf("\n Xs", &str[S]);
copying. }
35. Write a program to simulate the strepy function a main()
36, Write a program to read and display names of employees {
in a department. char ch = 'k*;
37, Write a program to sort the names of employees printf("%c", ch+10);
alphabetically.
346 ‘Computer Fundamentals and Programming in C
5. main() main()
{
char stri[ Programming” ; char str[]={'H',‘e','1',"1",'0'};
chat str2{] = “Is Fun"; printf("\n str = Xs", str);
strcpy(stri, str2); }
printf("\n Xs", str); main()
} {
6. main() char str[S]="HELLO";
{ printf("\n str = Xs", str);
char stri[]= “Programming”; }
chat str2[{) = “Is Fun"; main()
strncpy(str1, str2, 3);
printf("\n Xs", str); char str[10];
} strncpy(str1, “HELLO”, 3);
7. main() printf(“\n str = Xs", str);
{ }
char str1[]= “Programming”; main()
chat str2[ “Project";
printf("%d", strncmp(stri, str2, 3))5 char str[10);
} strcpy(str, “Hello there");
8. main() printf("\n str = Xs", str);
{ }
char str[]= “Oxford University Press”; main()
printf("%s", strstr(str, “Uni")); {
char str[]* “Hello there";
if(strstr(str, “Uni")#*0)
Find errors in the following codes. printf("\n Substring Found");
1, main() }
{ main()
char str1[]="Programming”; {
char str2{] = “In C"; char str1(10), str2[10};
strl « str2; gets(stri, str2);
printf("\n stel « Xs", stri); printf("\n str1 « Xs and str2 = Xs" » stra,
str2);
+
,
Pointers
+.
TAKEAWAYS
Pointer expressions Pointers with arrays * Function pointers
Pointer arithmetic Pointers with strings * Pointers to pointers
Null and generic pointers Arrays of pointers * Dynamic memory allocation
Pointers with functions. Pointers with 2D and 3D arrays
int numi=2, num2= 3, sum=0, mul=0, div=1; * Apointer variable can be initialized with a null value?
int *ptr1, *ptr2; + Prefix or postfix increment and decrement operators can
ptri = &numi; be applied on a pointer variable.
ptr2 = &num2; * An integer value can be added or subtracted from a
pointer variable.
sum = *ptrl + *ptr2; * Apointer variable can be compared with another pointer
mul = sum * *ptr1; variable of the same type using relational operators.
*ptr2 +91; * Apointer variable cannot be multiplied by a constant
div = 9 + *ptr1/*ptr2 - 30; * A pointer variable cannot be added to another pointer
variable.
In C, the programmer may add or subtract integers from
pointers. We can also subtract one pointer from the other. We 2. Write a program to print Hello World, using pointers.
can also use short hand operators
Programming Tip: #include <stdio.h>
with the pointer variables as we
aianeren usewith other variables int main()
but ock puelasiae’: C also allows to compare {
pointers by using relational char *ch = “Hello World";
eee . operatorsinthe expressions. For printf("%s", ch);
po te ‘waatle Hak example, pl > p2, pl == p2, return 0;
bef and pi! © p2are all valid in C. }
elo pe When using pointers, unary Output
Narisbie's eddies. increment (++) and decrement
(--) operators have greater Hello World
precedence than the dereference operator (*). Both these
3. Write a program to add two floating point numbers. The
operators have a special behaviour when used as suffix. In
result should contain only two digits after the decimal
that case the expression is evaluated with the value it had
before being increased. Therefore, the expression #include <stdio.h>
int main()
*ptres
{
is equivalent to * (ptr++) as ++ has greater operator precedence float num1, num2, sum = 0.0;
than *. Therefore, the expression will increase the value of float *pnuml = Snum1, *pnum2 = &num2,
ptr so that it now points to the next memory location. This *psum = Ssum;
means the statement *ptr++ docs not perform the intended printf("\n Enter the two numbers: “);
task. Therefore, to increment the value of the variable whose scanf ("Xf Xf", pnuml, pnum2);
address is stored in ptr, you should write // prumd = &numi ;
*psum = *pnuml + *pnum2;
(*ptr)e+
printf("\n Xf + Xf = %.2f", *pnumi,
Now, let us consider another C statement *pnum2, *psum);
Output {
if(*pnum/i «= 0)
Enter the starting and ending limit of the flag «1;
numbers to be summed: 0 10 }
Sum of numbers = 55 if(flag == 0)
Average of numbers = 5.50 printf("\n Xd is prime", *pnum);
else
10. Write a program to print all even numbers from m to n. printf("\n %d is composite", *pnum);
include <stdio.h> }
#include <conio.h> printf("\n Enter any number: “);
int main() scanf("Xd", pnum);
{ }
int m, *pm = &m; return 0;
int n, *pn = &n; }
printf("\n Enter the starting and ending Output
limit of the numbers: ”);
scanf("Xd Xd", pm, pn); ** ENTER -1 TO EXIT *
while(*pm <= *pn) Enter any number: 3
< 3 is prime
if(*pm %2 == 0) Enter any number: 1
printf("\n %d is even", *pm); 1 is neither prime nor composite
(*pm) +45 Enter any number: -1
354 Computer Fundamentals and Programming in C
void *ptr;
UEP Nutt pointers
In C, since you cannot have a variable of type void,
We have seen that a pointer variable is a pointer to some the void pointer will therefore
other variable of the same data type. However, in some A be pod not point to any data and thus
cases we may prefer to have null pointer which is a special Legare be aot be dereferenced. You
pointer that does not point to any value. This means that a f ‘ need to type cast a void pointer
null pointer does not point to any valid memory address. (generic pointer) to another
To declare a null pointer you may use the predefined kind of pointer before using it
constant NULL, which is defined in several standard header Generic pointers are often used when you want a
files including <stdio.h>, <stdlib.h>, and <string.h>. pointer to point to data of different types at different times.
After including any of these files in your program, write For example, look at the code given below
int *ptr = NULL; #include <stdio.h>
int main()
You can always check whether a given pointer variable
{
stores address of some variable or contains a NULL by int x«10;
writing char ch = ‘A’;
if (ptr == NULL) void *gp;
{ ep = &x;
Statement block; printf("\n Generic pointer points to the
} integer value = Xd", *(int*)gp);
Bp = Bch;
You may also initialize a pointer as a null pointer by printf("\n Generic pointer now points to the
using a constant 0, as shown below character = X%c", *(char*)gp);
return 0;
}
This is a valid statement inC, Output
Programming
Tip:
as which is cc: Generic pointer points to the integer value
es eee psec)ro ically
typic ha$s
ie vidiiC,or
OF = 10
dereferencea null Leer
replacement text, 0. Howeve Generic pointer now points to the character
pointer,
to avoid ambiguity it is always =A
better to use NULL to declare a null pointer. It is always recommended to avoid using generic
A function that returns pointer values can return a null pointers unless absolutely necessary, as they effectively
pointer when it is unable to perform its task. allow you to avoid type checking
Null pointers are used in situations where one of the
pointers in the program points to different locations at
different times. In such situations it is always better to set PASSING ARGUMENTS TO
it to a null pointer when it doesn’t point anywhere valid, FUNCTION USING POINTERS
and to test to see ifit’s a null pointer before using it
We have already seen call-by-value method of passing
parametres to a function. Using call-by-value method,
Arun time error isgenerated ifyou try todereferencea it is impossible to modify the actual parameters when
null pointer. you pass them to a function
Programming Tip: Furthermore, the incoming
While using pointers arguments to a function are
GPRD GENERIC POINTERS etecroe treated as local variables in
calling f the function and those local
A generic pointer is a pointer variable that has void as its wait pane variables get a copy of the
data type. The void pointer, or values passed from their
ogre ig Tip the generic pointer, is a special valerbodsoyes calling function.
Acompiler error will type
ype of of pointer that can
cans bea usedtines ial eae Pointers provide a
be generated if you ariables of
sisigna pointer of to point to variables of any data ear the mechanism to modify data
i type. It is declared like a normal RE eee in one ai
ee typepe ad pointer variable but using the B using code written in another
wi ne zBed void keyword as the pointer's hea rages function. In other words: If
data type. For example, data is declared in func1() and
Pointers — (355
we want to write code in func2() that modifies the data in int main()
funci(), then we must pass the addresses of the variables {
to func2(). int numl, num2, num3, large;
The calling function sends the addresses of the variables printf("\n Enter the first number: “);
and the called function declares those incoming arguments scanf("Xd", &num1);
's. In order to modify the variables sent by the print#("\n Enter the second number: ");
function, the called function must dereference the scanf("Xd", &num2);
pointers that were passed to it. Thus, passing pointers to printf("\n Enter the third number: “);
a function avoids the overhead of copying data from one scanf("%d", &num3);
function to another, Hence, to use pointers for passing greater(&num1, Snum2, &num3, &large);
arguments to a function, the programmer must do the return 0;
following }
* Declare the function parametres as pointers int greater (int *a, int
* Use the dereferenced pointers in the function body
fe *b, int *c, int *large)
Acompiler error will {
* Pass the addresses as the actual argument when the
function is called be generated ifyou if(*a > *b && *a > *c)
use pointer arithmetic *large « *a;
with multiply, divide if(*b > *a && *b > *c)
or modulo operators. slarge = *b;
It isan error toreturn a pointer to a local variable in the
else
called function, because when the function terminates ,
*large = *c;
its memory may be allocated to a different program.
printf("\n Largest number = Xd", *large);
Hy
Let us write some programs that pass pointer variables as Output
parameters to functions.
Enter the first number: 1
12. Write a program to add two integers using functions Enter the second number: 7
#include <stdio.h> Enter the third number: 9
#include <conio.h> Largest number = 9
void sum (int *a, int *b, int *t); 14. Write a program to calculate area of a triangle:
int main()
{ include <stdio.h>
int num1, num2, total; void read(float *b, float *h);
printf("\n Enter the first number: void calculate_area (float *b, float *h,
scanf("%d", &numi); float *a);
printf("\n Enter the second number: “); int main()
scanf("%d", &num2); {
sum(&inumi, &num2, &total); float base, height, area;
printf("\n Total = %d", total); read(&base, &height);
getch(); calculate_area(&base, &height, &area);
return 0; printf("\n Area of the triangle with base
} %.1f and height %.1f = %.2f", base, height,
void sum (int *a, int *b, int *t) area);
{ return 0;
*t= ‘a+ *b; }
} void read(float *b, float *h)
Output {
printf("\n Enter the base of the
Enter the first number: 2 triangle: ");
Enter the second number: 3 scanf("%#", b);
Total = 5 printf("\n Enter the height of the
triangle: ");
13. Write a program, using functions, to find the biggest of scanf("%#", bh);
three integers. }
#include <stdio.h> void calculate_area (float *b, float *h,
int greater(int *a, int *b, int *c, int float *a)
*large); {
656 Computer Fundamentals and Programming in C
POINTERS AND ARRAYS The print€() function will print the value 2 because after
being incremented Lasspoints to the next location. One
point to note here is that if x
The concept of array is very much bound to the one of
is an integer variable, then x++
the pointers. An array occupies consecutive memory
adds 1 to the value of x. But
locations. Consider Figure 14.2. For example, if we have
ptr is a pointer variable, so
an array declared as
when we write ptr +4, then
int arr[] = {1, 2, 3, 4, 5}; then in memory it
adding i gives a pointer that
would be stored as shown in Figure 14,2.
pola i henna further along an array than the original
pointer.
Since ++ptr and ptr++ are both equivalent to ptr
+1, incrementing a pointer using the unary ++ operator,
ace[O}are{1]arr{2]arr{3} _arr{4]
1000 100210041006 1008 increments the address it stores by the amount given by
sizeofitype) where type is the data type of the variable
Figure 14.2. Memory representation of arr[{) it points to (i.¢., 2 for an integer). For example, consider
Figure 14.4.
Array notation is a form of pointer notation. The name If ptr originally points toarr({2}, then ptr++ will point to
of the array is the starting address of the array in memory. the next clement, i... arr[3}. This isshown in Figure 14.4.
It is also known as the base address. In other words, base
address is the address ofthe first clement in the array or
the address of arr{0}. Now lect us use a pointer variable as Sasa aS
given in the statement below. 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
int *ptr;
arr{0} an{1} arr{2] arr[3] art[4]
ptr = &arr[0];
pir
Bee nae j Here, ptr is made to point
to the first element of the array. Figure 14.4 ptr pointing to the fourth element of the
Execute the code given below array
and observe the output which
will make the concept clear Had this been a character array, every byte in the
to you. memory would have been used to store an individual
character. pte++ would then add only | byte to the address
main()
of ptr.
{ When using pointers, an expression like arr[i] is
int arr[]={1,2,3,4,5};
equivalent to writing *(arr+i). If arr is the array name,
printf("\n Address of array = %p Xp Xp",
then the compiler implicitly takes
arr, &arr[0), &arr);
} arr = &arr[0)
Similarly, writing ptr = &arr[2], makes ptr to point to To print the value ofthe third element ofthe array, we
the third clement ofthe array that has index 2. Figure 14.3 can straightaway use the expression * (arr+2). Note that
shows ptr pointing to the third element of the array. arr[i] = “(arr + i)
Many beginners get confused by thinking of array name
ais a pointer, For example, while we can write
2
ptr = arr; // ptr = &arr[0})
In the code, ptr1 and ptr2 are pointers pointing to the
We cannot write elements of the same array. We may subtract two pointers
arr = ptr; as long asthey point tothe same array, Here, the output is
2 because there are two elements between ptri and ptr2.
This is because
while ptr is a variable, arr isa constant. Both the pointers must point to the same array orone past
The location at which the first the end of the array, otherwise this behaviour cannot be
clement of arr will be stored defined.
cannot be changed once arr{} Moreover, C also allows pointer variables tobe compared
has been declared. Therefore, with cach other. Obviously, if two pointers are equal, then
an array name is often known they point to the same location in the array, However,if
to be a constant pointer. one pointer isless than the other, it means that the pointer
To summarize, the name of points tosome clement nearer to the beginning of the array.
an array is equivalent to the
address of its first clement,as 1S. Write a program to display an array of given numbers.
@ pointer is equivalent to the include <stdio.h>
address of the clement that it main()
points to,Therefore, arrays and
{
pointers use the same concept. int arr[]={1,2,3,4,5,6,7,8,9};
int *ptri, *ptr2;
ptri = arr;
ptr2 = Sarr[8);
while(ptri<#ptr2)
Look at the following code and understand the result of {
executing them, printf("Xd", *ptr1);
main() ptrire;
{ }
int arr[]#{1,2,3,4,5}; }
int ‘ptr, i; Output
ptreBarr[2);
‘ptr = -1; 123456789
*(ptr+1) = 0; 16.Write a program to read and display an array of n
*(ptr-1) = 1; integers.
printf("\n Array is: “);
for(i=0;i<S;ie+) include <stdio.h>
printf(" Xd", *(arr+i); int main()
} {
int i, n;
Output
int arr[10], *parr = arr;
Array is: 12 1-10 °5 printf("\n Enter the number of elements: “);
scanf("%d", &n);
In C we can add or subtract an integer from a pointer printf("\n Enter the elements: ”);
to get a new pointer, pointing somewhere other than the
for(i = 0; i< nj; ier)
original position, C also permits addition and subtraction scanf("Xd", parr+i);
of two pointer variables. For example, look at the code printf("\n The elements entered are: ");
given below, for(i=0; i <n; i++)
main() printf("\t Xd", *(parr+i));
{ return 0;
int arr[]={1,2,3,4,5,6,7,8,9}; }
int *ptri, *ptr2; Output
ptri = arr;
ptr2 = ptr+2; Enter the number of elements: 5
printf("%d", ptr2 -ptri); Enter the elements: 12345
} The elements entered are: 12345
358 Computer Fundamentals and Programming in C
} }
Output }
printf("\n The numbers you entered are:
Enter the number of elements: 5 for(i = 0; i < *pn;i++)
Enter the number: 1 printf("xd “, *(parr+i));
Enter the number: 2 printf("\n The largest of these numbers is:
Enter the number: 3 Xd", *plarge);
printf("\n The position of the largest int main()
es
number in the array is: Xd", *ppos); {
return 0; int num[{i0), n, small=32767, pos;
+ printf("\n Enter the size of the array: ");
scanf("%d", &n);
Output
read_array(num, n);
Enter the number of elements in the array: 5 print_array(num, n)
Enter the number: find_small(num, n, &small, &pos);
Enter the number: printf("\n The smallest number in the array
Enter the number: is %d at position %d", small pos);
Enter the number: return 0;
Enter the number: vbwnhe }
The numbers you entered are: void read_array(int *arr, int n)
12345 {
The largest of these numbers is: 5 int i;
The position of the largest number in the printf("\n Enter the array elements: “);
array is: 4 for(i=O;icn;ie+)
scanf("%d", Sarr[i]);
}
PASSING AN ARRAY TO void print_array(int
{
‘arr, int n)
A FUNCTION int 4;
printf("\n The array elements are: ");
An array can be passed to a function using pointers. For for(ieO;icn;it+)
this, a function that expects an array can declare the formal printé("\t Xd", are[i]);
parameter in cither of the two following ways: }
void find_small(int *arr, int n, int *small,
func(int are[}); OR func(int arr);
int *pos)
When we pass the name of the array to a function,
the address of the zeroth element of the array is copied for(isO;i<n;ie+)
to the local pointer variable in the function. Observe {
the difference; unlike ordinary variables the values of if(*(areei}])< *small)
the elements are not copied, only the address of the first {
clement is copied. small = *(arr+i);
When a formal parameter is declared in a function *pos = i;
header as an array, it is interpreted as a pointer to a
variable and not as an array. With this pointer variable }
you can access all the clements of the array by using the }
expression, array_name + index. To find out how many }
clements are there in the array, you must pass the size of
the array as another parameter to the function. So fora Output
function that accepts an array as parameter, the declaration Enter the size of the array: 5
should be as follows. Enter the array elements: 12345
The array elements are: 12345
func(int arr[], int n); OR
The smallest number in the array is 1 at
func(int *arr, int n);
position 0
Look at the following program which illustrates the use
of pointers to pass an array to a function. It isnot necessary to pass the whole array to a function.
We can also pass a part of the array known as a sub-
19.Write a program to read and print an array ofn array. A pointer to a sub-array is also an array pointer. For
numbers, then find out the smallest number. Also print example, if we want tosend the array starting from the third
the position of the smallest number. element then we can pass the address of the third element
and the size of the sub-array, i.e., if there are 10 elements
#include <stdio.h> in the array, and we want to pass the array starting from the
void read_array(int *arr, int n);
third element, then only cight elements would be apart of
void print_array(int *arr, int n);
the sub-array. So the function call can be written as
void find_small{int *arr, int n, int «small,
int *pos); func(@arr[2}, 8);
360 Computer Fundamentals and Programming in C
But this also takes more typing than is convenient. So. int upper = 0, lower = 0;
C permits printf("\n Enter the string: “);
gets(str);
char str[10] = "Hil"; pstr = str;
When the double quotes are used, NULL is automatically
appended to the end of the string while(*pstr t= ‘\0')
When a string is declared like this, the compiler sets {
aside a contiguous block of memory 10 bytes long to if(*pstr >= ‘A’ && *pstr <= 'Z")
hold characters and initializes its first four characters to uppert+;
Hi!\o, else if(*pstr >= ‘a’ && *pstr <= ‘2!
Now, consider the following program that prints a text lower++;
pstre+;
#Hinclude <stdio.h>
}
int main() printf("\n Total number of upper case
{ characters = %d", upper);
char str{] = “Hello”; print#("\n Total number of lower case
char *pstr;
characters = %d", lower);
pstr = str; return 0;
printf("\n The string is: ");
while(*pstr t= '\o") }
{ Output
printf("%e", *pstr); Enter the string: How are you
pstr+s; Total number of upper case characters = 1
} Total number of lower case characters = 8
return 0;
} 20. Write a program to read and print a text, Also count the
Output number of characters, words, and lines in the text.
Sinclude <stdio.h>
The string is: Hello int main()
In this program, we declare a character pointer *pstr {
to show the string on the screen, We then point the pointer char str[100], *pstr;
pstr to str. Then we print cach character of the string in the int chars = 0, lines = 0, words = 0;
while loop. Instead of using the while loop, we could have printf("\n Enter the string: ");
straightaway used the function puts() as shown below pstr = str;
while(*pstr I= ‘\0')
puts(pstr); {
The function prototype for puts() is as follows if(*pstr == ‘\n')
lines++;
int puts(const char *s); if(*pstr == * B& *(pstr +1) Im * *)
Here the const modifier is used to assure the user that words++;
the function will not modify the contents pointed to by the chars++;
pstree;
source pointer. The address of the string is passed to the
function as an argument }
The parameter passed to puts() is a pointer which is printf("\n The string is: ");
the address to which it points to, or, simply, an address. puts(str);
Thus writing puts(str); means passing the address of printf("\n Number of characters = Xd",
str(0]. chars);
Similarly, when we write puts(pstr); we are passing printf("\n Number of lines = %d", lines +1);
the same address, because we have written pstr = str; printf("\n Number of words = %d", words +1);
Consider another program which reads a string and return 0;
then scans each character to count the number of upper }
and lower case characters entered. Output
#include <stdio.h> Enter the string: How are you
int main() Number of characters = 11
{ Number of lines = 1
char str[100], *pstr; Number of words = 3
362 Computer Fundamentals and Programming in C
{ }
if(*pstr t= '5") return 0;
{} // do nothing }
else if (*pstr == *.*)
Output
*pcopy_str = °,°;
else Enter * to end
*pcopy_str = *pstr; Enter the string: Learning C++
pstre+; pcopy_stres; The new text is: ++C gninraeL
}
*pcopy_str = '\0'; 26. Write a program to concatenate two strings.
printf("\n The new text is: #include <stdio.h>
pcopy_str = copy str;
int main()
while(*pcopy_str t= ‘\O") {
{ char stri(100), str2[100}, copy_str[200];
printf("%c", *pcopy_str); char *pstrl, *pstr2, *pcopy_str;
pcopy_stre+; pstri = stri;
} pstr2 = str2;
return 0; pcopy_str = copy str;
} printf("\n Enter the first string: “);
Output gets(stri);
printf("\n Enter the second string: “);
Enter the string: Programming in C; is a book gets(str2);
written by; Reema Thareja. while(*pstr1 != ‘\0")
The new text is: Programming in C is a book {
written by Reema Thareja, *pcopy_str = *pstri;
pcopy_stre+, pstrit+;
25. Write a program to reverse a string.
}
#include <stdio.h> while(*pstr2 != ‘\0")
int main() {
{ *pcopy_str = *pstr2;
char str[100], copy_str[100}; pcopy_str++, pstr2++;
char *pstr, *pcopy_str; }
pstr = str; *pcopy_str = '\0';
pcopy_str = copy str; printf("\n The new text is: ");
printf("\n Enter * to end"); pcopy_str = copy_str;
printf("\n Enter the string: “); while(*pcopy_
str I= ‘\0')
scanf("%c", pstr); {
while(*pstr l= ‘* printf("%e", *pcopy_str);
{ pcopy_stre+;
pstr++; }
scanf("%e", pstr); return 0;
} }
*pstr = "\0"; Output
pstr--;
while (pstr >= str) Enter the first string: Programming in C by
{ Enter the second string: Reema Thareja
*pcopy_str = *pstr; The new text is: Programming in C by Reema
pcopy_stre+; Thareja
pstr--;
Got Computer Fundamentals and Programming in C
An array of pointers whose clements point to arrays of which would make ptr the name of an arnay of 10 pointets
varying sizes is called a ragged array, Therefore, array to type int. You must be thinking how pointer arithmetic
of pointers week_day and ptr in the above discussion are works if you have an array of pointers. For example:
better known as ragged arrays.
int * arr[10] ;
int ** ptr = arr ;
URE) POINTERS AND 2D ARRAYS In this case, arr has type int **. Since all pointers
have the same size, the address of ptr + i can be
Elements of a two-dimensional array are stored in
calculated as:
contiguous memory locations. A two-dimensional array is
not the same as an array of pointers to one-dimensional addr(ptr + i) = addr(ptr) + [sizeof(int *) + i)
arrays, To declare a pointer to a two-dimensional array, = addr(ptr) + (2 * 4]
you may write
Since arr has type int **,
int +*ptr; arr[0) = Sarr[0}[0},
Here int **ptr is an array of pointers (to one- arr(1) = Sarr[1][0], and in general,
dimensional arrays), while int mat({5}(5)] is a 2D array arr[i] » Sarr[i)[o}.
They are not the same type and are not interchangeable.
According to pointer arithmetic,arr + i = & arr[i],
Consider a two-dimensional array declared as
yet this skips an entire row of 5 elements, i.c., it skips
int mat(5}[5]; complete 10 bytes (5 elements cach of 2 bytes size).
Therefore, if arr is address 1000, then arr + 2 is address
Individual elements of the array mat can be accessed 1010. To summarize, &arr[{0)[0), arr[0}, arr, and
using cither: &arr[0] point to the base address.
mat[iJ[4] or &arr[0][0] + 1 points to arr[0][1]
*(*(mat + 4) + 9) or arr(0) + 1 points to arr(0}(1]
“(mat (i}+3); arr + 1 points to arr[1}[0]
To understand more fully what is going on, let us &arr[0) + 1 points to arr[1][0]
replace
To conclude, a two-dimensional array is not the same
«(multi + row) with X so the expression as an array of pointers to ID arrays. Actually a two-
*(*(mat + 1) + J) becomes *(X + col) dimensional array is declared as
Using pointer arithmetic, we know that the address int (*ptr)[10) ;
pointed to by (i.c,, value of) X + col + 1 must be
Here ptr is a pointer to an array of 10 elements, The
greater than the address X + col by an amount equal to
parentheses are not optional, In the absence of these
sizeof(int).
parentheses, ptr becomes an array of 10 pointers, not a
Since mat is a two-dimensional array, we know that
pointer to an array of 10 inte; ors.
in the expression multi + row as used above, multi +
row + 1 must increase in value by an amount equal to that
needed to point to the next row, which in this case would
be an amount equal to cols * sizeof(int).
Pointer to a one-dimensional array can be declared as
Thus, in case of a two-dimensional array, in order to
evaluate expression (for a row major 2D array), we must int arr[]={1,2,3,4,5};
know a total of 4 values int *parr;
parr = arr;
1, The address of the first clement of the array, which is
given by the name of the array, i.c., mat in our case Similarly, pointer to a two-dimensional array can be
2. The size of the type of the clements of the array, i.c., declared as
size of integers in our case int are[2)}(2)={{1,2},{3,4}}5
3. The specific index value for the row int (*parr)[2);
4. The specific index value for the column parrearr;
Note that
int (*ptr)[10]; Look at the code given below which illustrates the use
declares ptr to be a pointer to an array of 10 integers. of @ pointer to a two-dimensional array
This is different from include <stdio.h>
int *ptr[10}; main()
366 Computer Fundamentals and Programming in C
printf("\t mat[X%d][%d] = Xd",i,j, *(*(mat +
int arr[2]}(2)={{1,2},{3,4}}; i)+9));
int i, (*parr)[2]; }
pare = arr; return 0;
for(i = 0; i < 2; ite) }
{
OR
for(j = 0; j < 2 ;5++)
printf(" Xd", (*(parrei))(3])5 include <stdio.h>
} int main()
} {
int i, j, mat{3}(3)
Output
printf("\n Enter elements of the matrix");
1234 PPANtf("\n *eeeeeseweeeewraneewnenne”):
The golden rule to access an clement of a two- for(i=0;ic3;
i++)
‘pointerto pointer of T’can’t serve as a '2D array of T”. array are: “);
The 2D array isequivalent to a pointer torow of T,and for(t © 0; 1 < 25 dee)
this is very different from pointer to pointer of T. { Pew 0 ra
When a double pointer thatpoints tothefirstelement eC HD) Op Dees oe)
of an array isused with the subscript notation ptr{0}{0], for(k = 0; k < 2; k++)
it isfully dereferenced two times and the resulting object printf("%d", *(*(*(parr+i)+j)+k));
will have an address equal to the value of the first element }
of the array, }
getch();
return 0;
ETRT) POINTERS AND 3D ARRAYS :
Output
In this section, we will sce how pointers can be used to Enter the elenents of a 2.= 2 «2 array: 123
access a three-dimensional array. We have seen that peers
pointer to a one-dimensional array can be declared as The elements of the 2 * 2 2 array are: 123
int are[]={1,2,3,4,5}; 45678
int *parr;
eden
Similarly, pointer to a two-dimensional array can be
|
Note|
declared as in the printfstatement,
you could also
have used *(*(*(arr+i)+j)+k)) insteadof
int arr({2)(2)={{1,2},{3,4}}; *(*(*(parrei)+j)+k)).
int (*parr)[(2);
parr = arr;
Got Computer Fundamentals and Programming in C
FUNCTION POINTERS OR
func(1,2);
C allows operations with pointers to functions. We have Look atthe program given below which makes use ofa
seen earlier in this chapter that every function code along pointer to a function.
with its variables is allocated some space in the memory.
Thus, every function has an address. Function pointers are #include <stdio.h>
pointer variables that point to the address of a function. void print(int n);
Like other pointer variables, function pointers can be void (*fp)(int);
declared, assigned values, and used to access the functions main()
they point to. {
This is a useful technique for passing a function as an fp = print;
argument to another function. In order to declare a pointer (+p) (10);
to a function we have to declare it like the prototype of the #p(20);
function except that the name of the function is enclosed return 0;
between parentheses () and an asterisk (*) is inserted }
before the name. The syntax of declaring a function void print(int value)
pointer can be given as {
printf("\n %6", value);
return_type(*function_pointer_name) (argument_
}
list);
Output
Look at the declaration below in which we declare a
pointer to @ function that returms an integer value and 10
accepts two arguments—one of type int and the other of 20
type float. Now let us write another code that illustrates how the
int (*func)(int a, float b); contents of fp can be changed at run time to point to two
different functions during program execution.
Because of precedence, if you do not put the function
name within parenthesis, you will end up declaring a #include <stdio.h>
function returning a pointer as shown: float (*func)(float, float);
float add(float, float);
/* function returning pointer to int */
float sub(float, float);
int *func(int a, float b);
main()
{
14,15.1 Initializing a Function Pointer func = add;
As in case of other pointer variables, a function pointer // function pointer points to add
printf("\n Addition = %.2f", func(9.5,
must be initialized prior to use. If we have declared a
pointer to the function, then that pointer can be assigned 3.1))5
the address of the correct function just by using its name. func = sub;
Like in the case of an array, a function name is changed // function pointer points to sub
printf("\n Subtraction = %.2€", func(9.5,
into an address when it’s used in an expression. It is
optional to use the address operator (&) in front of the 3.1))5
function name. }
For example, if fp is a function pointer and we have a float add(float x, float y)
function add() with prototype given as {
return (x + y);
int add(int, int); ¥
float sub(float x, float y)
Then writing fp = add; initializes the function pointer fp
with the address of add(). {
return (x - y);
Pointer Output
Addition = 12.60
When a pointer to a function is declared, it can be called
using one of two forms: Subtraction = 6.40
(*func) (1,2);
A function pointer can be declared and initialized to return result;
ea 4
NULL as shown below: }
int (*fp)(int) = NULL; Output
Addition = 16
14.15.3 Comparing Function Pointers Subtraction = 2
Comparison operators such as == and != can be used the
same way as usual. Consider the code given below which
checks if fp actually contains the address of the function ARRAY OF FUNCTION POINTERS
print(int).
When an array of function pointers is declared, the
if(fp 20){ // check if initialized
appropriate function is selected using an index. The code
if(fp == print)
given below shows the way to define and use an array of
printf("\n Pointer points to print”);
function pointers in C.
else
printf("\n Pointer not initialized!”); Step 1; Use typedef keyword so that fp can be used as
} type
typedef int (*fp)(int, int);
14.15.4 Passing a Function Pointer as an
Argument to a Function Step 2: Define the array and initialize cach element to
NULL. This can be done in two ways:
A function pointer can be passed as the calling argument
of a function, This is in fact necessary if you want to pass /* with 10 pointers to functions which return
4 pointer to a callback function. The following code shows an int and take two ints */
how to pass a pointer to a function which retums an int 1. fp funcArr{[10] = {NULL};
and accepts two int values. 2. int (*funcArr[10])(int, int) = {NULL};
Note that in the program below, the function operate calls Step 3: Assign the function's address—Add and Subtract
the functions add and subtract with the following line:
funcArri(0) «= funcAre2[1] = Add;
result = (*operate_fp) (numi, num2); funcArr[0) = &Add;
#include <stdio.h> funcArr(1] = &Subtract;
int add(int, int);
int sub(int, int);
Step 4: Call the function using an index to address the
int operate(int (*operate_fp) (int, int), int, function pointer
int); printf("Xd\n", funcArr[1](2, 3));
main() // short form
{ printf("%d\n", (*funcArr[0])(2, 3));
int result; // correct way
result = operate(add, 9, 7);
printf ("\n Addition = Xd", result); 28.Write a program, that uses an array of function
result = operate(sub, 9, 7); pointers, to add, subtract, multiply, or divide two given
printf ("\n Subtraction = %d", result); numbers,
return 0; include <stdio.h>
; int sum(int a, int b);
int add (int a, int b)
int subtract(int a, int b);
{ int mul(int a, int b);
return (a + b);
int div(int a, int b);
}
int sub (int a, int b)
int (*fp[4}) (int a, int b);
{
return (a - b);
int main(void)
} {
int operate(int (*operate_fp) (int, int), int int result;
a, int b)
int numi, num2, op;
{ fp[O] = sum;
int result;
fp[1] = subtract;
result = (*operate_fp) (a,b);
fp[2] = mul;
370 Computer Fundamentals and Programming in C
Function Task
malloc() Allocates memory and returns a pointer to the
Program memory Data memory first byte ofallocated space
calloc() Allocates space for anarray ofelements and
initializes them to zero. Like malloc(),
calloc() also returns a pointer tothe memory
ptr = realloc(ptr,newsize); With realloc(), you can allocate more bytes without
The realloc() function allocates new memory space losing your data.
of size specified by newsize to the pointer variable ptr. It
returns a pointer to the first byte of the memory block. The
allocated new block may or may not be at the same region. Dynamically Allocating a 20 Array
Thus, we sce that realloc() takes two arguments. The We have seen how malloc() can be used to allocate a
first is the pointer referencing the memory and the second block of memory which can simulate an array. Now we
is the total number of bytes you want to reallocate. If you can extend our understanding further to do the same to
pass zero as the second argument, it will be equivalent to simulate multidimensional arrays.
calling free(). Like malloc() and calloc(), realloc If we are not sure of the number of columns that the
returns a void pointer if successful, else a null pointer is array will have, then we will first allocate memory for cach
returned row by calling malloc. Each row will then be represented
Ifrealloc() was able to make the old block of memory by a pointer. Look at the code below which illustrates this
bigger, it returns the same pointer. Otherwise, if real loc() concept
has to go elsewhere to get enough contiguous memory
then it returns a pointer to the new memory, after copying include <stdlib.h>
your old data there. However, if realloc() can’t find #include <stdio.h>
enough memory to satisfy the new request at all, it returns main()
4 null pointer, So again you must check before using that {
the pointer returned by realloc() is not a null pointer. int **arr, i, J, ROWS, COLS;
printf("\n Enter the number of rows and
/*Example program for reallocation*/ columns in the array: “);
#include < stdio.h> scanf("%d Xd", BROWS, &COLS);
#include < stdlib.h> arr = (int **)malloc(ROWS * sizeof(int *));
#define NULL O if(arr «= NULL)
main() {
{ printf("\n Memory could not be
char *str; allocated");
/*Allocating memory*/ exit(-1);
str = (char *)malloc(10); }
if (stre=NULL) for(i=0; i<ROWS; i++)
{ {
printf("\n Memory could not be arr[i] = (int *)malloc(coLs +
allocated"); sizeof(int));
exit(1); if(arr[i] == NULL)
{
strepy(str, "Hi"); printf("\n Memory Allocation Failed”);
printf("\n STR = Xs", str); exit(-1);
/*Reallocations/ }
str = (char *)realloc(str,20); }
if(str==NULL) printf("\n Enter the values of the array:
{ “)3
printf("\n Memory could not be for(i = 0; i < ROWS; i++)
reallocated"); {
exit(1); for(j = 0; j < COLS; j++)
} scanf("Xd", Barr[i][j]);
printf("\n STR size modified. \n");
printf("\n STR = %s\n", str);
374 Computer Fundamentals and Programming in C
oo
ls
+)
.
To dynamically allocate space for a 3-D array, arr{10}{20]
[30], perform the following
steps
Figure 14.11 Memory allocation for a two-dimensional array 1, int ***arr;
2. arr = (int + ) malloc(10* sizeof(int
Once the memory is allocated for the two-dimensional **)
array, We can use subscripts to access its elements. When 3. for(4n0;4<10; 4+) arr(i] = (int **)
we write, arr{i] (J), it means we are looking for the 1™ malloc(20*sizeof(int *));
pointer pointed to by arr, and then for the 7 int pointed 4. for(in0;1<10; e+) {for(je0; j<20; j++)
to by that inner pointer. arr(i}(3) = (int *)malloc(30 +
When we have to pass such an array to a function, then sizeof(int));
the prototype of the function will be written as
func(int **arr, int ROWS, int COLS);
ptr = NULL; /* ptr is no more a dangling Memory corruption errors can be broadly classified
pointer */ into following categories:
}
Using un-initialized memory: An un-initialized memory
Output contains garbage value. Hence, using the contents of
WELCOME an un-initialized memory can lead to unpredictable
program behaviour.
Here ptr becomes a dangling pointer. A solution to the Using un-owned memory: A common programming
above is to assign O(NULL) to ptr immediately before mistake is t0 use pointers for accessing and modifying
exiting the block in which it is declared. An alternative memory that is not owned by the program. This situation
solution would be to somehow guarantee that ptr will not may arise when the pointer happens to be a null pointer or a
be used again without further initialization. dangling pointer. Using such a pointer to write to amemory
Memory corruption Memory corruption offen occurs location is 4 serious programming flaw as it may lead to
when due to programming errors, the content of a crash of another program or even the operating system,
memory location gets modified unintentionally, When Using beyond allocated memory (buffer overflow); It
the program uses the contents of the corrupted memory, the elements of the array are accessed in a loop, with
it cither results in program crash or in strange and bizarre incorrect terminating condition, memory beyond the
results. array bounds may be manipulated, Buffer overflow is
Memory corruption is one of the most difficult a common programming flaw exploited by computer
programming errors to trace mainly because of two reasons: viruses causing serious threat to computer security.
> Faulty de-allocation of memory: Memory leaks and
* Thesource ofthe memory corruption and its manifestation freeing of un-allocated memory can also result in
may be far apart, Therefore, it may become hard to
memory corruption
correlate the cause and the effect of the problem
Symptoms of memory corruption problem may appear These days, memory debuggers such as Purify, Valgrind,
under unusual conditions thereby making it even harder and Jnsure++ are widely used for detecting memory
to consistently reproduce the error corruption errors
POINTS TO REMEMBER
All data and programs need to be placed in the primary constant NULL. You may also initialize a pointer as a
memory for execution. null pointer by using the constant 0.
A pointer is a variable that contains the memory A generic pointer is a pointer variable that has ‘void’
address of another variable. as its data type. The generic pointer can be used to
The ‘&’ operator retrieves the Ivalue (address) of the point to variables of any data type.
variable. We can dereference a pointer, i.e, refer to When the memory for an array is allocated, its base
the value of the variable to which it points by using address is fixed and it cannot be changed during
unary ‘*’ operator. Program execution.
. The address of a memory location is a pointer When we dynamically allocate memory for variables,
constant, therefore it cannot be changed in the heap acts as a memory pool from which memory is
program code. allocated to those variables. The process of allocating
Unary increment and decrement operators have memory tothe variables during execution of the program
Breater precedence than the dereference operator (*). of at run time is known as dynamic memory allocation.
Null pointer is a special pointer value that is known malloc(), calloc(), and realloc returns a void
not to point anywhere. This means that a null pointer pointer if successful, else a NULL is returned.
does not point to any valid memory address. To Memory leakage occurs when memory is allocated
declare a null pointer you may use the predefined but not released when it is no longer required.
GLOSSARY
Dereference To look up a value referred to. Usually, the points to, In C, a pointer is dereferenced either using the
‘value referred to’ is the value pointed to by a pointer. unary * operator or the array subscripting operator [].
Therefore, ‘dereference a pointer’ means to see what it Function pointer {tis a pointer to any function type.
Pointers 377
tvalue An expression that appears on the left-hand sign Null pointer constant It is an integral constant expression
of an assignment operator, hence, something that can with value 0 (or such an expression cast to void *), that
perhaps be assigned to. An lvalue specifies something that represents a null pointer.
has a location, as opposed to a transient value. Pointer It is a variable that stores addresses,
Null pointer A pointer value which is not the address Rvalue An expression that appears on the right-hand sign
of any object or function. A null pointer points to of an assignment operator. Generally, rvalue can participate
nothing. in an expression or be assigned to some other variable.
EXERCISES
Fill in the Blanks ,- can be used as parameter declaration to declare
1, Size of character pointeris an array of integers passed to a function.
2. Allocating memory at run time is known as 23. Dynamically allocated memory can be referred using
3. Apointer to a pointer stores _ _of another
variable. 24 ____ function returns memory to the heap.
4, ___ pointer does not point to any valid memory 25. Ragged array is implemented using an array of pointers
address, to =
5. The size of memory allocated for a variable depends on
ir, Multiple-choice Questions
6. On 16-bit systems, integer variable is allocated 1. The operator * signifies a
bytes. (a) referencing operator (b) dereferencing operator
7, The______s appears on the right side of the assignment (c) address operator (d) none of these
statement 2. *(&num) is equivalent to writing
8. Pointers are nothing but (a) &aum (b) *num
9. ____ enable programmers to return multiple values
from a function via function arguments.
(c) num (d) none of these
10, The Operator informs the compiler that the
3. Pointers are used to create complex data structures like
variable is a pointer variable (a) trees (b) linked list
Data and programs need to be placed in the __ _for (c) stack (d) queve
execution. (e) all of these
When compared with heaps, _ are faster but also 4. While declaring pointer variables, which operator do we
smaller and expensive. use?
All variables declared within main() are allocated space (a) address (b) arrow
onthe {e) indirection (d) dot
Shared libraries segment contains
5. Which operator retrieves the lvalue of a variable?
The malloc() function returns
(a) & (b) *
. When memory is de-allocated using free(), it is
returned back to the _within the (c) -> (d) None of these
The malloc(), calloc(), and realloc functions return 6. The code of the main() program is stored in memory in
if successful, else _ is returned (a) stack (b) heap
. The realloc() function is used to {c) global (d) bss
A two-dimensional array is a_ 7. For dynamically allocated variables, memory is allocated
. An un-initialized memory contains = from which memory area?
The only integer value that can be assigned to a pointer (a) Stack (b) Heap
variable is __ {c) Global (d) BSS
378 ‘Computer Fundamentals
and Programming in C
(a) malloc() (b) calloc() Explain the result of the following code
int numl = 2, num2 = 3;
(c) realloc() (d) free()
int *p = &numl, *q = &num2;
epee = 9qees
What do you understand by a null pointer?
State True or False
What is an array of pointers? How is it different from a
1. Apointer is a variable.
pointer to an array?
2. The & operator retrieves the Ivalue of the variable.
Write a short note on pointer arithmetic.
3. Array name can be used as a pointer. How are generic pointers different from other pointer
4, Unary increment and decrement operators have greater variables?
precedence than the dereference operator.
What do you understand by the term pointer to a
5. The generic pointer can be pointed at variables of any
function?
data type.
Differentiate beween ptr++ and *ptr++
6. A function pointer cannot be passed as a function's
How are arrays related to pointers?
calling argument.
Briefly explain array of pointers.
7, On 32-bit systems, integer variable is allocated 4 bytes
Give the advantages of using pointers.
8. Lvalue cannot be used on the left side of the assignment
Can we have an array of function pointers? If yes,
statement
illustrate with the help of a suitable example.
9. Pointers provide an alternate way to access individual
Explain the term dynamic memory allocation
elements of the array.
Differentiate between malloc(), calloc, and realloc()
10, Pointer is a variable that represents the contents of a
data item Write a short note on pointers to pointers.
Differentiate between a function returning pointer to
11, A fixed size of stack is allocated by the system and is filled
as needed from the top to bottom.
int and a pointer to function returning int
12. All the parameters passed to the called function will be Differentiate between pointer to constants and constant
stored on the stack.
to pointers
13. When the memory for an array is allocated, its base Explain the call by address technique of passing
parameters to function.
address is fixed and it cannot be changed during program
execution. How are pointers used on two-dimensional arrays?
14. An array can be assigned to another array. How can you declare a pointer variable?
15, Memory leakage occurs when memory is allocated but Differentiate between a variable address and a variable’s
not released when it is no longer required. value. How can we access a variable’s address and its
16. mat(i]}[4] is equivalentto *(*(mat + i) + 3) value using pointers?
17, Dangling pointers arise when an object is deleted or de- Givea brief summary of different memory areas available
to the programmer.
allocated, without modifying the value of the pointer.
What do you understand by dereferencing a pointer
18. It is possible to add two pointer variables
19, Pointer constants cannot be changed.
variable?
Write a short note on pointer expressions and pointer
20, The value of a pointer is always an address.
arithmetic.
21. *ptr++ will add 1 to the value pointed by ptr.
What will *p++ = #q++ do?
22. Pointers of different types can be assigned to each other
Write 3 short note on pointer and a three-dimensional
without a cast.
array.
23. Adding 1 to a pointer variable will make it point 1 byte
How can a pointer be used to access individual elements
ahead of the memory location to which it is currently
pointing,
of an array? Illustrate with an example.
24, Any arithmetic operator can be used to modify the value Can we assign a pointer variable to another pointer
variable? Justify your answer with the help of an
of a pointer.
example.
25. Only one call to free() is enough to release the entire
31 What will happen if we add or subtract an integer to or
array allocated using calloc()
from a pointer variable?
26. Ragged arrays consume less memory space.
Pointers 379
32. Is it possible to compare two pointer variables? Wlustrate 16. Using a program, explain how pointer variables can bé
using an example. used to access strings.
33, Can we subtract two pointer variables? 17. Write a program to print “Good Morning” using pointers.
34. With the help of an example explain how an array can be 18. Write a program to print the lowercase characters into
Passed to a function? Is it possible to send just a single uppercase and vice versa in the given string “gOOd
element of the array to a function? moORninG”
35. Can array names appear on the left side of the 19. Write a program to copy “University” from the given
assignment operator? Why? string “Oxford University Press” in another string.
36. Differentiate between an array name and an array 20. Write a program to copy last five characters from the
pointer. given string “Oxford University Press” in another
37 How can you have array of function pointers? Illustrate string.
with an example. 21 Write a menu-driven program to perform various string
38. Briefly discuss memoryallocation schemes in C language operations using pointers
39. Write a short note on realloc(). Give a program to 22 Write a program to read and print a floating point array.
explain its usage. The space for the array should be allocated at the run
40. With the help of an example, explain how pointers can time.
be used to dynamically allocate space for two 23. Write a program to demonstrate working of calloc()
dimensional and three-dimensional arrays. 24. Write a function to calculate roots of a quadartic
41 Write a short note on wild pointers. equation. The function must accept arguments and
42 Give a brief description of memory leakage problem return result using pointers.
with the help of an example 25. Write a program using pointers to insert a value in an
43, What is a dangling pointer? array.
44 Explain memory corruption with the help of suitable 26. Write 3 program using pointers to search a value from
examples. an array.
45, Differentiate between * (arrei) and (arrei) 27. Write a function that accepts a string using pointers. In
46. How can we access the value pointed by a pointer to a the function, delete all the occurrences of a given
pointer? character and display the modified string on the screen.
28. Write a program to reverse a string using pointers.
Programming Exercises 29. Write a program to compare two arrays using pointers
1 Write a program to print ‘Hello World’ using pointers.
2 Write a program to enter a lowercase character. Print Find the output of the following codes.
this character in uppercase and also display its ASCH! 1 main()
value {
Write a program to subtract two integer values. int arr[)*{1,2,3,4,5};
Write a program to calculate area of a circle int *ptr, 1;
ANNEXURE 3
Deciphering Pointer Declarations Now decipher the following declaration
‘The right-left rule is a widely used rule for creating as well int *(*func())();
as deciphering C declarations, Before starting. let us first
understand the mes ing of different symbols and the way in Step 1: Find the identifier. Here, the identifier is func, So we
which they are read. can say,
func is
Symbol | Read as Location
* pointerto | placed
on the left side Step 2: Identify the symbols on the right side of the identifier
until you run out of symbols or encounter a right parenthesis.
Uh pon eeeel Here. the symbol is (). So say
0 function
returning func is function returning
The following are the steps to decipher the declaration Step 3: Move to left of the identifier until you run out of
symbols or encounter a left parenthesis, Here, the symbol is
Step 1: Find the identifier and read as ‘identifier is*
*. So say,
Step 2: Read the symbols on the right of the identifier. For
example, if you find ‘( )', then you know that it is a function
func is function returning pointer to
declaration, So you can now say, “identifier is function Step
4: Can't move left anymore because of the left parenthesis,
returning’. Orif you encounter a °[ |’, then read it ax “identifier so now mave to right. Here, you will encounter a symbol ().
is array of So say,
Continue moving right until you either run out of symbols or func is function returning pointer to
you encounter a right parenthesis. function returning
Step3: Now, check the symbols to the left of the identifier. If it Step 5: Can't move right anymore as all symbols have
is not a symbol given in the table, then just say it, For example exhausted so move to left, Here you will encounter a ‘*', So
if you encounter int, then just say it as it is. Otherwise, say,
translate it into English using the above table. Continue going
left until you cither run out of symbols or you encounter a left func is function returning pointer to
parenthesis, function returning pointer to
Step 4: Repeat Steps 2 and 3 until the entire declaration is Step6:Continue moving left. Here you will find int. So say,
completely deciphered func is function returning pointer to
Consider some examples: function returning pointer to int.
int *ptr[];
Some declarations also contain array size and function
Step 1: Find the identifier. Here, the identifier is ptr. So we parameters. So if you encounter a symbol as *[10)', then read
can say, it as ‘array (size 10)’. If you encounter, something like ‘(int
*, char)’, then read it as ‘function expecting (int *, char) and
‘ptr is*
returning..... Now consider such an example and decipher the
Step 2: Identify the symbols on the right side of the identifier following declaration:
unul you run out of symbols or encounter a right parenthesis. int (*(*func)(int *, char))(3][5];
Here, the symbol is []. So we can say
Use the steps illustrated above and check your answer.
‘ptr is array of’
func is pointer to function expecting (int
Step 3: Move to left of the identifier until you run out of symbols *,char) and
‘or encounter a left parenthesis, Here, the symbol is *. So we returning pointer to array (size 3) of array
can say, (size 5) of int.
ees
what is legal in C and what is not allowed in the language. For Let us look as some more illegal combinations in C
example, consider a declaration as shown: language
int *((*fune)Q) 05 (JO-€ does not permit an array of functions
Thiscan
bedeciphered asfunc4 pointer to function Buk sonia abit pach sparta
returning array of array of pointer to int. But
did you notice that a function cannot return an array, butonlya ‘The table given below lists the declaration, meaning,
pointer to an array. Therefore, this declaration is illegal and its remarks as valid or invalid.
Declaration Meaning Remarks
‘oat nam;— um is a float Valid
char *ch; ch is pointer to char Valid
int are{}; art is an array of int Valid
float fune(); fune is a function returning float Valid
int **ptr; pir is a pointer to pointer to int | Nalid |
E (* pti}: ptrisa pointer to array of char | Nalid
|char(* pir), ptr is a pointer to function returning char Vata
float *ptrl}: ptr is array of pointers to float Valid
jet moat] |}; mat is an array of array of int Valid
int fane{}O func is an array of function returning int Invalid
float *fune(): func is a function returningpointer to float Valid
float func()[}; func is a function returning array of float Invalid
float fancy iO: func is a function returning function returning float Invalid
int ** *ptr, pir isa pointer to pointer topointer
to int Valid
int (* *pir){]; ptr is a pointer to pointer to array of int Valid
float (* * func, fune is a pointer to
pointer to a function returning float Valid
char *(* put]: _|
pit is a pointer to array of pointer tochar Valid
float (* pred): ptr is a pointer to array of array of float Valid
float (*ptry[}0; __| ptr is a pointer toarray of function returning float __ |Howalid
char *(* (piri), ptr is a pointer to function returning a pointer to char Valid
char (* pinot: ptr is a pointer to
function returning an array of char |
tavatia
fot (* pts ptr is a pointer to function returning function returning int Invalid
float * *purl}: ptr is an array of pointer to pointer to int Valid
char (* ptrt11: ptr is array of pointer to array of char Valid
char (* ptr] 0s pu is array of pointer to function returning char Valid
float * ptrl
IL; ptr is array of array of pointer to float Valid
toe arelIEE: [arr is array of array of array of int _| Valid
int arr{ILI0; "[ arr is array of array of function returning int Tiewatia |
float *aer[ JO; arr is array of function returning pointer to float Invalid
int arrfJOU): att is array of function returning array of int Invalid
float * *fune(); func is a function returning pointer to float pointer (or pointer to float) |
Vaid
char *funct)[}; func is a function returning array of char pointer Invalid
Moat (*funcd)){}; func is a function returning pointer to array of float Valid
float (*func())O; func is a function returning pointer to function returning float Valid
char func(III1: func is a function retuming array ofarray of char | invalid
char funeQ[}O; func is a function returning array of array of function returning char Invalid
char *funcO); func is a function returning function returning char pointer Invalid
384 Computer Fundamentals and Programming in C
char course(20);
ERB intropuction float fees;
A sstructure is a user-defined data type that can store related
information (even of different data types) together. It is Now, the structure has become a user-defined data type.
similar to records and can be used to store information Each variable name declared within a structure is called
about an entity, The major difference between a structure a member of the structure, The structure declaration,
and an array is that an array contains related information however, docs not allocate any memory or consume
of the same data type. storage space. It just gives atemplate that conveys to the C
A structure is, therefore, a collection of variables under compiler how the structure should be laid out in memory
a single name. The variables within a structure are of and gives details of the member names. Like any other
different data types and each has a name that is used to data type, memory is allocated for the structure when we
sclect it from the structure declare a variable of the structure. For example, we can
define a variable by writing
15.1.1 Structure Declaration struct student stud2;
Astructure is declared using the keyword struct followed Here, struct student is a data type and stud1 is a
by the structure name. All the variables of the structure are variable. Look at another way of declaring variables. In
declared within the structure. A structure type is generally the following syntax, the variable is declared at the time
declared by using the following syntax: of structure declaration.
struct struct-name struct student
Medd as {
{
not forgetto data_type var-name; int r_no;
eiepesendyy data_type var-name; char name[20];
char course[20];
structures
andunions. float fees;
}studl, stud2;
For example, if we have to define a structure for a
student, then the related information probably would be In this declaration we declare two variables stud1
roll_number, name, course, and fees. This structure and stud2 of the type student. So if you want to declare
can be declared as: more than one variable of the structure, then separate the
struct student
variables using a comma
When we declare variables of the structure, eparate
{
int r_no;
memory is allocated for cach variable, This shown in
char name[20]; Figure 15.1
Structure, Union, and Enumerated Data Type 387
Tip: Solution
Programming Tip: truct BOOK
Use different member ai
names for different char title[20];
structfor ure s.
clarity char author[20);
int pages;
float price;
int yr_of_publication;
i
Example 15.5
Variable name with the data type name (new). Therefore, data_type member_name1;
to define an integer variable, we may now write Programming Tip: data_type member_name2;
btalhiliaS areas data_type member_name3;
INTEGER num=
celeste ~~ s
When we precede a struct name with typedef
another type. :
keyword, then the struct becomes a new type. It is used
to make the construct shorter with more meaningful names struct struct_name struct_var = {constant1,
for types already defined by C or for types that you have constant2, constant 3,...};
declared. A typedef declaration is a synonym for the type.
For example, writing For example, we can initialize a student structure by
writing
typedef struct student
{ struct student
int r_no; {
char name[20]; int r_no;
char course[20); char name[20];
float fees; char course[20];
i float fees;
}studi = {01, "Rahul", "BCA", 45000};
Now that you have preceded the structure's name with
the keyword typedef, student becomes a new data type. or by writing
Therefore, now you can straightaway declare variables struct student studl = (01, "Rahul", "BCA",
of this new data type as you declare variables of type 45000};
int, float, char, double, cic. To declare a variable of
structure student you will just write Figure 15.2 illustrates how the values will be assigned
to the individual fields of the structure.
student stud1;
Note that we have not written struct student studi
struct student stud
= (O01, "Rahul", "BCA", 45000);
15.1.3 Initialization of Structures
A structure can be initialized in the same way as other
[or] [itabat] [nea 45000,
om) name fees
data types are initialized. /nitializing a structure means
assigning some constants to the members of the structure. Struct student stud2 « (07,"Rahul");
When the user docs not explicitly initialize the structure,
thenCautomatically does that. For int and float members, (07) [ram] [0] [Loo]
the values are initialized to zero and character and string r_no name course fees
members are initialized to *\0" by default (in the absence
of any initialization done by the user), Figure 15.2 Assigning values to structure members
The initializers are enclosed in braces and are separated
by commas. However, care must be taken to see that the
When all the members of a structure are not initialized, it
initializers match their corresponding types in the structure
is called partial initialization. In case of partial initialization,
definition,
first few members of the structure are initialized and those
The general syntax to initialize a structure variable is
that are uninitialized are assigned default values.
given as follows:
struct struct_name 15.1.4 Accessing the Members of a Structure
{
data_type member_namel; Each member of a structure
data_type member_name2; Amember of the can be used just like a normal
data_type member_name3; structure cannot be variable, but its name will be a
accessed directlyusing bit longer. A structure member
}struct_var = {constant1, constant2, its name. Rather you variable is generally accessed
constant 3,...)}; must use the structure using a '.' (dot) operator. The
name followed by syntax of accessing a structure
OR the dot operator or a member of a structure can
struct struct_name before specifying the be givenas follows:
{ member name. struct_var.member_name
Structure, Union, and Enumerated Data Type 389
Simple Addition
Ofall the operators -> ,.,(), and [} have the highest
priority. This is evident from the following statement: In this technique, we will make a list of all data type:
and add the memory required by each. For example, let’s
studl.fees++ will be interpreted as (studi. consider a simple structure of an employee.
fees)++
struct Employee
{ intemp_I0;
15.1.5 Copying and Comparing Structures char name[20];
We can assign 4 structure to another structure of the double salary;
same type, For example, if we have two structure char designation[
20];
variables studi and stud2 of type struct student float experience;
given as i
struct student studi = Now, Size size of emp_ID + size of name + size of
Programming Tip:
Anarrorwill be {01, a Rahul",
il inact
BCA", salary + size of designation + size of experience
tedif 45000}; Size of emp_1D =2
yore you struct student stud2; Size of name = 20 x size of character
try to compare
two
structure variables. Then to assign one structure Size of salary = 8
variable to another we will write, Size of designation = 20 x size of character
Size of experience = 4
stud2 = studi;
This statement initializes the members of stud2 with
the values of members of studi. Therefore, now the
values of studi and stud2 can be given as shown in
Figure 15.3.
390 Computer Fundamentals and Programming in C
FEES = 5678
DOB = 9 9 91 15.4.2 Passing the Entire Structure
ssee0e**DETAILS OF STUDENT 2****8+8* Just like any other variable, we can pass an entire structure
ROLL No, = 2 as a function argument, When a structure is passed as an
NAME = kangana argument, it is passed using the call by value method, i.c.,
FEES = 7000 a copy of cach member of the structure is made. This is
008 = 27 8 92 a very inefficient method especially when the structure
is very big or the function is called frequently. In such a
situation, passing and working with pointers may be more
STRUCTURES AND FUNCTIONS efficient
The general syntax for passing a structure to a function
and returning a structure can be given as
For structures to be fully useful, we must have a mechanism
to pass them to functions and return them. A function may struct struct_name func_name(struct struct_
access the members of a structure in three ways as shown name struct_var);
in Figure 15.4. This syntax can vary as per need. For example, in some
situations We may want a function to receive a structure
but return a void or value of some other data type. The
Passing individual following code passes a structure to the function using the
members
call-by-value method.
break; 5. EXIT
case 3: Enter your option: 2
d3 = add_distance(d1, d2); Enter the first distance in kms and metres: 5 300
Structure, Union, and Enumerated Data Type 397
Enter the second distance in kms and metres: printf("\n The sum of the two time
3 400 values is: Xd hr Xd min %d sec”, t3.hr,
+eee* MAIN MENU *#86 t3.min, t3.sec);
Read the distances break;
Display the distances case 4:
Add the distances t4 = subtract_time(ti, t2);
Subtract the distances printf("\n The difference in time
EXIT is: Xd hr %d min Xd sec", t4.hr, t4.min,
Enter your option: 3 t4.sec);
The sum of two distances is: 8 kms 700 metres break;
)
9. Write a program to read, display, add, and subtract }while(option != 5);
two time variables defined using hours, minutes, and getch();
seconds, return 0;
#include <stdio.h> }
#include <conio.h> TIME add_time(TIME t1, TIME t2)
typedef struct {
{ TIME sum;
int hr; sum.sec = tl.sec + t2.sec;
int min; while(sum.sec >= 60)
int sec; {
}TIME; sum.sec -=60;
TIME ti, t2, t3, t4; sum.mine+;
TIME subteact_time(TIME, TIME); }
TIME add_time(TIME, TIME); sum.min = tl.min + t2.min;
int main() while(sum.min >= 60)
{ {
int option; sum.min -=60;
clrser(); sum. hre+;
do }
{ sum.hr = tl.hr + t2.hr;
printf("\n **** MAIN MENU ****"); return sum;
int main() 13. Write a program to read, display, add, and subtract two
{ heights. Height should be given in feet and inches.
int P
for (i=0;1<2;i++) #include <stdio.h>
{ #include <conio.h>
ptr[i] = (struct student *)malloc(size typedef struct
of(struct student)); {
printf("\n Enter the data for student int ft;
int inch;
Md ",i91);
printf("\n ROLL NO.
HEIGHT;
scanf("Xd", &ptr[i] -> r_no);
print#("\n NAME: "); HEIGHT hi, h2, h3;
gets(ptr[i] -> name); HEIGHT add_height(HEIGHT +, HEIGHT +);
HEIGHT subtract_height(HEIGHT *, HEIGHT *);
print#("\n COURSE: “);
gets(ptr[i] -> course);
int main()
printf("\n FEES: ");
{
int option;
scanf("Xd", &ptr[i] -> fees)
clrser();
) do
printf("\n DETAILS OF STUDENTS”);
for(iw0;i<2;i++) {
printf("\n *** MAIN MENU ***");
{
printf("\n ROLL NUMBER = Xd",
printf("\n 1. Read height ");
printf("\n 2. Display height");
ptr_stud[i] -> r_no);
printf("\n 3. Add");
printf("\n NAME = Xs", pte_stud[i] ->
name);
printf("\n 4. Subtract");
printf("\n COURSE = Xs", ptr_stud[i] ->
printf("\n 5. EXIT");
printf("\n Enter your option: ");
course);
scanf("Xd", Soption);
printf("\n FEES = Xd", ptr_stud[i] ->
switch(option)
fees);
{
} case 1:
return 0;
printf("\n Enter the first height in feet
} and inches: *);
Output scanf("Xd Xd", &h1.f#t, &h1.inch);
Enter the data for student 1
printf("\n Enter the second height in feet
ROLL NO.: O21
and inches: *);
NAME: Rahul scanf("%d Ad", &h2.ft, &h2.inch);
COURSE: BCA break;
FEES: 45000 case 2:
printf("\n The first height is: %d ft %d
Enter the data for student 2 inch", h1.ft, hi.inch);
ROLL NO. :02 printf("\n The second height is: Xd ft Xd
NAME: Priya inch", h2.#t, h2.inch);
break;
COURSE: BCA
case 3:
FEES: 25000 h3 = add_height(&h1, &h2);
DETAILS OF STUDENTS printf("\n The sum of two heights is: %d
15. Write a program to illustrate the use of arrays within a Enter the marks obtained in three subjects by
structure student 2: 90 100 89
oe ee eDETAILS*
e+e
#include <stdio.h>
NAME — = Goransh
#include <conio.h> ROLL NO = O1
#include <alloc.h>
MARKS = 99 100 99
typedef struct student
NAME = Pranjal
{ ROLL NO = 02
char name[20);
MARKS = 90 100 89
int roll_no;
int marks(3);
hi
GGED seLF-REFERENTIAL STRUCTURES
void display(struct student* s)
{ Self-referential structures are those structures that contain
int i; a reference to data of its same type, i.c., in addition to
printf("\n NAME » Xs \n ROLL NO = other data, a self-referential structure contains a pointer
Xd\n", s => name, s -> roll_no); to a data that is of the same type as that of the structure.
printf("\n MARKS = “); For example, consider the structure node given as follows:
for(i = Osi < 35444) struct node
{
printf(" %d", s -> marks[{i]); int val;
} struct node *next;
int main()
i
{
struct student *s[2]; Here the structure node will contain two types of data—an
int 4,3; integer val and next, which is
clrscr(); @ pointer to a node. You must
Programming
for(i = O54 < 2;44+) Mead be wondering why we need
{ elsthunih such a structure, Actually,
s[i}=(struct student*) astructure/union self-referential structure is
malloc(sizeof(struct student)); heedatet a the foundation of other data
printf("\n\n Enter the name of student obec structures. Their purpose will
Xd: “, 442); Waele beclear to you when
you study
gets(s[i] -> name); union type union, linked list representation of
respectively,
printf("\n Enter the roll number of data structures.
student Xd: ", ivl);
scanf("Xd", &s[i] -> roll_no);
printf("\n Enter the marks obtained in 115.6 MUON
three subjects by student %d: “, iv1);
for(j = O;j < 3;j++) Similar to structures, a union is a collection of variables
scanf("%d",&s[i] -> marks{j]); of different data types. The only difference between a
} structure and a union is that in case of unions, you can
printf("\n \n\n *****DETAILS*+** only store information in one field at any one time,
for(ie0;i<2;i++) To better understand a union, think of it as a chunk of
display(s[i}); memory that is used to store variables of different types.
getch(); When a new value is assigned to a field, the existing data
return 0; is replaced with the new data.
} Thus unions are used to save memory. They are useful
Output
for applications that involve multiple members, where
values need not be assigned to all the members at any one
Enter the name of student 1: Goransh time
Enter the roll number of student 1: 01
Enter the marks obtained in three subjects by 15.6.1 Declaring a Union
student 1; 99 100 99
Enter the name of student 2: Pranjal The syntax for declaring a union is the same as that of
Enter the roll number of student 2: 02 declaring a structure. The only difference is that instead
Structure, Union, and Enumerated Data Type 403
of using the keyword struct, the keyword union would printf("\n The co-ordinates of P1 are %d
be used, The syntax for union declaration can be given as and Xd", Pl.x, Pl.y
printf("\n The co-ordinates of P2 are Xd
union union-name
and Xd", P2.x, P2.y);
{ return 0;
data_type var-name;
data_type var-name;
}
Output
hi The co-ordinates of P1 are 2 and 3
Again,
the typedef keyword The co-ordinates of P2 are 5 and 5
tidinteshed es can be used to simplify the
In this code, POINT! is a structure name and POINT2 is &
Vorebie ofasvucture declaration of union variables. union name. However, both the declarations are almost same
The most important thing
(except the keywords—struct and union); in main(), you
sonatas to remember about a union is
see a point of difference while initializing values. The fields
sructire/union that the size of a union is the
of a union cannot be initialized all at once
ethane bea A size of its largest field. This is
Look at the output carefully. For the structure variable
edaaa mace und because sufficient number of the output is fine but for the union variable the answer
ab) bytes must be reserved to store does not seem to be correct
the largest sized field.
To understand the concept
Programming Tip: of union, execute the following
15.6.2 Accessing a Member of a Union The sizeofa union code, The code given below
Amember of a union can be accessed using the same syntax
is equal to the just re-arranges the printf
as that ofa structure. To access the fields of a union, use the sizeofitslargest statements, You will be
dot operator (.), i.c., the union variable name followed by
member. surprised to see the result
the dot operator followed by the member name. include <stdio.h>
typedef struct POINT1
15.6.3 Initializing Unions {
int x, y;
A striking difference between hi
Nad a structure and a union is
eel tect that in case of a union, the typedef union POINT2
meats
ihermember
union except men
fieldsisshare€ the: anesame par
the first member. sh data replaces
a existing data.
Look at
the following code and observe the difference between a
structure and union when their fields are to be initialized. int main()
#include <stdio.h> {
typedef struct POINT1 POINT1 P1 = {2,3};
{ POINT2 P2;
int x, y; printf("\n The co-ordinates of P1 are %d and
hi Xd", Pl.x, Pl.y);
P2. x = 4;
typedef union POINT2 printf("\n The x co-ordinate of P2 is Xd",
{ P2.x)5
int P2.y = 5
int y; printf("\n The y co-ordinate of P2 is Xd",
ny P2.y)5
int main() return 0;
{ }
POINT2 Pl = {2,3}; Output
// POINT2 P2 ={4,5}; Illegal with union
The co-ordinates of Pl are 2 and 3
POINT2 P2;
The x co-ordinate of P2 is 4
P2.x = 45 The y co-ordinate of P2 is 5
P2.y = 55
Here although the output is correct, the data is still over-
written in memory.
404 Computer Fundamentals and Programming in C
printf("\n YELLOW = Xd", YELLOW); for declaring a variable of an enumerated data type can be
printf("\n PURPLE = Xd", PURPLE); given as
printf("\n WHITE = Xd", WHITE);
return 0; enumeration_name variable_name;
} So to create a variable of COLORS, we may write
Output enum COLORS bg color;
RED = 2 This declares a variable called bg_color, which is of the
BLUE = 3 enumerated data type, COLORS. Another way to declare
BLACK = 5 a variable can be as illustrated in the following statement
GREEN = 7
YELLOW = 8
enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW,
PURPLE = 9
PURPLE, WHITE}bg_color, fore_color;
WHITE = 15
| POINTS TO REMEMBER
© Structure is basically a user-defined data type that can by default.
store related information (even of different data * A structure member variable is generally accessed
types) together. The major difference between a usinga’ .* (dot operator).
structure and an array is that an array contains related A structure can be placed within another structure.
information of the same data type That is, a structure may contain another structure as
© A structure is declared using the keyword struct its member. Such a structure is called a nested
followed by a structure name. The structure definition, structure.
however, does not allocate any memory or consume * Self-referential structures are those that contain a
storage space. It just gives a template that conveys to reference to data of its same type. That is, a self-
the C compiler how the structure is laid out in memory referential structure, in addition to other data,
and gives details of the member names. Like any other contains a pointer to data that is of the same type as
data type, memory is allocated for the structure when that of the structure.
we declare a variable of the structure. A union is a collection of variables of different data
« When we precede a struct name with typedef types in which memory is shared among these
keyword, then the struct becomes a new data type. variables. The size of a union is equal to the size of its
* When the user does not explicitly initialize the largest member.
structure C automatically does this, For int and float The only difference between a structure and a union is
members, the values are initialized to zero and that in case of unions information can only be stored
character and string members are initialized to *\0' in one member at a time.
GLOSSARY
Enumerated data type An enumeration consists of a set structure, When the user does not explicitly initialize
of named integer constants. the structure C automatically does this. For int and
Nested structure A structure placed within another float members, the values are initialized to zero and
structure, i,¢., a structure that contains another structure character and string members are initialized to the *\0'
as its member, by default.
Self-referential structures Structures that contain a Typedef declaration When we precede a struct name
reference to data of its same type. A self-referential with typedef keyword, then struct becomes a new data
structure, in addition to other data, contains a pointer to a type. It is used to make the construct shorter with more
data that is of the same type as that of the structure. meaningful names for types already defined by C or for
Structure Structure is a user-defined data type that can types that you have declared. A typedef declaration is a
store related information (even of different data types) synonym for the type.
together. Union A union is a collection of fields of different data
types in which information can be stored in one field at
Structure initialization Initializing a structure means
atime.
assigning some constants to the members of the
EXERCISES
Fill in the Blanks different data type(s)
1, Structure is a data type. 5. Memory is allocated for a structure when is
2, Astructure is similar to __ done.
3 ___ contains related information of the same data 6 ____ is just a template that will be used to reserve
type. memory when a variable of type struct is declared
4 contains related information of the same or
Structure, Union, and Enumerated Data Type 409
A is a collection of variables under a single 7. Typedef can be used with which of these data types?
name. (a) struct (b) union
8. A structure is declared using the keyword struct {c) enum (d) All of these
followedbya_ 8. The enumerated type is derived from which data type?
9, When we precede a struct name with , then
(a) int {b) float
struct becomes a new data type.
10, For int and float structure members, the values are ({c) double (d) char
initializedto
11, Character and string structure members are initialized State True or False
to_ by default 1 Structures contain related information of the same data
12. A structure member variable is generally accessed using type.
a
A struct type is a primitive data type
13. A structure placed within another structure is called a Structure declaration reserves memory for the structure.
Initializing a structure means assigning some constants
14 structures contain a reference to data of their to the members of the structure.
same type. When the user does not explicitly initialize the structure
15, The keyword typedef is used to C automatically does this.
| is a collection of data under one name in which The dereference operator is used to select a particular
memory is shared among the members. member of a structure
17. The selection operator is used to New variables can be created using the typedef
18. __ permits sharing of memory among different keyword.
types of data. Memory is allocated for a structure only when we
declare variables of the structure.
Multiple-choice Questions A nested structure contains another structure as its
1, A data structure that can store related information member.
together is C permits copying of one structure variable to another.
Unions and structures are initialized in the same way.
(a) array (b) string
A structure cannot have a union as its member,
(c) structure (d) all of these
C permits nested unions,
2, A data structure that can store related information of
In an enumerated type, an integer value can be assigned
different data types together is
to only one enumeration constant
(a) array (b) string
Declaring an enumerated type automatically creates a
{c) structure (d) all of these variable.
3. Memory for a structure is allocated at the time of The identifiers in an enumerated type are automatically
(a) structure definition assigned values.
(b) structure variable declaration A field in a structure can itself be a structure.
{c) structure declaration No two members of a union should have the same name.
No two identifiers in an enumerated type must have the
(d) function declaration
same value.
4, A structure member variable is generally accessed using
the 20. A union can have another union as its member.
(a) address operator {b) dot operator 21 Aunion can be a member of a structure.
(c) comma operator (d) ternary operator
Review Questions
5, Astructure can be placed within another structure and is 1 What is the advantage of using structures?
known as
2 Differentiate between a structure and a union.
(a) self-referential structure 3. How is a structure name different from a structure
{b) nested structure variable?
(c) parallel structure Structure declaration reserves memory for the structure.
(d) pointer to structure Comment on this statement with valid justifications.
6. Aunion member variable is generally accessed using the Differentiate between a structure and an array,
(a) address operator (b) dot operator Write a short note on structures and interprocess
communication.
(c) comma operator (d) ternary operator
410 ‘Computer Fundamentals
and Programming in C
bon Explain the utility of typedef keyword in structures. 18. Write a program to define a structure vector. Then write
Explain with an example how structures are initialized. functions to read data, print data, add two vectors, and
ed\s it possible to create an array of structures? Explain scale the members ofavector by a factor of 10.
with the help of an example 19. Write a program to define a structure for a hotel that has
10, What do you understand by a union? members’ name, address, grade, number of rooms, and
11. Differentiate between a union and a structure. room charges. Write a function to print the names of a
12. Explain how members of a union are accessed using a hotel in a particular grade. Also write a function to print
program code. names of a hotel that have room charges less than the
specified value.
13, In which applications unions can be useful?
20. Write a program to define a union and a structure both
14, Write a short note on nested structures.
having exactly the same members. Using the sizeof
Programming Exercises operator, print the size of structure variable as well as
1, Write a program using structures to read and display the union variable and comment on the result
information about an employee. 21 Declare a structure time that has three fields—hr, min,
2, Write a program to find the smallest of three numbers sec. Create two variables start_time and end_time. Input
using structures. their values from the user. Then while start_time does
not reach the end-time, display GOOD DAY on the screen.
3. Write a program to calculate the distance between the
given points (6,3) and (2,2). 22 Declare a structure fraction that has two fields—
4, Write a menu-driven program to add and subtract 5+6i numerator and denominator. Create two variables and
and 4-2i,
compare them using function. Return 0 if the two
fractions are equal, —1 if the first fraction is less than the
5. Write a program to read and display the information
second and 1 otherwise. You may convert a fraction into
about an employee using nested structures.
a floating point number for your convenience.
6. Write a program to read and display the information
23. Declare a structure POINT. Input the co-ordinates of a
about the entire faculty of a particular department
point variable and determine the quadrant in which it
7, Write a program to read and display the information
lies. The following table can be used to determine the
about all the employees in a department. Edit the details
quadrant
of the i" employee and redisplay the information.
8, Write a program to add and subtract distances 6 km and
Quadrant_| ¥
300 m and 4 km and 700m.
9. Write a program to add and subtract heights 6'2” and 5’4” } .1 |__
} Positive
1 -Positive |
} 2 t| Negative Positive
E _|
10. Write a program to add and subtract 10 hr 20 min 50 sec f 3 | Negative Negative _ |
and 5 hr 30 min 40 sec. 4 | Positive Negative
11, Write a program that uses a structure called date that
has It passed to an isLeapYear function to determine if 24 Write a program to calculate the area of one of the
the year is a leap year geometric figure—circle, rectangle, or a triangle. Write a
12, Write a program using pointer to structure to initialize function to calculate the area, The function must receive
the members in the structure. Use functions to print the one parameter which Is a structure that contains the
student's information. type of figure and the size of the components needed to
13. Write a program using pointer to structure to initialize calculate the area must be a part of a union. Note that a
the members in the structure using an alternative circle requires just one component, rectangle requires
technique. two components, and a triangle requires the size of
14. Define a structure date containing three integers—day, three components to calculate the area.
month, and year. Write a program using functions to 25. Write a program to create a structure with Information
read data, to validate the date entered by the user, and given below. Then read and print the data.
then print the date on the screen. For example, if you Employee!
10}
enter 29,2,2010 then that is an invalid date as 2010 is {a} Emp_id
not a leap year. Similarly 31,6,2007 is invalid as June (0) Name
does not have 31 days. (i) First Name
15. Using the structure definition of the above program, (li) Middle Name
write a function to increment that. Make sure that the (iii) Last Name
incremented date is a valid date. (ce) Address
16. Modify the above program to add a specific number of (i) Area
days to the given date. (ii) City
17. Using the structure definition of question 14, write 3
(iii) State
function to compare two date variables
Structure, Union, and Enumerated Data Type 4if
{ float price;
values val = {2, 3.4}; }product p[10];
printf("\n Xd Xf", val.i, val.f);
change(&val, 5, 7.9); Find errors in the following statements.
printf("\n Xd Xf", val.i, val.f); 1 struct student
} {
char name[20];
Find errors in the following structure definitions. int id;
1. struct }name = "Ram", 9;
{ union student
int item code; {
float price; char name[20);
} int id;
2. struct product }s = {'Ram",01};
{
char prod_name[20);
Structure, Union, and Enumerated Data Type 413
—
ANNEXURE 4
BIT FIELDS IN STRUCTURE Let us look at a structure that has bit fields.
C facilitates the users to store integer members in memory struct
spaces smaller than what the compiler would ordinarily allow. {
‘These space-saving structure members are called bir fields. In unsigned short a: 2;
addition to this, C also permits the users to explicitly declare unsigned short b: 1;
int c: 7;
the width in bits, Bit fields are generally used in developing
application programs that force a data structure to correspond to
unsigned short d: 4;
a fixed hardware representation and are unlikely to be portable. a
Therefore, besides having declarators for members of a In the aforegiven structure, the size of the structure is 2
structure or union, a structure declarator can also be a specified bytes. Bit fields have the same semantics as the integer type.
number of bits, generally known as a bit field. A bit field is This means a bit field is used in expressions in exactly the
interpreted as an integral type. The syntax for specifying a bit same way as avariable of the same base type would be used,
field can be given as regardless of how many bits are in the bit field,
The C99 standard requires the allowable data types for a
type-specifier declarator: constant-
expression
bit field to include qualified and unqualified signed int and
unsigned int in addition to the following types:
In the syntax, the constant-expression is used to specify * im
the width of the field in bits. The type-specifier for the * short, signed short, and unsigned short
declarator must be unsigned int, signed int, or int, and the + char, signed char, and unsigned char
constant -expression must be a non-negative integer value. + long, signed long, and unsigned long
If the value of the constant expression is zero, the declaration + long long, signed long long, and unsigned long long
has no deelarator
struct employee
In the figure, char grade will reserve two bytes but {
stores the data only in the first byte since size of char is one char grade;
byte, Now int id has a size of two bytes and will search for int id;
two bytes but there is only one byte available so it will again int emp_code;
reserve the next two byte of memory space. That one byte float salary;
will be useless as it will not be used to store any data. Such a char promotion due;
useless byte is known as slack byte and the structure is called );
an unbalanced structure. aie employee_m
ha FED ON se
Output
TE} INTRODUCTION TO FILES keyboard, etc. Although files may differ in the form and
capabilities, all streams are the same.
A file is a collection of data stored on a secondary storage The three standard
device like hard disk. Till now, we had been processing streams (Figure 16.1) in C KEYBOARD
data that was entered through the computer's keyboard. language are as follows: stdin
But this task can become very tedious especially when * standard input
(stdin) PROGRAM
there is a huge amount of data to be processed. A better
solution, therefore, is to combine all the input data into a * standard output stdout stderr
file and then design a C program to read this data from the (stdout)
SCREEN
file whenever required. * standard error
Broadly speaking, a file is basically used because real- (stderr) Figure 16.1 Standard streams
life applications involve large amounts of data and in such
applications the console-oriented /O operations pose two Standard input (stdin) Standard input or the stream from
major problems, which the program receives its data. The program requests
transfer of data using the read operation. However, not all
* First, it becomes cumbersome and time-consuming to
programs require input. Generally, unless redirected, input
handle huge amount of data through terminals.
for a program is expected from the keyboard.
* Second, when doing V/O using terminal, the entire data is
Jost when either the program is terminated or computer is Standard output (stdout) Standard output is the stream
tured off, Therefore, it becomes necessary to store data where a program writes its output data, The program
on a permanent storage device (¢.g. hard disks) and read requests data transfer using the write operation, However,
whenever required, without destroying the data not all programs generate output
In order to use files, we have to learn file input and Standard error (stderr) Standard error is basically an
output operations, ic, how data is read from or written output stream used by programs to report error messages
to a file. Although file /O operations are almost same as or diagnostics. It is a stream independent of standard
terminal I/O, the only difference is that when doing file output and can be redirected separately. No doubt, the
1/O, the user must specify the name of the file from which standard output and standard error can also be directed to
data should be read/written. the same destination.
Astream is linked to a file using an open operation and
16.1.1 Streams in C dissociated from a file using a close operation
In C, the standard streams are termed as pre-connected
16.1.2 Buffer Associated with File Streams
input and output channels between a text terminal and the
program (when it begins execution). Therefore, stream is When a stream linked to a disk file is created, a buffer
a logical interface to the devices that are connected fo the is automatically created and associated with the stream.
computer, A buffer is nothing but a block of memory that is used
Stream is widely used as a logical interface to a file for temporary storage of data that has to be read from or
where a file can refer to a disk file, the computer screen, written to a file.
416 Computer Fundamentals and Programming in C
Butlers are needed because disk drives are block- Another important thing is
Programming Tip: .
oriented devices as they can operate efficiently when data that when a text file is used, there
The contentsof a
has to be read/written in blocks of certain size. An ideal are actually two representations
buffer size is hardware-dependent. hu adnote of data—internal or external.
juman-readable.
The buffer acts as an interface between the stream ion ithe For example, an int value
(which is character-oriented) and the disk hardware (which —_ will be represented as 2 or 4
storedinthe fil 5
is block-oriented). When the program has to write data to be the Heto bytes of memory intemally,
the stream, it is saved in the buffer till it is full. Then the % but extemally the int value
entire contents of the buffer are written to the disk as a Si Me ne will be represented as a string
block. This is shown in Figure 16.2 of characters representing its
decimal or hexadecimal value
Data from the To convert internal representation into extemal, we can
Program buffer is use printf and fprintf functions. Similarly, to convert
writes data written to the
an external representation into intemal scanf and fscanf
PROGRAM Ww buffer disk file
DISK can be used. We will read more about these functions in the
coming sections.
Figure 16.2 Buffers associated with streams
Similarly, when reading data from a disk file, the data Ina text file, each line of data ends with a newline
is read as a block from the file and written into the buffer. character. Each file ends with a special character called
The program reads data from the buffer. The creation and the end-of-file
(EOF) marker.
operation of the buffer is automatically handled by the
operating system. However, C provides some functions
for buffer manipulation, The data resides in the buffer Binary Files
until the buffer is flushed or written to a file.
A binary file may contain any type of data, encoded in
binary form for computer storage and processing purposes.
16.1.3 Types of Files Like a text file, a binary file is a collection of bytes, In C, a
In C, the types of files used can be broadly classified into byte and a character are equivalent. Therefore, a binary file
two categories—ASCII text files and binary files. is also referred to as a character stream with the following
two essential differences:
ASCII Text Files * Abinary file does not require any special processing of
the data and cach byte of data is transferred to or from
A text file is a stream of characters that can be sequentially the disk unprocessed
processed by a computer in forward direction. For this + C places no restrictions on the file, and it may be read
reason, a text file is usually opened for only one kind of from, or written to, in any manner the programmer
operation (reading, writing, or appending) at any given wants.
time, Because text files only process characters, they can
only read or write data one character at a time. In C, a text While text files can be processed sequentially, binary
stream is treated as a special kind of file, files, on the other hand, can be either processed sequentially
Depending on the requirements of the operating system or randomly depending on the needs of the application, In
and the operation that has to be performed (read/write C, to process a file randomly, the programmer must move
operation) on the file, newline characters may be converted the current file position to an appropriate place in the file
to or from carriage return/line feed combinations. Besides before reading or writing data. For example, if 4 file is
this, other character conversions may also be done to used fo store records (using structures) of students, then
satisfy the storage requirements of the operating system. to update a particular record, the programmer must first
However, these conversions occur transparently to process locate the appropriate record, read the record into memory,
a text file. update it, and finally write the record back to the disk at its
In a text file, each line contains zero or more characters appropriate location in the file.
and ends with one or more characters that specify the end
of line. Each line in a text file can have 4 maximum of
characters. A line in a text file is not a C string, so it is not
Binary files store data in the internal representation
terminated by a null character. When data is written to a
format. Therefore, an int value will be stored in binary
text file, each newline character is converted to a carriage
return/line feed character, Similarly, when data is read
form as a 2 or 4 byte value. The same format is used
from a text file, cach carriage return/line feed character is to store data in memory as well asinfile. Like text file,
converted into newline character. binary file also ends with an EOF marker,
Files 417
Look at the program given below which illustrates the to ensure that the memory pointed to by str must be large
use of fread(). enough to hold the number of objects being read.
#include <stdio.h> If you have opened a stream for updating and later
main() you want to switch from reading to writing or vice versa,
you must first use the fseek() or rewind() function
{
FILE *fp; However, if you have been reading and have reached
char str[11]; end-of-file, then you can immediately switch to writing.
fp = fopen("Letter.TxT”, “r+"); We will discuss the fseek() and rewind functions later
if (fpe=NULL) in this chapter.
{
printf("\n The file could not be opened”); GZ WRITING DATA TO FILES
exit(1);
} C provides the following set of functions to read data from
fread(str, 1, 10, fp); a file
/* In the str 10 objects of 1 byte are read
from the file pointd by fp */ * fprint#()
str[10)= *\0"; * fputs()
printf("\n First 9 characters of the file * fputc()
are: Xs", str);
* fwrite()
fclose(fp); In this section, we will read about these functions.
}
Output 16.4.1 fprintf()
First 9 characters of the file are: Hello how The fprint#() function is used to write formatted output
to stream. The syntax of fprintf() can be given as
Since fread() returns the number of bytes successfully
read, we can also modify the above program to print the int fprintf (FILE * stream, const char *
number of bytes read. This would be helpful to know how format, ...)3
many characters were read.
The function writes data that is formatted as specified
#include <stdio.h>
by the format argument to the specified stream. After the
main() format parameter, the function can have as many additional
{ arguments as specified in the format.
FILE *fp; The parameter format in fprintf() is nothing but a
char str[80); C string that contains the text that has to be written on
size_t bytes_read; to the stream. Although not mandatory, fprintf() can
fp = fopen("Letter.TXT", “re"); optionally contain format tags that are replaced by the
if (fpe*NULL) values specified in subsequent additional arguments and
{ are formatted as requested.
printf("\n The file could not be opened”);
exit(1);
}
bytes_read = fread(str, 1, 79, fp); There must be enough arguments for format because
str[bytes_readel]= ‘\0'; ifthere are not, then result will be completely
/* explicitly store null character at the unpredictable. However, ifby mistake you specify more
end of str */ number of arguments, the excess arguments will simply
printf("\n First Xd characters of the file be ignored.
are: Xs", bytes_read, str);
fclose(fp); The prototype of the format tag can be given as
}
The output will depend on the contents of the file. %{flags}(width)[.precision][length]specifier
Assuming 14 characters were read, the output can be given as Each format specifier must begin with a % sign, The %
Hello how ru? sign is followed by
This program assumes that you have created a file
Letter. TXT that contains 14 characters which have been flags which specifies output justification such as decimal
displayed above, point, numerical sign, trailing zeros, or octal or hexa-
The fread() function does not check for overflow in decimal prefixes. Table 16.3 shows the different types of
the receiving area of memory. It is the programmer's job flags with their description.
422 Computer Fundamentals and Programming in C
}
{Flags Description -_ for(i = O;i < 10;i++)
z Left justify within the given data field width {
puts("\n Enter your name: ");
\+ Displays thedatawithitsnumeric sign(either + of~) gets(name);
” ‘Used toprovide additional specifiers such as0,x,X,0, fflush(stdin);
Ox, ofOX for octal andhexadecimal values, respectively, puts("\n Enter your salary: ");
for values except zero.
scanf("xf", &salary);
(OE iT sraisee SNe peed we zara pasado Spaces fprintf(fp, " (%d) NAME: [%-10.10s]
\t SALARY %S.2f", i, name, salary);
width specifies the minimum number of characters to print }
after being padded with zeros or blank spaces fclose(fp);
}
precision specifies the maximum number of characters to
print Tip: Output
Programming
* Por integer specifiers (d, i, 0, u, x, X): precision flag Ifyou open a filefor Enter your name: Aryan
specifies the minimum number of digits to be written. writing usingwmode, "ter your salary: 50000
However, if the value to be written is shorter than then the contents of Enter your name: Anshita
this number, the result is padded with leading zeros. file will bedeleted. if Enter your salary: 65000
a file has to be used Enter your name: Saesha
Otherwise, if the value is longer, it is not truncated.
* For character strings, precision specifies the maximum for reading aswellas Enter your salary: 70000
number of characters to be printed. writting, it must be This example asks the user
opened in w+ mode to enter the name and salary
tength field can be explained as given in Table 16.4 of 10 people. Each time the
specifier is used to define the type and the interpretation of user enters the name and salary, the data read is written to
the value of the corresponding argument. Details. TXT. The names are written on new lines in the
The fprintf() function may contain some additional file. In this example, we have used three format tags:
parameters as well depending on the format string. Each * Xd to specify a signed decimal integer.
argument must contain a value to be inserted instead of * %-10.10s. Here — indicates that the characters must be
cach % tag specified in the format parameter, if any. In left aligned. There can be a minimum of 10 characters as
other words, the number of arguments must be equal to the well as a maximum of 10 characters (.10) in the strings.
number of % tags that expect a value. Xf to specify a floating point number,
Table 16.4 Length field in printf()
Length |Description
h ‘When the argument
isashort int orunsigned short if you want to use fprint¢ (} to write on the screen, then
int specify stdout instead of specifying any other file pointer,
4 When the argument isalong int orunsigned long
int forinteger specifiers 16.4.2 fputs()
55 ‘When theargument
isalong double (used for
floating
point specifiers) The opposite of fgets() is fputs(). The fputs() function
is used to write a line to a file. The syntax of fputs() can
Look at the program given below which demonstrates be given as
the use of fprint#(). int fputs(const char *str, FILE *stream);
#include <stdio.h> The fputs() function writes the string pointed to by
main() str to the stream pointed to by stream, On suc ful
{ completion, fputs() returns 0. In case of any error,
FILE *fp; fputs() returns EOF.
int i;
char name(20); #include <stdio.h>
float salary; main()
fp = fopen("Details.TxT", “w"); {
if (fp==NULL) FILE *fp;
{ char feedback[100};
printf("\n The file could not be opened”); fp = fopen("Comments.
TXT", “w");
exit(1); if (fp==NULL)
Files 423
FILE *fp; {
char feedback[100]; fputc(feedback[i], fp);
int i; if (ferror(fp))
fp = fopen("Comments.
TXT", w")5 {
if (fp==NULL) clearerr(fp);
{ break;
printf("\n The file could not be opened”); /* clears the error indicators and
exit(1); jumps out of for loop +/
} }
printf("\n Provide feedback on this book: }
gets( feedback) ; // close the file
for(i = 0; i < feedback{i};i++) fclose(fp);
fputc(feedback[i], fp);
if(ferror(fp))
{ 16.6.2 perror()
printf("\n Error writing in file");
exit(1); The perror() function stands for print error. In case of an
} error, the programmer can determine the type of error that
fclose(fp); has occurred using the perror() function. The perror()
function defined in stdio.h header file is used to handle
}
errors in C programs. When called, perror() displays a
When you execute this code and an error occurs while message on stderr describing the most recent error that
writing the feedback, the program will terminate and occurred during a library function call or system call, The
a message indicating Error writing in file will be prototype of perror() can be given as
displayed on the screen.
void perror(char *msg);
16.6.1 clearerr() The perror() function takes one argument msg which
points to an optional user-defined message, This message is
The clearerr() function is used to clear the end-of-file
printed first, followed by a colon, and the implementation-
and error indicators for the stream. Its protoype can be
defined message that describes the most recent error,
given as
Ifa call to perror() is made when no error has actually
void clearerr(FILE *stream); occurred, then a No error will be displayed. The most
important thing to remember is that a call to perror()
The clearerr() function clears the error for the stream
docs nothing to deal with the error condition, It is entirely
pointed to by stream. The function is used because error
up to the program to take action. For example, the program
indicators are not automatically cleared; once the error
may prompt the user to do something such as terminate the
indicator for a specified stream is set, operations on that
program.
stream continue to return an error value until clearerr,
Usually the program's action will be determined by
fseek, fsetpos, or rewind is called. Look at the code
checking the value of errno and the nature of the error.
given below which uses clearerr()
In order to use the external constant errno, you must
#include <stdio.h> include the header file errno. h. The program given below
#include <stdlib.h> illustrates the use of perror(). Here we assume that the
#include <errno.h> file Comments
.TXT does not exist
main()
include <stdio.h>
{ #include <stdlib.h>
FILE *fp; include <errno.h>
fp = fopen("Comments.TXT™, “w");
if (fp==NULL)
main()
{
{ FILE *fp;
perror(“OOPS ERROR”); fp = fopen("Comments.
TXT", “w");
printf("\n error no = Xd", errno); if(fp==NULL)
exit(1);
{
} perror(“OOPS ERROR");
printf("\n Kindly give the feedback on this printf("\n error no = %d", errno);
book: ");
exit(1);
gets( feedback);
for(i = 0; i < feedback{i};i++)
426 Computer Fundamentals and Programming in C
printf("\n Provide feedback on this book: printf("\n arg{i] = %s",argv[i]);
gets(feedback); return 0;
for(i=0; icfeedback[i];i++) }
fputc(feedback(i], fp); In the program, main() accepts command line argu-
fclose(fp); ments through arge and argv. In the main() function,
}
the value of arge is printed which gives the number of
Output arguments passed. Then cach argument passed is printed
in the for loop using the array of pointers, argv.
OOPS ERROR: No such file or directory
For example when you execute this program from DOS
errno «2
prompt by writing
C:\ote clpro.c Reema Thareja
ACCEPTING COMMAND LINE Then arge = 3, where argv(0] = clpro.c argy[1] =
ARGUMENTS Reema and argy[2] = Thareja
C facilitates its programmers to pass command arguments. 1, Write a program to read a file character by character,
Command-line arguments are given after the name of a and display it simultaneously on the scteen.
program in command-line operating systems like 00S or #include <stdio.h>
Linux, and are passed in to the program from the operating #include <string.h>
system. main()
Till now, no arguments were passed to the main() {
function, But now in order to understand command-line FILE *fp;
arguments, you must first understand the full declaration int ch;
of the main function. The main() function can accept two char filename{ 20);
arguments, printf("\n Enter the filename: “);
* The first argument is an integer value that specifies the fp = fopen(filename, “r");
number of command-line arguments. if (fpe=NULL)
* The second argument is a full list of all of the command- {
line arguments printf("\n Error Opening the File");
exit(1);
The full declaration of main() can be given as }
int main (int arg c, char *argv[}) ch= fgete(fp);
while(ch! *E0F)
The integer, arg ¢ specifies the number of arguments {
passed to the program from the command line, including putchar(ch);
the name of the program, ch = fgetc(p);
The array of character pointers, argv contains the list }
of all the arguments, argv[0] is the name of the program, fclose(fp);
or an empty string if the name is not available. argv[1] to }
argy(argc - 1) specifies the command line argument. In
a C program, every clement in argv can be used as a string. Output
Moreover, elements of argv can also be accessed as a two- Enter the filename: Letter.TXT
dimensional array, Note that argv[argc] is a NULL pointer. Hello how are you?
In other words, cach element of the array argv is
4 pointer where h pointer points to a string, Thus, 2. Write a program to count the number of characters and
argv(0) points to a string that contains the first parameter number of lines in a file.
on the command line which is the program's name, include <stdio.h>
argy(1] points to the next parameter, and so on. Look
#include <string.h>
at the program given below which illustrates the use of main()
command line arguments.
{
int main(int argc, char *argv[]}) FILE *fp;
{ int ch, no_of_characters = 0, no_of_lines =
int i; char filename{20);
printf("\n Number of argumnets passed = printf("\n Enter the filename: “);
%d" argc); fp = fopen(filename, “r”);
for (i = 0; i < argc; i++) if (fp==NULL)
Files 427
{
printf("\n Error Opening the File”); line++;
exit(1); text{i] = ‘\0';
} printf("Xd %s", line, text);
che fgetc(fp); i= 0;
while(ch!=EOF) }
{ text[i] = ch;
if(ch=="\n") itt;
no_of_lines++; }
no_of_characters++; text{i] = ‘\o';
ch = fgetc(fp); printf("Xs", text);
} fclose(fp1);
if(no_of_characters > 0) getch();
printf("\n In the file %s, there are %¢ return 0;
lines and %d characters”, filename, no_of }
lines, no_of_characters); Output
else
printf("\n File is empty"); 1 Hello how are you?
fclose(fp); 4, Write a program to compare two files to check whether
} they are identical or not
Output
Sinclude <stdio.h>
Enter the filename: Letter. TxT Sinclude <conio.h>
In the file Letter. TXT, there is 1 line and 18 int main()
characters {
FILE *fpl, *fp2;
3. Write a program to print the text of a file on screen by int chi, ch2;
printing the text line by line and displaying the line char filename1(20}, filename2[20};
numbers before the text in cach line. Use command clrscr();
line argument to enter the filename print€("\n Enter the name of the first file: “);
#include <stdio.h> gets(filename1);
#include <conio.h>
fflush( stdin) ;
int main() printf("\n Enter the name of the second file: ");
{
gets(filename2) ;
FILE *fpl; fflush( stdin);
if((fpl=fopen(filenamel, “r"))==0)
char text[100], ch;
int line » 1; {
int i = 0;
clrscr(); printf("\n Error opening the first file");
if(arge != 2)
exit(1);
{ }
printf("\n Full information is not if((fp2=fopen(filename2, “r"))==0)
provided. Please provide a filename”); {
return 0; printf("\n Error opening the second file");
exit(1);
}
fpl = fopen(argv(1], “r*); }
if(fpl == NULL) chi = fgetc(fp1);
ch2 = fgetc(fp2);
{
printf("\n File Opening Error"); while(chl!=EOF && ch2!=EOF && chle=ch2)
return 0; {
} /* Reading and comparing the contents
i= 0; of two files */
while(feof(fp1) == 0) chl = fgetc(fp1);
ch2 = fgetc(fp2);
{
fscanf(fpl, "Xe", Bch); }
if (ch == ‘\n') if(chi==ch2)
428 Computer Fundamentals and Programming in C
{ }
fscanf(fp1, “Xc", &ch);
fprintf(fp2, “Xce", ch ~ 2);
Output
/*encrypted character is printed on File copied with upper case characters
the screen */
} 9, Write a program to merge two files into a third file, The
printf("\n The encrypted data is written to names of the files must be entered using command
the file"); line arguments,
fclose(fp2); #include <stdio.h>
fcloseall(); include <conio.h>
getch(); int main(int argc, char *argv[))
return 0; {
} FILE *fpl, *fp2, *fp3;
Output char ch;
clrscr();
The encrypted data is written to the file if(arge t= 4) /* Read three filenames
from the user */
8. Write a program to read a file that contains lower case
{
characters, Then write these characters into another
file with all lower case characters converted into
printf("\n Full information is not
provided");
upper case (¢.g., if the file contains data — ‘red” it must
be written in another file as RED’).
return 0;
}
#include <stdio.h> fpi = fopen(argy[1], "r");
#include <conio.h> if(fp1 == NULL)
int main(int argc, char *argv[}) {
{ printf("\n File Opening Error");
FILE *fpl, *p2; return 0;
char ch; }
clrser(); fp2 = fopen(argv[2], "r");
if(arge != 3) if(fp2 == NULL)
{ {
printf("\n Full information is not printf("\n File Opening Error");
provided");
430 Computer Fundamentals and Programming in C
#include <stdio.h>
// PRINT ON SCREEN
#include <string.h>
main() print#("\n *** STUDENT'S DETAILS ***");
{ printf("\n ROLL No. = %d", studi.roll_no);
FILE *fp;
printf("\n NAME = Xs", studl.name);
char filename[20], str[100]};
printf("\n FEES = Xf", studl. fees);
printf("\n Enter the filename: “);
printf("\n DOB = Xs", stud1.00B);
fp = fopen(filename, “w");
if (fpe*NULL)
// WRITE TO FILE
{
printf("\n Error Opening The File");
fprintf(fp,
"Xd %s Xf Xs", studi.roll_no,
studl.name, studl.fees, stud1.D0B);
exit(1);
} fclose(fp);
printf("\n Enter the text: 4
gets(str);
getch();
return 0;
fflush(stdin);
fprintf(fp, “Xs", str); }
fclose(fp); Outpu
}
Enter the roll number: 01
Outpu Enter the name: Aman
12. Write a program to read the details of a student from a char name[80);
file and then print it on the screen. float fees;
char 008[80);
#include <stdio.h>
}STUDENT;
#include <conio.h>
STUDENT stud1;
int main() clrser();
{ fp = fopen(“student_details.dat", “w");
FILE *fp; if(fp == NULL)
typedef struct student
{
{ printf(“\n File Opening Error");
int roll_no; return 0;
char name[80);
float fees; }
char D0B{80); printf("\n Enter the roll number: “);
scanf("Xd", &stud1.roll_no);
}STUDENT; while(stud1.roll_no I» -1)
{
STUDENT stud1;
printf("\n Enter the name: “);
clrser(); scanf("Xs", stud1.name);
fp = fopen("student_details.dat”, "r"); printf("\n Enter the fees: “);
if(fp == NULL)
scanf("Xf", &studl.fees);
‘3 printf("\n Enter the DOB: ");
printf("\n File Opening Error");
scanf("Xs", stud1.D08);
return 0;
fprintf(fp,"Xd Xs Xf Xs", studi.roll_
} no, studi.name, studl.fees, studi
// READ FROM FILE
008);
fscanf(fp,
"xd Xs Xf Xs", &studl.roll_no,
fflush(stdin);
studl.name, &studl.fees, stud1.D08); printf("\n Enter the roll number: ");
// PRINT ON SCREEN
printf("\n *** STUDENT'S DETAILS ***");
scanf("Xd", &stud1.roll_no);
}
printf("\n ROLL No. = Xd", studi.roll_no); fclose(fp);
printf("\n NAME = Xs", stud1.name);
getch();
printf("\n FEES = %f", studi.fees);
return 0;
printf("\n DOB = Xs", stud1.00B);
}
felose(fp); Output
getch(); Enter the roll number: 01
return 0;
Enter the name: Aman
} Enter the fees: 45000
Output Enter the DOB: 20-9-91
Enter the roll number: 02
*** STUDENT'S DETAILS ***
Enter the name: Divij
ROLL No. * O1
Enter the fees: 45000
NAME = Aman
Enter the 008: 29-10-91
FEES = 45000
Enter the roll number: 03
DOB = 20-9-91
Enter the name: Saransh
13. Write a program to read the details of student until a Enter the fees: 45000
1° is entered and simultancously write the data to a Enter the DOB: 2-3-92
file. Enter the roll number: -1
#include <stdio.h> 14, Write a program to read characters until a‘*' is entered.
#include <conio.h> Simultancously store these characters in a file
int main() #include <stdio.h>
{ #include <conio.h>
FILE *fp; int main()
typedef struct student
{
{
int roll_no;
432 Computer Fundamentals and Programming in C
} break;
printf("\n Enter the details “); printf("\n\n Employee Code: Xd", e.emp_code);
for(i = 0; 1 < 2; ive) printf(“\n\n Name: Xs", e.name);
i exit(1);
FILE *fp; }
struct employee e; printf("\n Enter the code of the employee
int i; whose information has to be edited: “);
fp = fopen("employee.txt™, “ab"); scanf("%d" Bec);
if (fp==NULL) while(1)
{ {
printf("\n Error opening file"); fread(&e,sizeof(e),1,fp1);
exit(1); if (feof (fp1))
} break;
printf("\n\n Enter the employee code:"); if(e.emp_code==ec)
scanf("%d", &e.emp_code); {
printf("\n\n Enter the name of employee: “); found=1;
scanf("Xs", e.name); printf("\n The existing record is: %d
printf("\n\n Enter the HRA, DA, and TA:”); Xs Xd Xd Xd", e.emp_code, e.name,
scanf("Sd Xd Xd", &e.hra, Se.da, Se.ta); e.hra, e.ta, e.da);
fwrite(&e, sizeof(e), 1, fp); printf("\n Enter the modified name: ");
fclose(fp); scanf("Xs", e.name);
printf("\n Record Appended”); printf("\n Enter the modified HRA, TA,
getch(); and DA: ");
return 0; scanf("Xd Xd Xd", &e.hra, &e.ta, &e.da);
} fwrite(Se, sizeof(e),1,fp2);
}
Output
else
Enter the employee code: 06 fwrite(Se, sizeof(e),1,fp2);
Enter the name of employee: Tanya }
Enter the HRA, DA and TA: 20000 10000 3000 fclose(fpi);
Record Appended fclose(fp2);
if(found==0)
24, Write a program to edit the employee record stored in printf("\n Record not found");
a binary file. else
#include <stdio.h> {
#include <conio.h> fp = fopen("employee.txt", “wb");
int main() if (fple=NULL)
{ {
typedef struct employee printf("\n Error opening file");
{ exit(1);
int emp_code; }
char name(20); fp2 = fopen("temp_emp.txt", “rb");
int hra; if (fp2==NULL)
int da; {
int ta; printf("\n Error opening file");
exit(1);
i
FILE *fpl, *fp2; }
struct employee e; while(1)
int i, ec, found = {
clrser(); fread(&e, sizeof(e),1,fp2);
fp1 = fopen("employee.txt", “rb"); if(feof(fp2))
if (fpl==NULL) break;
{ fwrite(&e, sizeof(e), 1, fp1);
printf("\n Error opening file"); }
exit(1); }
fclose(fp1);
}
fp2 = fopen("temp_emp.txt", “wb"); fclose(fp2);
if (fp2==NULL) printf("\n Record Edited”);
{ getch();
printf("\n Error opening file”);
438 Computer Fundamentals and Programming in C
return 0; fseek() can be used to move the file pointer beyond a file,
} but not before the beginning
Output
Enter the code of the employee whose ifa file has been opened for update and later if you want
information has to be edited: 01
to switch from reading to writing or vice versa, then you
The existing record is: 01 Gargi 10000 S000
must use fseek().
2000
Enter the modified name: Gargi
Table 16.5 gives the interpretation of the fseek()
Enter the modified HRA, TA, and DA: 20000 10000
fuction.
30000
Record Edited Table 16.5 Origin field in fseek()
Function Call | Meaning
fseek (fp, OL,SEEK_SET), Move tothe beginning
ofthe file
EGEB FUNCTIONS FOR SELECTING fseek (fp. OL, SEEK_CUR); Stay at the current position
A RECORD RANDOMLY fseek (fp, OL,SEEK_END), Go to the end ofthe file
fseek (fp, m,SEEK_CUR); Move forward by m bytes in the
In this section, we will read about functions that are used file from the current location
to randomly access a record stored in a binary file. These fseek (fp, -m,SEEK_CUR); Move backwards
by m bytes in
functions include fseek(), ftell(), rewind(), fgetpos(), file from the current location
and fsetpos() {seek (fp, -m,SEEK_END); Move backwards by m bytes from
the end ofthe file
16.8.1 fseek()
The fseek() function is primarily used with binary files as
The fseek() function is used to repositionabinary stream.
The prototype of fseek() function which is defined in it has limited functionality with text files.
stdio.h can be given as
int fseek(FILE *stream, long offset, int 25. Write a program to randomly read the n™ record of a
origin); binary file
fseek() is used to set the file position pointer for the @include <stdio.h>
@include <conio.h>
given stream. The variable offset is an integer value that
gives the number of bytes to move forward or backward int main()
in the file, The value of offset may be positive or negative, {
provided it makes sense, For example, you cannot specify typedef struct employee
a negative offset if you are starting at the beginning of the {
int emp_code;
file. The origin value should have one of the following
values (defined in stdio.h) char name[20];
int hra;
* SEEK_SET; to perform input or output on offset bytes int da;
from start of the file int ta;
* SEEK_CUR: to perform input or output on offset bytes
3
from the current position in the file FILE *fp;
* SEEK_END: to perform input or output on of fset bytes struct employee e;
from the end of the le int result, rec_no;
© SEEK_SET, SEEK_CUR, and SEEK_END are defined fp = fopen(“employee.txt", “rb");
constants with value 0, 1, and 2, respectively if (fp==NULL)
Tip: On_ successful operation, {
ir the modified
HRA, TA, and DA of the }
employee: 30000 1000 S000 fclose(fp);
Record Edited }
Output
abcdefghijkjdqjdh
16.8.2 ftell()
The #te11() function is used to know the current position
of file pointer. It is at this position where the next input
or ouput operation will be performed. The syntax of
#tell(), defined in stdio.h, can be given as
long ftell (FILE *stream);
Here, stream points to the file whose file position 16.8.3 rewind()
indicator has to be determined. If successful, ftel1() rewind() is used to adjust the position of file pointer so
function returns the current file position (in bytes) for that the next 1/O operation will take place at the beginning
stream, However, in case oferror, ftel1() returns -1. ofthe file. It is defined in stdio.h and its prototype can
When using ftell(), error can occur because of the be given as
following two reasons:
void rewind(FILE *f);
* First, using ftel1() with a device that cannot store data
(e.g. keyboard). rewind() is equivalent to calling fseek() with following
* Second, when the position is larger than that can be parameters:
represented in a long integer. This will usually happen fseek(f,OL,SEEK_SET);
when dealing with very large files.
We have seen carlier that if a file is opened for writing
Look at the program code which illustrates the use of and you want to read it later, then you have to close the
ftell(). existing file and reopen it so that data can be read from
/*The program writes data to a file, saves the the beginning of the file. The other alternative is to to use
number of bytes stored in it in a variable rewind(). Look at the program code given below which
n (by using ftell ()) and then re-opens demonstrates the use of rewind().
the file to read n bytes from the file and
#include <stdio.h>
simultaneously display it on the screen.+/
int main()
main() {
{ FILE *fp;
FILE *fp; char feedback[80];
char ¢; int i-0;
int n; fp = fopen(“comments.txt", “w+");
fp=fopen(“abc”,"w"); if( fp==NULL)
if (fp==NULL) {
printf("\n Error Opening The File");
printf("\n Error Opening The File"); exit(1);
exit(1); }
} printf("\n Provide comments on this book:
while((c=getchar())!=EOF) "5
pute(c, fp); scanf("Xs", feedback);
n= ftell(fp); while(feedback[{i]!="\0")
fclose(fp); {
fp=fopen("abc","r"); fputc(feedback[i], fp);
if (#p==NULL) ite;
}
printf("\n Error Opening The File”); rewind(fp);
exit (1); printf("\n Contents of the file are: “);
} while(feof(fp)==0)
while(ftell(#p)<n) printf("%c", fgetc(fp);
{ fclose(fp);
c = fgetc(fp); return 0;
printf("%c", c);
Files sat
€quivalent of unlink(filename). Look at the program is not a directory. In this case, if the directory named by
given below which deletes the file “temp.txt" from the the newname already exists then it shall be removed and
current directory. oldname will be renamed to newname.
include <stdio.h> Look at the program code given below which illustrates
main() the use of rename()
{
remove(“temp. txt”); #include <stdio.h>
return 0; main()
{
int success=0;
Note success = rename("comments.txt”,
“feedback .txt");
You may specify the path of the file which has to be if(success != 0)
deletedas the argument of remove(). printf("\n The file could not be renamed”);
POINTS TO REMEMBER
* A file is a collection of data stored on a secondary type of data, encoded in binary form for computer
storage device such as a hard disk. Storage and processing purposes. While text files can
Stream is a logical interface to the devices that are be processed sequentially, binary files, on the other
connected to the computer, The three standard hand, can be either processed sequentially or
streams in C language are standard input (stdin), randomly.
standard output (stdout), and standard error A file must be first opened before data can be read from
(stderr). it or written to it. In order to open a file and associate it
When a stream linked to a disk file is created, a buffer is with a stream, the fopen() function is used,
automatically created and associated with the stream. To close an open file, the fclose() function is used
A text file is a stream of characters that can be which disconnects a file pointer from a file. fclose()
sequentially processed by a computer in forward not only closes the file but also flushes all the buffers
direction. A binary file is a file which may contain any that are maintained for that file.
Files 443
* If you have opened a stream for updating and later you of file pointer. It is at this position at which the next
want to switch from reading to writing or vice versa, you input or output operation will be performed,
must first use the fseek() or rewind() function. «© The fgetpos() function is used to determine the
* When an output stream is unbuffered, information current position of the stream. The rename() function
appears on the destination device as soon as it is is used to rename a file. The remove() function is used
written. When it is buffered, characters are saved to erase a file
internally and then written out as a group. In order to © The tmpfile() function is used to create a temporary
force buffered characterstobe output on the destination file. The tmpfile() opens the corresponding stream
device before the buffer is full, use fflush() with access parameters set as “we". The file created
* fseek() is used to reposition a binary stream. The with tmpfile() will be automatically deleted when all
#tell() function is used to know the current position references to the file are closed.
GLOSSARY
Binary file A binary file is a file which may contain any Standard input Standard input is the stream from which
type of data, encoded in binary form for computer storage the program receives its data
and processing purposes. Standard output Standard output is the stream where a
Buffer A buffer is a block of memory that Is used for program writes its output data.
temporary storage of data, that has to be read from or Stream Stream is a logical interface to the devices that
written to a file. are connected to the computer.
File A file is a collection of data stored on a secondary Text file A text file is a stream of characters that can be
storage device like hard disk. sequentially processed by a computer in the forward
Standard error Standard error is basically an output stream direction.
used by programs to report error messages or diagnostics.
EXERCISES
Fill in the Blanks 9 is a block of memory that is used for
4 ___ is a collection of data temporary storage of data.
2. The standard streams in C are 10. The creation and operation of the buffer is automatically
i _,and handled by the hs
3, __ are pre-connected input and output 11s file can be processed sequentially as well
channels between a text terminal and the program. as randomly.
4. Afile must be opened in mode if it is being 12.______ funetion closes the file and flushes all the
opened for updating. buffers that are maintained for that file.
§. __. function can be used to move the file 13. To use fprintf() to write on the screen, specify
marker at the beginning of the file _ in place of the file pointer.
6. Ifa file is opened in ‘wb’ mode then it isa___ 14, If you have opened a stream for updating and later you
file opened for writing want to switch from reading to writing or vice versa, you
7, Block input in binary file is done using the must first use the or
function. function.
a ___ is the stream where a program writes its 15. The symbolic constant EOF is defined in
output data. and has the value
444 ‘Computer Fundamentals
and Programming in C
oo Write a program to write some contents into (a) a binary Find the output of the following codes.
file (b) a text file. main()
ad Write a program to read a text file using fscanf() {
10. Write a program to read a text file using fgetc() FILE *fp;
i Write a program to illustrate the use of fprintf() char ¢;
12 Write a program to illustrate the use of fputc() fp=fopen("abc",“w");
13 Write a program to count the number of characters in a
while((cegetchar())!=E0F)
file putc(c, fp);
14, Write a program that reads the file name and text of 20 printf("\n No. of characters entered =
Rld", ftell(fp));
words as command line arguments. Write the text into a
fclose(fp);
file whose name is given as the file name.
iia Write a program to read data from the keyboard and }
main()
write it to a file. Read the contents stored in the file and
display it on the screen
{
FILE *fp;
16. Write a menu-driven program to read, insert, append, char comment [20];
delete, and edit a record stored in a binary file int 4;
17, Write a program to read data from a text file and store it fp=fopen("Feedbacks”,"w");
in a binary file, Also read the data stored in the binary for(i = O34 < Sjit+)
file and display it on the screen.
{
18, Write a program to read a text file, convert all the lower fscanf(stdin, "Xs", comment);
case characters into upper case and re-write the upper fprintf(fp, "Xs", comment);
case characters in the file, Before the end of the program,
}
all the temporary files must be deleted. fclose(fp);
19, Modify the above code fragment to allow the user three }
chances to enter a valid filename. If a valid file name is main()
not entered after three chances, terminate the program.
{
20 Assume that there are two files—Names1 and Names2 char c;
that store sorted names of students who would be FILE *fp;
participating in Activityl and Activity2, respectively. fp = fopen("temp” +b");
Create a file NAMES.TXT which stores the names from for(c = ‘A'sc <= » ct)
both the files. Note that there should be no repetition of fputc(c, fp);
names in NAMES.TXT and while writing name into it, fseek(fp, 2, 0);
ensure that the file is also sorted, c = fgetc(fp);
21, Write a program to create a file that stores only integer printf("Xc", ¢);5
values, Append the sum of these integers at the end of fclose(fp);
the file. }
22. Write a program that reads a binary file that stores main()
employees records and prints on the screen the number {
of records that are stored in the file. char ¢;
23. Write a program to append a binary file at the end of FILE *fp;
another. fp = fopen("tem
24, Assume that a file INTEGERS.TXT stores only integer for(c = 'A';c <=
numbers. A value ‘-1' is stored as the last value to fwrite(&c, 1
indicate EOF. Write a program to read each integer value rewind(fp);
stored in the file. While reading the value, compute fread(&c,1,1,fp);
whether the value is even or odd. If it is even then write printf("Xe", c);
that value in a file called EVEN.TXT else write it in ODD.
fclose(fp);
TXT. Finally display the contentsof the two files— EVEN. }
TXT and ODD.YXT. main()
Hint: You may use getw and putw functions. They are {
char c;
same as getc()and putc(). The prototypes of getw()
and putw()are FILE *fp;
int getw(FILE *fp); and putw(int value, FILE long int pos;
fp = fopen("temp","w+b”);
*fp)s
446 ‘Computer Fundamentals and Programming in C
TAKEAWAYS
* Preprocessor directives * Pragma directives * Conditional directives
© #error directive * Predefined macro names
Preprocessor directive
Conditional
A function-like macro is invoked by writing the identifier define SQUARE(x) ((x) x (x))
followed by a comma-separated list of arguments in Now a statement like
parentheses. However, make sure that the number of
arguments should match the number of parameters in the © = SQUARE(a+b);
macro definition. One exception to this is if the parameter would be expanded as
list in the definition ends with an ellipsis, the number of
arguments in the invocation should exceed the number c= ((a +b) * (a + b));
of parameters in the definition, The excess arguments are
called trailing arguments.
When the preprocessor encounters a function-like macro For portability,
you should not have more than 31
invocation, argument substitution takes place. A parameter parameters
for a macro,
in the replacement code is replaced by the corresponding
argument. If there are trailing arguments (as permitted
17.3.3 Nesting of Macros
by the macro definition), then they are merged with the
intervening commas as if they were a single argument We can use a macro in the definition of another macro. For
ase of nested macros (macro within another example, consider the following macro definitions:
macro definition), i.c., if there are any macro invocations
contained in the argument itself, they are completely define SQUARE(x) ((x) * (x))
define CUBE(x) (SQUARE(x) « (x))
replaced before the argument replaces its corresponding
define FOURTH POWER(x) (CUBE(x) = (x))
parameter in the replacement code.
define FIFTH_POWER(x) (FOURTH _POWER(x) x (x))
The following line defines the macro MUL as having two
parameters a and b and the replacement string (a = b): In these definitions, the preprocessor will expand each
macro until all the macros do not exhaust in the text, For
#define MUL(a,b) (axb) example, the macro CUBE will be expanded as
Look how the preprocessor changes the following
statement provided it appears after the macro definition. CUBE(x) => SQUARE(x) « (x) => ((x) * (x)) * (x)
Generally, in C a macro can be nested to 31 levels.
Programming Tip: int a = 2, b = 3,¢;
Use macros instead c=MUL(a,b) //c=
17.3.4 Rules for Using Macros
of functions as and;
macros aremuch In the output of the Let us summarize some rules that must be used when
more efficient than preprocessor, the above specifying macro definitions and invoking them from an
functions since they statement would appear as: arbitrary place within the program
avoid the overhead c = axb; * The macro name and the formal parameters are
involved in callinga While using —_function- identifiers, so they must be specified in accordance with
function: like macros, you must use the rules for identifiers in the C language.
450 Computer Fundamentals and Programming in C
had already appeared in the source program at the point Undefining a macro means to cancel its definition. This 18
where the directive appear: done by writing #undef followed by the macro name that
The #include directive can be used in two forms. Both has to be undefined.
the forms make the preprocessor insert the entire contents Like definition, undefinition also occurs at a specific
of the specified file into the source code of our program. point in the source file, and it applies starting from that
However, the difference between the two is the way in point. Once a macro name is undefined, the name of the
which they search for the specified. macro ceases to exist (from the point of undefinition) and
the preprocessor directive behaves as if it had never been
#include <filename>
a macro name.
This variant is used for system header files. When we Therefore, the #undef directive removes the current
include a file using angular brackets, a search is made for the definition of macro and all subsequent occurrences of
file named filename in a standard list of system directories, macro name are ignored by the preprocessor,
#include “filename”
This variant is used for header files of your own program. If you had earlier defined a macro with parameters , then
When we include a file using double quotes, the preprocessor when undefining that macro you do not have to give the
searches the file named filename first in the directory parameter list. Simply specify the name of the macro.
containing the current file, then in the quote directories and
then the same directories used for <filename>. You can also apply the #undef directive to a macro
name that has not been previously defined. This can be
done to ensure that the macro name is undefined
The filename can optionally be preceded by a directory The #undef directive when paired with a #define
specification, For example, you may specify the exact directive creates a region in a source program in which
path by writing “c:\students\my_header.h”. the macro has a special meaning. For example, a specific
function of the source program can use certain constants
Points to Remember to define environment-specific values that do not affeet the
rest of the program.
The preprocessor stops searching the directory as soon as The #undef directive can also be paired with the #if
it finds a file with the given name. directive to control conditional compilation of the source
If a completely unambiguous path for the file is program. We will read about the #if directive later in this
specified between double quotation marks (" “), then chapter.
the preprocessor searches only that path specification and Consider the following example in which the #undef
ignores the standard directories. directive removes definitions of a symbolic constant and
If an incomplete path is specified for the filename in a macro.
double quotes, then the preprocessor first searches the
Sdefine MAX 10
parent file's directory (where a parent file is the one which
contains the #include directive. For example, if you Sdefine MIN(X,¥) (((X)<(¥))?((x)2(¥))
include a file named file2 within a file named file1, filet
is the parent file).
File inclusion can be ‘nested’, i.c., a #include directive
@undef MAX
can appear in a file named by another #include directive.
undef MIN
For example, file1 can include file2, and in turn file2 can
include another file named file3. In this case, file1 would
be the parent of file2 and the grandparent of file3. #line
When file inclusion is nested and when compiling is
done from the command line, directory searching begins Compile the following C program:
with the directories of the parent file and then proceeds #include <stdio.h>
through the directories of any grandparent files. main()
int a = 10:
Nesting of include files can continue up to 10 levels. printf("%d", a);
}
#tundef The above program has a compile-time error because
instead of a semicolon there is a colon that ends the line,
As the name suggests, the undef directive undefines or int a = 10. So when you compile this program an error is
removes a macro name previously created with #define. generated during the compilation process and the compiler
452 Computer Fundamentals and Programming in C
will show an error message Here, string can be one of the instructions given to
Programming Tip: with r 2
eferences to the name the compiler with any required parameters. Table 17.1
Theflenameinthe of the file where the error has describes some pragma directives.
ba cae i déible happened and a line number.
quotes This makes it casy to detect the Table 17.1 Pragma directives
erroncous code and rectify it |
Instruction | Description
The #1ine directive enables the users to control the line
numbers within the code files as well as the file name that COPYRIGHT To specify a copyright string
appears when an error takes place. The syntax of #line COPYRIGHT_DATE —_To specify a copyright date for the
directive is
copyright string
#line line_number filename HP_SHLIB_VERSION _To create versions of a shared
Here, line_number is the new line number that will library routine
be assigned to the next line of code. The line numbers of LOCALITY To name a code subspace
successive lines will be increased one by one from this
point onwards, The parameter filename is an optional OPTIMIZE To turn the optimization feature on
parameter that redefines the file name that will appear or off
in case an error occurs. The filename must be enclosed OPT_LEVEL ‘To set the level of optimization
within double quotes, If no filename is specified, then the
compiler will show the original filename. For example: VERSIONID ‘To specify a version string
#include <stdio.h>
main() Pragma COPYRIGHT
{ The syntax of pragma COPYRIGHT can be given as
#line 10 “Error.c”
int ae10: Spragma COPYRIGHT "string"
#line 20
Here, string specifies the set of characters included in
printf("*d, a);
the copyright message in the object file.
}
If no date is specified using pragma COPYRIGHT_DATE,
This code will generate an error that will be shown as then the current year is used in the copyright message. For
error in file “Error.C", lines 10 and 20. Please execute example, if we write
this program with the #line directive and without the
Spragma COPYRIGHT “JRT Software Ltd”
#Line directive to visualize the difference.
Hence, we see that #Line directive can be used to make Then the following string is placed in the object code
the compiler provide more meaningful error messages (assuming the current year is 2011):
© Copyright JRT Software Lid, 2011. All rights
reserved. No part of this program may be photocopied,
A preprocessor line control directive supplies line reproduced, or transmitted without prior written consent
numbers for compiler messages. It tells the preprocessor of JRT Software Ltd.
to change the compiler’s internally stored line number
and filename to a given line number and filename. Pragma COPYRIGHT_DATE
The syntax of pragma COPYRIGHT_DATE can be given as
Pragma LocaLIty
#pragma OPTIMIZE ON
void Func2() The syntax of pragma locality which is used to specify
{ // Restore optimization to level 2 a name to be associated with the code that is written to a
re-locatable object module can be given as
Spragma LOCALITY “string”
Pragma OPT_LEVEL Here, string specifies a name to be used for a code
subspace. After this directive, all codes following the
The syntax for pragma OPT_LEVEL which is used to set the directive are associated with the name specified in string. The
optimization level to 1,2,3, or 4 can be given as smallest scope of a unique LOCALITY pragma is a function.
#pragma OPT_LEVEL 1
#pragma OPT_LEVEL 2 Pragma versionzpD
#pragma OPT_LEVEL 3
The syntax of pragma VERSIONID can be given as
#pragma OPT_LEVEL 4
Like the OPTIMIZE pragma, even this pragma cannot be
pragma VERSIONID “string”
used within a function, Finally, OPT_LEVEL 3 and 4 are Here, string is a string of characters that is placed in
allowed only at the beginning of a file. the object file. For example, if we write
For example,
Spragma VERSIONID “JRT Software Ltd.,
acc -O prog.c Version 12345.A.01.10"
#pragma OPT_LEVEL 2
void Funci() Then this pragma places the characters JRT Software
{ // Optimize Funci() at level 1 Ltd., Version 12345.A.01.10 into the object file,
Pragma once
#pragma OPT_LEVEL 2 The pragma once specifies that the file, in which this
void Func2() pragma directive is specified, will be included (opened)
{ // Optimize Func2() at level 2 only once by the compiler in a building of a particular file
Its syntax can be given as
}
#pragma once
Pragma preprocessor directives are mainly used where
The kind of optimization done by the operating system cach implementation of C supports some features unique
at each level is beyond the scope of this book. to its host machine or operating system, For example,
454 Computer Fundamentals and Programming in C
Some programs may need to exercise precise control over 17.8.1 #ifdef
the memory areas where data is placed or to control the
way certain functions receive parameters. In such ca: #ifdef is the simplest sort of conditional preprocessor
#pragma directive provides machine- and operating- directive and is used to check for the existence of macro
system-specific features for each compiler while retaining definitions, Its syntax can be given as
overall compatibility with the C lang #ifdef MACRO
controlled text
EZ CONDITIONAL DIRECTIVES Rendif
You can also use #else directive with #ifdef and 17.8.4 #else
#ifndef directives like
The #else directive can be used within the controlled
#ifdef MACRO text of a #if directive to provide alternative text to be
controlled_text1 used if the condition is false.
The general format of #else
telse directive can be given as
controlled _text2
#if condition
tendif
controlled texti
felse
17.8.3 #if controlled text2
#endif
The #if directive is used to control the compilation
of portions of a source file. If the specified condition If condition evaluates to a non-zero va then
(after the #if) has a non-zero value, the controlled text controlled text1 becomes active and the #else directive
immediately following the #if directive is retained in the acts like a failing conditional and the controlled text2
translation unit is ignored. Similarly, if the condition fails or evaluates to
The #if directive in its simplest form consists of zero, then controlled text2 is considered included and
controlled text1 is ignored.
#if condition
The #e1se directive is usually used to delimit alternative
controlled text source text to be compiled if the condition tested for in the
tendif
corresponding #if, #ifdef, or #ifndef directive is false.
In the above syntax, condition is a C expression of However, a #e1se directive is optional,
integer type, subject to stringent restrictions, ic. the
condition may contain the following 17.8.5 #elif
* Integer constants (which are all treated as cither long or The #e1if directive is used when there are more than two
unsigned long) possible alternatives. The #elif directive like the #else
Character constants directive is embedded within the #if directive and has the
Arithmetic operators for addition, subtraction, following syntax
multiplication, division, bitwise operators, shift,
if condition
comparison, and logical operators.
controlled text1
If an identifier used in the expression is not 4 macro and
elif new_condition
has not been currently defined, the compiler treats the
controlled text2
identifier as though it were the constant zero.
selse
Macros which are actually expanded before computation
controlled text3
of the expression’s value begins sendif
* Defined operator can be used
* The sizeof operator is not allowed in #if directives. Here, when the if condition is non-zero then
* Type cast operator is not allowed controlled text1 becomes active and the #elif and #else
* Enumerated data types are not allowed directives act like a failing conditional and the controlled
* The condition must not perform any environmental text2 and controlled text3 are ignored. Similarly,
inquiries and must remain insulated from implementation grounds, if the condition fails or evaluates to zero, then
details on the target computer new_condition is evaluated. If it is true, controlled
Increment, decrement, and address operators are not text2 is considered included and controlled text1 and
allowed controlled text3 are ignored. Otherwise, if condition
and new_condition both are false then #else directive
The controlled text inside the directive can include
becomes active and controlled text3 is included.
other prepro ing directives, However, any statement or
The #elif directive is same as the combined use of the
any preprocessor directive in the controlled text will
else-if statements. The #e1if directive is used to delimit
be executed if that branch of the conditional statement
alternative source lines to be compiled if condition in the
succeeds,
While using the #if directive in your program, make
corresponding #if, #ifdef, #ifndef, or another #elif
sure that cach #if directive must be matched by a closing
directive is false and if the new_condition in the #elif
line is truc, an #elif directive is optional
#endif directive. Any number of #elif directives can
appear between the #if and #endif directives, but at define MAX 10
most one #else directive is allowed. However, the #else Sif OPTION ==
directive (if present) must be the last directive before int STACK[MAX];
#endif. Selif OPTION == 2
456 Computer Fundamentals and Programming in C
float STACK[MAX); use the defined unary operator. The defined operator has
#elif OPTION == 3 one of the following forms:
char STACK[MAX);
defined MACRO
telse
printf("\n INVALID OPTION");
or
endif
defined (MACRO)
The #elif does not require amatching ‘#endif? of its The above expression evaluates to 1 if MACRO is defined
own. Every #e1if directive includes
a condition to be and to 0 if it is not. The defined operator helps you to check
tested. The text following the #elif isprocessed only if for macro definitions in one concise line without having
the #if condition fails and the #e1if condition succeeds. to use many #ifdef or #ifndef directives. For example,
consider the following macro checks:
In the above example, we have used more than one
#elif directives in the same #if-#endif group. The text #ifdef MACRO1
after cach #elif is processed only if the ¢e1if condition ifdef MACRO2
succeeds after the original #if and any previous ¢elif controlled texti
directives within it have failed. Selse
printf("\n MACROS not defined");
sendif
If the condition specified with #if directive isfalse and if
either no #elif directives appear or no #elif condition OR
evaluates to true, then the preprocessor selects the text
block after the #e1se clause. If the #else directive isalso @if defined (MACRO1) && defined (MACRO2)
missing then no controlled text isselected. controlled text1
selse
17.8.6 #endif printf("\n MACROS not defined”);
sendif
The general syntax of #endif preprocessor directive
which is used to end the conditional compilation directive As evident from the above example, the defined
can be given as operator can be combined in any logical expression using
the logical operators. However, this operator can only
tendif be used in the evaluated expression of an #if or #elif
The #endif directive ends the scope of the #1f, #ifdef, preprocessor directive
#ifndef, #else, or #elif directives. The number of
#endif directives that is required depends on whether the AU) #error
#elif or #else directive is used. For example, consider
the examples given below which, although perform the The #error directive is used to produce compile-time
same task, requires different number of #endif directives. error messages. The syntax of this directive is
#if condition error string
Controlled textl
telif new_condition The error messages include the argument string. The
Controlled text2
#error directive is generally used to detect programming
tendif inconsistencies and violation of constraints during
OR preprocessing. When #error directive is encountered, the
#if condition
compilation process terminates and the message specified
Controlled text1
in string is printed to stderr. For example, consider
#else the picce of code given below which illustrates error
#if new_condition processing during preprocessing
Controlled text2 #ifndef SQUARE
#endif #error MACRO not defined.
#endif #endif
+ First, it helps you to determine whether a given line is A string literal inthe form “hhimmiss” which
is used to specify the time atwhich the
being compiled or not compilation process began,
* Second, when used within a heavily parameterized
body of code, it helps to ensure that a particular MACRO Specifies full conformance with ANSIC
standard.
has been defined.
_TIMESTAMP___ Astring literal intheform Dud Mem Date
Besides the #error directive, there is another bhomm:ss yyyy, where Dad istheabbreviated:
directive—#warning, which causes the preprocessor to day ofthe week and Date isaninteger from 1
issue a warning and continue preprocessing. The syntax of fo 31. Itisused tospecify the date and time of
4warning directive is same as that of #error, the lastmodification
ofthecurrent source tile,
#warning string printf("\n Current File’s Path Name:
Here, string is the warming message that has to be Xs", _FILE_);
displayed, One important place where #warning directive printf("\n Line Number in the
can be used is in obsolete header files. You can display a current file: Xd", LINE);
message directing the user to the header file which should printf("\n Date of Compilation: %s",
be used instead —DATE__);
printf("\n Time of Compilation: Xs",
PREDEFINED MACRO NAMES __TIME__);
Rifdef __STDC__
printf("\n Your C compiler
There are certain predefined macros that are readily
conforms with the ANSI C standard");
available for use by the C programmers. A list of such Selse
predefined macros is given in Table 17,2. printf("\n Your C compiler doesn’t
#include <stdio.h> conform with the ANSI C standard”);
void main(void) fendif
{
POINTS TO REMEMBER
* The preprocessor is a program that processes the © The merge operator is used to concatenate two tokens
source code before it passes through the compiler. into a third valid token.
. Preprocessor directives are lines included in the C * The #include directive is used to inform the
program that are not program statements but Preprocessor to treat the contents of a specified file
directives for the preprocessor. The preprocessor as if those contents had appeared in the source
directives are always preceded by a hash sign (#) and program at the point where the directive appears.
are executed before the actual compilation of program #undef directive removes a macro name previously
code begins. created with adefine. The #Line directive enables the
* To define preprocessor macros, we use #define users to control the line numbers within the code files
directive. An object-like macro is a simple identifier as well as the file name that appears when an error
which will be replaced by a code fragment. They are takes place.
usually used to give symbolic names to numeric © The #pragma directive is used to control the actions of
constants. Function-like macros are used to stimulate the compiler in a particular portion of a program
functions, without affecting the program as a whole.
458 Computer Fundamentals and Programming in C
*© A conditional directive is used to instruct the * The #else directive is used within the controlled text
preprocessor to select whether or not to include a block of a #if directive in order to provide alternative text
of code in the final token stream passed to the compiler. to be used if the condition is false. The #elif directive
#ifdef is used to check for the existence of macro is used when there are more than two possible
definitions, The #ifndef directive is the opposite of alternatives. The #elif directive like the #else
#ifdef directive. It checks whether the MACRO has not directive is embedded within the #if directive.
been defined or if its definition has been removed © The #error directive is used to produce compile-time
with #undef. The #if directive is used to control the error messages.
compilation of portions of a source file
GLOSSARY
Function-like macro |t is used to stimulate functions. sign (#)
Object-like macro It is a simple identifier which will be Self-referential macro A macro whose name appears in
replaced by a code fragment. They are usually used to give its definition.
symbolic names to numeric constants. Trailing arguments A function-like macro definition
Preprocessor It is a program that processes the source declares the names of formal parameters within
code before it passes through the compiler. parentheses, separated by commas. If the number of
Preprocessor directives These are lines included in the C arguments in the invocation exceeds the number of
program that are not program statements but directives parameters in the definition, the excess arguments are
for the preprocessor. They are always preceded by a hash called trailing arguments.
EXERCISES
Fill in the Blanks 12. File inclusion can be nested to levels,
1, _______ IS & program that processes the source code 13, The sundef directive removes a macro name previously
before it passes through the compiler. created with
2. Operates under the control of preprocessor 14. The directive is used to control the actions of
directive. the compiler in a particular portion of a program without
3. Before the source code is passed through the compiler, it affecting the program as a whole
is examined by the preprocessor for any 15. ___ is used to instruct the preprocessor to select
4, are lines included in the program that are not whether or not to include a chunk of code in the final
program statements but directives for the preprocessor. token stream passed to the compiler.
5. The___is also known as a macro. 16. Each #if directive must be matched by the
6. The #define directive is used to _ directive.
7. ____ is used to give symbolic names to numeric 17. The #elif directive and the #else directive are
constants, embedded within the __ directive
8. Trailing arguments are 18. When directive is encountered, the
TAKEAWAYS
* Data structures Linked lists Trees
* Primitive and non-primitive
data structures Stacks Graphs
* Linear and non-linear
data structures Queues
marks{O] marks{1] marks[2] marks[3] marks[4] marks[5] marks[6] marks[7] marks[8] marks[9]
Figure 18.1 Memory representation of an array of 10 elements
462 Computer Fundamentals and Programming in C
*L’ as the data. We repeat this procedure until we reach a The end of the list is marked by storing NULL or 1 in the
position, where the NEXT entry contains -1 or NULL, as this NEXT field of the last node. For traversing the linked list, we
would denote the end of the linked list. When we traverse will also make use of another pointer variable PTR, which
the DATA and NEXT fields in this manner, we will finally see will point to the node that is currently being accessed. The
that the linked list in this example stores characters that algorithm to traverse a linked list is shown in Figure 18.4
when put together forms the word *HELLO*
Step 1: [INITIALIZE] SET PTR = START
START
Step 2: Repeat Steps 3 and 4 while PTR I~ NULL
Ea) Step 3: Apply Process to PTR->DATA
Step 4: ‘SET PTR = PTR->NEXT
{END OF Loop)
Step 5: EXIT
7) 2D 2 2 Bo 6D Ee
START
Allocate memory for the new node and initialize its DATA part to 9.
oe
Add the new node as the first node of the list by making the NEXT part of
the new node contain the address of START.
1 ba
START
ee bb ea eT §]
Now make START to point to the first node of the list.
BD
GD fO 6D GD Go
Figure 18.8 inserting an element at the beginning of a linked list
464 Computer Fundamentals and Programming in C
7
START
Allocate memory for the new node and initialize its DATA part to 9 and
NEXT part to NULL.
on
Take a pointer variable PTR which points to START.
EE
START, PTR
pL GD
2D Oo Be
Move PTR so that it points to the last node of the list.
AD
START
eo a 7S 2b [s]x]
PTR
Add the new node after the node pointed by PTR. This is done by storing
the address of the new node in the NEXT part of PTR.
7] 2 Bo BA fo Oo 9[x]
START PT R
Figure 18.10 Inserting an element at the end of a linked list
Introduction to Data Structures: 465
1) fie Gi -e BD GO s[x
START
Allocate memory for the new node and initialize its DATA part to 9.
om
Take two pointer variables PTR and PREPTR and initialize them with START
so that START, PTR, and PREPTR point to the first node of the list.
1
START
FS 2s 2 [x
PTR
PREPTR
Move PTR and PREPTR until the DATA part of PREPTR = value of the node after
which insertion has to be done.PREPTR will always point to the node just
CS 2 6 6 oe
uae
i f2-G-S-2- eee
START PREPTR PTR
Add the new node in between the nodes pointed by PREPTR and PTR.
1 fe 3S SS 2s -2e-Ee
START PREPTR PTR
GT]
NEW_NODE
i 7 3] 9] +L) s.] Gx
START
Figure 18.12 inserting an element after a given node in a linked list
the node containing data 3. Let us look at the changes that am OVERFLOW message is printed. Otherwise, if a free
will be done in the linked list, The algorithm to add the memory cell is available, then we allocate space for the
new node is given in Figure 18,13 new node. Set its DATA part with VAL.
In step 1, we first check whether memory is available In step 5, we take a PTR and initialize it with START, That
for the new node. If the free memory has exhausted, then is, PTR now points to the first node of the linked list, Then,
we take another pointer variable PREPTR, which will be used
to store the address of the node preceding PTR. Initially,
Step 1: IF AVAIL = NULL, then
PREPTR is initialized to PTR. Hence, now, PTR, PREPTR, and
Write OVERFLOW
START all point to the first node of the linked list.
Go to Step 12
In the while loop, we traverse through the linked list to
[END OF IF} reach the node that has its value equal to NUM. We need to
Step 2: SET New Node » AVAIL
reach this node because the new node will be inserted after
Step 3: SET AVAIL = AVAIL ->NEXT this node. Once we reach this node, in steps 10 and 11, we
Step 4; SET NewNode->DATA » VAL change the NEXT pointers in such a way that a new node is
Step 5; SET PTR = START inserted after the desired node.
Step 6: SET PREPTR = PTR
Step 7: Repeat Steps 8 and 9 while PREPTR-> Case 4: The new node is inserted before a given node
DATA |= NUM Consider the linked list shown in Figure 18.14, Suppose
Step 8: SET PREPTR = PTR we want to add a new node with value 9 and add it before
Step 9: SET PTR = PTR->NEXT the node containing 3. Let us discuss the changes that will
[END OF LOOP) be done in the linked list
Step 10: PREPTR->NEXT = New Node Figure 18.15 shows the algorithm to insert a new node
Step 11: SET New_Node->NEXT « PTR before a given node. In step 1, we first check whether
Step 12: EXIT memory is available for the new node. If the free memory
has exhausted, an OVERFLOW message is printed. Otherwise,
Figure 18.13 Algorithm to insert a new node after a node if a free memory cell is available, then we allocate space
that has value NUM for the new node. Set its DATA part with VAL
466 Computer Fundamentals and Programming in C
AD 2
START
2 GD 6 oo
Allocate memory for the new node and initialize its DATA part to 9.
Om
Initialize PREPTR and PTR to the START node.
i i- 2e-s BO 5 |x|
PREPTR
Move PTR and PREPTR until the DATA part of PTR = value of the node before
which insertion has to be done.PREPTR will always point to the node just
before PTR.
7
START
2-2-2
PREPTR PTR
ee
Insert the new node in between the nodes pointed by PREPTR and PTR.
1) 2D 2D 7
START PREPTR PTR
2] |
START
a) 4.) EL 6[ 5 [x
Step 1: IF AVAIL = NULL, then to reach this node because the new node will be inserted
Write OVERFLOW before this node. Once we reach this node, in steps 10 and
11, we change NEXT pointers in such a way that new node
Go to Step 12
[END OF IF} is inserted before the desired node.
Step 2: SET New Node » AVAIL
Step 3: SET AVAIL » AVAIL~>NEXT
18.4.4 Deleting a Node from a Linked List
Step 4: SET New_Node->DATA = VAL In this section, we will discuss how a node is deleted from
Step 5; SET PTR = START an already existing linked list, We will take three cases and
Step 6: SET PREPTR = PTR then see how the deletion is achieved in each case.
Step 7: Repeat Steps 8 and 9 while PTR-> Case 1 The first node is deleted.
DATA |= NUM
Step 8: SET PREPTR = PTR Case 2 The last node is deleted,
Step 9: SET PTR = PTR->NEXT Case 3 The node afer a given node is deleted.
[END OF LOOP}
Step 10:PREPTR->NEXT = New Node
Before we start with the algorithms to do deletions
in all these three cases, let us first discuss an important
Step 11:SET New_Node->NEXT = PTR
term, UNDERFLOW. UNDERFLOW is a condition that occurs
Step 12:EXIT
when we try to delete a node from a linked list that is
Figure 18.15 Algorithm to insert a new node before a empty. This happens when START = NULL, or when we
node that has value NUM try to delete nodes even when there are no more nodes
left
In step 5, we take a pointer variable PTR and initialize it Note that, when we delete a node from a linked list,
with START, That is, PTR now points to the first node of the then we have to actually free the memory occupied by that
linked list, Then we take another pointer variable PREPTR node, The memory is returned to the free pool so that it can
and initialize it with PTR. Hence, now, PTR, PREPTR, and be used to store other useful programs and data. Hence,
START all point to the first node of the linked list whatever be the case of deletion, we always change the
In the while loop, we traverse through the linked list AVAIL pointer, so that it now points to the address that has
to reach the node that has its value equal to NUM. We need been recently vacated
Introduction to Data Structures 467
GE
START
--= 41 2D s[x
Make START to point to the next node in sequence.
GO
START
2 7 2D sf
Figure 18.16 Deleting the first node of alinked list
Case 1: The first node is deleted Consider the linked list Case 2: The last node is deleted from the linked list
in Figure 18.16. When we want to delete a node from the Consider the linked list shown in Figure 18.18. Suppose
beginning of the list, then the following changes will be we want to delete the last node from the linked list, then
done in the linked list. the changes shown in Figure 18.18 will be made in the
Figure 18.17 shows the algorithm to delete the first linked list.
node from a linked list. In step 1 of the algorithm, we Figure 18.19 shows the algorithm to delete the last node
check if the linked list exists or not. If START NULL, then from a linked list. In step 1 of the algorithm, we check
it signifies that there are no nodes in the list and control is if the linked list exists or not. If START = NULL, then it
transferred to the last statement of the algorithm. signifies that there are no nodes in the list and the control
However, if there are nodes in the linked list, then is transferred to the last statement of the algorithm.
We use a pointer variable that is set to point to the first In step 2, we take a pointer variable, PTR and initialize
node of the list. For this, we initialize PTR with START that it with START. That is, PTR now points to the first node of
stores the address of the first node of the list. In step 3, the linked list. In the while loop, we take another pointer
START is made to point to the next node in sequence and variable PREPTR, such that PRETR always points to onc
finally the memory occupied by the node pointed by PTR node before the PTR. Once we reach the last node and the
(initially the first node of the list) is freed and returned to second last node, we set the NEXT pointer of the second last
the free pool node to NULL, so that it now becomes the (new) last node
of the linked list. The memory of the previous last node is
Step 1: IF START » NULL, then freed and returned to the free pool
Write UNDERFLOW
Case 3: The node after a given node is deleted Consider
Go to Step 5
the linked list shown in Figure 18.20. Suppose we want
[END OF IF} to delete the node that succeeds the node containing data
Step 2: SET PTR = START
value 4, Then the following changes will be done in the
Step 3: SET START = START->NEXT linked list.
Step 4; FREE PTR Figure 18.21 shows the algorithm to delete the node
Step 5; EXIT after a given node from a linked list. In step | of the
algorithm, we check if the linked list exists also or not, If
Figure 18.17 Aijgorithm to delete the first node from a
START = NULL, then it signifies that there are no nodes in
linked list
7 GD 6b | 2 fe s[x
GD fo Go ED Go Go
Take pointer variables PTR and PREPTR which initially point to START.
47]
START
PREPTR
PTR
Move PTR and PREPTR such that NEXT part of PTR = NULL. PREPTR
always points to the node just before the node pointed by PTR.
ED
START
2 -2a 12D EB
PREPTR PTR
Set the NEXT part of PREPTR node to NULL.
fo ft
START
Go aT) 1 fe
Figure 18,18 Deleting the last node of a linked list
468 | Computer Fundamentals and Programming in C
Step 4:
Beat lars
SET PREPTR « PTR
Step 3: SET
fn
PREPTR
ape
= PTR
5 and 6 while PREPTR
Step S:“ = PTR->NEXT
SET PTR = PTR- Step Soh 4: ance
Repeat aSteps
eae,5 a ie
[END OF LOOP]
Step 6: SET PREPTR->NEXT « NULL Step 5: SET PREPTR = PTR
Step 7: FREE PTR Step 6: SET PTR = PTR->NEXT
Step 8: EXIT
[END OF LOOP]
Figure 18.19 Algorithm to delete the last node froma Step 7: SET TEMP « PTR
linked list
me Step 8: SET PREPTR->NEXT = PTR->NEXT
Step 9: FREE TEMP
the list and the control is transferred to the last statement Step 10:EXIT
of the algorithm
In step 2, we take a pointer variable PTR and initialize Figure 18.21 Algorithm to delete the node after a given
it with START, That is, PTR now points to the first node of node from a linked list
the linked list, In the while loop, we take another pointer
variable PREPTR, such that PREPTR always points to one —yWrite g program to create a linked list and perform
node before the PTR. Once we reach the node containing insertions and deletions of all cases. Write functions to
VAL and the node succeeding it, we set the NEXT pointer of sort and finally delete the entire list at once
the node containing VAL to the address contained in the =
NEXT field of the node succeeding it. The memory of the — Solution
node succeeding the given node is freed and returned to #include <stdio.h>
the free pool. @include <stdlib.h>
1] 7] 3] a] 2| 6] | {sx
START
Take pointer variables PTR and PREPTR which initially point to START.
al 7] 3] 4] 2] 6] s[x
PREPTR
PTR
Move PREPTR and PTR such that PREPTR points to the node containing VAL
and PTR points to the succeeding node.
{a 71 BI a] 2] 6] s[x
START PREPTR PTR
1 7| 3] 4] 2] 6] 5 |x
START PREPTR PTR
1 7] 3] 4] 2] 6] s|x
START PREPTR PTR
Set the NEXT part of PREPTR to the NEXT part of PTR.
1] 7] 3] 4.] BI al sx
START PREPTR PTR
1 7[ 3. ] I é| s[x
START
Figure 18.20 Deleting the node after a given node in alinked list
Introduction to Data Structures: 469
array. Every stack has a variable TOP associated with it Figure 18.25 An example of a stack
Introduction to Data Structures 473
aS 2 3 TOP = 5 6 7 8 9
condition. In step 2,
stack pointed by ToP
the value of the location in the
is stored in VAL. In step 3, TOP is
decremented
Figure 18.26 An example of a numeric stack
Step 1: IF TOP = NULL, then
To insert an clement with value 6, we will first check WRITE “UNDERFLOW"
if TOP = MAX - 1. If the condition is false, then we will Go to Step 4
increment the value of TOP and store the new element at [ENO OF IF}
the position given by stack[ TOP). Thus, the updated stack
Step 2: SET VAL = STACK[TOP]
becomes as shown in Figure 18.27
Step 3: SET TOP « TOP - 2
aa ee | ee (I
Step 4: EXIT
GERD queues i .
]
Let us explain the concept of queues using the analogies Figure 18.36 Queue after deletion of an element
given below
However, before inserting an clement in the queue, we
* People using an escalator—those who get on the must check for OVERFLOW conditions. An OVERFLOW will
escalator first will be the first ones to step out of it occur when we try to insert an clement into a queue that is
* People waiting for a bus—the first person standing in already full, when REAR = MAX - 1, where MAX is the size
the line will be the first one toget on to the bus. of the queue, that is, MAX specifies the maximum number
People standing outside the ticketing window of a of elements that the queue can hold. Note we have written
cinema hall—the first person in the line will get the MAX - 1, because the index starts from 0.
ticket first and thus will be the first one to move out of it Similarly, before deleting an clement from the queue,
Luggage kept on conveyor belts—the bag that was we must check for the UNDERFLOW condition. An UNDERFLOW
placed first will be the first to come out at the other end. condition occurs when we try to delete an element from a
Cars lined up for filling petrol—the car that comes first queue that is already empty. If FRONT = NULL and REAR =
will be filled first NULL, this means that there is no clement in the queue.
In all these examples, we sce that the element in the Figure 18.37 describes the algorithm to insert an element
first position is served first. The same is the case with the in a queue. In step |, we first check for the OVERFLOW
queue data structure, A queue is a first-in, first-out (FIFO) condition, In step 2, we check if the queue is empty. In case
data structure, in which the clement that is inserted first is the queue is initially empty, then the value of FRONT and
the first one to be taken out. The elements in a queue are REAR is set to zero, so that the new value can be stored at the
added at one end called the rear, and removed from the zero-th location. Otherwise, if the queue already has some
other end called the front. values, then REAR is incremented so that it points to the next
Queues can be implemented cither using arrays or free location in the array. In step 3, the value is stored in the
linked lists. In this chapter, we will see how queues are queue at the location pointed by REAR
implemented using arrays
Step 1: IF REAR*MAX-1, then
Weite OVERFLOW
18.6.1 Operations on Queues Go to Step 4
[ENO OF IF}
Queues can be casily represented using linear arrays. As Step 2: IF FRONT = NULL and REAR = NULL, then
stated carlier, every queue has FRONT and REAR variables SET FRONT = REAR « O
that will point to the position from where deletions and ELSE
insertions, respectively, can be performed. Consider the SET REAR = REAR + 1
queue shown in Figure 18.34 [END OF IF)
Step 3: SET QUEUE[REAR] » NUM
Step 4: EXIT
EH ry
ES a a Figure 18.37 Algorithm to insert an element in a queue
Figure 18.34 An example of a queue Figure 18.38 shows the algorithm to delete an clement
from a queue. In Step |, we check for UNDERFLOW condition.
Here, FRONT = O and REAR = S. If we want to add one An UNDERFLOW occurs if FRONT = NULL or FRONT >
more value in the list, say, another clement with value 45, REAR. However, if queue has some values, then FRONT
then REAR would be incremented by | and the value would is incremented so that it now points to the next value in the
be stored at the position pointed by REAR. The queue after queue.
addition would appear as shown in Figure 18.35
Step 1: IF FRONT = NULL OR FRONT > REAR, then
Pile
iee =SE
Write UNDERFLOW
ELSE
SET VAL = QUEUE[FRONT]
SET FRONT = FRONT + 1
Figure 18.35 Queue after insertion of a new element [ENO OF IF]
Step 2: EXIT
Here, FRONT = Oand REAR = 6. Every time anew element Figure 18.38 Algorithm to delete an element from a queue
has to be added, we will repeat the same procedure.
Now, if we want to delete an clement from the queue,
then the value of FRONT will be incremented. Deletions 3. Write 4 program to implement a linear queue.
are done from only this end of the queue. The queue after Solution.
deletion of an element will be as shown in Figure 18.36. ##include <stdio.h>
Here, FRONT = 1 and REAR = 6. #include <conio.h>
476 Computer Fundamentals and Programming in C
“ @@
right sub-trees of R. If T, is non-empty, then T, is said to be
the left successor of R.Likewise, if T, is non-empty then, it
is called the right successor of R
“ @0@®@
) Root node
1 @) @) a
©6660©
600 @ Figure 18.40 Binary tree
©6@@ ©
that a node has. The degree of a leaf node is zero. For
example, in the tree, degree of node 4 is 2, degree of
node 5 is zero and degree of node 7 is 1
Figure 18.39 Binary tree Sibling: All nodes that are at the same level and share the
same parent are called siblings (brothers). For example,
In Figure 18,39, node 2 is the left successor and node nodes 2 and 3; nodes 4 and 5; nodes 6 and 7; nodes 8
3 is the right successor of root node 1. Note that the left and 9; and nodes 10 and 11 are siblings.
sub-tree of root node consists of the nodes 2,4, 5,8, and * Leaf node: A node that has no children is called a leaf
9, Similarly, the right sub-tree of the root node consists of node or a terminal node. The leaf nodes in the tree are:
nodes 3, 6, 7, 10, 11, and 12. 8,9, 5, 10, 11, and 12.
In a binary tree, every node has 0-2 successors, A node Path: A sequence of consecutive edges, For example, in
that has no sur ors is called a leaf or terminal node. In Fig. 18.40, the path from the root node to the node 8 is
the tree in Figure 18.39, root node & has two successors given as: 1, 2, 4, and 8.
2 and 3. Node 2 has two successor nodes, 4 and 5; node * Depth: The depth of a node N is given as the length of
4 has two successors 8 and 9; node 5 has no successor; the path from the root R to the node N. The depth of the
node 3 has two successor nodes 6 and 7; node 6 has two root node is Zero,
successors 10 and 11; and finally, node 7 has only one * Height of a tree: \t is the total number of nodes on the
successor, 12, path from the root node to the deepest node in the tree.
A binary tree is recursive by definition as every node in Atree with only a root node has a height of 1. A binary
the tree contains a left sub-tree and a right sub-tree. Even tree of height b has at least h nodes and at most 2h -
the terminal nodes contain an empty left sub-tree and an 1 nodes. This is because every level will have at least
empty right sub-tree. In Figure 18.39, nodes 5, 8, 9, 10, one node and can have at most 2 nodes. So, if every
11, and 12 have no or zero successors, and are thus said to level has two nodes then a tree with height h will have
have empty sub-trees. at the most 2h ~ 1 nodes as at level 0, there is only one
478 Computer Fundamentals and Programming in C
es Bl
Cet) LTT]
T+T} (elsT*] IT) eb
¢lementcalled the root, The height of a binary tree with Sequential representation of binary trees Sequential
n nodes is at least log,(n +1) and at most n. representation of binary trees is done using a single or one-
* Ancestor and descendant nodes: Ancestors of a node dimensional array. Although it is the simplest technique for
are all the nodes along the path from the root to that memory representation, it is very inefficient as it requires
node, Similarly, descendants of a node are all the nodes a lot of memory space. A sequential binary tree follows the
along the path from that node to the leaf node. following rules:
Binary trees are commonly used to implement binary * Aone-dimensional array, called TREE, is used.
search trees, expression trees, tournament trees, and * The root of the tree is stored in the first location, That is,
binary heaps TREE[1) will store the data of the root clement
* The children of a node K will be stored in location (2*K)
18.7.1 Representation of Binary Trees in and (2*K+1)
Memory * The maximum size of the array TREE is given as (2"=1),
where h is the height of the tree
In the computer's memory, a binary tree can be maintained * An empty tree or sub-tree is specified using NULL. If
cither using a linked representation (as in case of a linked TREE[1] = NULL, then the tree is empty
list) or using a sequential representation (as in case of
single arrays). Figure 18.42 shows a binary tree and its corresponding
sequential representation. The tree has 11 nodes, and its
Linked representation of binary trees In the linked height is 4
representation of binary trees, every node will have three
parts: the data clement, a pointer to the left node, and a
I 0
pointer to the right node. Hence, in C, the binary tree is 2 15
built with a node type given as follows: 3 35
struct node { 4 12
struct node* left; S|_i7_ |
int data; 6), 21)
struct node* right; 7) 39)
i @ i
Every binary tree has a pointer ROOT, which will point
to the root clement (topmost clement) of the tree. If ROOT ® ® itt
@®®o@® i
= NULL, then it means the tree is empty. The schematic
diagram of the linked representation of the binary tree is
shown in Figure 18.41.
(c) ® @ @ is[ 45
In this figure, the left field is used to point to the left
child of the node or, in technical terms, to store the address Figure 18.42 Binary tree and its sequential representation
of the left child of the node. The middle field is used to
store the data. Finally, the right field is used to point to the
18.7.2 Traversing a Binary Tree
right child of the node or to store the address of the right
child of the node. Empty sub-trees are represented using X Traversing a binary tree is the process of visiting each
(meaning NULL) in the figure. node exactly once in a systematic way. Unlike linear data
Introduction to Data Structures 479
structures in which the elements are traversed sequentially, Step 1: Repeat Steps 2 to 4 while TREE! = NULL
a tree is a non-linear data structure in which the elements Step 2: INORDER (TREE->LEFT)
can be traversed in many different ways. There are Step 3: Weite “TREE-> DATA”
different algorithms for tree traversals. These algorithms Step 4: INORDER(TREE- RIGHT)
differ in the order in which the nodes are visited. In this [END OF LOOP]
section, we will read about these algorithms. Step 5: EXIT
Pre-order algorithm To traverse a non-empty binary
Figure 18.45 Algorithm for in-order traversal
tree in pre-order, the following operations are performed
recursively at cach node, The algorithm works by
Post-order algorithm To traverse a non-empty binary
+ Visiting the root node
tree in post-order, the following operations are performed
* Traversing the left sub-tree
recursively at each node, The algorithm works by:
* Traversing the right sub-tree
* Traversing the left sub-tree
Consider the tree given in
* Traversing the right sub-tree
Figure 18.43 * Visiting the root node
The pre-order traversal
of the tree is given as A, Consider the tree given in Figure 18.43 The post-
B, C; first the root node, order traversal of the tree is given as B, C, A; first the
second the left sub-tree, and left sub-tree, second the right sub-tree, and then the root
then the right sub-tree. Pre- node. In this algorithm, the left sub-tree is always traversed
Figure 18.43 Binary tree before the right sub-tree and the root node. The word ‘post’
order traversal is also called
depth-first traversal. In this algorithm, the left sub-tree is in ‘post-order’ specifies that the root node is accessed after
always traversed before the right sub-tree, The word “pre” the left and right sub-trees. The post-order algorithm is also
in “pre-order” specifies that the root node is accessed prior known as left-right-node (LRN) traversal algorithm. The
to or before any other nodes in the left and right sub-trees. algorithm for post-order travel is shown in Figure 18.46,
The pre-order algorithm is also known as node-left-right
(NLR) traversal algorithm. The algorithm for pre-order Step 1: Repeat Steps 2 to 4 while TREE != NULL
traversal is given as shown in Figure 18.44 stevia POSTORDER(TREE=>LEFT)
Step 3: POSTORDER (TREE ~>RIGHT)
: Repeat Steps 2 Step 4: Write “TREE->DATA
Step 1: tk toto 4 while ile TREE TREE t= NULL [ENO oF }
Step 2: Write TREE->DATA Step 5: EXIT
* Transportation networks in which nodes are airports, = 0, it means that u does not belong to any edge, and
intersections, ports, ctc. The edges can be airline flights, such a node is known as an isolated node.
one-way roads, shipping routes, etc. Path: A path P, written as P = (Vo, Viy Vay ms Vads
of length n from a node u to v is defined as a sequence
Definition of (n + 1) nodes. Here, u = vo, V = Vp, and yy. is
adjacent to v, fori = 1, 2, 3, ~)
+ A graph G is defined as an ordered set (Vv, €), where Loop: An edge that has identical end-points is called a
V(G) represents the set of vertices and £(G) represents
loop. That is,e = (u, u)
the edges that connect these vertices. * Size of the graph: The size of a graph is the total number
Figure 18.47 shows
a graph with V(G) = { A, B, C, D,
of edges in it.
E} and €(G) = { (A, B), (B, C), (A, 0), (8, 0),
(Db, £), (C, E) }. Note that there are five vertices or Terminology of a Directed Graph
nodes and six edges in the graph.
* A graph can be directed or undirected. In an undirected * Out-degree of a node; The out-degree of a node u,
graph, the edges do not have any direction associated written as outdeg(u), is the number of edges that
with them, That is, if an edge is drawn between nodes originate at u
A and 6, then the nodes can be traversed from A to B as * In-degree of a node: The in-degree ofa node u, written
well as from 6 to A. Figure 18.47 shows an undirected as indeg(u), is the number of edges that terminate at u
graph because it does not give any information about * Degree of a node: Degree of a node, written as deg(u),
the direction of the edges. is equal to the sum of in-degree and out-degree of that
node. Therefore, deg(u) = indeg(u) + outdeg(u)
* Source: Anode u is known as a source if it has a positive
out-degree but an in-degree = 0
* Sink: Anode u is known as a sink if it has a positive in-
degree but a zero out-degree.
Reachability: Anode v is said to be reachable from node
u, if and only if there exists a (directed) path from node
wu to node v. For example, if you consider the directed
graph given in Figure 18.48, you will observe that node
Dis reachable from node A
Figure 18.47 Graph
18.8.1 Representation of Graphs
Look at Figure 18.48, which shows a directed graph. In
There are two common ways of storing graphs in computer
a directed graph, the edges form an ordered pair. If there
memory, They are:
is an edge from A to B, then there is 4 path from A to 8,
but not from B to A, The edge (A, 8) is said to initiate + Sequential representation by using an adjacency
from node A (also known as initial node) and terminate matrix
at node B (terminal node). * Linked representation by using an adjacency list that
stores the neighbours ofanode using a linked list
In this section, we will discuss both these schemes,
Adjacency matrix representation An adjacency matrix
is used to represent the nodes that are adjacent to one
another, By definition, we have learnt that two nodes are
said to be adjacent if there is an edge connecting them,
In a directed graph G, if node v is adjacent to node u,
then surely there is an edge from u to v. That is, ifv is
adjacent to u, we can get from u to v by traversing one
edge. For any graph G having n nodes, the adjacency
Figure 18,48 Directed graph
matrix will have dimensions of n « n.
In an adjacency matrix, the rows and columns are
Graph Terminology labelled by graph vertices. An entry aij in the adjacency
* Adjacent nodes or neighbours: For every edge e = matrix will contain 1, if vertices vi and vj are adjacent to
(u, v)that connects nodes u and v; the nodes u and v each other. However, if the nodes are not adjacent, aij will
are the end-points and are said to be the adjacent nodes be set to zero, To summarize, look at Figure 18.49
or neighbours. Since an adjacency matrix contains only 0s and 1s,
+ Degree of anode: The degree of anode u, deg(u), is the it is called a bit matrix or a Boolean matrix. The entries
total number of edges containing the node u. If deg(u) in the matrix depend on the ordering of the nodes in 6.
Introduction to Data Structures 4st
C) ©
if ¥, is adjacent to v). that is,
there is an edge (¥,. v,)
0 = otherwise
ABCDE
o1010
|® Ol sreis D
choice. "3
Adding new nodes in G is easy and straightforward scanf("%d", &no_of_nodes);
when G is represented using an adjacency list. Adding for(i = 0; i < no_of_nodes; i++)
new nodes in an adjacency matrix is a difficult task as Adj({i] = NULL;
the size of the matrix needs to be changed and existing createGraph(Adj, no_of_nodes);
nodes may have to be reordered. printf("\n The graph is: ");
displayGraph(Adj, no_of_nodes);
Consider the graph given in Figure 18.51, and see how deleteGraph(Adj, no_of_nodes);
its adjacency list is stored in memory. getch();
return 0;
4. Write a program to create a graph of n vertices using an
}
adjacency list. Also write the code to read and print its void createGraph(struct node *Adj[], int no_
information and finally to delete the graph of_nodes)
Solution {
#include <stdio.h> struct node *new_node, *last;
#include <conio.h> int i, j, n, val;
#include <alloc.h> for(i = 0; i < no_of_nodes; i++)
482 Computer Fundamentals and Programming in C
SUMMARY
* A data structure is a collection of elements that are empty. This happens when START = NULL or when
grouped under one name. there are no more nodes to delete.
Data structures can be broadly classified into linear Astack is a linear data structure in which elements are
and non-linear data structures. The examples of linear added and removed only from one end, which is
data structures are arrays, linked lists, stacks, and called top. Hence, a stack is called a LIFO data structure
queues. The examples of non-linear data structures as the element that is inserted last is the first one to
are trees and graphs. be taken out.
. A linked list is a linear collection of nodes. A queue is a FIFO data structure in which the element
Before we insert a new node in a linked list, we need that is inserted first is the first one to be taken out.
to check for the OVERFLOW condition, which occurs The elements in a queue are added at one end called
when AVAIL = NULL or no free memory cell is present rear and removed from the other end called front.
in the system. A tree is a data structure mainly used to store data
. Before we delete a node from a linked list, we must that is hierarchical in nature. in a binary tree, every
first check for the UNDERFLOW condition, which occurs node has 0, 1, or at the most 2 successors. A node that
when we try to delete a node from a linked list that is has no successors is called the leaf node or the
Introduction to Data Structures 483
terminal node. Every node other than the root node edges containing the node u. When the degree of a
has a parent. node is zero, it is also called an isolated node. A path P
* Degree of a node is equal to the number of children is known as a closed path if the edge has the same
that a node has. The degree of a leaf node is zero. All end-points.
nodes that are at the same level and share the same © Graphs can be represented in memory by using
parent are called siblings. adjacency matrix or adjacency list.
A graph is basically a collection of vertices (also called
nodes) and edges that connect these vertices.
© Degree of a node u, deg(u), is the total number of
GLOSSARY
Adjacency list A representation of a directed graph with Level-order traversal The traversal technique in which all
n nodes using an array of n lists of nodes. List i contains nodes of a tree are processed by depth: first the root and
vertex j if there is an edge from vertex i to vertex 4. then the children of the root. It is equivalent to a breadth-
Adjacency matrix A representation of a directed graph first search from the root.
using ann » n matrix, where n is the number of nodes. Link A reference, pointer, or access handle to another
An entry at (1,3) is 1 if there is an edge from vertex 4 to part of the data structure. Usually, it stores the memory
vertex j; otherwise, the entry is 0. address of next node in the list.
Binary tree A tree in which every node can have at most Linked list A list in which each node has a link to the next
two children. node.
Depth-first search A search algorithm that considers Out-degree The number of out-going edges of a node in
outgoing edges of a node before any of the node’s siblings. a directed graph.
That is, extremes are searched first. Path A list of nodes of a graph where each node has an
Directed graph A graph that has edges represented by edge from it to the next node.
ordered pairs of nodes. In a directed graph, each edge can Post-order traversal The traversal technique in which all
be followed from one vertex to another vertex nodes of a tree are processed by recursively processing all
Edge A connection between two nodes of a graph. In a sub-trees and then finally processing the root.
directed graph, an edge goes from one node (source) to Pre-order traversal The traversal technique in which all
another node (destination), thereby making a connection nodes of a tree are processed by processing the root first
in only one direction. and then recursively processing all sub-trees.
First-in, first-out A policy in which items are processed in Queue Acollection of items in which the first item added
the order of arrival. is accessed first.
Graph A set of nodes connected by edges. That is, a graph Sink A node with zero out-degree. That is, a node of a
is a set of nodes and a binary relation between nodes directed graph with no outgoing edges.
(adjacency).
Source A node of a directed graph with no incoming
In-degree In-degree of a node is equal to the number of edges, that is, a node with zero in-degree.
in-coming edges of that node in a directed graph. Stack Acollection of items in which only the most recently
In-order traversal The traversal technique in which all added item is removed.
nodes of a tree are processed by recursively processing Tree A set of notes where a node is designated as the
the left sub-tree first, then processing the root, and finally root of the tree and all remaining nodes are partitioned
the right sub-tree. into non-empty sets each of the which is a sub-tree of
Last-in, first-out A policy in which the most recently the root.
arrived item is processed first.
484 Computer Fundamentals and Programming in C
EXERCISES
Fill in the Blanks 6. Aline in a grocery store represents a
1, ___ is used to store the address of the first free (a) stack (b) queue
memory location. (c) linked list (d) array
2. Inserting a node in the middle of the singly linked fist 7. In a queue, insertion is done at the
needs to modify pointers.
{a) rear
3. Deleting a node from the beginning of the singly linked
{b) front
list needs to modify __ pointers.
4. Data elements ina linked list are known as (c) back
5. New nodes are added atthe __ of the queue. {d) top
6A _ is the appropriate data structure to process 8. The degree of a leaf node is
batch computer programs submitted to the computer fa) 0
centre.
{b) 1
7, A_____ is the appropriate data structure to process a
{c) 2
list of employees that have a contract for a seniority
system for hiring and firing. (d) 3
8. The parent node is alsoknown asthe _ node. 9, The depth of the root node is
9. The maximum number of nodes at the &” level of binary fa) 0
tree is (b) 1
10, Ina binary tree, every node can have maximum {c) 2
successors. (d) 3
11, Nodes at the same level that share the same parent are 10. Abinary tree of height
hhas at least
h nodes and at most
called _ __ nodes.
12, The height of a binary tree with n nodes is at least
(a) 2h
and at most
(b) 2°
13 node has a zero degree
14, In-degree of a node is the number of edges that (ce) 2"
atu, (d) 2”*
15, Adjacency matrix is also known as a 11. Pre-order traversal is also called
16. A path P is known asa_____ path if the edge has the (a) depth-first traversal
same end-points. (b) breadth-first traversal
(c) level-order traversal
Multiple-choice Questions
(d) in-order traversal
1, Alinked list isa
12. The total number of nodes in the n" level of a binary tree
(a) random access structure can be given as
(b) sequential access structure (a) 2n
(c) Both (a) and (b) (b) 2°
2. An array isa
(c) 2"
(a) random access structure
(d) 2"*
(b) sequential access structure 13. The number of edges that originate at u is called
(c) Both (a) and (b) (a in-degree
3, Astackisa
(b) out-degree
(a) UFO (b) FIFO (c) degree
(c) FILO (d) LILO (d) source
4. Which function places an element on the stack? 14. Total number of edges containing the node u is called
(a) Pop() (b) Push() (a) in-degree
(c) Peek() (d) isEmpty() {b) out-degree
5. Disks piled up one above the other represents a
(c) degree
(a) stack (b) queve
{d) None of these
(c) linked list (d) array
Introduction to Data Structures 485
20,
node.
The size of a graph is the total number of vertices in it
@
©
21. Anode is known as a sink if it has a positive out-degree
but an in-degree = 0.
© @ © ®@
Review Questions
1, Make a comparison between a linked list and a linear
array, Which one will you prefer to use and when?
2, What do you understand by stack overflow? Write a
© @
program to implement a stack using a linear array that
checks for stack overflow condition before inserting
elements into it
Differentiate between an array and a stack. * Make a list of the leaf nodes
How does a linked stack differ from a linear stack? * Name the leaf nodes
Differentiate between peek() and pop() functions. * Name the non-leaf nodes
. Give the stack when
pw
On the following operations are
* Name the ancestors of node E
performed on an empty stack:
* Descendants of A
* AddA, B, C, D, E, F
* Sibling of C
* Delete two letters
© Height of the tree
* AddG
© Height of sub-tree at E
* Addi
* Level of node E
* Delete four letters
* Give the in-order traversal of the tree
© AddI
* Give the pre-order traversal ofthe tree
7. Give the queue when the following operations are
performed on an empty queue. Give the post-order traversal of the tree
* AddA, 8, C, D, E, F Give the level-order traversal of the tree
486 ‘Computer Fundamentals and Programming in C
14, Give the binary tree having the following memory 16. Explain the relationship between a linked list structure
representation and a digraph
17. What is a graph? Explain its key terms.
ROOT 18. How are graphs represented inside the computer
memory? Which method do you prefer, and why?
19. Draw a complete undirected graph having five nodes.
20. Consider the following graph and give the degree of
each node.
Go
21. Consider the following graph and state all the simple
©
paths from A to D, B to D, and C to D. Also give the in
degree and out-degree of each node. Is there any source
or sink in the graph?
© ®)
>
a ()
22. Consider the following graph and show its adjacency list
@
a
© ©
15. Give the memory representation of the following binary
tree.
[ Flight Number | ORIG DEST 14, Write a program to input an n digit number. Now, break
this number into its individual digits and then store
| ‘ 103 | e «
every single digit in a separate node, thereby forming a
| 1os | c | d linked list. For example, if you enter 12345, now there
| 105 b e will be five nodes in the list containing nodes with
values—1, 2, 3, 4, and 5.
ls | « | |
15. Write a program to sum the values of the nodes of a
107 e a linked list and then calculate the mean.
108 a d 16 Write a program that prints the minimum and maximum
The byte is the lowest level at which data can be accessed. Since the result is 0010 (non-zero), it clearly indicates
C does not support bit-type. Therefore, we cannot perform that the second bit in the original pattern was |. Such
any operation on an individual bit, Even a bitwise operator an operation is called bit masking because it masks the
will be applied to, at a minimum, an entire byte at a time. portions that should not be altered or which are not of
We have already studied bitwise NOT, AND, OR, and interest. In this case, the 0 values mask the bits that are
XOR operators in Chapter 9. To summarize: not of interest.
The bitwise AND can also be combined with the bitwise
* The bitwise NOT (~), or complement, is a unary NOT to clear bits.
operator used to perform logical negation on each bit
thereby resulting in 1s complement of the given binary
value. Bits that are Os become 1s, and vice versa. For BITWISE SHIFT OPERATORS
example, ~(1010) = 0101.
* A bitwise OR (|) takes two bit patterns of equal length, In bitwise shift operations, the bits are moved, or shifted,
and produces another one of the same length by to the left or right. The CPU registers have a fixed number
performing the logical inclusive OR operation on cach of available bits for storing numerals, so when we perform
pair of corresponding bits. In each pair, the result is 1 if shift operations; some bits will be ‘shifled out’ of the
the first bit is1 OR the second bit is1 OR both bits are register at one end, while the same number of bits are
1, otherwise the result is0. ‘shifted in’ from the other end.
1001 | 0101 = 1101 In an arithmetic shift, the bits that are shifted out of
* Abitwise exclusive or (*) takes two bit patterns of equal cither end are discarded. There are two types of arithmetic
length and performs the logical XOR operation on each shift: left arithmetic shift and a right arithmetic shift.
pair of corresponding bits. In the result, a bit is set to | Ina left arithmetic shift, zeros are shifted in on the right,
For example, consider the register with the following bit
if the two bits are different, and 0 ifthey are the same.
The XOR operation is generally used by assembly
language programmers as a short-cut to set the value of
a register to zero, Performing XOR on a value against
itself always results in zero. The XOR operation requires
7 6 5 4 3 2 1 0
fewer CPU clock cycles when compared with the
sequence ofoperations that has to be performed to load
a zero value and save it to the register. The bitwise XOR
is also used to toggle flags in a set of bits. For example, 7 6 5 a 3 2 1 0
Bitwise Operations 4 sy
Note that in arithmetic shift lefi, the leftmost bit was Then x >> 2 = 00110001 eo.
shifted past the end of the register, and a new 0 was shifted Note that inarithmetic shift right operatio bits inn,
opare
into the rightmost position. The general form of doing a shifted to right by n positions. In this process, the rightmost
left shifi can be given as n bits will belost and zeros will be shifted in the leftmost n
op <<¢n bits. (Thi isstrue for unsigned integers, for signed integers
the shift right operation is machine dependent).
Here, op is an integer expression that has to be shifted
and n is the number ofbit positions to be shifted.
For example, if we write Points to remember
unsigned int x = 11000101; * op and n can be constants or variables,
Then x << 2 = 00010100 * ncannot be negative.
+ nshould not exceed the number of bits used to represent
Ifa right arithmetic shifi is performed on an unsigned
op.
integer then zeros are shifted on the left.
+ Left shifting is the equivalent of multiplying by a power
of 2.
of+s]{sfofofo]s]o]:| Right shift will be theequivalent ofinteger division by 2.
7 6 $s 4 3 2 1 °
fofs{s}ofofo]:]o|
7 6 5 a 3 2 1 0
double 1og(double 7 Calculates the natural size_t // Specifies the type for
x); logarithm of x objects declared to store
char* fgets(char* // Used to copy characters void* ptr, size_t stream, nobj objects of
s, int n, FILE* from input stream stream size, size_t nobj, size size from array ptr.
stream); to s until either n- 1 FILE* stream); Returns number of objects
characters are copied, weitten. |
newline is copied, end-of- int fseek(FILE* // To set file position for
file is reached or an error stream, long stream stream and clears
occurs. If no error, s is offset, int end-of-file indicator. For a
NULL-terminated. Returns origin); binary stream, file position
NULL on end-of-file or is set to offset bytes from
error, s otherwise. the position indicated by
int fputc(int c, // To write the character origin: SEEK_SET, SEEK_CUR, |
FILE* stream); ¢ to stream. Returns ¢ or or SEEK_END. Returns non-
EOF on error. zero on error.
long ftell(FILE* // Returns current file
char* fputs(const // To write s, to the
chare s, FILE* output stream. Returns stream); position for stream or -1
on error
stream); non-negative on success or
EOF on error. void rewind(FILE* // Same as fseek(stream,
int getc(FILE* // Same as fgetc except stream); OL, SEEK SET); |
Streams that it may be a macro int fgetpos(FILE* // To store current file
int getchar(void); // Same as getc(stdin) stream, fpos_t* position for stream in
ptr); *ptr. Returns non-zero on
char* gets(char* // To copy characters from error.
s)3 stdin into s until either
a newline is encountered, int fsetpos(FILE* // To set current position
end-of-file is reached, or
stream, const of stream to *ptr. Returns
error occurs. Note that it fpos_t* ptr); non-zero on error.
does not copy newline and void clearerr(FILE* // To clear the end-of-file
terminates s with a ‘\0’. stream); and other error indicators
Returns s, or NULL on end- for stream
of-file or error. Should int feof(FILE* : // To returns non-zero if
not be used because of stream); end-of-file indicator is
the potential for buffer set for stream
overfiow. int ferror(FILE* // To return non-zero if |
int putc(int c, /{ Same as fputc except stream); ante |
error indicator is set for |
FILE* stream); that it may be a macro stream J
404 Computer Fundamentals and Programming in C
void perror(const 7 To print (if non-null) long strtol(const |// To convert initial
char* s); and strerror(errno) to char* s, chare* characters (ignoring
standard error endp, int base); leading white space)
tbe se stdlib.h> _ 7 3 of s to type long. If
EXIT_FAILURE //Specifies value for
endp non-null, stores
status argument to exit pointer to unconverted
indicating failure suffix in *endp, If base
lies between 2 and 36,
EXIT_SUCCESS //Specifies value for that base is used for
status argument to exit conversion; if OX or Ox
indicating success implies hexadecimal; 0
RAND_MAX // Specifies maximum value implies octal, otherwise
returned by rand() | decimal assumed. ]
NULL // Specifies Null pointer unsigned long // Same as strtol except
| constant strtoul(const result is unsigned long
div_t // Specifies the return char* s, chare*
type of div(). Structure endp, int base);
having members: int quot, void* // Returns pointer to |
[int rem; _ - . calloc(size_t nobj, allocated space for an
ldiv_t // Specifies the return type size_t size); array of nobj objects each
of Idiv(). Structure having of size size, or NULL on
| member's : long quot, rem; error |
size_t // Specifies type for voide malloc(size_t // Returns pointer to
objects declared to store size); allocated space for an
object of size size, or
result of sizeof operator
| NULL on error
int abs(int n); // Returns absolute value
of n
void // Returns pointer to
realloc(void* p, allocated space for an
long labs (ong n); // Returns absolute value size_t size); object of size size to
of n existing contents of p
div_t div(int num, // Returns quotient and (if non-null), or NULL
int denom) ; remainder of num/denom on error. On successful
Adiv_t Idiv(long // Returns quotient and operation, old object is
num, long denom);_| [remainder of num/denom deallocated, else remains
double atof(const // Same as strtod(s,
unchanged.
char* 5); (char**)NULL) except that
void free(voids // De-allocates space to
errno is not necessarily Pp); which p points (if p is
set on conversion error not null) j
void abort(); // To abnormally terminate |
// Same as (int)
|int atoi (const
char* s); strtol(s, (char**)NULL,
the program |
void exit(int // To terminate the
10) except that errno is
not necessarily set on status); program normally. When
| conversion error
exit() is called, open
files are flushed, open
long atol(const // Same as strtol(s, streams are closed and
char* s); (char**)NULL, 10) control is returned to
except that errno is environment. status is
not necessarily set on
returned to environment.
| conversion error Zero or EXIT_SUCCESS
double strtod(const |// To convert initial indicates successful
char* s, chare* characters (ignoring termination and EXIT_
endp); leading white space) of FAILURE indicates
Ss to type double. If endp unsuccessful termination.
non-null, stores pointer to However, implementations
[unconverted suffix in *endp. may define other values.
ANSI C Library Functions 495
void qsort(void« // To arrange the elements |int strcoll(const |// To compare cs with
base, size_t n, of an array base (of n char* cs, const ct, returning negative
size_t size, int objects each of size size) char* ct); value if cs < ct, zero if
(*cmp) (const according to comparison | cse=ct, positive value if
void*, const function cmp into
voide)); ascending order cmp must // Returns pointer to first
return negative value if char* cs, int c); occurrence of c in cs, or
first argument is less than [NULL if not found
second, zero if equal, and char* strrchr(const | // Returns pointer to last
| positive if greater. char* cs, int c); occurrence of ¢ in cs, or
int rand(void); // To return a pseudo- } NULL if not found
random number in the range size_t strspn(const |// The function returns
0 to RAND_MAX char *stri, const (the index of the first
void srand(unsigned | // To return a new char *str2); | character in stri that
int seed); sequence of pseudo-random doesn’t match any
numbers using the specified | character in str2
seed. Initial seed is 1. size_t |// The function returns
<string.h> strespn(const char | the index of the first
NULL // Specifies the Null *stri, const char | character in stri that
pointer constant *str2); |matches any of the
size_t // Specifies the type for characters in str2.
objects declared to store char *strpbrk(const | // The function strpbrk()
result of sizeof operator char *stri, const | returns a pointer to the
chare strcpy(char* // Copies ct to s char *str2); | first occurrence in stri of
Ss, const char* (including ‘\0’) and any character in str2, or
ct); returns s | NULL if none are present.
chare // Copies atmost n char* strstr(const |// To return a pointer
char* cs, const to first occurrence of ct
strncpy(char* s, characters of ct to s.
const char* ct, If ct is of length less char* ct); within cs, or NULL if none
the object it aceesses, making the pointer and expressions void *memmove(void * si, const void * s2,
based on that pointer, the only way to directly or indirectly size_t n);
access the value of that object. The restrict keyword provides a straightforward
We have studied that a pointer isthe address of amemory implementation of memcpy in C, which gives a level of
location. More than one pointer can be used to access the performance that previously required assembly language
same memory location and modify it during the course of or other non-standard means.
a program. The restrict type qualifier indicates to the
compiler that if the memory addressed by the restrict-
qualified pointer is modified, no other pointer will access INLINE FUNCTIONS IN C
that same memory. The compiler may choose to optimize
code involving restrict-qualified pointers in a way that An inline function is a programming language construct
might otherwise result in incorrect behaviour. which instructs the compiler to perform inline expansion
on a particular function. For an inline function, the
Points to remember compiler will copy the code from the function definition
* Itis a new addition for C99 (the standard from 1999) directly into the code of the calling function rather than
which is not available in older compilers. crealing a separate set of instructions in memory. So,
+ Ifa particular piece of memory is not altered then it can instead of transferring control to and from the calling
be aliased using more than one restricted pointer. function and the called function, a modified copy of the
* In the absence of the restrict keyword, other pointers function body may be substituted directly for the function
can alias the object. call. In this way, the performance overhead of a function
* Caching the value in an object designated through a call is avoided.
restrict-qualified pointer is safe at the beginning of The general format of an inline function is as follows:
the block in which the pointer is declared since no pre- inline return_data_type function_
existing aliases may also be used to reference that object. name(arguments)
However, the cached value must be restored to the A function is declared inline by using the inline
object by the end of the block, where some pre-existing function specifier. However, the inline specifier is just
aliases again become available, If new aliases are formed @ request to the compiler that it should perform inline
within the block, they can be identified and adjusted to expansion. The compiler is free to ignore the request.
refer to the cached value.
function is completely executed, the control is transferred * Amacro cannot use the return keyword, i.c., a macro
back to the calling program. This concept of function cannot return something which is not the result of the
execution may be time consuming since the registers and last expression invoked inside it
other processes must be saved before the function gets * Since macros usually use textual substitution, this may
called cause unintended side-effects and inefficiency due to re-
The extra time and space required may be justified for evaluation of arguments and order of operations.
larger functions but for small functions, the programmer + Compiler errors within macros are often difficult to
may wish to place the code of the called function in the understand.
calling program for it to be executed. This is done by using * Many constructs are awkward or impossible to express
an inline function using macros. Moreover, it uses a significantly different
An inline function reaps the benefits of a function while syntax, Inline functions, on the other hand, use the same
avoiding its overhead. Inline expansion is used to eliminate syntax as ordinary functions.
the overhead involved in a function call. Inline functions + Debugging a macro is much more difficult than
are usually used for functions that are executed frequently debugging an inlined code
They provide space benefit for very small functions and
enable transformation for other optimizations Advantages
In the absence of inline functions, the compiler
* An inline function generates faster code as it saves the
automatically decides which functions to inline. The
time required to execute function calls,
programmer has little or no control over which functions
* Small inline functions (three lines or less) create less
inlined and which are not
code than the equivalent function call, as the compiler
docs not have to generate code to handle function
Comparison to macros arguments and a return value
Initially in C, inline expansion was accomplished at the + Inline functions are subject to code optimizations
source level using parameterized macros, However, C99 that are usually not available to normal functions,
opened the way for true inline functions which provided as the compiler does not perform inter-procedural
several benefits over macros. These include the following optimizations.
* Whena macro is invoked, no type checking is performed.
However, function calls usually do.
<
rview Questions
Solutions
Structure definition must be placed before the display()
1. #include <std function
main()
{
char far *ch;
printf("\n Size of far pointer is : xa", 4. include <stdio.h>
sizeof(ch)); main()
} {
struct student
Ans: 2 {
char name[100);
Senn ener eee int rno;
2. #include <stdio.h>
main()
struct student s = {"Kamesh"};
{
int arr[10) = {1,2,3,4,5,6}; printf("\n Xs Xd Xf", s.name, s.rno, s.fees);
{ if(num == 80)
int option = 2, i; goto print_mesg;
switch( option)
{ }
default: print#("Please check your option"); void fun()
case 1: printf(“\n SUM"); {
break; print_mesg:
case 2: printf(“\n SUBTRACT"); printf("\n Hello World");
break; }
case i: printf("\n MULTIPLY"); Ans: ERROR, goto cannot take the control outside the
break; function (main() in this case)
}
Ans: Error. 10. #include <stdio.h>
Cannot use 4 in the case statement main()
{
tonnes one int num = 7;
printf("xd", num++);
7, #include <stdio.h> num = numel;
main() print#("Xa", ++num);
{ }
int i= 1;
Ans: 7 10
for(;;)
{
printf("Xd", 1);
itt; 11. Sum(int num, int num2)
if (i #5) {
break; int numl = 20;
} int num2 = 30;
} return (numl + num2);
Ansi1234 }
Ans: Redeclaration of variables — numi and num2
8. #include <stdio.h>
main() 12, main()
{ {
int i = 1; int num;
while() num = find(7);
{ if(num == 1)
printf("Xd", i); printf("\n Positive”);
if (i = =5) else
break; printf("\n Negative");
}
int find(int n)
{
Ans: ERROR, condition in the while loop is a must. The n > 0? return(1) : return(0);
statement should be re-written as while(1)
}
SONA RN AERO RENEE RRO T REE R eee Ans: Illegal use of return statement. Rather use it as
return (nm > 0 ? 1:0);
9, #include <stdio.h>
main()
{
int num = 10; 13, #include <stdio.h>
{ {
printf("\n Xd", num*10); int const * num = 7;
Interview Questions with Solutions 503
print#(*Xd",++(*num)); int i,*parr = arr;
} for(i = O;i < S;it+) {
printf(" %d",*parr);
Ans: Error because num is 4 pointer to a “constant integer”
++parr; }
and its value is being changed.
}
Perrtrrireer
itritr trrrrretire Ams:12345
14, main()
{
char str[ ]="abc"; 18. main()
int i=0; {
while(s[i] != "\o") int a =-1,b = -1,c = 0, d = 2, res;
{ res = att B& bee BB c++ || des;
printf("\nXcXckcXe", str[i],*(strei), print# ("Xd %d Xd Xd Xd", a, b, c, d, res);
*(itstr),i[str]); }
its;
Ansi0 0131
}
Ans: aaaa
**bbbb 19. main()
**ccce {
char *str;
Because str{i], *(ivstr), *(strei), if[str) are all printf ("Xd Xd", sizeof(*str), sizeof(str));
different ways of accessing the 4 clement of the array- str. }
Ans: 1 2
Pree rirrer rc itti rr er rr
Since str is a pointer to a character type, its value needs
15, main() I byte in memory and the address of this value will be of
{ 2 bytes
static int counter = 5;
printf("%d", counter--);
if (counter)
main(); 20. main()
) {
char str[]J*"Hello World";
Ans:5 4321 show(str);
Since static variables are initialized only once and their }
values persist between function calls. void show(char *str)
{
printf("%s", str);
Prrrrrrr ier er rte rrr
}
16, main()
{ Ans: ERROR. The default argument type and return
int are{ ] = {1,2,3,4,5); type of a function is int. So a function that has any other
int i,*parr = arr; type of arguments and/or return type must be declared
for(i = Osi < Sjise) ( before it is called. In this case, the return type is void
printf(" %d",*arr); and argument type is char and there is no declaration
+eparr; } statement which gives the details to the compiler in
advance. Hence it is an error because the compiler
}
assumes that the function will accept and return an
Ans: 11111 integer value
Because parr is being incremented and we are printing the
value of arr.
21. main()
SENT RH HERE E RENEE ERROR REE renee {
17, main() int num = 2;
{ printf("c=xd", --2);
int are{ ] = {1,2,3,4,5}; }
504 Computer Fundamentals and Programming in C
rrrrrrrteer
rte errr) Although arr is declared as a 3-D array, the third
dimension is not initialized. Therefore, *p will contain
22. #define int char garbage value as no value exists for arr[2)[2][2]. *q
main() contains the address of the first clement in the array, that
{ is | in this case.
int num = 65;
printf("%d", sizeof(num)) ;
}
26. main()
Ans: 1
{
Because num is actually a char, not an int. See the int num = 5;
#define statement printf("Xd Xd Xd Xd Xd Xd", num++, num-—,
enum, --num, num);
rrrrrrr
errr ttre }
23. main() Ansi4 5545
{ Because evaluation is done from right to left
int rese5;
res = |i > 6;
printf("res = Xd", res);
} 27, define square(x) x*x
main()
Ans: res = 0
{
Because res « S$ in line 1. In line 2, when we write tres, int res;
here | is the negation operator which converts the value of res = 125/square(S);
res to Zero. Now, 0 is not > than 5. Therefore the value print€("%d",res);
of res © 0. }
Ans: 125
Porter iri ci iet iii titre teri
Because when the macro gets expanded
24, main()
{ res = 1285/5 * 5 = 25 * 5 = 125
char str[] #{‘a',‘b’,'c',"\n","c »'\0"};
char *p,*pstr;
pe&str[3]; 28. main()
printf("%d", *p);
{
pstrestr;
char *pstr ="hello”,*pstr1;
printf("%d", ++*pstr); pstrispstr;
} while(*pstr l= '\O') *+*pstr+s;
Ans: 10 98 printf("%s", pstr);
printf("%s", pstri);
Because p is pointing to the third character in str which
is '\n'. The ASCII value of new line character is 10. pstr }
stores the address of the first character in the str which is Ans: efmmp
a’. The value of *pstr is being incremented, therefore it
Evaluate the expression in the following manner
is 98, The ASCII value ofa + 1 = 97 + 1 = 98
(++(*pstr))++. This means the value of pstr is
incremented first and then the address of pstr is
SANA RN AERO RENEE RRO T Ree neenee incremented so that it points to the next character, After
25, main() the while loop gets executed every character in pstr is
{ incremented and pstr finally points to the null character.
Therefore, the first printf statement prints nothing and
int arr{2}(2][{2] = { {1,3,5,7}, {2.4,6,8} }3
int *p,*q;
the second statement prints the modified contents of pstr.
peBarr(2)(2}(2)3
*q = *#8a;
Interview Questions with Solutions 505
29. #include <stdio.h> Because scanf returns the number of items read
#define num S succes fully. In this case, you will be entering only 1
main() value, so scan reads only | item and reports |
{
#define num 100
printf("xd", num);
34, #include <stdio.h>
} pain()
Ans: 100 {
A preprocessor directive can be redefined anywhere in the struct x
program {
int roll_no=1;
char name[]="RAM";
SERPENT ERO E EERO ETRE EERE RHEE ER
hi
30. main() struct x stud;
{ printf("%d", s.roll_no);
printf("%p", main); printf("%s",s.name);
} }
Ans: Address of the main() will be printed. Xp specifies Ans: ERROR
that the address be displayed in hexadecimal numbers Because you cannot initialize structure members within
the structure declaration.
Prrrerrrie
titi ittiti rrr rrr rry
31, main()
{ 35. main()
char str[]="Hello”;
{
char pstr = str;
extern num;
printf("%c\n",*&*pstr); printf("Xd", num);
} }
Ans: 4 int num = -1;
rErrrtt tr
36. main( )
32. main() {
{ int arr{} = {1,2,3,4,5};
int arr{2}(3]= {{1,2,3),44,5,6}}5 for(j = 0; j < 5; j++)
int 4; {
printf("%d" ,*arr);
arr[1)=arr(2); arr++;
}
for (inO;i<2;i++)
}
printf("Xd",arr{i]);
Ans: ERROR
)
arr is the name of an array and not a pointer variable so
Ans: ERROR
writing arr++ creates an error
Because array names are pointer constants, 30 it cannot be
modified
ird
rd
d
Because the strlen function returns 4, ic, the length of the printf("num = Xd, -num = Xd \n", num,-num);
string. In the next statement the value of the n™ location is }
assigned to the first location. In the for loop, the string
is printed in cach iteration. The only difference is that Ans: num = -S, -num = 5S.
during each iteration the starting position of the string =(-5) becomes 5
is incremented, The first iteration prints a blank space
because as soon as printf statement encounters *\0', it
prints nothing and simply increments the pointer valuc
43. main()
FERN EEE EERE EERE REE E RRR E EE Ee {
const int num =
39. main() int res = ++num;
{ printf("Xd", res);
printf("\n HELLO");
}
main();
Ans: ERROR
}
The value of a constant cannot be changed.
Ans: Runtime error will occur because of stack overflow
Prrrerrrieertr
rititirri tr rir
44. main()
40, main()
{
{ register num = 5;
void *pnum, num;
float fnum = 1.5;
num = 0; print#("xd Xf", num, frum);
pnum = #
}
printf ("%v", num) ;
} Ans: 5 1.5
Interview Questions with Solutions 507
Register values are same as other values. The only return ch-32;
difference is that the variable declared as register may }
cither be in register or in memory
Ans: ERROR
errer
rrrerr errr
Function declaration error
45. main()
{
int a = 2, b = 3, res;
printf("res = Xd", ar++b); 49. int arr[) = {1,2,3};
} main()
{
Ans: 5
int ‘parr;
Because the expression is evaluated from night to left as parr = arr;
arr eb printf("%d",*(parr + 5));
rere }
46, struct complex Ans: Garbage value because array index is out of r
{
int real;
int imag; 50. Mesgi(){
hi print#("GOoD") ;
struct complex c, *pc; }
main() Mesg2(){
‘ printf(“Average");
pe = &c; }
printf("Complex number is (Xd +%di) Mesg3(){
\n",(*pc).real, (*pc).imag); print#("BAD") ;
} }
Ans: Complex number is (0 + 01). main()
Because when a structure is declared, all its members are {
automatically initialized to 0. int (*pfun[3})();
pfun[O]»Mesg1;
rrtrrrretirrritr
irri irri pfun(1)=Mesg2;
47, main() pfun[2]=Mesg3;
{ pfun(1}();
int res « (7); }
printf("Xd\n", --res); Ams: AVERAGE
}
int €(int x) Only pfun[2}() is called from main()
{
return(x++)5
} 51. main()
Ans: 6 {
FILE *fp;
The return statement will first return the value of x and char ch;
then print it, Writing ~-res, will first decrement and then
fp = fopen("student.txt",r");
print the value
while((ch = fgetch(fp))!= EOF)
sere printf("%c",ch);
48, main()
}
{ Ans: Infinite loop because the condition should have been
char che'a'; checked against NULL and not EOF
ch = convert(ch);
printf("%c", ch);
}
convert (ch) 52. main()
{
{
508 Computer Fundamentals and Programming in C
55, main()
{ 60, #define mul(x,y) x * y
char str[]="abcd\0"; main()
printf("%d", strlen(str)); {
} int numl = 5, num2 = 7, res;
res = mul(numi + 2, num2 - 5)
Ans: 4 printf("%d", res);
}
”
Ans: 14
56. main()
{ On macro expansion, the expression becomes
Interview Questions with Solutions 509
teeneneeee
62. main() 67. main()
{ {
int num « 2;
int num = 0;
print#("Xd",+enum == 3);
while((num--)!= 0)
numet 5 }
printf("%d", num); Ans: 1
}
The expression in the printf statement is evaluated as
Ans: -1 3==3, which is true and returns 1
Heeneerennenene
63, main() 68. main()
{ {
float fnumi » 5S, fnum2 = 2.5; int res;
printf("%f\n", fnumi<<2); res = strcmp("abc",abc\0");
printf("%1f\n", fnumiXfnum2) ; print#("Xd", res);
} }
Ans: ERROR Ans: 0
Left shift operator does not work for floating point Ending the string constant with \0 explicitly makes no
numbers. % is used for integers. For floating point numbers difference. So both abc and abc\0 are same.
use, fmod().
followed by a symbol to indicate the end of the prompt (a Command | Description Example
hash symbol). © To copy a file To copy filet.txt from
user linux. box.com/home/user# current directory 10 usr/
students directory
The prompt differs duc to the reasons as given below write,
a. default configuration set by the creators of your ep filel.txt usr/
particular Linux distribution students/
b. specifically configured by the person who administers To copy all C files in
the computer the current directary to
another directory write
cp *.€ usr/codes/
EB pirectory ORIENTED COMMANDS rs To remove or delete a rm filename. txt
file
‘Command | Description Example
w To move or rename
afile mv filel.txt file2.txt
|cd ‘To change directory If the directory is in the
current working directory “ ‘To print the number wefilel. txt
then specify the name of newline characters,
otherwise mention the full words and byte counts
path of file
ed marks cmp ‘To compare two files emp filet.txt file2.
ot ed /students/marks byte by byte. Ifa txt
To move up one directory difference is found, it
| type, displays the byte and
ed. line number where the
|ep To copy a directory cp -F existing dir first difference is found.
| ‘with all its contents new_dir In case the files are
|mkdir To create a new mkdir new_dir
exactly same then emp
fetus nooutput
| directory
|mv To move adirectory my existing
dir newane_
| (rename it) dir
| pwd To display the full pwd
path of the current (359 FILE ACCESS PERMISSIONS
| directory COMMANDS
|mie To remove an rmdir
existing empty Linux is a multi-user operating system, In such an
| directory environment, it is very important to protect one user's files
| em To remove a Removes all the files and from being accessed by another user(s). Therefore, before
| directory containing directories with the specified discussing the chmod command which is used to modify
other files and directory file access rights, let us first understand what we actually
directories rm = existing
dir mean by the term file permissions
Filepermissions In Linux, cach file or directory is assigned
(223 Fite ORIENTED COMMANDS access rights for the owner of the file, the members of a
group of related users, and everybody else. These rights
Command | Description Example can be categorized into three groups —read a file/directory,
write to a file/directory, and to execute a file (for example,
cat To concatenate files and — To displayafilewrite
run the file as a program).
print on the standard cat filename.ext
output To concatenate two
tiles, write
cat filel >> file2 > fwxrw = or = -
yaa vans a
touch To create
new (empty) Te create a mew file, write Read, write, and exeeute permissions
file touch filename for all other users
Tis also used twupdate — To update access time, Read. write, and execute permissions
access and modification —write for member of the group owning the file.
times of a file touch -a filename Read, write, and execute permissions
To update modification for the owner of the file.
time, write File type, "_” indicate a regular file. A
touch -m filename “d” indicates a directory
Linux: A Short Guide $13
To view the existing permission of a file, just write To sce all the processes run by a particular user, use thé
-u option as,
ls - 1 file.txt
ps -u jaya
The output would be like, -rwxr-xr-x and other details
To understand this output, separate this access nights This will display all the processes run by jaya
byte in groups of three. To display processes sorted by their by CPU or memory
You may think of these permissions as a series of bits. usage, use the sort command as given below.
A bit is | if the permission is given otherwise it is zero.
Therefore, the three sets of permissions (owner, group and
pS -aux -sort -pcpu
other) can be expressed as, Or, ps -aux -sort -pmem
rwxrwxewx = 111 111 111 = 777 To display processes by their name or ID use the -C option.
For example, to see the details of the processes named abc,
rwxrw- f-- © 111 110 106 * 764
write
Pwx e-x P-- © 111 101 1006754
ps -C abc
chmod
Afler having a basic understanding of file permissions, let's
To display the thread of a particular process use the -L
option as given below
now use the chmod command to alter the file permissions.
chmod 640 file
ps -L 1234 where 1234 is the PID of the process.
corresponds to 110100 000 in binary thereby indicating To display the process hierarchy in a tree form, use the
pstree command
that the owner has only read and write permissions, the
group has only read permission and other users have no
permissions at all for the file ps command can be used to monitor the daily usage
of the Linux system.
Changing file ownership To change the owner, you can
use the chown command as given below
chown new_owner_name file Command —Description Example
However, to use this command you must be the superuser. kill ‘To kill of kill 1234 where 1234 is the
terminate a process ID of the process to
Changing group ownership You can even change the
process: be terminated
group ownership of a file or directory by using the chgrp
Killall ‘To terminate all killall getty (where
command as shown below
the processes
ofa getty is thename ofthe
chgrp new_group file particular name process)
Note that only the owner of the file can change the group xille Tosopallthe = kill @
processes except
ownership of that file
your shell y
‘Command |Description Example Pipes One of the most useful applications of Linux I/O
netstat Toget details To display allconnections,
redirection is to connect multiple commands together using
about network write pipes. With pipes, the standard output of one command is
connection, netstat -a fed into the standard input of another. The symbol of pipe
routing tables, To display only TCP is |.For example, if we write
interfaces, etc. connection, write cat file.txt | we
netstat -tep
‘To display only UDP Now, the output of file. txt file will be sent as input for we
connection, write command which counts the number of words in that file.
netstat -udp Pipes are useful to make a chain of several programs, so
nslookup To find the nslookup google.com that multiple commands can execute at once
hostname if IP
address is known Filters Filter is a class of programs that can be used with
pipes. It takes input from the standard input device, performs
telnet ‘To communicate telnet syhost .com:5555
with another host where myhost.com isthe host an operation upon it and then sends the results to standard
mame and 5555 is the port output. Some common filter programs are given below
number
Program | Description
To view finger
sort ‘Takes standard input, sorts itand then outputs the
information
result on standard output.
about users Gogin
name, terminal uniq ‘Stands forunique. Ittakes a sorted stream ofdata from
name, etc) standard input and remeves duplicate lines ofdata
Command Description
Deletes N words beginning with character
under cursor
|:wq Quits vi by writing the modified contents Deletes the current line
\eq Quits vi
Deletes N lines beginning with the current
iq! Quits vi without saving the changes line
+| Moves the cursor down one line Copies the current line into bullfer
\k Moves the cursor up one line Copies N lines into buffer stasting from the
lh Moves the cursor left one character current line
1 Moves the cursor right one character Pastes the line(s) in the buffer after the
current line
le Moves thecursor to thestartofcurrent Hine
Searches forward in file for any occurrence
$ Moves the cursor to the end ofcurrent line
of string
on Moves the cursor to line
Searches backward in file for any
|:@ and =$ Moves thecursor to firstandbastlineinthe occurrence of string
| file Displays the line number of current line at
“and *b Moves forward and backward one screen the bottom of the screen
lu Undoes the last action Displays the total numberof lines at the
@ Inserts text before the cursor bottoms ofthe sereen
pry
“APPENDIX.
"
_— Answersto Objective
~~ Questions
“
CHAPTER 1
Multiple-choice Questions
1, UNIVAC; 2. Transistors;3,Third generation;4.LISP, Prolog; 5. Network computer; 6. CPU
State True or False
1. True 2. False 3. False 4. False 5. True 6. False
7, True 8, False 9. Truc 10. True
CHAPTER2
Multiple-choice Questions
1, Function keys; 2. All of these; 3. Daisy wheel and band printer; 4. None of these; 5. LCD
CHAPTER 3
Multiple-choice Questions
1, Cache memory;2.Auxiliary memory; 3.Disk latency;4.Allofthese;5. Flash memory; 6.CU; 7. MBR; 8.GFLOPS
CHAPTER 4
Multiple-choice Questions
1, EBCDIC; 2, Gray code; 3. EBCDIC; 4. 5349; 5. 181CD
r
CHAPTER 5S
Multiple-choice Questions
1. NAND; 2, 2"; 3. Distributive; 4. 6; 5. Intersection
CHAPTER 6
Multiple-choice Questions
1. ROM; 2.FORTRAN; 3.Assembly language; 4. Machine language:5.Linker;6.Anti virus; 7. BIOS; 8,Computer
hardware; 9, Operating systems; 10. MS EXCEL; 11. GUI; 12. Windows 8; 13. Third generation; 14, Fourth
generation; 15. All of these
CHAPTER 7
Multiple-choice Questions
1, Simplex; 2.Duplex; 3. Asynchronous; 4.Bus; 5. Ring;6.Ring; 7. Router;8.Allofthese; 9. NIC; 10. Client; 11
Application; 12. Network; 13. Internet
State True or False
1. False 2. Truce 3. True 4. False (two not necessary) 5. True
6. True 7. False 8. False 9. False 10. True 11. True
12. True 13. False 14. True 15. True 16. True 17. True
18. False 19. True
i y
CHAPTER 8
Fill in the Blanks
1, Jump, Goto; 2.Object-oriented programming; 3. procedural; 4. Algorithm; 5. Decision; 6. while, do-while and
for loops; 7. Terminal; 8. Pseudocode; 9, Programming language: 10. design; 11 design; 12. implementation; 13
requirement analysis; 14. Run-time; 15. execution testing, code execution
Multiple-choice Questions
1. Constraint-based;2,Rule-based; 3.Monolithic;4.Structured;5.Object-oriented; 6, Maintenance; 7, Requirements
analysis; 8. Design; 9, all of these; 10. Decision; 11. Flowchart; 12. Activity; 13. All of these; 14, Run-time;
Syntax error
Multiple-choice Questions
1. relational; 2. Logical AND and Logical OR; 3. 3; 4. Bitwise NOT; 5. comma; 6. %hd; 7 8. ‘a’, pi;
9, Floats; 10. %; 11. x=y=2,4
r =
CHAPTER 10
Fill in the Blanks
1. there is no matching else; 2. integral; 3. n; 4. break/continue; 5. infinite; 6. loop; 7. decision control; 8. iterative;
9. post test; 10. sentinel controlled; 11. goto; 12. goto
Multiple-choice Questions
1, conditional branching; 2. n; 3. conditional branching; 4, if-clse-if, 5. : ; 6,anywhere 7. {}; 8. Break; 9, continue
CHAPTER 11
Multiple-choice Questions
1, called function; 2. all of these; 3. void; 4. defined; 5. static; 6, exter; 7. static; 8. auto
520 Computer Fundamentals and Programming in C
CHAPTER12
Multiple-choice Questions
2; 2.7; 3. 200;4. $0;5.25;6.best case; 7. allofthese
CHAPTER 13
Fill in the Blanks
1, a null-terminated character array;2. null character; 3. 5;4.zero; 5. consecutive;6.99; 7. scanf{); 8. zero; 9. 65-91;
10. convert
acharacter into upper case; 11. in dictionary order$1 will come after $2; 12. strrev(); 13. ORNING; 14.
15; 15. index; 16. stdlib.h; 17. Appends the string pointed to by str2 to the end of the string pointed to by str] upto n
characters; 18. if str! is greater than str2 respectively x; 19. strlen(); 20. puts()
Multiple-choice Questions
1, 0; 2,97-123; 3.XPPPXXYYYZZZ; 4,XXXYZZ; 5. world; 6. string.h; 7. all of these; 8.XXABYYZZZ; 9. 7; 10.
streat(s, 1(streat(s2,s3))); 11, 23; 12. streat()
CHAPTER 15
Multiple-choice Questions
1, all of these; 2. structure; 3. Structure variable declaration; 4. dot operator; 5. nested structure; 6. dot operator; 7
all of these; 8, int
CHAPTER16
F the Blanks
1, fil stderr, stdin, stdout; 3. standard stream; 4. w/a; 5. rewind(); 6. binary; 7. fread(); 8. stdout; 9. buffer; 10.
Operating system; 11. binary files; 12. flushall(); 13. stdout; 14. fSeck(), rewind(); 15. stdio,h, -1
22 Computer Fundamentals and Programming in C
Multiple-choice Questions
1, fell();
2.fwrite(); 3. all of these; 4. stdin; 5. buffer; 6. fopen(); 7. fgete()
rc
CHAPTER 17
f~ >
CHAPTER18
Fill in the Blanks
1, AVAIL; 2. two; 3,one;4.node; 5, rear; 6. queue; 7, queue; 8. ancestor; 9,2*'; 10, 2. 11, siblings; 12. at least
log,(n+1) and at most n; 13, Isolated node; 14. terminate; 15. bit matrix or a Boolean matrix; 16. closedpath
Multiple-choice Questions
1, Sequential access structure; 2.Both (a) and (b); 3. LIFO;4.Push(); 5. Stack; 6.Queue;7.Rear; 8.0; 9. 0; 10. 2!
IL. Depth-first traversal; 12. 2h'; 13. out-degree; 14. degree
Reema Thareja is presently Assistant Professor, Department of Computer Science, Shyama Prasad Mukherji College for
Women, University of Dethi.
|ONLINE2:5OURES a
aaah
The following resources are available towapport the Lacuty and students unig this text
For Faculty For Students
* PowerPoant presentations +»Mult choice
iple questions
* Solutions manual * Model question papers
+ Projects * Codes ofchapter wise programming
carmnples
OXFORD
UNIVERSITY PRESS