[go: up one dir, main page]

0% found this document useful (0 votes)
695 views546 pages

CP Text

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

CP Text

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

Computer

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

Oxford University Press is a department of the University of Oxford.


It furthers the University’s objective of excellence in research, scholarship,
and education by publishing worldwide. Oxford is a registered trade mark of
Oxford University Press in the UK and in certain other countries.

Published in India by
Oxford University Press
YMCA Library Building. 1 Jai Singh Road, New Delhi 110001, India

© Oxford University
Press 2012. 2016

The moral rights of the author/s have been asserted.

First Edition published in 2012


Second Edition published in 2016

All rights reserved. No part of this publication may be reproduced, stored in

poe ee
a retrieval system, or transmitted, in any form or by any means, without the
i ifOxford University Press, ited

rightsorganization. Enquiries ncerning reproduction outside the scope of


cot stthe
souldbe sent to
the RightsDepartment, OxfordUniversityPres at the
address above.

You must not circulate this work in any other form


and you must impose this same condition on any acquirer.

ISBN-13: 978-0-19-946373-2
ISBN-10; 0-19-946373-5

eISBN-13 (eBook): 978-0-19-909037-2


elSBN-10 (eBook): 0-19-909037-8

in Times New Roman


by Ideal Publishing Solutions, Delhi
Printed
in India by Magic International (P) Ltd., Greater Noida
bocaoronrehmpepneary erally adap ead whaler
pha University Press in good faith and for inf n only.
Oxford University Press disclaims any responsibility for the material contained therein.
1 dedicate this book to my family
and
my uncle Mr B.L. Theraja
Features of
.
Sag
$: G4aprcuction to Computers
* yor > Yat
bore aan Comprehensive Coverage
nos q aterm
Chapters provide a comprehensive coverage of topics
bee ana ranging from basics of computer hardware and
ee software to the basics of C programming

fiber Systems and c Amays


ee ist S

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

* Acomputer is an electronic machine that accepts data Points to Remember


and instructions and performs computations on the
Summary points at the end of each chapter help
data based on those instructions.
* Computers are used in all interactive devices, such as readers to revise all the important concepts explained
cellular telephones, GPS units, portable organizers, in the chapter
ATMs, and gas pumps.

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

2. Write a program to print Hello World, using pointers.


#include <stdio.h>
int main()
Programming Examples (
char *ch « “Hello World";
About 250 C programs are included, which printf("Xs", ch);
demonstrate the applicability of the concepts learned return 0;
)
Output
Hello World

.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

Steps to register and access Online Resources

‘Step5: Signinwithyour Oxford 10 | Step 7: Fill in your details


Sign i eh pre Ontors 10 | + Fillthe detated
registration form with
correct particulars,
wes * Fields marked with ‘**
lothe form are
mandatory
— © Upitate
© AOVANCED SEARCH eee
» KEYWORDS a,
‘AuTHOR
Tme Step 6:ifyoudenethaveanOxford ID,register withws ‘Step& Validation
SUBTITLE © We shallrevert toyou
PUBLICATION OATE — within 48 hours after
vwerityingthedetails
‘Step 3: Sebect tite on provided by you. Once
© Select Preduct — wadsted, please login
© Select CGntine Resources «sing yourusername
| —_—
tavsorcinie vi
and password
and

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.

ABOUT THE BOOK


This second edition of Computer Fundamentals and Programming in C has been designed as a textbook for the
undergraduate students of engineering, computer science, and computer applications. The objective of this book is to
introduce the readers to the elements of computing, computer hardware and software, and C programming.

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,

NEW TO THIS EDITION


The following are the most notable additions in this:
+ Introduces a chapter on Boolean Algebra and Logic Gates, which discusses the basic concepts underlying digital
computing systems
* Many new sections have been added in this edition, The details are as follows:

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.

CONTENT AND COVERAGE


The book is divided into two parts spanning 18 chapters and five appendices.

Part |: Computers in Fundamentals


Chapter 1, Introduction to Computers, provides an introduction to computers. The chapter explains the generations,
classifications, applications, and the basic organization of a computer system.
Chapter 2. Input and Output Devices, presents a detailed description of the different types of input and output devices.
Chapter 3, Computer Memory and Processors, explains the significance of memory hierarchy and discusses the different
types of primary and secondary memory that are widely used to store data, It also discusses the basic processor architecture
{including RISC and CISC) and the instruction set.
Chapter 4, Number Systems and Computer Codes, discusses binary, octal, and hexadecimal number systems. The
chapter enables the reader to perform arithmetic operations on different number systems, Important codes such as ASCII,
EBCDIC, Excess 3, Gray code, and Unicode are also discussed in the chapter.
Chapter 5, Boolean Algebra and Logic Gates, introduces the concepts of digital computing systems such as Boolean
algebra, Boolean functions, Boolean expressions, and logic gates.
Chapter 6, Computer Software, provides a thorough overview of computer software. It discusses different types
of
system software and application software packages that are widely used.
Chapter 7, Computer Networks and the Internet, talks about different types of computer networks, wired and wireless
media, network devices and topologies, area networks, and data transmission mode. It also discusses the
Internet, TCP/
IP protocol, and different services provided by the Internet.
Chapter 8, Designing Efficient Programs, details the different steps in software development
process, which are
performed for creating efficient and maintai: inable programs. It also explains the different tools, which
are used to obtain
solution(s) of agiven problem at hand.
Preface to the Second Edition {& )

Part Il: Programming in C


Chapter 9, Introduction to C, discusses the building blocks of the C programming language, It includes descriptions on
identifiers, constants, variables, and operators supported by the language.
Annexure 1 shows the steps to write, compile, and execute a C program in Unix/Linux and Ubuntu environments,
Chapter 10, Decision Control and Looping Statements, deals with special types of statements such as decision control,
iterative, break, control, and jump.
Case Study 1 includes two programs which harness the concepts learnt in Chapters 9 and 10.
Chapter 11, Functions, deals with declaring, defining, and calling functions. It also discusses the storage classes as well
as variable scope in C. The chapter ends with the concept of recursion and a discussion of the Tower of Hanoi problem.
Annexure 2 discusses how to create user-defined header files,
Chapter 12, Arrays, provides a detailed explanation of arrays that includes one-dimensional, two-dimensional, and
multi-dimensional arrays, Towards the end of the chapter, the operations that can be performed on such arrays are also
explained.
Case Study 2 provides an introduction to sorting and various sorting techniques such as bubble sort, insertion sort, and
selection sort.
Chapter 13, Strings, discusses the concept of strings, which are better known as character arrays. The chapter not only
focuses on reading and writing strings but also explains various operations that can be used to manipulate them.
Chapter 14, Pointers, presents a detailed overview of pointers, pointer variables, and pointer arithmetic. The chapter also
relates the use of pointers with arrays, strings, and functions. This helps readers to understand how pointers can be used
to write better and efficient programs,
Annexure 3 explains the process of deciphering pointer declarations.
Case Study 3 includes a program which demonstrates how pointers can be used to access and manipulate strings.
Chapter 15, Structure, Union, and Enumerated Data Type, introduces user-defined data types— structures and unions.
It includes the use of structures and unions with pointers, arrays, and functions so that the inter-connectivity between the
programming techniques can be well understood.
Annexure 4 provides an explanation about bit fields and slack bytes.
Chapter 16, Files. discusses how data can be stored in files. The chapter deals with opening, processing, and closing of
files through a C program. These files are handled in text mode as well as binary mode for better clarity of the concepts,
Chapter 17, Preprocessor Directives, deals with preprocessor directives. It includes small program codes that illustrate
the use ofdifferent directives in a C program.
Chapter 18, Introduction to Data Structures, provides an introduction to different data structures such as linked lists,
stacks, queues, trees, and graphs,
Appendix A, Bitwise Operations, discusses bit-level programming and some of the bitwise operators.
Appendix B, ANS! C Library Functions, lists some of theANSI C library functions and their descriptions,
Appendix C, Advanced Type Qualifiers and Inline Functions in C, introduces some advanced type qualifiers as well as
inline functions.
Appendix D, Interview Questions with Solutions, includes about 100 frequently asked interview questions along with
their solutions.
Appendix E, Linux: A Short Guide discusses the basics of Linux kere! and shell and describes the most commonly used
Linux commands.
Appendix F, Answers to Objective Questions, provides answers to objective questions.

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.

ABOUT THE BOOK


Computer Fundamentals and Programming in C is aimed at serving as a textbook for undergraduate level courses in
computer science and engineering and postgraduate level courses of computer applications, The objective of this book
is to introduce the students to the fundamentals of computers and the concepts of the C programming language and
enable them to apply these concepts for solving real-world problems. The book has been designed keeping in mind the
requirements of a basic first-level course on computer fundamentals and programming, which is offered as a common
subject in all engineering disciplines. It comprehensively covers the fundamental concepts of computers, including topics
such as introduction to computers, number system, input/output devices, computer memory, computer software, the
Internet, and introduction to algorithms and programming languages. Programming is a skill best developed by rigorous
practice, Keeping this in mind, the book provides a number of examples and exercises that would help the reader learn
how to design efficient, workable programs. Various programming examples that have been thoroughly implemented and
tested have been included in the book.
To further enhance the understanding of the subject, there are numerous chapter-end exercises provided in the form of
objective type questions, review questions, and programming problems.
The book is also useful as a reference and resource to computer professionals.

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

PART I: COMPUTER FUNDAMENTALS


1 Introduction to Computers
2 Input and Output Devices
3 Computer Memory and Processors
4 Number Systems and Computer Codes
§ Boolean Algebra and Logic Gates
6 Computer Software
7 Computer Networks and the Internet 124
8 Designing Efficient Programs 149

PART Il: PROGRAMMING IN C 163


9 Introduction to C 165
10 Decision Control and Looping Statements 205
11 Functions 248
12 Arrays 275
13 Strings 317
14 Pointers 347
15 Structure, Union, and Enumerated Data Type 386
16 Files 415
17 Preprocessor Directives 447
18 Introduction to Data Structures 460

Appendix A: Bitwise Operations 488


Appendix B: ANSI C Library Functions 490
Appendix C: Advanced Type Qualifiers and Inline Functions inC 498
Appendix D: Interview Questions with Solutions 501
Appendix E: Linux: A Short Guide 511
Appendix F: Answers to Objective Questions 516
Index 523
About the Author 525
Detailed Contents
Companion Online Resources vi
Preface to the Second Edition vii
Preface to the First Edition x
Brief Contents xi

PART I: COMPUTER FUNDAMENTALS 1


1 Introduction to Computers 3 3.12.1 CD-ROM 47
1.1 Computer 3 3.12.2 DVD-ROM 47
1,2 CharacteristicsofComputers 3 3.12.3 CD-R 47
1.3 Stored Program Concept 4 3.12.4 CD-RW 47
1.3.1 Types of Stored Program Computers 4 3.12.5 BLU-Ray Disks 48
1.4 History of Computers 5 3.13 USB Flash Drives 48
1.5 Classification of Computers 9 3.14 Memory Cards 49
1.5.1 Supercomputers 9 3.15 Mass Storage Devices 50
1.5.2 Mainframe Computers 9 3.15.1 Disk Array 50
1.5.3 Minicomputers 9 3.15.2 Automated Tape Library 50
1.5.4 Microcomputers 10 3.15.3 CD-ROM Jukebox 50
1,6 Applications of Computers // 3.16 Basic Processor Architecture 5/
1.7 Basic Organization of aComputer /5 3.16.1 Execution Unit 51
1.8 Lab Session—Inside theComputer 16 3.16.2 Registers 51
1,9 Motherboard 17 3.16.3 Bus Interface Unit 52
1.9.1 Characteristics of aMotherboard 17 3.16.4 Instruction Set 52
3.16.5 System Clock 53
2 Input and Output Devices 22
3.16.6 Processor Speed 53
2.1 Input Devices 22
3.16.7 Pipelining and Parallel
2.1.1 Keyboard 22
Processing 54
2.1.2 Pointing Devices 23
3.16.8 Types of Processors 54
2.13 Handheld Devices 25
21,4 Optical Devices 26 4 Number Systems and Computer Codes 59
2.1.5 Audiovisual Input Devices 28 4.1 Introduction to Number Systems 59
2,2 Output Devices 29 4.2 Binary Number System 59
2.2.1 Soft Copy Devices 29 4.3 Working With Binary Numbers 60
2.2.2 Hard Copy Devices 33 4.3.1 Converting a Binary Number into
Decimal Form 61
3 Computer Memory and Processors 39
4.3.2 Converting a Decimal Number into
3.1 Introduction 39
Binary Form 61
3.2 Sequential and Random Access 39
4.3.3 Adding Two Binary Numbers 61
3.3 Memory Hierarchy 39
4.3.4 Subtracting Two Binary Numbers 62
3.4 Processor Registers 40
4.3.5 Subtracting Two Binary Numbers Using
3.5 Cache Memory 40
Twos Complement 62
3.6 Primary Memory 40
4.3.6 Multiplying Two Binary Numbers 63
3.6.1 Random Access Memory (RAM) 41
4.3.7 Dividing Two Binary Numbers 63
3.6.2 Read-only Memory (ROM) 41
44 Octal Number System 63
3.6.3 Finding Required Data from Main
44.1 Converting an Octal Number into
Memory 42
Decimal Form 63
3.7 Secondary Storage Devices 42
4.4.2 Converting a Decimal Number into
3.7.1 Offline Storage 42
Octal Form 64
3.8 Magnetic Tapes 43
4.4.3 Converting an Octal Number into
3.9 Floppy Disks 43
Binary Form 64
3.10 Hard Disks 44
4.4.4 Converting a Binary Number into Octal
3.11 External Hard Disks 46
Form 64
3.12 Optical Drives 46
4.4.5 Adding Two Octal Numbers 65 5.8.2 NOR Universal Gate 86
4.4.6 Subtracting Two Octal Numbers 65 5.9 Simplification of Boolean Expressions
4.5 Hexadecimal Number System 66 Using Karnaugh Map 87
4.5.1 Converting a Hexadecimal Number into
6 Computer Software 92
Decimal Form 66
6.1 Introduction to Computer Software 92
4.5.2 Converting a Decimal Number into
6.2 Classification of Computer Software 93
Hexadecimal Form 66
6.2.1 System Software 93
4.5,3 Converting a Hexadecimal Number into
6.2.2 Application Software 96
Binary Form 67
6.3 Acquiring Computer Software 96
4.5.4 Converting a Binary Number into
6.3.1 Buying Pre-written Software 96
Hexadecimal Form 67
6.3.2 Having Customized Software 96
4.5.5 Converting a Hexadecimal Number into
6.3.3 Downloading Public Domain
Octal Form 67
4.5.6 Converting an Octal Number into
Software 97
6.4 Productivity Software 97
Hexadecimal Form 67
6.4.1 Introduction to Microsoft Office 97
4.5.7 Adding Two Hexadecimal
6.5 Graphics Software 1/09
Numbers 68
6.6 Multimedia Software 109
4.5.8 Subtracting Two Hexadecimal
6.7 Database Management Software /09
Numbers 68
6.8 Operating Systems //0
4.6 Working with Fractions 68
6.8.1 Types of Operating Systems 110
4,7 Signed Number Representation in Binary
6.8.2 Command Interpretation 111
Form 69
6.9 Popular Operating Systems //2
4.7.1 Sign-and-magnitude 70
6.9.1 Microsoft DOS 112
4.7.2 Ones Complement 70
6.9.2 Windows H3
4.7.3 Twox Complement 70
6.9.3 UNIX HS
4.8 BCD Code 70
6.9.4 Linux 116
4,9 Other Codes 71
6.10 Mobile Operating Systems 1/6
4.9.1 ASCH Code 71
6.11 Programming Languages 1/7
4.9.2 Extended Binary Coded Decimal
6.12 Generation of Programming Languages 1/8
Interchange Code 71
6.12.1 First Generation: Machine
4.9.3 Excess-3 Code 71
Language 118
4.9.4 Weighted Codes 71
6.12.2 Second Generation: Assembly
4.9.5 Gray Code 73
Language 118
4.9.6 Unicode 73
6.12.3 Third Generation; High-level
5 Boolean Algebra and Logic Gates 76 Language 119
5.1 Boolean Algebra 76 6.12.4 Fourth Generation: Very High-level
5.2 Venn Diagrams 77 Language 119
5.3 Truth Tables 77 6.12.5 Fifth Generation Programming
5.4 Basic Laws of Boolean Algebra 78 Language 120
5.4.1 Identity Law 78
7 Computer Networks and the Internet 124
5.4.2 Idempotency Law 78
7.1 Introduction to Computer Networks /24
5.4.3 Complement Law 78
7.1.1 Advantages of Computer
5.4.4 Involution Law 78
Networks 124
5.4.3 Commutative Law 78
7.2 Types of Networks 1/25
5.4.6 Associative Law 79
7.2.1 Local Area Network 125
5.4.7 Distributive Law 79
7.2.2 Wide Area Network 125
5.4.8 Absorption Law 80
7.2.3 Metropolitan Area Network 125
5.4.9 Consensus Law 80
7.2.4 Campus/Corporate Area Network 126
5.4.10 De Morgans Laws 80
7.2.5 Personal Area Network 126
5.5 RepresentationsofBoolean Functions 8/
7.2.6 Peer-to-Peer Networks 126
5.5.1 Minterm 81
7.3 Physical Components of a Network [27
5.5.2 Maxterm 82
7.4 Wired Media 127
5.6 Logic Gates 82
7.4.1 Twisted-pair Wires 127
5.7 Logic Diagrams and Boolean Expressions 84
7.4.2 Coaxial Cables 127
5.8 Universal Gates 85
5.8.1 NAND Universal Gate 85
7.4.3 Fibre Optic Cables 127
- 7.5 Wireless Media /28 7.13.1 Types of IP Addresses 139
7.5.1 Terrestrial Microwaves 128 7.14 Domain Name System 139
7.5.2 Satellite Communication 128 7.15 Uniform Resource Locator or Universal Resource
7.5.3 Infrared Communication 128 Locator [40
7.6 Networking Devices /28 7.16 Internet Services /4/
7.61 Hub 128 7.16.1 Electronic Mail 141
7.6.2 Repeater 129 7.16.2 File Transfer Protocol 142
7.6.3 Switch 129 7.16.3 Chatting 142
7.6.4 Bridge 129 7.16.4 Internet Conferencing 143
7.6.5 Router 129 7.16.5 Electronic Newspaper 143
7.6.6 Gateway 130 7.16.6 World Wide Web 143
7.6.7 Network Interface Card 130 7.16.7 Online Shopping 143
7.7 Network Topologies 130 7.16.8 Search Engine 144
7.7.1 Bus Topology 130
8 Designing Efficient Programs 149
7.7.2 Star Topology 130
8.1 Programming Paradigms /49
7.7.3 Ring Topology 131
8.1.1 Monolithic Programming 149
7.7.4 Mesh topology 131
8.1.2 Procedural Programming 149
7.7.5 Hybrid Topology 131
8.1.3 Structured Programming 150
7.8 Wireless Networks /32
8.1.4 Object-oriented Programming
7.9 Data Transmission Mode =/33
7.9.1 Simplex, Half-duplex, and Full-duplex
(OOP) 151
8.2 Example ofaStructured Program =/5/
Connections 133
8.3 Design and Implementation of Efficient
7.9.2 Serial and Parallel Transmissions 134
Programs /52
7.9.3 Synchronous and Asynchronous Data
8.4 Program Design Tools: Algorithms, Flowcharts,
Transmission Modes 135
Pseudocodes 153
7.10 Open System Interconnection
&4.1 Algorithms 153
Model 136
8.4.2 Control Structures Used in
7.11 Transmission Control Protocol/Internet
Protocol Model /38
Algorithms 153
&4.2 FLOWCHARTS $154
7.12 Internet 138
84.3 Pseudocodes 156
7.12.1 History 139
8.5 Typesof Errors 157
7.13 Internet Protocol Address /39
8.6 Testing and Debugging Approaches /58

PART Il: PROGRAMMING IN C 163


9 Introduction to C 165 9.11.1 How are Float and Double Stored? 173
9.1 Introduction 1/65 9.12 Variables 173
9.1.1 Background 165 9.12.1 Numeric Variables 173
9.1.2 Characteristics of C166 9.12.2 Character Variables 174
9.1.3 Uses of C 166 9.12.3 Declaring Variables 174
9.2 Structure ofa C Program 166 9.12.4 Initializing Variables 174
9.3 Writing the firstC Program /67 9.13 Constants 174
9.4 Files UsedinaC Program 168 9.13.1 Integer Constants 174
9.4.1 Source Code Files 168 9.13.2 Floating Point Constants 175
9.4.2 Header Files 168 9.13.3 Character Constants 175
9.4.3 Object Files 169 9.13.4 String Constants 173
9.4.4 Binary Executable Files 169 9.13.5 Declaring Constants 175
9.5 Compiling and Executing C Programs 169 9.14 InpuvOutput Statements inC 176
9.6 Using Comments 1/70 9.14.1 Streams 176
9.7 C Tokens 17/ 9.14.2 Formatting Input/Output 176
9.8 Character SetinC 171 9.14.3 printf() 176
9.9 Keywords 171 9.144 scanf() 179
9.10 Identifiers 172 9.14.5 Examples of printf/scanf 1/80
9.10.1 Rules for Forming Identifier 9.14.6 Detecting Errors During Data Input 182
Names 172 9.15 OperatorsinC 1/82
9.11 Basic Data Types inC 172 9.15.1 Arithmetic Operators 183
Detailed Contents

9.15.2 Relational Operators 184 11.9.3 extern Storage Class 260


9.15.3 Equality Operators 185 11.9.4 static Storage Class 26]
9.15.4 Logical Operators 185 11.9.5 Comparison of Storage Classes 262
9.15.5 Unary Operators 186 11.10 Recursive Functions 262
9.15.6 Conditional Operator 187 11.101 Greatest Common Divisor 263
9.15.7 Bitwise Operators 187 1110.2 Finding Exponents 264
9.15.8 Assignment Operators 189 1110.3 Fibonacci Series 264
9.15.9 Comma Operator 189 Loa} Types of Recursion 265
9.15.10 sizeof Operator 191 1111.1 Direct Recursion 265
9.15.11 Operator Precedence Chart 191 1111.2 Indirect Recursion 265
9.16 Type Conversion and Typecasting /95 11.113 Tail Recursion 265
9.16.1 Type Conversion 195 11.114 Linear and Tree Recursion 266
9.16.2 Typecasting 196 11.12 TowerofHanoi 266
Annexure 1 204 11.13 Recursion Versus Iteration 267
Annexure 2. 274
Decision Control and Looping Statements 205
10.1 Introduction to Decision Control 12 Arrays 275
Statements 205 12.1 Introduction 275
10.2 Conditional Branching Statements 205 12.2 Declaration of Arrays 275
10.2.1 Uf Statement 205 Points to Remember 276
10.2.2 if-else Statement 207 12.3 Accessing the Elements ofan Array 276
10.2.3 if-else-if Statement 209 12.3.1 Caleulating the Address of Array
10.2.4 switch case 2/2 Elements 277
10.3 Iterative Statements 2/6 12.3.2 Calculating the Length of an
10.3.1 while Loop 216 Array 277
10.3.2 do-while Loop 218 124 Storing Values in Arrays 278
10.3.3 for Loop 221 12.4.1 Initializing Arrays during
10.4 Nested Loops 224 Declaration 278
10.5 Break and Continue Statements 232 12.4.2 Inputting Values from the
10.5.1 break Statement 232 Keyboard 278
10.5.2 continue Statement 232 12.4.3 Assigning Values to Individual
10,6 goto Statement 233 Elements 278
Case Study 1: Chapters 9 and 10 245 12.5 Operations on Arrays 279
12.5.1 Traversing an Array 279
Functions 248
11.1 Introduction 248
12.5.2 Inserting an Element in an Array 283
11.1.1 Why are Functions Needed? 248 12.5.3 Deleting an Element from an
Array 286
11,2 Using Functions 249
12.5.4 Merging Two Arrays 287
11.3 Function Declaration/Function Prototype 249
12.5.5 Searching for a Value in an
11.4 Function Definition 250
11.5 Function Call 25/
Array 289
12.6 Passing Arrays to Functions 292
11.5.1 Points to Remember While Calling
12.7 Two-Dimensional Arrays 295
Functions 251
11.6 Return Statement 12.7.1 Declaring Two-dimensional
252
Arrays 295
11.6.1 Using Variable Number of
12.7.2 Initializing Two-dimensional
Arguments 253
Arrays 296
11.7 Passing Parameters to Functions 253
12.7.3 Accessing the Elements of
11.7.1 Call by Value 253
Two-dimensional Arrays 297
11.7.2 Call by Reference 254
12.8 Operations on Two-Dimensional Arrays 300
11.8 Scope of Variables 257 12.9 Passing Two-Dimensional Arrays to
11.8.1 Block Scope 257 Functions 302
11.8.2 Function Scope 258 12.9.1 Passinga Row 303
11.8.3 Program Scope 258 12.9.2 Passing an Entire 2D Array 303
11.8.4 File Scope 259 12.10 Multidimensional Arrays 305
11.9 Storage Classes 259 12.11 Sparse Matrices 306
11.9.1 auto Storage Class 259 12.111 Array Representation of Sparse
11.9.2 register Storage Class 260 Matrices 307
et Detailed Contents

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

15.10.3 Assigning Values to Enumerated 17.2 ‘Types ofPreprocessor Directives 447


Variables 406 17.3 #define 447
15.10.4 Enumeration Type Conversion 406 17.3.1 Object-like Macro 448
1510.5 Comparing Enumerated 17.3.2 Function-like Macros 448
Types 407 17.3.3 Nesting of Macros 449
15,10.6 Input/Output Operations on 17.3.4 Rules for Using Macros 449
Enumerated Types 407 17.3.5 Operators Related to Macros 450
Annexure 4 413 174 #include 450
17.5 #undef 451
16 Files 415
17.6 #line 451
16.1 Introduction to Files 4/5 17.7 #pragma 452
16.1.1 StreamsinC 415 17,8 Conditional Directives 454
16.1.2 Buffer Associated with File 17.81 Bifdet 454
Streams 415 17.8.2 #ifndef 454
16.1.3 Types of Files 416 17.8.3 wif 455
16.2 Using Files inC 4/7 17.84 telse 455
16.2.1 Declaring a File Pointer Variable 417 17.8.5 telif 455
16.2.2 Openinga File 417 17.8.6 tendif 456
16.2.3 Closing a File Using fclose() 418
17,9 defined Operator 456
16.3 Reading Data From Files 4/8 17,10 #error 456
16.3.1 fscanf() 418 17.11 Predefined
Macro Names 457
16.3.2 fgets() 419
16.3.3 fgetc() 420 18 Introduction to Data Structures 460
16.3.4 fread() 420 18.1 Introduction 460
16.4 Writing Data to Files 42/ 18.2 Classification of Data Structures 460
16.4.1 fprint#() 421 18.2.1 Primitive and Non-primitive Data
16.4.2 puts () 422 Structures 460
164.3 fpute () 423 18.2.2 Linear and Non-linear Structures 460
16.4.4 fwrite () 423 18.3 Arrays 461
16.5 Detecting the End-of-File 424 18.4 Linked Lists 46/
16.6 Error Handling During File Operations 424 18.4.1 Traversing a Linked List 462
16.6.1 clearerr() 425 18.4.2 Searching Linked List 462
16.6.2 perror () 425 18.4.3 Inserting a New Node in a Linked
16.7 Accepting Command Line Arguments 426 List 463
16.8 Functions for Selecting a Record 18.4.4 Deleting a Node from a Linked
Randomly 438 List 466
16.8.1 fseek() 438 18.5 Stacks 47/
16.8.2 ftell () 440 18.5.1 Operations on Stack 473
16.8.3 rewind () 440 18.6 Queues 475
16.84 fgetpos() 44/ 18.6.1 Operations on Queues 475
16.8.5 fsetpos() 441 18.7 Trees 477
16.9 Deleting a File 441 18.7.1 Representation of Binary Trees in
16.10 Renaminga File 442 Memory 478
16.11 Creating a Temporary File 442 18.7.2 Traversing a Binary Tree 478
18.8 Graphs 479
17 Preprocessor Directives 447 18.8.1 Representation of Graphs 480
17.1 Introduction 447

Appendix A: Bitwise Operations 488


Appendix B: ANSI C Library Functions 490
Appendix C: Advanced Type Qualifiers and Inline Functions in C 498
Appendix D: Interview Questions with Solutions 501
Appendix E: Linux: A Short Guide $11
Appendix F: Answers to Objective Questions 516
Index 523
About the Author 525
PART |
COMPUTER
NDAMENTALS

1 Introduction to Computers

2 Input and Output Devices

3 Computer Memory and Processors


4 Number Systems and Computer Codes

5 Boolean Algebra and Logic Gates

6 Computer Software
FA Computer Networks and the Internet

8 Designing Efficient Programs


oduction to Computers

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

CHARACTERISTICS OF COMPUTERS Speed Computers can perform millions of operations per


second, which means that data that may otherwise take
We have seen that a computer is an electronic device that many hours to process is output as information in the
blink of an eye. The speed of computers is usually given
performs a function based on a given set of instructions
known as a program. A computer accepts data, processes in nanoseconds and picoseconds, where | nanosecond =
it, and produces information. Here, data refers to some
1 x 10” seconds and 1 picosecond = 1 x 10~™ seconds.
raw fact or figure, and information implies the processed Accuracy A computer is a very fast, reliable, and robust
data. For example, if 12-12-92 is the date of birth of a electronic device. It always gives accurate results,
student, then it is data (a raw fact/figure). However, when provided the correct data and set of instructions are input
we process this data (subtract it from the present-date) to it. Hence, in the event ofan error, it is the user who has
{4 Computer Fundamentals and Programming in C

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*

Figure 1.4 Transistors


Source: yurazaga/Shutterstock

Third Generation (1964-1975)


Hardware Technology Third generation computers were
manufactured using integrated chips (ICs) (shown in
Figure 1.5). ICs consist of several components such as
transistors, capacitors, and resistors on a single chip to
avoid wired interconnections between components, These
computers used S$/ and MSI technology. Minicomputers
came into existence,
Figure 1.3 Vacuum tube
Source: Viadyslav Danilin/Shutterstock
Initially, (Cs contained 10-20 components,This
technology was called Small ScaleIntegration (SSi). Later,
Second Generation (1955-1964) was enhanced tocontain about 100 components. This
Hardware Technology Sccond generation computers was called MSI (Medium Scale integration),
were manufactured using transistors (see Figure 1.4).
Transistors were reliable, powerful, cheaper, smaller, and Memory Larger magnetic core memory was used as
cooler than vacuum tubes. primary memory; larger capacity magnetic tapes and
magnetic disks were used to store data and instructions.
Memory Magnetic core memory was used as primary
memory; magnetic tapes and magnetic disks were used Software Technology Programming was done in high level
to store data and instructions. These computers had faster programming languages such as FORTRAN, COBOL,
and larger memory than the first generation computers. Pascal, and BASIC. Time sharing operating system was
used. Software was separated from the hardware. This
Software Technology Programming was done in high allowed users to invest only in the software they need.
level programming languages. Batch operating system
was used. Used for Scientific, commercial, and interactive online
applications
Used for Scientific and commercial applications
Examples 1BM 360/370, PDP-8, PADP-11, CDC6600
Examples Honeywell 400, IBM 7030, CDC 1604,
UNIVAC LARC Highlights
* Faster, smaller, cheaper, reliable, and easier to use than
Highlights the second generation computers
* Faster, smaller, cheaper, reliable, and easier to use than * They consumed less power than second generation
the first generation computers computers
8 Computer Fundamentals and Programming in C

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

Figure 1.5 Integrated circuits Figure 1.6 VLSI chip


Source: cooldesign/FreeDigitalPhotos. net
Fifth Generation (1989-Present)
Fourth Generation (1975-1989) are
Hardware Technology Fifth generation compute:
Hardware Technology Fourth generation computers manufactured using ICs with ULSI (Ulta Large Scale
were manufactured using ICs with LSI (Large Scale Integrated) technology. The use of Internet became
Integrated) and later with VLSI technology (Very Large widespread and very powerful mainframes, desktops,
Scule Integration), Microcomputers came into existence. portable laptops, and smartphones are being used commonly
Use of personal computers became widespread. High Supercomputers use parallel processing techniques,
speed computer networks in the form of LANs, WANs,
and MANs started growing, Besides mainframes,
supercomputers were also used ULSI circuits contain about 10 million electronic
componen ts
on a single chip.

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

Supercomputers Mainframe computers Minicomputers Microcomputers

Dumb terminals Intelligent terminals Desktop PCs Laptops Handheld devices

Workstations Network computers

Figure 1.8 Classification of computers


fi
10 Computer Fundamentals and Programming in C

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.

Microcomputers, commonly known as PCs, are very small Workstations


and cheap. The first microcomputer was designed by IBM
in 1981 and was named IBM-PC, Later on,many computer Workstations are single-user computers that have the same
hardware companies copied this design and termed their features as PCs, but their processing speed matches that
microcomputers as PC-compatible, which refers to any of a minicomputer or mainframe computer. Workstation
PC that is based on the original IBM PC design. computers have advanced processors, more RAM and
Another type of popular PC is designed by Apple. PCs storage capacity than PCs. Therefore. they are more
designed by IBM and other PC-compatible computers expensive and powerful than a normal desktop computer.
have a different architecture from that of Apple computers. Although workstation computers are widely used as
Moreover, PCs and PC-compatible computers commonly powerful single-user computers by scientists, engineers,
use the Windows operating system, while Apple computers architects, and graphic designers, they can also be used as
use the Macintosh operating system (MacOS). PCs can be servers in a networked environment,
classified into the following categories:
Network Computers
Desktop PCs
Network computers have less processing power,
A desktop PC is the most popular model of PCs. The memory, and storage than a desktop computer. These are
system unit of the desktop PC can be placed flat on a desk specially designed to be used as terminals in a networked
or table. It is widely used in homes and offices. environment. For example, some network computers are
specifically designed to access data stored on a network
Laptops (including the Intemet and intranet).
Some network computers do not have any storage space
Laptops (Figure 1.9) are small microcomputers that can and merely rely on the network’s server for data storage and
eusily fit inside a briefcase. They are very handy and can processing tasks. The concept of network computers had
become popular in the mid-1990s when several variations
of computers such as Windows terminals, NetPCs, and
diskless workstations were widely used.
Network computers thatare specifically designed to access
only the Internet or intranet are often known as Internet PCs
or Intemet boxes. Some network computers used in homes do
not even have a monitor. Such computers may be connected
to a television, which serves as the output device, The most
common example of a home-based network computer is
Web TV, which enables the user to connect a television to the
Internet. The Web TV is equipped with a special set-top box
that is used to connect to the Internet. The set-top box also
provides controls to enable the user to navigate the Internet,
send and receive e-mails, and to perform other tasks on the
network while watching television. The other reason for the
Figure 1.9 Laptop popularity of network computers is that they are cheaperto
Source: You can more/Shutterstock purchase and maintain than PCs.
Introduction to Computers {or i

Handheld Computers + Watching movies


+ Playing games
The mid-1990s witnessed a range of small personal * Sharing pictures, video, songs, documents, etc.
computing devices that are commonly known as handheld * Browsing the Internet
computers, or mobile computers. These computers are * Keeping in touch with friends and family on popular
called handheld computers because they can fit in one social networks, sending emails
hand, while users can use the other hand to operate them. * Business people use them to perform tasks such as
Handheld computers are very small in size, and hence they editing a document, exchanging documents, taking
have small-sized screens and keyboards. These computers notes, and giving presentations
are preferred by business travellers and mobile employees + Tablets are best used in crowded places such as airports
whose jobs require them to move from place to place. and coffee shops, where size and portability become
Some examples of handheld computers are as follows: more important.
* Smartphones
* Tablet PCs
Smartphones Thescdays,cellularphones are web-enabled ‘Tablets may replace laptops ifusers don’t have to
telephones. Such phones are also known as smartphones perform heavy processing tasks and do not require a CD
because, in addition to basic phone capabilities, they also or DVD player
facilitate the users to access the Intemet and send e-mails,
edit Word documents, generate an Excel sheet, create a
presentation, and lots more,
Smartphones run an advanced mobile operating
system that enables it to run various applications, The
four major mobile operating systems are iOS, Android,
BlackBerryOS, and Windows Mobile. Smartphones also
have a CPU, more storage space, more memory, and 4
larger screen than a regular cell phone.
In & nutshell, smartphone refers to a multi-functional
mobile phone handset that packs in varied functionalities
from a camera to a web browser to a high-density display.
Tablet PCs A tablet PC (sce Figure 1.10) is a computing
device that is smaller than a laptop, but bigger than a
smartphone. Features such as user-friendly interface,
Figure 1.10 Tablet
portability, and touch screen huve made them very
popular in the last few years. These days, a wide range Source: bloomua/Shutterstock/OUP Picture Bank
of high-performance tablets are available in the market.
While all of them look similar from outside, they may RD Appuications OF COMPUTERS
differ in features such as operating system, speed of data
connectivity, camera specifications, size of the screen, When the first computers were developed, they were used
processing power, battery life, and storage capability. only in the fields of mathematics and science, In fact, the
Some operating systems that are used in tablets are first effective utilization of computers was for decoding
Android Jellybean (an open-source operating system messages in military applications. Later on, computers
built by Google), Windows 8, and iOS (developed by were used in real-time control systems, like for landing on
Apple), Each operating system has its own advantages the moon. However, with the advancement of technology,
and disadvantages and a proprietary app store, from which the cost of computers and their maintenance declined.
users can download applications, extending the tablet’s This opened the way for computers to be extensively used
functionality, These apps range from games to specialized in the business and commercial sector for information
word processors and even instruments. processing. Today, computers are widely used in fields
While users can easily type directly on the surface of a such as engineering, health care, banking, education,
tablet, some users prefer a wireless or bluctooth-connected etc, Let us discuss how computers are being effectively
keyboard. These days, tablets also offer an optional utilized to perform important tasks.
docking station with keyboards that transforms the tablet
Word processing Word processing software enables users
into a full-featured netbook.
to read and write documents. Users can also add images,
Uses The following are the uses of Tablet PCs: tables, and graphs for illustrating a concept. The software
+ View presentations automatically corrects spelling mistakes and includes
« Videoconferencing copy-paste features (which is very useful where the same
* Reading e-books, e-newspaper text has to be repeated several times).
i12 Computer Fundamentals and Programming in C

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.

e-Business Electronic banking Electronic banking, also known as


cyberbanking or online banking, supports various banking
e-Business or electronic business is the process of activities conducted from home, a business, or on the road
conducting business via the Internet. This may include instead of a physical bank location,
buying and selling of goods and services using computers
and the Internet, Use of email and videoconferencing Bioinformatics
technology has revolutionized the way business is being
conducted these days, Bioinformatics is the application of computer technology
While an e-mail is a service that delivers messages fo manage large amount of biological information.
from a sender to One or more receivers via computer, Computers are used to collect, store, analyse, and integrate
voice mail systems capture, store, and transmit spoken biological and genetic information to facilitate gene-based
messages. Videoconferencing, which is an advanced form drug discovery and development, The need for analysis has
of teleconferencing, provides a complete simulation of become even more important with enormous amount of
a normal meeting environment in which all concerned genomic information available publicly from the Human
parties can sec, heur, and present material, just as if they Genome Project.
were in the same room, These meetings not only speed up Bioinformatics is an interdisciplinary field of molecular
business process but also save the cost of travel and cost of biology, computer science, statistics, and mathematics. It
the time wasted during travel. involves analyses of genomic information to understand
human diseases and thus discover new drugs to treat those

We know that DNA is made up of smaller picces of


molecules and the sequence of molecules along a string
of DNA contains all information about an organism, This
information can be used to grow new organisms. For
Companies today use ¢-commerce applications for example, scientists are using this information to grow
marketing, tansaction, processing, and product and better variety of crops, to generate a genome that will
customer services processing. For example, the website enable cows to yield more milk, so and so forth.
of a company can perform activities such as interactive Therefore. bioinformatics helps scientists to store the
marketing, ordering, payment, and customer support DNA information in huge databases, retrieve it as and
process. when required, and analyse it to grow and develop new
e-commerce used to perform transactions between
business partners or customers has several applications Scientists also use bioinformatics to identify diseases
such as home banking. electronic shopping, buying and discover drugs for them. This is done by writing
Introduction to Computers (13

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,

Maritime meteorology Maritime meteorology is the Retail Business


study of air and wave forecusts for ships operating al sea,
Computers are used in retail shops to enter orders, calculate
Multimedia and Animation costs, and print receipts. They are also used to keep an
inventory of the products available and their complete
Multimedia and animation that combines still images, description,
moving images, text, and sound in meaningful ways is
one of most powerful aspects of computer technology. We Sports
all have seen cartoon movies, which are nothing but an
example of computer animation. In sports, computers are used to compile statistics,
identify weak players and strong players by analysing
N ote
statistics, sell tickets, create training programs and diets
for athletes, and suggest game plan strategies based on
Displaying a number ofstillimages within afraction ofa the competitor's past performance. Computers are also
used to generate most of the graphic art displays flashed
atleast 30stillimages ina second gives
aneffect ofa on scoreboards.
Television networks use computers in the control room
to display action replays and insert commercial breaks as
Using animation software, we can reproduce real- per schedule.
world phenomena such as fire, smoke, fluids, movement of In addition, there are simulation software packages
chemicals through the air and ground. and the respiratory available that help a sportsperson to practice his or her
system to name a few, Animation is an easy and effective skills as well as identify flaws in the technique,
way to show complex interactions or events. Thus, it is an
excellent tool for educating an audience. Travel and Tourism
A dynamic multimedia presentation (created using Computers are used to prepare tickets, monitor the train's
tools like MS PowerPoint) can make the message not or airplane's route, and guide the plane to a safe landing.
only easily understood but also effective. Multimedia ‘They are ulso used to research about hotels in an area,
presentation helps corporate people to share information reserve rooms, Or to rent a car.
or their ideas and graphically present information in a
more understandable and persuasive manner. Multimedia Simulation
presentations can be recorded and played or displayed
dynamically depending on user's inputs. Multimedia and Supercomputers that can process enormous amount of
animation is used to create computer games. A laser show data are widely used in simulation tests. Simulation of
is also an example of a multimedia application, automobile crashes or airplane emergency landings is done
Multimedia and animation is used to add special effects to identify potential weaknesses in designs without risking
in movies. In education, multimedia is used to prepare human lives. Supercomputers also enable engineers to
training courses, Students find learning complex computer design aircraft models and simulate the effects that winds
algorithms and data structures by reading only a textual and other environmental forces have on those designs.
Introduction to Computers ce

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.

Education Expert Systems

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

Figure 1.11 Block diagram


of a computer

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

Figure 1.12 Computer case and its parts

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

Figure 1.13 Computer's motherboard

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

Figure 1.14 1/O connectors

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

TAKEAWAYS © Soft copy devices


© Input devices * Optical devices
* Hard copy devices
* Pointing devices * Audiovisual input devices
* 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

Keyboard Pointing devices Handheld devices Optical devices Audio/Visual devices

Mouse Pen Barcode readers

Trackball Touchscreen Scanners

Trackpad Joystick OCR

OMR

MICR

Figure 2.1 Categories of input devices

2.1.2 Pointing Devices


A pointing input device enables the users to easily control
the movement of the pointer to select items on a display
re) screen, to select commands from commands menu, to draw
fTITTIi11i.
— a
a" graphics, etc. Some examples of pointing devices include
mouse, trackball, light pen, joystick, and touchpad.

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,

When the processor finds a closed circuit, it compares Scroller


the location of
that circuit on the key matrix to the character
map in its read-only memory (ROM). A character map is
a lookup table that tells the processor what each keystroke
or a combination of keystrokes represents. For example,
the character map tells the processor that pressing the key
*¢' corresponds to a small letter *¢” but the keys “Shift and Right button
*e’ pressed together is a °C”.
Note that a computer can also use separate character
Left button
maps, overriding the one found in the keyboard. This is
usually done when the user is typing in a language that Figure 2.3. Mouse
uses letters that don’t have English equivalents on a
keyboard with English letters. The mouse has two buttons and a scroll wheel. It can
be held in the hand and easily moved, without lifting,
Advantage The keyboard is casy to use and inexpensive. along a hard flat surface to move the cursor to the desired
location—up, down, left, or right. Once the mouse is
Disadvantages placed at the appropriate position, the user may perform
* The keyboard cannot be used to draw figures. the following operations:
* The process of moving the cursor to another position is Point Placing the pointer over the word or the object on
very slow. Mouse and other pointing devices are more the screen by moving the mouse on the desk is termed as
apt for this purpose. pointing.
(4 Computer Fundamentals and Programming in C

Pressing cither the left or the right button of the


mouse is known as clicking. Clicking a mouse button
initiates some action; for example, when you click the
right button by pointing the mouse on a word, a menu pops
up on the screen. When you move the pointer over the icon
of an application, say Internet Explorer, and double-click
on it, then it opens that application for you. Trackball
Drag Dragging means pointing to a desired location while
pressing the left button.
Fig. 2.4 Trackball on keyboard
Scroll The scroll wheel, which is placed in between the
Source: Eugene Sergeev/Shutterstock
left and right buttons of the mouse, is used to vertically
scroll through long documents,
Today, the mouse has become so important that every
user buys a mouse when he or she buys a computer. The
mouse is specially used to create graphics such as lines,
curves, and freehand shapes on the screen. It is connected
to a serial or a universal serial bus (USB) port on the system
unit. Some ofthe popular mouse types are as follows:
Mechanical mouse This type of mouse has a rubber or
metal ball at its bottom and an electronic circuit containing
sensors, When the mouse is moved over a flat surface, the
sensors detect the direction of movement of the ball. The Figure 2.5 Trackball used like a mouse
electronic circuit translates the movement into signals and Source: Andrew Buckin/Shutterstock
feeds it as input to the computer.
Optical mouse The optical mouse is more advanced (identical to mouse buttons) near the trackball, cither to
than the mechanical mouse, It contains a ball inside. The select objects or to position the cursor for text entry. This
movement of the mouse is detected using laser technology, is shown in Pigure 2.5.
by using optical sensors. To move the pointer, the ball is rotated with the thumb,
fingers, or the palm of the hand. The advantage of a
Cordless mouse A cordless or wireless mouse is not trackball over a mouse is that the former is stationary,
connected to the computer. The movement of the mouse is and so it does not require much space to use, Moreover,
detected using radio waves or infrared light waves. individual trackballs can be placed on any type of surface,
Advantages including the user's lap. These advantages make trackballs
* The mouse is easy to use and can be used to quickly very popular pointing devices for portable computers and
place the cursor anywhere on the screen. mobile phones.
* Italso helps to quickly and easily draw figures. Note that the working ofa trackball is identical to that
* Itis inexpensive. of mouse.
* Its point-and-click capabilities make it unnecessary to Advantages
remember and type in commands. * The trackball provides better resolution.
Disadvantages * It occupies less space.
* The mouse needs extra desk space to be placed and * It is easier to use as compared to a mouse as its use
moved easily. involves less hand and arm movements.
* The ball in the mechanical mouse must be cleaned to Di
remove dust from it. The trackball chamber is often covered with dust, so it
must be cleaned regularly.
Trackball
A trackball is a pointing device that is used to control the Touchpad
position of the cursor on the screen, It is usually used in A touchpad (or trackpad), as shown in Figure 2.6, is a
notebook computers, where it is placed on the keyboard, small, flat, rectangular stationary pointing device with
as shown in Figure 2.4. a sensitive surface of 1.5—2 square inches, The user has
The trackball is nothing but an upside-down mouse to slide his or her fingertips across the surface of the pad
where the ball rotates in place within a socket. The user to point to a specific object on the screen. The surface
rolls the ball to position the cursor at an appropriate translates the motion and position of the user’s fingers to
position on the screen and then clicks one of the buttons a relative position on the screen. There are also buttons
Input and Output Devices 25

buttons, called switches, whose position can also be read


by the computer,
The lever of ajoystick moves in all directions to control the
movement of the pointer on the computer screen. A joystick
is similar to a mouse, but with the mouse, the cursor stops
moving as soon as you stop moving the mouse. However,
in case of a joystick, the pointer continues moving in the
direction to which the joystick is pointing. To stop the pointer,
the user must return thejoystick to its upright position,

Figure 2.6 Touchpad Stylus


Source: Yulia Nikulyasha Nikitina/
A stylus (shown in Fig. 2.8) is a pen-shaped input device
Shutterstock/OUP Picture Bank
used fo enter information or write on the touchscreen of
around the edge of the pad that work like mouse buttons. a handheld device
Touchpads are widely used in laptops, and are in built on It is a small stick
the laptop keyboards, They can also be attached to a PC or that can also be used
be used with personal digital assistants (PDAs) and iPods. to draw lines on a
The working of a touchpad is similar to that of amouse Surface as input into
or a trackball. The pressure of the finger on the surface a device, choose an
leads to a capacitance effect, which is detected by the option from a menu,
sensors, The sensors send appropriate signals to the CPU, move the cursor to
which interprets them and displays the pointer on the another location
screen on the sereen, take
Advantages notes, and create
* Touchpads occupy less space. short messages. The
* They are casier to use as compared to a mouse as their stylus usually slides
use involves less hand and arm movements. into a slot built into
Figure 2.8 Stylus
* A touchpad is in-built in the keyboard, and hence the device for that
Source: Photodisc/OUP Picture Bank purpose
negates the need to carry an extra device
Touchscreen
2.1.3 Handheld Devices
A handheld device is a pocket-sized computing device Atouchsereen (shown in Figure 2.9) is a display screen that
with a display sereen and touch input and/or a miniature can identify the occurrence and position of a touch inside
keyboard, Some common examples of handheld devices the display region, The user can touch the sereen either by
include smartphones, PDAs, handheld game consoles, using a finger or a stylus. The touchscreen facilitates the
and portable media players (c.g., iPods). In this section, users fo interact with what is displayed on the sercen in a
we will read about joystick stylus (pen) and touchscreens, straightforward manner, rather than in an indirect way by
which are the means to input data to handheld devices using 4 mouse or a touchpad, Touchscreens make using
another input device redundant, since the user can interact
with the sereen by directly touching it. Such touchscreen
Joystick
displays are available on computers, laptops, PDAs, and
A joystick = (refer mobile phones.
Figure 2.7) is a cursor
control device widely
used in computer
games and computer-
aided design (CAD)
computer-aided
manufacturing (CAM)
applications. It
consists of a handheld
lever that pivots on
one end and transmits
its coordinates to a
Figure 2.7 Joystick Figure 2.9 Touchscreen
computer. A joystick
Source: Viktor Kunz/Shutterstock has one or more push Source: Gareth Boden/OUP Picture Bank
26 Computer Fundamentals and Programming in C

‘ouchscreen monitors are an casy way of entering Disadvantages


information into the computer (or mobile phone, etc). * Barcode readers must be handled with care. If they
Touchscreen monitors have become more and more develop a scratch, the user may not be able to read the
commonplace as their price has steadily dropped over the code.
past decade, These days, touchscreen monitors are widely * They can interpret information using a limited series of
used in different applications including point-of-sale thin and wide bars. To interpret other unique identifiers,
(POS) cash registers, PDAs, automated teller machines the bar display area must be widened.
(ATMs), car navigation screens, mobile phones, gaming
consoles, and any other type of appliance that requires the Image Scanner
user to input and receive information instantly,
A scanner (shown in Fig. 2.10) is a device that captures
2.1.4 Optical Devices images, printed text, and handwriting, from different
sources such as photographic prints, posters, and magazines
Optical devices, also known as data-scanning devices, and converts them into digital images for editing and
use light as a source of input for detecting or recognizing display on computers, Scanners come in handheld, feed-in,
different objects such as characters, marks, codes, and and flatbed types, and for scanning cither colour imuges,
images. These devices convert these objects into digital black-and-white images, or both. While lower resolution
data and send it to the computer for further processing. scanners are adequate for capturing images for computer
Some optical devices that are discussed in this section display, very high resolution scanners, on the other hand,
include barcode readers, image scanners, optical are used for scanning of high-resolution printing, Some
character recognition (OCR) devices, optical mark scanners have software like Adobe Photoshop to help the
readers (OMR), and magnetic ink character recognition user resize or modify a captured image.
(MICR) devices.

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:

4 ‘Scans the documents and


makes a bitmap of size
50-150 KBper page
Figure 2.11 OCR technology
((28 | Computer Fundamentals and Programming in C
———— routing number, account number, and, in some cases, the
amount on the cheque) for processing to the receiving party.
MICR characters are usually printed in E-13B or
CMC-7 fonts. Each font is made up of a series of numbers
and symbols specifically designed for readability on high-
speed check-sorting machines. The symbols provide
beginning and end points for cach group of numbers in
order to enable the machine to determine what cach series
of numbers mean. To print the magnetic characters on the
Figure 2.12 Optical mark reader
check is a critical task, and the line placement, character
placement, skew, quality, and the positioning of the line
The OMR sheet is scanned by the reader to detect the in the MICR clear band area (depicted by an arrow in
presence of a mark by measuring the reflected light levels. Figure 2.13) must be done very precisely.
The dark or the marked areas reflect less light than the MICR is widely used to enhance security, speed up the
unmarked ones, The OM reader interprets this pattern sorting of documents, and minimize the exposure to check
of marks and spaces, and stores the interpreted data in a fraud. Let us take a real-world problem to understand how
computer for storage, analysis, and reporting, The error rate MICR reduces risk to fraud. If a person gives a cheque
for OMR technology is less than 1%. For this reason, OMR produced using a colour photocopying machine, the
is widely used for applications in which large numbers of magnetic ink line will either not respond to the magnetic
hand-filled forms have to be quickly processed with great fields, or will produce an incorrect code when scanned
accuracy, such as surveys, reply cards, questionnaires, using an MICR reader. The MICR device even rejects
ballots, or sheets for multiple-choice questions. cheques issued by an account owner who has a history of
writing bad cheques.
Advantage
Optical mark readers work at very high speeds. They can 2.1.5 Audiovisual Input Devices
read up to 9000 forms per hour. Today, all computers are multimedia-enabled_ that is,
Disadvantages computers not only allow one to read or write text, but also
+ It is difficult to gather large amounts of information enable the user to record songs, view animated movies,
using an OMR. etc. Hence, in addition to having a keyboard and a mouse,
+ Some data may be missing in the scanned document. audio-video devices have become a necessity today.
+ Itis a sensitive device that rejects the OMR sheet if itis
folded, torn, or crushed. Audio Devices
Magnetic Ink Character Reader Audio devices are used to either capture or create sound.
They enable computers to accept music, speech, or sound
Magnetic ink character reader (MICR) is used to verify effects for recording and/or editing. Microphones and CD
the legitimacy of paper documents, especially bank players are examples of two widely used audio input devices.
checks, It consists of magnetic ink printed characters that A microphone feeds audio input to the computer.
can be recognized by high-speed magnetic recognition However, the audio input must be converted into digital
devices (refer Figure 2.13), The printed characters provide data before being stored in the computer. For this, the
important information (such as cheque number, bank computer must have a sound card. The sound card is a
hardware unit that converts analog signals generated
through the microphone into digital data, so that it can
be stored in the computer. When the user wants to hear
the pre-recorded audio input, the sound card converts the
digital data into equivalent analog signals and sends them
Pay DATE:
to the speakers, This process is depicted in Figure 2.14.
ae) A computer with a microphone and speakers can be
RUPEES used to make telephone calls and do videoconferencing
(using a web camera or ‘webcam’) over the Internet.

Video Input Devices

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

Figure 2.14 Recording and retrieving audio data

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).

2.2.1 Soft Copy Devices


Soft copy output devices are those that produce an
electronic version of an output—for example, a file that is
stored on a hard disk, CD, or pen drive—and is displayed
on the computer screen (monitor). Features of a sofi copy
@) (b)
output include the following:
Figure 2.15 Video input devices (2) Web camera * The output can be viewed only when the computer is on.
(b) Digital camera + The user can easily edit soft copy output.
Computer Fundamentals and Programming in C

Hard
copy devices

Projector Speaker

Figure 2.16 Classification of output devices

(a) (b) {e)


Figure 2.17 Types of monitors (a) CRT (b) LCD (c) Plasma

* 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

Most LCD displays use active matrix technology


which a thin film transistor (TFT) arranges tiny transistors
and capacitors in a matrix on the glass of the display. To
refer to a particular pixel, the proper row is turned on, and
then a charge is sent through the correct column. Since all
the other rows are switched off, only the capacitor at the
designated pixel receives a charge.
Passive matrix technology is the other type of LCD,
which uses a grid of conductive metal to charge each
pixel. Although these LCDs are cheaper, they are hardly
used today because of slow response time and imprecise
voltage control compared to active matrix technology.
Cathode ray tube Advantages
Figure 2.18 Working of a CRT monitor + LCD monitors are very compact and lightweight.
* They consume less power.
Disadvantages * They do not suffer from geometric distortion.
* CRT monitors occupy a large space on the desk. * There is little or no flicker of images (depending on the
* They are bigger in size and weight and therefore difficult backlight technology used).
to move from one place to another when compared with * They are more reliable than CRTs.
other types of monitors. * They can be made in almost any size or shape.
* Power consumption is higher than the other monitors. * They cause less eye fatigue.
LCD Monitor An LCD monitor (shown in Figure 2.19)
is a thin, flat, electronic visual display that uses the light Disadvantages
* They are more expensive than CRTs.
modulating properties of liquid crystals, which do not emit
* Images are not very clear when tried to view from an
light directly, LCD screens are used in a wide range of
applications ranging from computer monitors, televisions, angle.
instrument panels, aircraft cockpit displays, signage, Plasma monitor Plasma monitors are thin and flat
etc,, 10 consumer devices such as video players, gaming monitors widely used in televisions and computers.
devices, clocks, watches, calculators, and telephones. The plasma display contains two glass plates that have
hundreds of thousands of tiny cells filled with xenon and
Polarizing Liquid crystal layer neon gases. The address clectrode and the transparent
filters display electrode are sandwiched between the glass plates.
The display electrode is covered by a magnesium oxide
protective layer and is arranged in horizontal rows along
the screen, while the address electrodes are arranged in
vertical columns, thereby forming a grid-like structure as
shown in Figure 2.20.

Figure 2.19 Working of a LCD monitor

These days, LCDs have become so popular that there are


replacing the traditional CRT displays at a fast pace. LCD
screens are more compact, lightweight, portable, more
reliable, and casier on the eyes. LCDs are more energy
efficient and offer safer disposal than CRTs. It is because of
their low electrical power consumption that they are widely
being used in battery-powered electronic equipment,
LCD technology is based on the principle of blocking
light. The LCD consists of two pieces of polarizing
filters (or substrates) that contain a liquid crystal material
between them. A backlight creates light, which is made
to pass through the first substrate. Simultaneously, the
electrical currents cause the liquid crystal molecules to
align, thus allowing varying levels of light to pass through
to the second substrate and create the colours, and hence
images are seen on the screen. Figure 2.20 Working of a plasma monitor
32. Computer Fundamentals and Programming in C
‘To ionize the gas in a particular cell, the electrodes that on a big screen, the projector first displays that image
intersect at that cell are charged at least thousands of times (represented in the video signal) onto a small screen inside
within a small fraction of a second (charging cach cell the projector itself, which is then projected onto the final
in turn). sercen using bright light and a lens. The lens is shaped in
Once the intersecting electrodes are charged, an electric such a way that it takes the small image and turns it into a
current begins to flow through the gas in the cell. The dramatically larger one.
current creates a rapid flow of charged particles, thereby Projectors can be broadly classified into two categories
stimulating the gas atoms to release ultraviolet photons. depending on the technology they use.
When these UV photons hit a phosphor atom in the cell, LCD projector LCD projectors make use of their own light
one of phosphor’s electrons jumps to a higher energy level,
to display the image on the screen/wall. These proj
and the atom heats up. When the electron falls back to its
are based on LCD technology. To use these projectors, the
normal level, it rele: es energy in the form of a visible
room must be first darkened, else the image formed will
light photon, be blurred.
Advantages Digital light processing (DLP) projector DLP projectors
* The technology used in plasma monitors allows
use a number of mirrors to reflect the light. When using
producing a very wide sereen using extremely thin
the DLP projector, the room may or may not be darkened
materials, because it displays a clear image in both situations.
* Very bright images are formed which look good from
almost every angle.
Speakers
* These monitors are not heavy and are thus easily
Initially, computers were designed to be used only
portable.
for scientific purposes, but later, with the advances in
Disadvantages technology, computers became so popular and inexpensive
* These monitors are very expensive. that they are now used in almost every sphere of our day-
* They have a high power consumption. to-day lives. Today, all business and home users demand
* Since the images are phosphor-based, at times, they audio capabilities from their computers. For this purpose,
may suffer from flicker speakers were developed in different sizes and shape:
and with different powers and sound quality, With all
Projectors these types of speakers, the user can enjoy music, movie,
A projector (Figure 2.21) is a device that takes an image or a game, and the voice will be spread through the entire
from a video source and projects it onto a screen or another room. With good quality speakers, the voice will also be
surface, These days, projectors are used for a wide range audible even to people sitting in another room or even to
of applications, varying from home theater systems for neighbours!
projecting movies and television programs onto a screen However, in case the user wants to enjoy loud music
much larger than even the biggest available television, to without disturbing the people nearby, a headphone can
organizations for projecting information and presentations be used. Headphones are small devices that fit in or on
onto screens large enough for rooms filled with many the car, and give about the same quality and power of the
people, Projectors also allow users to change/adjust sound, as the speakers, only to the listener. Most of today’s
some features of the image such as brightness, sharpness, headphones feature some noise-cancelling technologie:
and colour settings, similar to the features available in so that the listener may listen to only the sound from
a standard television. Projectors are now available in a the speakers and not anything else from the surrounding
variety of different shapes and sizes, and are produced by environment.
many different companies. Users often use headphones to chat with people over
The projector works by receiving a video signal from the Internet. With headphones, they are assured that
some external device such as a DVD player or a computer the conversation is heard only by them, However, in
and projects that signal onto a sercen. To display the image addition to the headphones, they are also required to
use a separate microphone to talk to the other person
Hence, another device called the headset was developed

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.

Resolution The resolution of a printer means the


Figure 2.22 Audio devices (a) Speakers (b) Headphones sharpness of text and images rendered on paper. It is
(c) Headset usually expressed in dots per inch (dpi). Even the least
expensive printer provides sufficient resolution for most
range of quality and prices, The normal computer speakers purposes at 600 dpi
are small, plastic, and have mediocre sound quality. Other
Speed Speed means number of pages that are printed in
speakers are available that have equalization features
one minute. The speed of a printer is an important factor
such as bass and treble controls. Users can also use a lead
for users who have a large number of pages to print, While
to connect their computer's sound output to an existing
high-speed printers are quite expensive, the inexpensive
stereo system to give much better results than the small,
printers, on the other hand, can print only about 3-6 sheets
low-cost computer speakers.
per minute. Colour printing is even slower

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

Dot matrix Daisy wheel Line Inkjet

Figure 2.23 Classification of printers


34 Computer Fundamentals and Programming in C

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.

Figure 2.26 Laser printer


Source: restyler/Shutterstock
Figure 2.25 Inkjet printer
Source: lakov Filimonov/Shutterstock While colour laser printers are also available in the
market, users mostly prefer monochrome printers, because
The printhead of inkjet printers has several tiny nozzles, the former is up to ten times more expensive than the latter.
also called jets. As the paper moves past the printhead, the
nozzles spray ink onto it, forming characters and images. Plotters
If you observe a printout that has just come out from an
inkjet printer, you will see that the dots are extremely A plotter as shown Fig. 2.27 is a printing device that is
small (usually between 50 and 60 microns in diameter) usually used to print vector graphics with high print
and are positioned very precisely, with resolutions of up to quality. They are widely used to draw maps, in scientific
1440 x 720 dpi. To create a coloured image, the dots can applications, and computer-aided engineering (CAE).
have different colours combined together. Architects use plotters to draw blueprints of the structures
An inkjet printer can produce from 100 to several they are working on.
hundred pages (depending on the nature of the hard copy), A plotter is basically a printer that interprets commands
betore the ink cartridges must be replaced. There is usually from a computer to make line drawings on paper with one
one black ink cartridge and one colour cartridge containing or more automated pens. Since plotters are much more
ink in primary pigments (cyan, magenta, and yellow). expensive than printers, they are used only for specialized
While inkjet printers are cheaper than laser printers, applications. There are two different types of plotters,
they are more expensive to maintain. The cartridges of drum and flatbed.
36 Computer Fundamentals and Programming in C

is mounted on a carriage, is moved across the width of the


paper. Hence, the vertical movement of the paper and the
horizontal movement of the pen create the required design
under the control of the computer.
Drum plotters can make multicolour drawings by using
pens with different coloured inks. Moreover, drum plotters
support very large plot sizes with paper widths of up to
1 meter,

Flatbed plotter In a flatbed plotter, the paper is spread


on the flat rectangulur surface of the plotter, and the pen
is moved over it. Flatbed plotters are less expensive, and
are used in many small computing systems, The size of
the plot is limited only by the size of the plotter's bed
Figure 2.27 Plotter In this type of plotter, the paper does not move; rather,
Source: Michal Vitek/Shutterstock plotting is done by moving an arm that moves a pen over
the paper.
Drum plotter A drum plotter is used to draw graphics In case of a flatbed plotier, pens of different colours
on paper that is wrapped around a drum. This type of are mounted in the pen-holding mechanism that moves on
plotter is usually used with mainframe and minicomputer te surface. The microprocessor in the plotter selects the
systems, The drum plotter works by rotating the drum desired pen and controls its movement under the control
back and forth to produce vertical motion, The pen, which of the computer.

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

€X9 intrRopuction Differences between sequential and


random access
Memory is an internal storage area in the computer, Sequential access [Random access
which is used to store data and programs either Data isread sequentially
ina Data is read in an arbitrary
temporarily or permanently. Computer memory can spocitiod order. manner,
be broadly divided into two groups—primary memory
and secondary memory. While the main memory holds
instructions and data when a program is executing, Ifthe 99th record isdesired Random access always
the auxiliary or the secondary memory holds data and after the Ist one, then allthe returns data in constant time,
programs that are not currently in use and provides records have tobe traversed
long-term storage to reach the desired one,
To execute a program, all the instructions or data Therefore, the time required to
that has to be used by the CPU has to be loaded into return data can vary depending
the main memory. However, the primary memory is on the position ofthe record.
volatile and so it can retain data only when the power is Sequential access devices can Random access devices are
on, Moreover, it is very expensive and therefore limited store a large number of records expensive than sequential
in capacity ata very low cost. access devices,
On the contrary, the secondary memory stores data Magnetic
tapes support RAM (Random Access
or instructions permanently, even when the power sequential access. Memory) supports random
is turned off. It is cheap and can store large volumes access,
of data, Moreover, data stored in auxiliary memory is Sequential-access is faster if Random-access is faster if
records are tobe accessed inthe records are to be accessed in a
highly portable, as the users can easily move it from one
same order. random order.
computer to another. The only drawback of secondary
memory is that data can be accessed from it at very low
speeds as compared with the data access speed of the
primary memory if the need of application is to access all the records in
order then sequential
access isbetter.
2 SEQUENTIAL AND RANDOM ACCESS
XE) memory HIERARCHY
Memory devices can be accessed cither randomly or
sequentially, The method of access has a great impact on In contemporary usage, memory usually refers to
application efficiency in terms of disk usage, Therefore,we random access memory (RAM), typically dynamic
must understand the differences between these two access RAM (DRAM), but it can also refer to other forms of
methods which are listed in Table 3.1 data storage. In computer terminology, the term storage
40 Computer Fundamentals and Programming in C

féfers to storage devices that are not directly accessible


by the CPU (secondary or tertiary storage). Examples of 9 cAcHE MEMORY
secondary storage include hard disk drives, optical disk
drives, and other devices that are slower than RAM but are Cache memory is an intermediate form of storage between
used to store data permanently the ultra-fast registers and the RAM. The CPU uses cache
These days, computers use different types of memory, memory to store instructions and data that are repeatedly
which can be organized in the hierarchy as shown (Figure required to execute programs, thereby improving the
3.1). As we can sce from the figure, there is a trade-off overall system speed and increasing the performance of
between performance and cost. The memory at the higher the computer. Maintaining frequently accessed data and
levels in the storage hierarchy has less capacity to store instructions in the cache helps in avoiding the need to
data, is more expensive, and is faster to access. access the slower DRAM repeatedly
Cache memory is widely used for memory caching.
Cache memory is a portion of memory made of high speed
static RAM (SRAM) instead of the slower and cheaper
(C)system’s memory DRAM which is used for main memory
CPU registers
Some memory caches are in-built in the architecture
of microprocessors. For example, the Intel 80486
«© Less access time microprocessor has an SK memory cache, and the Pentium
Level I cache £2160 has a 1 MB cache, Such internal caches are often
= = * Smaller in size called level 1 (L1) caches. However, modern PCs also
come with extemal cache memory, called level 2 (L2)
* Le a c it) caches, which are built into the motherboard outside the
Level 2 cache i ia CPU. Although L2 caches are composed of SRAM, they
= oo * Stores data till the power is on are much larger in size than L1! caches, Another type of
cache, called level 3 (L3), which is not normally used, is
Level 3 cache an extra cache that has a much larger size than L1 and L2
caches, but is slower than them (but faster than RAM).

Working of the Cache Memory


Primary memory
When a program is being executed and the CPU wants to
read data or instructions, the following steps are performed.
* Less expensive The CPU first checks whether the data or instruction is
available in the cache memory, If it is not present there, the
* More access time CPU reads the data or instructions from the main memory
into the processor registers and also copies it into the
* Bigger
insize cache memory, When the same piece of data/instruction
is needed again, the CPU reads it from the cache memory
* More capacity
instead of the main memory.
* Stores data even when the
power is not on 83 primary Memory
Primary memory (or main memory or internal memory)
[[]system’s memory [J] Ontine [Ii] Near tine [I omine can be directly accessedby the CPU. The CPU continuously
reads instructions stored in the primary memory and
Figure 3.1 Memory hierarchy executes them. Any data that has to be operated by the
CPU is also stored there.
Historically, early computers used delay lines, William's
EXD PROCESSOR REGISTERS tubes, or rotating magnetic drums as primary storage.
From 1954 to 1970s, magnetic core memory became the
Processor registers are located inside the processor and dominant technology to be used as the primary memory
are therefore direct sed by the CPU. Each register of computers. Later, in the 1970s, magnetic core memory
stores a word of data (which is either 32 or 64 bits). CPU was replaced by semiconductor memory that used a large
instructions instruct the arithmetic and logic unit (ALU) number of integrated circuits. This led to the development
to perform various calculations or other operations on this of the modern RAM.
data. Registers are the fastest among all types of computer However, there is another type of primary memory
data storage. called read-only memory (ROM), which is non-volatile
Computer Memory and Processors | 41

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

Example 3.1 on the other hand


can transfer data at
Ahard disk has 10 disk plates, 2000 tracks per surface, 125 speeds ranging from
sectors per track, and 512 bytes of data can be stored per 400 to 800Mbps.
sector, Using this information, calculate the storage capacity The external hard
of the disk. drive can also be
connected to the
Solution computer wirelessly.
The disk has 10 plates, which means 20 recording surfaces. Figure 3.8 External hard disk External — drives
However, in a double-sided disk, the upper surface of the allow users to save
first disk and the lower surface of the last disk are normally sensitive, confidential, or otherwise important data on
not used for recording data because these surfaces may be them and kept at separate (away from the computer) secure
scratched easily, locations. As external hard drives are lightweight portable
Therefore, by using the formula, the storage capacity can devices, they can be easily carried away anywhere and also
be calculated as. be stored in a safe, secure location to protect the data from
theft or disaster. Moreover, some extemal devices come with
Storage capacity = 18 x 2000 x 125 x 512
security features like fingerprint recognition to prohibit other
= 2,30,40,00,000 bytes people from gaining access to the stored data
= 2x 10° bytes = approximately 2G8 External hard drives have high storage capacities.
External hard disks with a storage capacity of 2TB are
very common these days (1 TB = 1000GB), Therefore,
Advantages they are often used to back up numerous computer files or
serve as a network drive to store shared content.
Magnetic disks enable random access of data, which is
They are extensively used by people who do audio/video
useful for all types of real-world applications.
editing. These media files require high-quality settings, and
* They can be used as a shared device in a multi-user therefore consume a large amount of disk space,
ronment
are preferred for both online and offline storage of

* 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

data on the CD-RW disk multiple times. However, the


reliability of the disk tends to decrease, cach time you
Very soon a Blu-ray disk having 20 layers and storing 500
rewrite data. Both CD-Rs and CD-RWs can be used for
GB of data will beavailable in the market.
taking backup of important data. Moreover, CD-RWs are
also used to create audio CDs, so that users can record
their own music or movies on purchased CDs.
A CD-RW drive is used to write data on the CD-RW
USB FLASH DRIVES
Such drives have read and write speeds up to 48X or more, USB flash drives (Figure 3.11) are removable, rewritable,
but the re-write speed is 10X or more. The CD-RW drive
and are physically much smaller drives, weighing less
is advanced and more expensive than a CD-R drive. The
than 30g. In 2010, the storage capacity of the USB flash
CD-RW drive is compatible with both CD-R and CD-RW,
drives was as large as 256GB. Such devices are a good
and can therefore read or write data on both CD-R and substitute for floppy disks and CD-ROMs as they are
CD-RW disks,
smaller, faster, have thousands of times more ¢: and
are more durable and
3.12.5 BLU-RAY DISKS reliable. Until 2005,
Blu-ray disk (BD) is a new optical disk developed by most desktop and
the Blu-ray Dise Association (BDA), which includes laptop computers had
leading companies such as Apple, Dell, Hitachi, HP, floppy disk drives,
JVC, LG, Mitsubishi, Panasonic, Pioneer, Philips, but nowadays floppy
Samsung, Sharp, Sony, TDK, and Thomson. The disk drives have been
format of a Blu-ray disk was specifically developed Figure 3.11 USB flash drive abandoned in favour
to bring forward a recordable, rewritable disk that can Source: Coprid/Shutterstock/OUP of USB ports,
store large amount of data and display a high-definition Picture Bank A flash drive
video (HD), consists of a small
Although a Blu-ray disk has the same size as that ofa printed circuit board carrying the circuit elements and
CD ora DVD, it can store much more data than a DVD. a USB connector, insulated electrically and protected
A single-sided Blu-ray disk can store 25 GB of data and inside a plastic, metal, or rubberized case that can be
a dual-layer disk can store 50GB of data, While CDs carried in a pocket or on a key chain. The USB connector
and DVDs use a red laser to read and write data, the is often protected inside a removable cap, although it
Blu-ray disk on the other hand uses a blue-violet laser, is not likely to be damaged if unprotected, USB flash
hence the name Blu-ray. The advantage of using a blue drives draw power from the computer via external USB
laser with a shorter wavelength of 405 nm than the red connection
laser (650.nm) is that it allows it to focus the laser spot Uses of flash drives USB flash drives are useful in several
with even greater precision. This means that data can be ways.
packed more tightly and therefore stored in less space.
Moreover, the storage capacity of this disk is enough to Personal data transport Flash drives are used to transport
store a continuous backup copy of most people's hard and store personal files such as documents, pictures, and
drives on a single disk videos
A Blu-ray disk player is backwards compatible with System administration Flash drives are widely used by
CDs and DVDs and can therefore play a CD or a DVD system and network administrators to store configuration
despite the differences between the types of laser used. information and software used for system maintenance,
However, the Blu-ray disks will not play on CD and DVD troubleshooting, and recovery. They are also used to
players, because those players lack the blue-violet laser transfer recovery and antivirus software to infected PCs.
required to read the disks. As these drives have much larger storage capacities, they
Blu-ray disks will soon replace the use of CDs have also replaced CD-ROMs, which were earlier needed
and DVDs. They have already been supported by when reinstalling or updating a system.
about 200 of the world’s leading consumer electronics,
personal computer, recording media, video game, and Booting operating systems These days, PC firmware
music companies. Besides this, they are also being allows booting from USB drives. Such a configuration is
supported by Hollywood studios and a number of known as a live USB.
smaller studios that have already announced that they Music storage and marketing Digital audio files stored
will release new films on Blu-ray disks. Blu-ray disks on a USB flash drive can be easily transported from one
are also being used in physical distribution of video computer to another and played on a compatible media
games for PlayStation 3, Wii U, PlayStation 4, and player. Moreover, many home hi-fi and car stereo head
Xbox One. Sony’s Playstation 3 has a Blu-ray drive units are now equipped with a USB port, so that flash
installed in it drives can be connected to them.
Computer Memory and Processors 49

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

Fall data backup Incremental data backup

* 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

3.16.1 Execution Unit


Hierarchical storage management is a strategy that moves The execution unit mainly consists of the CU, ALU, and
less frequently used or unused documents from a fast registers,
magnetic disk to optical jukebox devices in a process called
migration. Ifthefiles areneeded, they are migrated back Control unit The main function of the CU is to direct
to the magnetic disk.
and coordinate the computer operations, It interprets the
instructions (program) and initiates action to execute
them. The CU controls the flow of data through the
ERTD Basic PROCESSOR ARCHITECTURE computer system and directs the ALU, r ters, buses,
and input/output (I/O) devices. It is, therefore, called the
As discussed in Chapter 1, a basic processor consists of brain of the computer system. Similar to the human brain,
two main parts— airthmetic and logical unit (ALU) and the CU controls all operations within the processor, which
in turn controls all other parts of the computer system, In
control unit (CU). Besides these components, there are
addition, the CU is responsible for fetching, decoding,
also registers, an execution unit, and a bus interface unit
executing instructions, and storing results.
(BIU) as shown in Figure 3.16.
Arithmetic and logic unit The ALU performs arithmetic
(add, subtract, multiply, divide, ete.), comparison (less
than, greater than, or equal to), and other operations.

Cache memory 3.16.2 Registers


A processor register is a computer memory that provides
Secondary Input quick access to the data currently being used for processing.
storage pe The ALU stores all temporary results and the final result in
devices Pen the processor registers. As mentioned earlier, registers are
at the top of memory hierarchy and are always preferred to
speed up program execution.
Registers are also used to store the instructions of the
Control Arithmetic program currently being executed. There are different
unit and types of registers, cach with a specific storage function.
logic unit
Accumulator and general-purpose registers These are
frequently used to store the data brought from the main
Figure 3.16 Basic computer organization memory and the intermediate results during program
52 Computer Fundamentals and Programming in C

€xccution. The number of general-purpose registers Decode Interpreting the instruction.


present varies from processor to processor. When
Execute Running the corresponding commands to process
program execution is complete, the result of processing is
the data.
transferred from the accumulator to the memory through
the memory buffer register (MBR), Store Writing the results of processing into memory,
Special-purpose registers These include the following This instruction cycle is repeated continuously until the
power is turned off
* The memory address register (MAR) stores the address
of the data or instruction to be fetched from the main 3.16.3 Bus Interface Unit
memory, The value stored in the MAR is copied from
the program counter, The BIU provides functions for transferring data between
* The MBR stores the data or instruction fetched from the execution unit of the CPU and other components of
the main memory (Figure 3.17), If an instruction is the computer system that lie outside the CPU, Every
fetched from the memory, then the contents of the computer system has three different types of busses to
MBR are copied into the instruction register (IR). If a carry information from one part to the other. These are the
data is fetched from the memory, the contents are either data bus, control bus, and address bus (Figure 3.19).
transferred to the accumulator or to the VO register. The Address bus
MBR is also used while writing contents in the main
memory. In this case, the processor first transfers the r
contents to the MBR, which then writes them into the RAM [nom|Primer|Disk Moni Keyhoud
memory, cru
Reads Data bus
Processor | [Memory butterregister | | Memory| he Control bus
Figure 3.17 Data to and from memory comes from and to
processor through the MBR Figure 3.19 Buses with a computer system
The BIU puts the contents of the program counter on the
* The IR stores the instructions currently being executed. address bus. Note that the content of the program counter
In general, an instruction consists of two parts is the address of the next instruction to be executed, Once
operation and address of the data on which the operation the memory receives an address from the BIU, it places
has to be performed. When the IR is loaded with an the contents at that address on the data bus, which is then
instruction, the address of the data is transferred to the transferred to the IR of the processor through the MBR, At
MAR and the operation part is given to the CU, which this time, the contents of the program counter are modified
interprets it and executes it (c.g., incremented by 1) so that it now stores the address of
* The I/O register is used to transfer data or instructions to the next instruction.
or from an I/O device. An input device transfers data to
the /O register for processing. Correspondingly, any data 3.16.4 Instruction Set
to be sent to the output device is written in this register.
* The program counter The instruction set is a set of commands that instructs the
stores the address of processor to perform specific tasks. It tells the processor
Store Fetch the next instruction to what it needs to do, from where to find data (register,
be executed. memory, or I/O device), from where to find instruction,
and so on. Nowadays, computers come with a large set
The size of a register is of instructions, and each processor supports its own
usually specified by the instruction set. Although the instructions across processors
number of bits it can store.
are almost the same, they may vary in their internal design.
For example, a register can
A basic set of instructions that is supported by every
be of 8 bits, 16 bits, 32
Execute Decode processor is given in Table 3.12
bits, or 64 bits. Higher the
An instruction set can be built into the hardware of the
register size, more the data
processor or it can be emulated in the software, using an
Figure 3.18 Instruction cycle that can be stored in it
Instruction cycle To execute an instruction, a processor
normally follows a sect of basic operations that are Every instruction contains two parts—opcode and
together known as an instruction cycle (Figure 3.18). The operand. Opcode specifies the instruction to be
operations performed in an instruction cycle involve the performed (e.g., ADD, SUB) and operand isthe data (e.g.,
following in register, in memory, oravailable through |/O device)
Fetch Retricving an instruction or a data from memory on which the instruction is tobe applied.
Computer Memory and Processors 53

interpreter. The hardware design is more efficient and fast?


LELCEe® Basic instruction set
for running programs than the emulated software version,
Instruction |Purpose Example |Comment
ADD Toaddtwo = =ADD AX and BX are 3.16.5 System Clock
sumbers AX, BX processor registers A small quartz crystal circuit called the system clock
that hold data. controls the timing of all operations within the computer
SUB To subtract SUB AX and BX are system. The system clock regularly generates ticks to
control the functioning of the computer. Every processor has
two numbers AX,BX processor registers
that hold data. a system clock to synchronize various operations that take
place within the computer system. Many modern computers
MUL To multiply MUL AX and BX are even have multiple system clocks that vibrate at a specific
two numbers AX, BX processor registers frequency. When we talk of the system clock, two important
that hold data. questions need to be answered. First, how does the system
clock affect the speed of the processor? Second, why is there
DIV To dividetwo DIV AX and BX are a need for multiple clocks within a single computer system?
numbers AX, BX processor registers Clock speed is measured by the number of ticks
that hold data. per second, where a tick is the smallest unit of time in
CMP To compare CMP AX stands for the which processing is done. A processor can perform some
two numbers AX,BX accumulator.
operations in a single clock tick, whereas others may
require more ticks. The ticking of the clock drives the
IN To inputdata INPDX DX is a processor circuits in the computer. Therefore, faster the clock ticks,
from a device register. more is the number of operations that can be performed
(considering other factors to be the same).
OUT To output ouT Data to be output Nowadays, processors have system clocks with speeds
data toa DX is in DX. in the gigahertz range, where giga stands for billion and
device hertz means one cycle per second. Therefore, a computer
that operates at 3GHz has three billion clock cycles in
JMP To jump JMP MAIN is the name
one second, which means that the computer can perform
to another MAIN of the location.
more than one billion operations in a second, Hence, clock
address in
memory
JMPIF To jump JIMPZ The program will Other factors that can affect a computer's performance
fo another MAIN goto MAIN if the include the type of processor, availability of cache
address in (Gump if value is equal to memory, memory access time, and speed of BIU.
memory zero) zero.
only when speed is one of the factors that have a profound effect on a
the specified computer's performance
condition is Initially, computers had a single unified system clock that
true operated at a very low speed. This clock was connected
with the processor, memory, and other components. As
LOAD LOAD The data will the technology advanced, some devices could operate at
AX be loaded from a much higher speed than others. However, a single slow
memory in the speed clock could not drive the components that operated
accumulator. at different speeds, Hence, computers today have four or
five different clocks, each operating at a different speed.
STORE STORE The data in
AX accumulator
will be stored in 3.16.6 Processor Speed
memory. The speed of PCs and minicomputers is usually specified in
CALL CALL — Call a subroutine
MHz or GHz. However, the speed of a mainframe computer
is measured in MIPS (millions of instructions per second)
PROC named Proc.
or BIPS (billions of instructions per second) and that of
RET RET - @ supercomputer is measured in MFLOPS (millions of
floating-point operations per second), GFLOPS (giga or
billions of floating-point operations per second), or TFLOPS
(10° floating-point operations per second). The reason for
54 Computer Fundamentals and Programming in C

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.

Reduced Instruction Set Computer


Whether RISC or CISC is used depends on the application.
Apple's software-oriented approach has led to RISC For some applications, RISC performs better, whereas for
architecture, which utilizes a small but highly optimized others, CISC will bepreferable.
set of instructions, A research done by IBM found that
20 per cent of the instructions perform 80 per cent of Since both RISC and CISC have their own advantages, the
the work in computers. Programmers rarely used many recent trend is the convergence of these two technologies.
instructions, and so companies wanted to reduce the The lines between the two architectures have begun to blur
number of instructions and to have only frequently as both the architectures have started adopting cach other's
used instructions in the hardware. Others could be strategy. For example, pipelining, which is an important
implemented in the software using the basic instructions concept of RISC machines, is now being implemented in
set, The main principle of RISC is that it takes long and CISC machines. Similarly, RISC machines are adopting
complex instructions from a CISC design and reduces it superscalar execution and are also moving towards having
to multiple shorter instructions, which can execute faster more transistors on a single chip to incorporate more
The simplicity of RISC gave more freedom to computer complicated, CISC-like commands,
oo,
POINTS TO REMEMBER
Computer memory is an internal storage area in the Most computers contain a small amount of ROM that
computer that is used to store data and programs stores critical programs like the BIOS which is used to
either temporarily or permanently. boot up the computer when it is turned on. The BIOS
While the main memory holds instructions and data consists of a few kilobytes of code that tells the
when a program is being executed, the auxiliary or the computer what to do when it starts up, e.g., running
secondary memory holds data and programs not hardware diagnostics and loading the operating
currently in use and provides long-term storage. system into the RAM,
To execute a program, all the instructions or data that © Magnetic tapes are mass storage devices capable of
has to be used by the CPU has to be loaded into the backing up and retaining large volumes of data, They
main memory. However, the primary memory is are available in the form of cassettes, reels, and
volatile, so the data can be retained in it only when cartridges.
the power is on, Moreover, it is very expensive and Floppy disks are data storage devices that consist of a
therefore limited in capacity, thin magnetic storage medium encased in a square
On the contrary, the secondary memory stores data or plastic shell.
instructions permanently, even when the power is Hard disk drive is a storage device, which is a part of
turned off. It is cheap and can store large volumes of the general-purpose computers and is used for storing
data. Moreover, data stored in auxiliary memory is data on a set of disks that are stacked together like
highly portable. phonograph records.
Processor registers are located inside the processor The optical disk stores information in the form of pits
and are therefore directly accessed by the CPU. Each and lands. Pits are the tiny reflective bumps created
register stores a word of data (which is either 32 or 64 with a laser beam, and lands are flat areas separating
bits). Registers are the fastest of all forms of computer the pits. While a land reflects the laser light and is
data storage. read as binary digit 1, a pit on the other hand absorbs
Cache memory is an intermediate form of storage the light and is read as binary digit 0.
between the ultra-fast registers and the RAM. Cache The CU directs and coordinates the computer operations.
memory is basically a portion of memory made of The BIU provides functions for transferring data
high-speed SRAM instead of the slower and cheaper between the execution unit and other components of
DRAM, which is used for main memory. the computer system that lie outside the CPU,
56 Computer Fundamentals and Programming in C

* 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

CEB INTRODUCTION TO NUMBER SYSTEMS At position 0,


At position 1, d
At position 2, d;
Data is stored in a computer in the form of 0s and Is. This
is because computers understand only binary language
(which consists of just two digits, 0 and 1). Therefore, for a
computer, all data and information is reduced to numbers. We can form the number using the aforementioned
Whether the user stores songs, pictures, numbers, or information as follows:
documents, all information is treated as binary numbers. (NYT = dyn 8+. + dor + dl + + dg ™
In this chapter, we will learn about the different types
of number systems used in computers as well as different =100* 2410x341" 4+0.1x5+0.01x6
types of codes that convert human language, consisting = 200 +30+4+0.5+0.06
of numeric and alphanumeric characters, into machine = 234.56
language (in binary code) which the computer understands.

Representation of Numbers in Radix r


Before considering number systems, let us first understand
the haseorradix of a numbersystem, The number of unique
CRD inary numBer sysTEM
digits used to form numbers within a number system is
called radix of that system. For example, in the decimal Computers are electronic machines that operate using
number system we use digits 0-9 to form numbers; thus, binary logic. These devices use two different values to
its radix is 10. represent the two voltage levels (0 V for logic 0 and +5 V
A general number system (Njr of radix r can be for logic 1), Therefore, the two values,0and |, correspond
represented as follows: to the two digits used by the binary number system,
(Nyr = d,y 7! + + dyt+ dy! + The binary number system works like the decimal
number system, with the following exceptions:
where r= radix
d, = Digit at position i-m<sisn-1 * While the decimal number system uses base 10, the
= Weight of position /-m <isn—-1 binary number system uses base 2
a = Number of integral digits in NV * The decimal number system uses the digits 0 to 9, but
m= Number of fractional digits in N the binary number system uses only two digits, 0 and |
Digits in radix r number system include 0, .... r—1
Some important terms in the binary number system include
Example 4.1 the following
+ Bit is the short form of ‘binary digit’. It is the smallest
Let us consider a decimal number 234.56, Form the number possible unit of data. In computerized data, a bit can be
using the aforegiven radix representation either 0 or I
60 Computer Fundamentals and Programming in C

* Nibble is a group of four bits.


Binary representation with four bits
* Byte is a group of eight bits. A nibble is a half byte. Bits
0-3 are called the low-order nibble, and bits 4-7 form Number of bits: 4
the high-order nibble Data values that can be represented = 2‘ = 16 |
Word is a group of two bytes. Bits 0-7 form the low-
Decimal value | Binary value |Decimal value | Binary value
order byte and bits 8-15 form the high-order byte.
0 0000 8 1000
However, computers today have redefined word as a
group of four bytes (32 bits). ! 0001 9 1001
2 0010 10 1010
Table 4.1 lists these terms in the binary number system
with examples. 3 ool i tou
4 0100 be] 1100,
5 101 3 Hob
LC® Some important terms in the binary number
6 ono 4 to
system
7 On 1s Witt
Term | Size (bits) Example
|Bit 1 0
|Nibble 4 1010 Applications of Binary Numbers
|Byte 8 0101 1100 * The binary system is best suited to be used with computers,
(Word 16 6101 11000101 1100 as mechanical and electronic relays recognize only two
states of operation—on/off or closed/open. In the binary
number system, character | on © closed circuit © true
Now let us understand how much data can be encoded and character 0 =off «open circuit false.
in the binary form using different numbers of bits. If we Binary numbers can be casily translated into electrical
have a single bit, we can represent only 2! 2 values, 0 or impulses.
1. With two bits, we can represent 2° = 4 values, namely * The binary system can be effectively used to encrypt
00, 01, 10, and 11, Tables 4.2-4.4 illustrate this concept messages
better + The binary system is the backbone of the development
of computer science and many forms of electronics. It
led to the development of devices such as typewriter,
Table 4. Binary representation with two bits
cathode ray tube, telegraph, and transistor
Number of bits: 2 * Binary number system is also used in statistical
Data values that can be represented = 2° = 4 investigations
and probability studies to explain strategy,
Decimal Binary value
prove mathematical theorems, and solve puzzles
value
| 0 00 CED WORKING WITH BINARY NUMBERS
| 1 oO
| 2 10 We all are very familiar with how decimal numbers operate
, 3 u The same concept can be applied to binary numbers (base
2), octal numbers (base 8), and hexadecimal numbers
(base 16). So before discussing other number systems,
ACC Binary representation with three bits let us first take a look at how we form a number in the
decimal number system.
Number of bits: 3 Suppose we have a decimal number 123, what do you
Data values that can be represented = 2' = 8 call this number? How did you get its value? The answer
Decimal Binary Decimal Binary is that we first arrange individual digits into columns and
value value value value then multiply each digit with the value of its position
Figure 4,1 illustrates this concept
0 000 4 100

1 oo1 $ 101 Hundreds(10°)Tens (10) | Ones (10?)

2 O10 6 110 Decimal 1 | 2 3

| 3 ol 7 Lb Figure 4.1 Position of the digits of 123 using the decimal


number system
Number Systems and Computer Codes fo

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

10110111 4.3.7 Dividing Two Binary Numbers


+ 11001110
Binary division is again similar to dividing two decimal
1 10000101
numbers. According to the long division method, the
Now discard the carry from the last bit; hence the divisor is multiplied with the quotient, and the result is then
result = 10000101. subtracted from the dividend.
Consider the following examples to understand the
concept better.
Example 4.8
0011 O10 OO101111
Calculate 1010110 — 0101010 using two's complement 11) 1001 ( 10) 111011 ( 101 ) 11101110¢
method. 1] 0 i]
Solution 10 1 11
Step 1; Find the two’s complement of the subtrahend.
o 10 a
100 i Mt
Subtrahend = 0101010
One’s complement of subtrahend = 1010101
4 10 101
i 10 100
Two's complement of subtrahend = 1010101 + 1
i 10 0
= 1010110
o ol 1001
Step 2: Add the minuend and the two’s complement of the
0 LOL
subtrahend,
i 1001
1010110
+.1010110 Nowdiscard the carry from the last
10 LOL
ak 1001
10101100 bit; hence the result «0101100
LOL
1000
LOL
4.3.6 Multiplying Two Binary Numbers AL
Binary numbers are multiplied in the same manner as we
multiply two decimal numbers.
Two numbers A and 8 are multiplied using partial
OCTAL NUMBER SYSTEM
products. For each bit in 8, the product of that bit with The octal number system is the base 8 number system
the corresponding bit in A is calculated and written on a which uses digits 0-7, This number system was used
new line (shifted leftward). The partial products are added extensively in carly mainframe computer systems, but
together to get the final result. has become less popular in comparison with binary and
The rules of multiplication of binary numbers are the
hexadecimal number systems,
same as that of decimal numbers, that is:
Octal decimals operate in the same manner in which
+ Ox 080 *Ox1l=0 decimal and binary numbers operate. In the octal
° 1x0=0 eixtlel number system, each column is a power of 8 as shown
Consider the following examples to understand this concept. in Table 4.6.

1010 * 11 = 11110 1011 * 1001 = 1100011


Decimal, binary, and octal number systems
1010 1011
x11 x1001 Fourth Third
1010 1011
digit
digit
mas

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

cach group into its equivalent octal number. Combine Case 2


these individual octal numbers to get the final result You can use the same concept while doing octal
addition. When we add two octal numbers there can be
two cases.
Example 4.14
Case |: The sum is less than 8. In this case, we just write
Convert (1101 100), into its octal equivalent the digit obtained after addition.
Solution
Case 2: The sum is greater than or equal to 8. In this case,
The steps to convert (1101 100), into octal form are as follows: 8 is subtracted from the sum and the result is
Step 1; Divide the number into groups of 3 bits each, written at that position, Moreover, a carry is given
starting from the LSB. Therefore, to the next digit
1101100 Consider the following examples
Step 2: Convert each group of binary bits into its equivalent
octal number. Thus, we have 15 4. | 4 3
Step 3: Merge the octal values to get the final result. Hence, |+3 #2
(1101100), = (154), | 7 5

Let us take another example and convert (10100110), into Case 1


its octal equivalent.
Step 1: Divide the number into groups of 3 bits each
|! :
| 14
Therefore,
10 100 110
\+27 c
43 1
Step 2: Convert each group of binary bits into its equivalent
octal number. Thus, we have 2 4 6. | Now, 4+7 in) Now, 5+7= 12
Step 3: Merge the octal values to get the final result. Hence, | which is greater than which is greater than
(10100110), = (246), 8. So subtract 8 from 8. So subtract 8 from
| 11, we get 3. Write 3 12, we get 4. Write 4
4.4.5 Adding Two Octal Numbers | at that position and at that position and
add a carry to the next add a carry to the next
How do you add two numbers in decimal? For example, |digit digit
when we add two numbers there can be two cases:
Case 2
Case 1; The sum is less than 10. In this case, we just write
the digit obtained after addition.
4.4.6 Subtracting Two Octal Numbers
Case 2 The sum is greater than or equal to 10. In this
case, 10 is subtracted from the sum and the result How do you subtract two numbers in decimal? For example,
is written at that position. Moreover, a carry is when we subtract two numbers there can be two cases:
given to the next digit Case 1: If the digit in the minuend is greater than the digit
4 3 in the subtrahend, subtract the digits and write the
+5 +2 result at that position.
9 5 Case 2: Ifthe digit in the minuend is smaller than the digit
Casel in the subtrahend, borrow | from the immediate
1 1 higher place. When a digit is borrowed, the
14 36 minuend digit at the current place gets 10 and 1 is
subtracted from the minuend digit at the immediate
+27 +48 higher place.
41 84

Now, 4+7=11 Now, 6+8= 14 | 9 8


which is greater which is greater |-5 6
than 10. So subtract than 10. So subtract | 4 2
10 from 11, we get 10 from 14, we get Case l
1, Write | at that 4. Write 4 at that
position and add position and add | 842 6 ¥4
a carry to the next a carry to the next 92 74
digit. digit 48 6 5
66 Computer Fundamentals and Programming in C

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

Example 4.18 Step2: Write the binary equivalent of 1, which is


0001.
Convert (56789),, into its hexadecimal equivalent. Step 3: Write the binary equivalent of £, which is equal to
Solution 1110.
Step4: Merge the individual values. Thus, (A1E),_ = (1010
16 | 56789 |R
0001 1110).
16 | 3549 | 5 Step 5: Divide the binary number into groups of 3 binary
16 | 221 |D Nowwrite
the result starting from the bits. Therefore,
16 | 13 [0 fast remainder obtained. 101 000 011 110
Step 6: Convert each group of binary bits into its equivalent
| 0 | D Therefore, (56789), =(DDDS),. octal number.
Thus, we have 5 0 3 6.
Step 7: Merge the octal values to get the final result. Hence,
4.5.3 Converting a Hexadecimal Number into
(A1E)s6 = (5036).
Binary Form
=.
Figure 4.2 can be used to casily convert a hexadecimal
number into its binary equivalent. Simply break the binary Example 4.20
number into 4-bit groups beginning with the LSB, and Convert (680),, into its octal equivalent.
substitute the corresponding four bits in binary for cach
hexadecimal digit in the number. Solution
For example, convert OxABCD into its binary equivalent, Step 1: Write the binary equivalent of 6, which is equal to
From Figure 4.2, we have, (ABCD), = (1010 1011 0110.
1100 1101), Step 2: Write the binary equivalent of 8, which is equal to
Let us take another example and convert (F1E2),, into 1011.
binary, (F1E2),¢ = (1111 0001 1110 0010), Step 3: Write the binary equivalent of 0, which is equal to
0000.
4.5.4 Converting a Binary Number into Step4; Merge the individual values. Thus, (680),, = (0110
Hexadecimal Form 1011 0000).
Figure 4.2 can also be used to convert a binary number Step 5: Divide the binary number into groups of 3 binary
into its hexadecimal form. The first step is to pad the bits. Therefore,
binary number with leading zeroes (if necessary), so that 011 010 110 000
it contains multiples of four bits. Step 6: Convert each group of binary bits into its equivalent
For example, let us convert the binary number octal number. Thus, we have 3 2 6 0.
01101110010110 into its hexadecimal equivalent. Step 7: Merge the octal values to get the final result. Hence,
Note that the given binary number contains 14 bits. Pad (680),¢ = (3260).
the number with two zeroes on the left so that the number
———-_
has 16 bits (multiple of 4 bits).
Now, the binary number = 0001 1011 1001 0110. 4.5.6 Converting an Octal Number into
The next step is to look up these binary values in
Figure 4.2 and substitute the appropriate hexadecimal Hexadecimal Form
digits. The equivalent hexadecimal number = 1B96. To convert an octal number into its equivalent hexadecimal
number, first convert the octal number into its binary
4.5.5 Converting a Hexadecimal Number into equivalent and then convert the binary number into its
Octal Form hexadecimal form.
To convert a hexadecimal number into its octal equivalent, Example 4.21
first convert the hexadecimal number into its binary
equivalent. Then, convert the binary number into its Convert (567), into its hexadecimal equivalent.
equivalent octal number. Solution
The steps to be performed to convert (567), into its
Example 4.19 hexadecimal equivalent are as follows:
Step 1: Write the binary equivalent of 5, which is equal
Convert (A1E),, into octal form.
to 101.
Solution Step2: Write the binary equivalent of 6, which is equal to 110.
Perform the following steps: Step3: Write the binary equivalent of 7, which is equal to
Step1: Write the binary equivalent of A,which isequal to 1010. 111.
Computer Fundamentals and Programming in C

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

Loa Position values of digits in various number systems

Position 5 4 WE: ! 0 wf, | <a | od | 26 | a8


|Position value in decimal 10° «10° 10° 10 10 10" 10% 10% 10%
Position value in binary 2 ES ee a FE) a) Ea) ee iat
| Position value in octal oy (RS) ES] Ee ie 5 AST eS ee
\Position value inhexadecimal 16° 16¢ 16" 16° is 16°16" 167 16? 16 16%)
these individual parts of the decimal number into binary. While Example 4.25
the whole number part (before the decimal) is converted using
repeated division by 2 and considering the remainders, the Convert the decimal number 12345.48 into its equivalent
fractional part on the other hand, is converted by repeated hexadecimal number.
multiplication with 2 and considering only the whole number Solution
part of the result, Figure 4.3 clarifies this concept Figure 4.5 shows the conversion process.
Number
Whole number part Fractional Number = 12445
2) 92)R 0.25 Whole number = 12345 Fractional =048
2/46/00 2 16 |12345 |R 048
212310 0.50 16] 771 |9 x16
2|it zs 16] 48 |3 7.68
215 [1 1,00 16] 3 Jo x16
21211 a 3 ABS
2) 1}0 0.00 (12345),, = (3039), 216
ofl 0.25)»
=(0.010), Note down the remainders B08
(02),, = (1011100), Note the digit before the starting from the last x16
Note down the remainders) decimal point obtained remainder obtained. 1.28
starting from the last from the first (0.48), = (O.7AEL),,
obtained, multiplication to the last.
Hence (02.25), = (011100010), Note the whole number
part of result obtained
Fig.4.3 Conversion of a decimal number to its from the first
equivalent binary number multiplication to the last.
(12345.48), = (3039.7AE1),,
Example 4.24
Fig. 4.5 Conversion of a decimal number to its
Convert the decimal number 178.92 into its equivalent octal equivalent hexadecimal number
number,
Solution
Figure 4.4 shows the conversion process. SIGNED NUMBER REPRESENTATION
[ Number = 178.92 IN BINARY FORM
Whole number part
=178 Fractional part = 0.92
BII78|R 0.92 Signed number representation is required to encode
x8 negative numbers in the binary number system. Basically,
8] 22)2
the negative numbers in any base system are written by
8| 2|6
preceding the number with a~sign (minus sign), However,
ol2 in computers, negative numbers too are represented
(178),, = (262), in binary. The binary language, which the computer
Note down the remainders understands, does not support the minus sign to write
starting from the last negative numbers.
92),, = (0.7270),
remainder obtained. Hence, a different technique is required to encode the
Note the whole number minus sign in terms of 0s and Is. There are three widely
part ofthe result obtained used techniques for extending the binary number system to
from the first
multiplication to the last. represent signed numbers. These techniques are sign-and-
Hence (178.92), = (262.7270), ] magnitude, one’s complement, and two's complement.
Out of the three, the two's complement method is the most
Fig. 4.4 Conversion of a decimal number to its popular for representing signed numbers in the binary
equivalent octal number number system.
70 Computer Fundamentals and Programming in C

4.7.1 Sign-and-magnitude In two's complement —54 can be given as:


Binary representation of +54 is 0011 0110.
Sign-and-magnitude is the simplest technique in which the Complement each bit: 1100 1001
most significant bit (MSB) is set to 0 for a positive number Add I to this result. Therefore,
or zero, and set to | for a negative number. The other bits
denote the value or the magnitude of the number 11001001
Hence, a byte having cight bits can use only seven bits +1
to denote the magnitude, and one bit is used to denote the 1100 1010 (-S4 in two's complement)
sign of the number. Using 7 bits, numbers from —127 to The main advantage of using two's complement is that
+127 can be represented (i.c., 2’ combinations). there is only one zero (0000 0000). For example, when
For example, consider Table 4.8 which illustrates how signed converting —0 in two's complement form, complementing
numbers are represented using sign-and-magnitude method. the bits gives IIIIIII1 and adding | gives 0000 0000
and a carry bit of 1. When we add numbers in two's
Representation of signed numbers in sign- complement, we discard the carry from the last bit. Hence,
and-magnitude method the result is only 0000 0000
Binary equivalent in sign-and-magnitude form
Decimal
Decimal Tsien] 7™ |6 |s® |]a®] a¢ |=| a
Similar to the one’s and two's complements, there is also
bit | bit | bit | bit | bit | bit | bit | bit
nine’s complement and ten's complement.
| 436 7 On (AT) GON Lee Se ee we To find the nine’s complement of anumber, subtract
| -4s Sal Fe EET RG ES FS (SP cach digit of thenumber from 9. Forexample, the nine’s
esi OS GH EE a aT A (RE complement of 12345 is 87654.
\ 108 iy TAT) (Eee) [Sey] Peel as bw Tofind the ten’s complement of a number, first find the
nine’s complement of that number and then add 1to it.
For example, let us find the nine’s and ten’s
4.7.2 One’s Complement complements of 314700.
The one’s complement representation of a negative Nine’s complement = 685299 and ten’s complement=
number is obtained by taking the complement of its 685300.
positive counterpart (in binary). For example, if one wants
to represent —45 in the binary number system using one’s
complement method, then perform the following steps CEB scp cope
* Write the binary representation of the number's positive Binary coded decimal (BCD) is a very simple technique
counterpart, that is, write the binary equivalent of +45, used for encoding decimal numbers, In this scheme,
* Negate cach bit in the binary representation of the digit is represented by its own binary sequence. The main
positive number (+45 in this case). advantage of using BCD is that it allows casy conversion
to decimal digits for printing or display, and allows faster
So, +45 in binary form is 0010 1101. Now negate cach bit
decimal calculations.
to obtain the binary representation of —45.
Consider Figure 4.2 in which the binary representation
Hence, —45 in binary = 1101 0010
of numbers 0-15 is shown. In BCD representation the digits
The PDP-1 and UNIVAC 1100/2200 series use one’s
0-9 are used. Each decimal digit (0-9) is represented by
complement arithmetic, The range of signed numbers that
four binary digits. For example, decimal 7 =0111 in BCD.
can be represented using one's complement in a byte is There are two types of BCD numbers—packed BCD and
from ~127)9 t0 +127).
unpacked BCD.
In unpacked BCD representation, only y one decimal
4.7.3 Two's Complement digit is represented per byte. The digit is stored in the
In one’s complement method, +0 is represented as lower nibble, and the higher nibble is not relevant to the
00000000 and —0 is represented as 11111111. In sign-and- value of the represented number. For example,
magnitude method, -0 is represented as 10000000. These Decimal 17 0000 0001 0000 0111 (in BCD)
different representations sometimes become problematic ;
Therefore, to avoid such a situation, the two's complement 1 7
representation is generally used. This representation is
Hence, to convert a decimal number into an unpacked
obtained in the following two steps:
BCD number, assign cach decimal digit, its 8-bit binary
* Complement or negate the bits in the binary equivalent.
representation of the positive number. In packed BCD representation, two decimal digits are
* Add 1 to the result of the first step. stored in a single byte, For example,
Number Systems and Computer Codes {£)

Decimal 17 = 0001 0111


ee
(in BCD)
CED otter coves
E ‘7
In this section, we will read about other coding techniques
Hence, to convert a decimal number into a packed BCD that arewidely used toconvert data into the form of 0sand Is.
number, assign to cach digit of the decimal its 4-bit
equivalent, padding the upper nibble with zeroes. if 4.9.1 ASCII Code
necessary (in case it is required to write a byte value rather
than a nibble value). For example, ASCII stands forAmerican Standard Code for Information
Decimal 7 = 0111 (in packed BCD) or 0000 O111 (in Interchange. It is a 7-bit character
code (refer Figure 4.6) that
packed BCD, if padding is required). was introduced by the American National Standards Institute
To convert a number from BCD to decimal, just reverse (ANSD) and is used by personal and workstation computers,
the process, that is, perform the following steps: ASCII characters are examples of unpacked BCD
numbers. Values in ASCII codes are represented as their
+ Start with the least significant byte. 4-bit binary equivalents stored in the lower nibble, while
* Group the binary digits into groups of four if it a packed the upper nibble contains 011 and has no bearing on
BCD number, otherwise in groups of eight bits if it is an the value of the represented number. ASCII is the most
unpacked BCD number, common format for text files in computers and on the
* Convert each set into its decimal equivalent. Internet. It can define 128 different characters because it is
For example, consider the packed BCD number, 0010 4 7-bit code, and can support 2’ combinations, The various
1001, Convert it into its equivalent decimal number. Now, ASCII characters are listed in Figure 4.6.
in the number, identify the LSB to start with. So, 0010
1001,sq.Group the binary digits into sets of four because 4.9.2 Extended Binary Coded Decimal
the number is in packed BCD format. Interchange Code
aZz 93
0010
Extended binary coded decimal interchange code
(EBCDIC) is an 8-bit character-encoding technique used
Hence, the decimal equivalent of the packed BCD number on IBM mainframe operating systems. It supports a wider
0010 1001 = 29, range of control characters than ASCII because it supports
Now, let us discuss another example, Consider the 8-bit character codes that can encode 2" or 256 characters.
unpacked BCD number, 0000 0011 0000 0110, Convert EBCDIC is easier to use on punched cards, Although
it into its equivalent decimal number. Now, in the number, it is considered to be an obsolete coding system, it is still
identify the LSB. So, 0000 0011 0000 0110, 69. Group the used in some equipment, to allow for continued use of
binary digits into sets of eight because the number is in software written many years ago that requires an EBCDIC
unpacked BCD format. communication environment.
EBCDIC characters are similar to ASCII characters.

a While the lower nibble contains the 4-bit binary equivalent


(as in ASCII), the upper nibble on the other hand is padded
with 1111, instead of O11.
Hence, the decimal equivalent of the unpacked BCD
number 0000 0011 0000 0110 = 36. 4.9.3 Excess-3 Code
The following are the advantages and disadvantages of
In the excess-3 (XS3) coding method, cach decimal digit
BCD codes:
is the 4-bit binary equivalent with 3 (0011) added.

Advantages 4.9.4 Weighted Codes


* Similar to decimal number system
* You must remember binary equivalent of only 0-9 In weighted binary codes, cach position of the number
decimal numbers represents a specific weight. For example, we have 8421,
2421, 5211, and 4221 codes.
* It is easy to use BCD codes for input and output
operations in digital systems.
8421 BCD Code
Disadvantages BCD codes are also known as 8421 codes because each of
* BCD addition and subtraction has different rules the four bits is given a *weighting’ according to its column
* BCD arithmetic is more complex than binary arithmetic value in the binary system. The LSB has the weight or
* BCD is less efficient than binary numbers because it value 2° = 1, the next bit has value 2' = 2, the next bit has
requires more number of bits to store the same decimal value 2? = 4, and the MSB has the value 2) = 8, as shown
number in Table 4.9.
Fundamentals
and Programming in C

Dec HxOctChar Dec Hx GetHtml Che


0 0.000 NUL (ally 32:20 040 432 Space |6440 10D Ase @ =| 96 60 140KN,"
1 1 001SOH (startofheading) 3321 041 33,1 6541 LOLAES. 4 97 OAL HO? a
2 2,002 STX (start oftext) 34 22042 Ae, ~ (6642102 £966. B 88 62142 HIRD
3 3003 TX (end oftex) AS DOES AHS. 67.43 103 £967. 99 6S143N99. €
4 4.004 BOT (end oftransmission) OH AES 68 44108 £968. 100 64144 NEO
S $.005 ENQ (enquiry) 37 28085 A937: 45 WS £O6). E 1OL 6S 145 KMIOL ©
6 6 006 ACK (acknowledge) 38 26046 AOS, & W046 106 £870. F 102 66 146W102: 1
7 7 007 BEL (bell) 3927 O87 Reo.” 71.47 107 &e7.G 10S 67 147 HW103.
8 8010 BS(hackspace) 40 250180 8H: ( 7248 10 R072 1k 6 150 104 by
9 9.001 TAB (herrizental
tats) 41 29051 aesl:) 7349 TL RATS. 10S69181 GMTOS. i
10 A012 LFUNL bine feed. new line) 422A 082 aed 4A 12 aed 106 GA 1ST &H106, 5
11.B O13 VT (wemcal tab) 43:2B O83 kee TSAB LIS ASTS. KK 107 GE ESS A107
12.C 014 PF(NP frm feed, mew page) | 44 20-054 eee, | HAC 14 &eTe OR OC ES em1OH IL
13 D OFS CR (carriage retam) 45 2DOSS WHS, - TT AD LES &77. M 109 6D 15S #109,mm
14 B O16SO (shaft owt) 46 2B OS Be, ‘TS4E 116 ROT 110 68 156 Rat On
ISP O17 St(shift way 47 POST weet. / TO4P 117 £879, 0 111 OF157 att 1.0
16 10.030 DLE (datalinkexcape) 45 00080 £48, 0 850 13) een. P 11270160AMEND. p
17:11.021 DCI (device comtrot 1) 47 31 061 aeay. 1 ‘SUSE 121 ean.Q TAS71161GML. g
18 12.022 DC2 (device comtrot 2) $0 32062 ASO, 2 HL 12 AK $14 72162 Reta
19 13.023 DCS (device contrat 54 $1: 33063 east. s ‘8553 125 AeRd, S HES TS 163 MATES: ©
20 14.04 DCA (device comtrot 4) S234 064 aeS2.4 454 124 aOR T 11674164RHEL
21.15 02S NAK (negative ackawtedge) | $3.38
065 AWS: 5 5555 125 AAS. LIT 7S165 QW? @
22 16036 SYN (symchromous ithe) S456 086 BaSa, 6 80 56128 RON 118 76166det Ley
23.17 027 ETH (ond ofcrams Ihocky ‘SS 57067 aess, 7 5757 127 AO Ww 119 77167 dew bh we
24 IROOM CAN (cancel) $6 38070 Awe, & ‘8s58 10 EX 120-78170 WLIO ©
25.19.091 EM (ondofmedium) ST.9071 est. 8959 101 BAY 128-70
171 andy
261A O82 SUB {subsuitute) SS MAOT? Aeon, WOSA TN a Ze 122 7A 172 RH
TT 1B O38 ESC (escaped 9 OTS BEM, 9 SB LSS Ae | 128 7H ETS RAIDS,
261C OM ES(ikeseparator) 6010 04 kata, < 1s 7e174anal
20 1DO45 GSigroup separator) 61 1DOFS APO, = 125-71)
17S sends)
30 1E.056 RS (rocerd separation) 62 32076 A002. > 126 TE 176 ew 26 ~
SLIP OS? US @ i 127,78
177 aqiz? DEL.

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.

eee Decimal number represented in different codes


Digit Binary ASCII EBCDIC XS3 4221 Gray code Unicode
0 0000 0011 0000 1111 0000 ool ‘0000 1000 U +0030
1 0001 0011 0001 1111 0001 0100 0001 OOK U+0031
2 0010 0011 0010 1111 0010 o101 no10 ool U +0032
3 oO1L O11 OO11 11110018 ono oor 0010 U +0033
a 0100 0011 0100 1110100 ol 1000, O10 U+ 0034
s olor oo 0101 ti) o1or 1000 out Ont U +0035
6 ono OO11 0110 M1010 1001 1100 O1oL U+ 0036
7 oll ool OLE PeERRURLT 10 1101 0100 U +0037
& 1000 0011 1000 1111 1000 wn Ho 1100 U +0038
9 1001 OOLT 1001 1111 1008 1100 tit 110k U +0039

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

The proposition can be represented diagrammatically


8B BOOLEAN ALGEBRA as shown in Figure 5.2
As already discussed in Chapter 4, computers understand
only binary numbers, in which only the digits 0 and | are Get admission
used. These binary computer systems work on propositional in MSe
OR
logic, wherein a proposition may be true or false and may Get admission
also be stated as functions of other propositions that are in MCA
UJ
connected by three basic logical connectives—AND, OR, ARDS Do post-
and NOT, For example, graduation
1 will do postgraduation if 1 get admission in MSc or
MCA
This statement functionally connects the proposition Geta job NOT
‘I will do postgraduation’ to two propositions—‘if 1 get
admission in MSc’ and ‘if | get admission in MCA’. This
scenario can be represented as shown in Figure $3.1 Figure 5.2 Statement and complex propositions

Thus, we see that a complex proposition can be casily stated


Get admission
in terms of binary (two) variables and binary operators (OR,
in MSe Do post
~ graduation AND, and NOT). Itis for this purpose that the mathematician
Get admission George Boole developed Boolean algebra in 1854.
in MCA In Boolean algebra, a Boolean system has either of two
Figure 5.1 Statement and simple propositions states—true (T) or false (F). The following are the salient
points of Boolean algebra
From this discussion, we can conclude that the meaning + Value *1* means true.
of the OR connective is that the corresponding output * Value °0’ means false.
is true if either one of the inputs is true; otherwise, it is * A Boolean expression is a combination of Boolean
false variables and Boolean operators. Boolean expressions
We can make this proposition a little more complex that are logically equivalent to one another are called
by saying “I will do postgraduation if 1 do not get a job equivalent expressions.
and if 1 get admission cither in MSc or in MCA’. Before * A Boolean function bas one or more input variables and
preparing the block diagram for this preposition, we must generates an output based on these input values, The
first state it in a well-structured way to understand how it result may be 0 or 1
is composed. The proposition can be given as follows: * Boolean operators take certain inputs and produce an
Do postgraduation = (NOT (Get a job)) AND ((Get output based on a predetermined table of results (also
admission in MSc) OR (Get admission in MCA)) known as the truth table).
Boolean Algebra and Logic Gates 7

* The Boolean operator AND (conjunction or intersection) Absorption


Law: x > (xy) =x
is used as a *." and in some texts as *4". For example,A -
Bor A B meansA andB. The ANDoperator takes two Shade the portion forxUy. Next, shade the portion forx,
(or more) inputs and returns a 1 only when both (or all) Then, shade the area that is common in both the diagrams.
inputs are I, The resultant shaded area will be the whole of the circle x
* The Boolean operator OR (disjunction or union) is used (Figure 5.4).
as a ‘+’ and in some texts as “n". For example, A + B
or A U B means A or B. The OR operator takes two
(or more) inputs and returns a 1 when any or all of the
inputs are 1,
* The Boolean operator NOT (negation) is used as “" and
in some texts as “~’. It simply negates the value of the auy
operator. For example, A' means NOT A. If the input is Figure 5.4 Venn diagrams for absorption law
1, the output will be 0 and vice versa.
Boolean algebra forms the basis of digital systems. It is Double Negation
Law: (x')' = x
extensively used to design digital circuits and is applied
First, shade the circlex.Then, shade the area not in.x. This
in digital logic, computer programming, set theory, and will give the region for x’. Next shade the area that is not in
statistics.
x’, which will be the whole of circle x (Figure 5.5).

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

Boolean algebra laws 5.4.4 Involution Law


The involution law, also known as the double negation
(Applicable onsingle variable} {Applicableonmultiple variables } law, states that a term that is inverted twice is equal to the
original term.
* Identity law * Commutative law
(AyY=A
* Idempotency law * Associative law
* Complement law * Distributive law If4 = 0, then (0’Y can be solved as I' =0, which is equal to A
* Involution law * Absorption law If = 1, then (1’Y can be solved as 0 = 1, which is equal to A
* Consensus law
+ De Morgan's law 5.4.5 Commutative Law
Figure 5.7 Classification of laws of Boolean algebra The commutative law states that the order of application
of two separate terms is not important
5.4.1 identity Law 1, A+B=B+A
The identity law states that a term OR’ed with a 0 or The truth table of the Boolean functions proves this law, as
AND’ed with a 1 will always equal that term. Similarly, a shown in Table 5.3
Boolean Algebra and Logic Gates 79

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

5.4.7 Distributive Law


Lee Truth table to prove the commutative law of
the AND operator The distributive law enables multiplication or factoring
A B A-B BA
out of an expression.
0 0 0 o L. AB+ OC) =A BAe’
0 1 o 0 The truth table of the Boolean functions, shown in
1 0 0 0 Table 5.7, proves this law
1 1 1 1

[Table 5.7]Truth table to prove the first distributive law


5.4.6 Associative Law A} BC) B+C) AUB4+O) | ASB IASC|ABHAC
The associative law allows the removal of brackets from 000 oO ) 0 0 0 |
an expression and regrouping of the variables. oot. 0 o 0 0 |
1, At+(B+C)=(A+B)+O i Es a) ee o o 06 0 |
The truth table of the Boolean functions, shown in mB) 0 0 0 0 |
Table 5.5, proves this law 1oo 0 0 0 0 a
2 ) a t on fi 1 |
a A) Vs ! 1 0 1 |
Table 5. Truth table to prove the associative 5 0 Fn) ee 1 1 i 1 }
law of the OR operator
A i wx | € A+(B+O) | (A+B)+€
0 0 0 0 0 2. A+(B+C)=(4+B)*
(A+)
0 0 1 t i (A+B) (A+C)
0 1 0 1 1 4d-A+A°BtA>C+B-C (Opening
0 ! 1 1 ! the brackets and multiplying)
1 0 0 1 1 =A+A°B+A’C+B>C(Since A» A=A)
1 o 1 1 1 4-(1+B)+A*C+B-C(TakeA
1 ! 0 1 1
common from the first two terms)
4+A°C+B-+C(Since 1+B=1 and
1 I 1 1 !
4-1 =A)
A(1+Cy+B-C
= A+B+C=LHS (Since 1 + C = 1 and
2. As (B+ C)=(A*BY C A-1l=A)
The truth table of the Boolean functions, shown in Let us prove this law using the truth table of the Boolean
Table 5.6, proves this law functions (Table 5.8)
80 Computer Fundamentals and Programming in C

=A BU +C)+A CL +B)
1S: Truth table to prove the second distributive law A+ B+A'C=RHS (Since 1+C=1

Ale lc|p-c |A+B-C \A+B A+ | A+B) A+ and 1+B=1)


ER KO 9, Sit nd On x 2. (A+ BYA' + C(B+ O = (4+ BYA' +O
joo1 0 ° 0 1 C) LHS (A + BYA' + CYB+ OC)
jo1o 06 0 i o ° (A: A'+A'B+A CHB CKB+C)
Jie CARE AS (eg 1 1 1 1 (Opening the brackets)
100 0 1 1 1 1 (a B+aA is +B CYB+C)
1o1 0 1 ' 1 1 aes eae B C+A'; BCH;
AB B+A°B+C+B
110 0 ' ' ' ' 4°C°C+B+C+C (Opening
the brackets)
i fs Sif 1 i 1 1 d'B+A°BC+B°C+A BC
+A C+B°C (SinceA A= A)
A's B+ Be CA+A)+B° CHAS
5.4.8 Absorption Law (Since
A+4=A)
The absorption
law permits
thereduction ofa complicated A’ B+B-C+A'C (Since A+ A’= 1)
expressic
expression intojo aa simpler
simpler one
one by absorbing
by absorbing like term:
terms. RHS (A
AA+ BYA'
+hed
C) CEO C
1, A+A*B=A d's B+A-C+B°C (SinceA: A'=0)
LHS A+AB
4-14+4°B Therefore,
LHS =RHS.
A(1 +B) (Since A» l= A)
A-1 (Since 1+B= 1) 5.4.10 De Morgan’s Laws
san The two laws of De Morgan are as follows:
2. A (A+B)=A Peis
LHS 4 (A+B) 1, (A+ By =A'-B
1 A+AB The first law states that the complement of the union
4+A-B (Since A: A= A) of two terms is the intersection of their complements.
a(1+B) (SinceA-1=A Let us prove
thislawusing the truth table of the Boolean
) 1+eeB= 1)
A 1 (Since ) functions (Table 5.9)
A RHS (Since A+ 1 = A) LEGER, Truth table to prove the first De Morgan’s law
3 "B=A+B A] 8 | AoB | Ase | at] oe | Ale
A+A'°B
(4 +A): (A+B) (Apply distributive oe RON =e . hem Ee .
law in which A+ B> C= (A+B) (A+©) Boll ' o ves ew) ba
=1:(A+B) (Since A+A'@ 1) 1 0 ' Oo) od SY 0
A+B~RHS ii \ 0 oo oy
4. As (A'+B)=A°B re
LHS A:(4'+B) ch Nae
A-A'+A°B De Morgan's second law states that the complement
=0+A*B (SinceA+ A’=0) of the intersection of two terms is the union of their
A~Be=RHS (Since A +0 A) complements.
Letus prove this law using
5.4.9 Consensus Law :
functions (Table 5.10)
: the truth tableofthe Boolean

The consensus law is the conjunction of all the unique


literals of the terms, excluding the literal that is not negated
LL LEB UD Truth table to prove the second De
Morgan’s
law
1 A+ B+A'sC+B°C=A' B+ AC A B A-B | (A-B) A B’ | A'+R’
LHS =A B+A' C+BC °o Oo 0 1 1 1 1
=A: B+A'sC+B:C:1 (Since A’ 1)=A) 0 1 0 1 1 0 1
A+ B+A'-C+B°C(A+A')
=A*B+A'-C+A*>B°C+A'-B-C i & 8 2 a : 3
As B+A-BsC+A'C+A'
BOC Le u e JEL 4
Boolean Algebra and Logic Gates 81

GGGB REPRESENTATIONS OF BOOLEAN Truth table of XOR operation


FUNCTIONS 4 B 4XORB | Minterm
r) 0 0 z
As shown in Figure 5.8, a Boolean function can be 0 i 1 m, =A'B
represented using any one of the following methods:
1 ° 1 my = AB
* A Boolean expression (canonical form) 1 1 0 J =
* Atruth table
* A logic diagram (refer to Section 5.7) By looking at the truth table, we can say that the XOR
function can be represented as a sum of the minterms or
the canonical SOP form as follows:
Representation of a Boolean function
FIA, B) = A’B + AB’
The shorthand notation is as follows:
(Boolean expression ) (Truth table) (Logic diagram )
Figure 5.8 Different ways of representing a
FIA, B) m, + my or F(A,B)=Em(1,2)
Boolean function A Boolean function with n variables has 2” minterms, as
each variable can be in cither the complemented or un-
complemented form. Thus, a three-variable function,
In Boolean algebra, a variable or a complemented F(A, B, C), bas 2° ~8 minterms as shown in Table 5.12
variable is called a literal. Designers of logical circuits
prefer to use a standardized form of literals known as
the canonical form to represent a Boolean function. ITable5.12]Minterms of a three-variable function
The key advantage of using a canonical form is that B |Minterm
it helps to reduce the number of logic gates and thus my = ABC |
interconnections between the components, thereby
im, ABC |
helping in the simplification and minimization of
digital circuits. A canonical form can be either a sum of my = ABC |
minterms or & product of maxterms m, = ABC
my = ABC” |
5.5.1 Minterm ms = AB'C |
A minterm is a canonical product (or a canonical sum of ng = ABC’
products—-SOP) term and has the following features —-—---sosooe
—--sce-os my = ABC
-eo-s=—-cs-so%7
* It includes all variables of a function.
* Each variable is in cither the un-complemented or Only those minterms for which the function produces |
complemented (inversed) form. as the output are used to represent the Boolean functions
* Each variable appears exactly once
A Boolean function can be represented as a sum of
minterms; f = I(minterms).
Aminterm |s a product term, but a product term may or
Note that the sum of minterms form is unique for any
may not be a minterm.
function. We can convert any SOP expression into the
canonical SOP form using the following steps:
* Determine the product terms of the expression.
Let us look at some examples of product terms and * Ensure that each product term has all the variables used
minterms for a function of three variables 4, B, and C in the Boolean expression.
Product terms 4, 8 AC, Ae B CAV SiC, * Ifthere is a product term in which one or more variables
A’: B are missing, then multiply that term with the sum of the
Minterms 4-8 -C.4° BC, rhe CA
missing variables and their complement.
+ Expand the Boolean expression and delete the repeated
A minterm is represented by a symbol m,, where the terms from the expression.
subscript /is the decimal equivalent of the minterm. For
example, consider the truth table of the XOR operation Example
5.1
given in Table 5.11 and note the corresponding
minterms Convert F(A, B, C) = AB’ + BC’ + AC’ to the canonical SOP form.
q Computer Fundamentals and Programming in C

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)

re Therefore, A’ B + A» BY and (A + B) + (A' + B’) are


equivalent expressions for the XOR function.
5.5.2 Maxterm
A maxterm is a canonical sum (or a canonical product of
sums—POS) term and has the following features:
* It includes all variables of a function.
* Each variable is in cither the un-complemented or We can convert any POS expression into the canonical
complemented (inversed) form. POS form using the following steps:
* Each variable appears exactly once. * Determine the sum terms of the expression.
+ A function with n variables has 2" maxterms. * Ensure that each sum term has all the variables used in
* Each maxterm is false for exactly one combination of the Boolean expression.
input variables, * If there is a sum term in which one or more variables
are missing, then add that term with the product of the
missing variables and their complement.
+ Expand the Boolean expression and delete the repeated
terms from the expression.

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

Truth table of XNOR gate


Input, | Input, Output Cc c

) 0 1 (a) AND operation

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

Figure 5.9 Conversion of logic circuit diagram to Boolean Example 5.3


expression
Represent ¥ = A + B using logic gates.
Converting a Boolean expression into its equivalent logic
diagram isalittle difficult, as itrequires a good understanding Solution
of the order of operations, which is as follows: Y=A+B
* Parentheses
* NOT
* AND
* OR
Example 5.4
Now, let us draw the circuit diagram for the Boolean expression
Y=(A4+B+ C)+(B + ©)(Figure 5.10), First, consider the Represent Y= A- B using logic gates.
parentheses (4 + B +C), Within this parentheses, we will first
Solution
perform the AND operation followed by the OR operation. y
Now, consider the second parentheses (B" + C ), Within
this parentheses, we will first perform the NOT operation
followed by the OR operation
lly, the OR operation between the two parentheses
is performed in Fig-ure 5.10(c). Note that in Figure 5.10(f),
the same figure has been redrawn with single inputs of
each input variable
Boolean Algebra and Logic Gates 85

Example 5.5 5.8.1 NAND Universal Gate


Represent Y = (A~B)+ Cusing logic gates. Let us first see how the basic gates can be represented
Solution using a NAND gate
Y=tA B+ NOT Gate
A AB ANOT gate is made by joining the inputs of aNAND gate
B oY=(A- B+

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

A (A+B) An AND gate can be implemented by following a NAND


gate with a NOT gate to get a NOT NAND, that is, AND
B Y=tA+B€
output (Figure 5.12).
A A
Example 5.7 R R

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

Y=A+(s-C) means that an AND gate can be implemented by inverting


A —_ = the inputs to a NOR gate (Figure 5.16).
B YeA+s oe

c ae

Solution

Figure 5.16 Representation of an AND gate


using a NOR gate

Conversion of Boolean Expression into Circuit


Diagram using NOR Gates
The following are the steps to convert a given expression
into a circuit diagram using only NOR gates:
* Read the expression carefully and draw its corresponding
circuit diagram.
* Replace every AND, OR, and NOT gate with its
equivalent NOR gate.
5.8.2 NOR Universal Gate * Redraw the circuit
Let us see now how the basic gates can be represented Identify and remove double inversions (i.¢., back-to-back
using a NOR gate inverters, if any).
* Redraw the final circuit
NOT Gate
The NOT gate is implemented by joining the inputs of a Example 5.10
NOR gate. This is because a NOR gate is equivalent to an
OR gate leading to a NOT gate (Figure 5.14). Y=(A-B) + Chas been represented using AND, OR, and NOT
gates. Represent it using the NOR universal gate.

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.

Locks Truth table and K-map for two variables


A B | Output ¥
\B
o 0 1 A o 1
Oi [ht 1 0 ria.]
1) 0 I olo}
i) ig 0
Wrong: This is not a group

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

Considerthe expression Y = A’: B'+A- B'+A'- B. Plota


K-mapto minimize the expression.

oo Ol tt 10

In group |,there is an entry 1 when A = 0 and B=0 and when


A=Oand B = 1, which means that the output is 1 whenA=0
or A’ = 1. That is, the output is independent of the input
value
of B.
Similarly, in group li, there is a 1 when A= 0 and B =O and
when A= Land 8 = 0, which means that the output is 1when
it 10 8 = 0 or 8 = 1. Thus, the output is independent of the input
value of A. Hence, the minimized form of this expression can
be given as A’+ BY.
Therefore, Y =A’ + B’.

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

Solution In group Il, the output is independent of 8. Rather


aC The group of is is the output is 1 when A = 1 and C = 1. Therefore, group It
00 01 11 10 independent of the value minimizes to AC.
1 0 of A (as output is 1 when A In group lil, the output is independent of B. The output is
= 0 or A= 1). Similarly, the a lwhen A=0(A= 1) and C=0 whenC herefore, group
1 o}1]1jo0 output is also independent Ill minimizes to AC. Hence, Y= B+ AC +
of the value of 8. However,
the output is 1 when the value of Cis 1. Hence, the result is Example 5.15
Y=C.
Consider the expression Y = ABCD + ABCD + ABCD + ABCD +
ABCD + ABCD + ABCD + ABCD and minimize it using K-map
Solution
Example 5.14

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

In group I, the output Is independent of A and D, The output


{ Group | ] is 1 when both B and C are equal to 1, Hence, group |
minimizes to BC.
in group Ii, the output is independent of 8 and C. The
output is 1 when A = 1 and D = 1. Hence, group II minimizes
| Group il to AD.
In group Ill, the output is independent of C. The output
In group |, the output is independent of C and A as whether is 1, when A = 0, 8 = 1, and D = 1. Therefore, group Ill
the value ofA or Cis 0 or 1 the output is always 1. So, the first minimizes to ABD.
group minimizes to B. Hence, Y= BC + AD +ABD

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

Fill in the Blanks 5. The Boolean operator AND is also known as


1, Computers understand language. operator.
2. Binary computers work on __ logic (a) union (b) intersection
3. represent Boolean operations using shaded (c) disjunction (d) complement
overlapping regions
4. ______ is. a visual tool for defining the input-output State True or False
relationship of binary variables in a Boolean function 1. Binary language is a language of 15 and 2s.
A+0=Aisan example of slaw. 2. Boolean algebra was developed by Charles Boolean.
Avariable or a complemented variable is called a 3. In the Venn diagram, for NAND operation, the region
A_ _ is a canonical
sum term. common to both the circles is shaded to indicate ANAND
Bisl
enaw
in a maxterm, will be represented in the un
complemented form. A+ A> B= Ais given by the consensus law.
9. Alogic diagram is used to specify a Aminterm is a canonical product term.
10 and __ gates are known as universal in a maxterm, 1 is represented in the complemented form.
gates. NOwes
In a K-map, groups of cells are formed such that they do
not include a cell with the value 1
Multiple-choice Questions Review Questions
1, The operator that returns 1 when both the inputs are 1. What is Boolean algebra? Give its applications
false is: 2. Explain Boolean laws using Venn diagrams.
(a) AND (b) OR 3. Draw the Venn diagram for the Boolean expression
(ce) NAND (4) NOR AvBay nc.
2. A Boolean function of n variables has _ rows of 4. Explain the utility of a truth table as a visualization tool in
possible input combinations. Boolean algebra
(a) 9 (b) 2° Draw the truth table for 2=A (BU C)
(c) 2" (d) 2"-1 Prove the validity of the consensus and absorption laws.
3, A+B+C=(A+B)(A+C)isanexampleof__ law. How are Boolean functions represented?
(a) Involution (b) Commutative Differentiate between a minterm and a maxterm.
(c) Distributive (d) Absorption Cenaw
Give the minterms and maxterms for the Boolean AND
operation.
4, AK-map represents Boolean functions of up to
variables. 10. Explain the steps to convert an SOP expression into its
canonical SOP form with the help of an example.
(a) 2 (b) 4
11. Convert F(A, 8, C) = A'B + B'C + A’C to the canonical SOP
(c) 6 {d) 8 form.
Boolean Algebra and Logic Gates 91

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 hardware cannot think and make decisions


83 INTRODUCTION To ComPUTER on its own. Hence, it cannot be used to analyse 4 given set
SOFTWARE of data and find a solution on its own. The hardware needs
a software (a set of programs) to instruct what has to be
When we talk about a computer, we actually mean the done. A program is a set of instructions that is arranged
following two parts. in a sequence to guide a computer to find a solution for a
* The first is the computer hardware, which performs all given problem. The process of writing a program is called
the computation and calculation work that computers programming.
are known for. Computer software is written by programmers using
* The second part is the computer software, which 4 programming language. The programmer writes a set
instructs the hardware what to do and how to do it of instructions (program) using a specific programming
language. Such programs are known as the source code.
Figure 6.1 illustrates these parts Another computer program called a compiler is then used
If we think of a computer as a living being, then the on the source code, to transform the instructions into a
hardware would be the body that performs actions such as language that the computer can understand. The result is
secing with the eyes, lifting objects, and filling the lungs an executable computer program, which is another name
with air, The software would be the intelligence that helps for software.
in interpreting the images that are seen through the eyes, Examples of computer software include the following
instructing the arms how to lift objects, and instructing the
body to fill the lungs with air * Driver software, which allows a computer to interact
Since the computer hardware is a digital machine, it can with hardware devices such as printers, scanners, and
understand only two basic values—on and off. The on and video cards.
off concept forms the basis of binary language. Computer Educational software, which includes programs and
software was developed to convert binary language into a games that help in teaching and providing drills to help
form that is useful to tell the computer hardware what to do. memorize facts, Educational software can be used in

Computer system

Computer hardware Computer software

System software Application software

Figure 6.1 Parts of a computer system


Computer Software 93

diverse areas, from teaching computer-related activities


like typing to subjects like chemistry.
Media players and media development software, which
are specifically designed to play and/or edit digital
media files such as music and videos.
For example, games, spreadsheets, word
Productivity software, which is an older term used to
processor, database systems. web browsers
denote any program that allows the user to be more
productive in a business sense. Examples of such
software include word processors, database management
utilities, and presentation software.
Operating systems software, which helps in coordinating For example, operating system
system resources and allows execution of other
programs. Some cxamples of operating systems arc
Windows, Mac OS X, and Linux
Computer hardware
Computer games, which are widely used as a form of For example, printer, mouse, scanner, keyboard,
entertainment software that has many genres. CPU, hard disk

ED cuassiFication oF ComPUTER Figure 6.2 Relationship among hardware, system


SOFTWARE software, and application software

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

Similarly. if we examine the programs that help us in


using input devices such as the keyboard/mouse, all the
complex details of the character-reading program are
hidden from the user. We, as users, simply press buttons to
perform the input operation regardless of the complexity
of the details involved. The details are handled by the
operating system.
An operating system ensures that system resources
(such as CPU, memory, I/O devices, and so on) are
utilized efficiently. For example, there may be many
service requests on a web server, and cach user reque:
needs to be serviced, Similarly, there may be many
programs residing in the main memory, The system needs
to determine which programs are active and which need
to wait for some I/O operation, since the programs that
Figure 6.3 The BIOS menu need to wait can be suspended temporarily from engaging
the processor. Hence, it is important for an operating
system to have a control policy and algorithm to allocate
The BIOS chip then locates the software held on system resources.
4 peripheral device such as a hard disk or a CD, and
loads and executes that software, giving it control of the Utility Software
computer, This process is known as booting.
BIOS is stored on a ROM chip built into the system. It Utility software is used to analyse, configure, optimize,
also has a user interface similar to a menu, which can be and maintain the computer system. Utility programs
accessed by pressing a certain key on the keyboard when may be requested by application programs during their
the PC starts, A BIOS screen is shown in Figure 6.3 execution for multiple purposes, Some examples of utility
The BIOS menu enables the user to configure programs include the following:
hardware, set the system clock, enable or disable system + Disk defragmenters can be used to detect computer files
components, and, most importantly, select the devices whose contents are broken across several locations on
which are eligible to be a potential boot device and set the hard disk, and the fragments can be moved to one
various password prompts location in order to increase efficiency
In summary, BIOS performs the following functions: + Disk checkers can be used to scan the contents of ahard
Initializes system hardware disk to find files or areas that are either corrupt in some
Initializes system registers way, or were not correctly saved, and eliminate:
Initializes power management system in order to make the hard drive operate more
Tests RAM * Disk cleaners can be used to locate files that are
Tests all the serial and parallel ports cither not required for computer operation, or take up
Initializes CD/DVD disk drive and hard disk controllers considerable amounts of space. Disk cleaners help the
Displays system summary information user to decide what to delete when their hard disk is full
+ Disk space analysers are used for visualizing disk spac
Operating System usage by obtaining the size of all folders (including
subfolders) and files in a folder or drive.
The primary goal of an operating system is to make * Disk partitions are used to divide an individual drive into
the computer system (or any other device in which it is multiple logical drives, each with its own file system.
installed, such as a cell phone) convenient and efficient Each partition is then treated as an individual drive.
to use. The operating system offers generic services to * Backup utilities can be used to make a copy of all
support user applications information stored on a disk. In case a disk failure
From the point of view of users, the primary occurs, backup utilities can be used to restore the entire
consideration is always convenience. Users should disk. Even if a file gets deleted accidentally, the backup
find it easy to launch an application and work on it. For utility can be used to restore the deleted file.
example, we use icons, which give us an idea about which + Disk compression can be used to enhance the capacity
application they launch. We have different icons for of the disk by compressing/uncompressing the contents
launching a web browser, an e-mail application, or even ofadisk.
a document preparation application. In other words, it is + File managers can be used to provide a convenient
the human-computer interface that helps to identify and method of performing routine data management tasks,
launch an application. The interface hides a lot of details such as deleting, renaming, cataloguing, movin,
of the instructions that performs all these tasks. copying, merging, generating, and modifying data sets.
Computer Software “95

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

Outsourcing the customized software When the


customized software is to be created by a different
23 propuctivity soFTWARE
organization, then the following steps are performed
Productivity software is any software that is used to
* Requirements are enlisted. attain something productive, especially in the office or
* Different software development companies are home, as opposed to game software or entertainment
contacted to give an estimate of time, effort, and moncy software
involved in creating the software. Word processing programs, spreadsheet applications,
* The best software vendor is ied based on the cost and graphic design software are all examples of
quoted by them, their reputation in the market, and their productivity software. These are the tools people use to
proposal create and produce documents, presentations, databases,
The selected software development organization works charts, graphs. calendars, labels, to-do lists, etc
closely with user(s) and develops a software package as per Today, there are hundreds of productivity software
their preference. When developing a customized software packages available in the market, but undoubtedly the
, it is not necessary that the software will be created Microsoft Office package dominates the industry. This
ich. Many a time, pre-written software that partially may be truc because the Windows operating system, which
meets user's requirements can be enhanced to deliver the final is also produced by Microsoft, is the most widely used
customized software. This would help to reduce the time, operating system, and many computer vendors include
effort, and money involved to create the software package. full or trial versions of Microsoft Office on new Windows
PCs. In addition to this, Microsoft Office gives users the
functionality they need to do their jobs,
When the user orders both hardware and software However, some users prefer to use specialized
from the same vendor, the vendor develops software software dedicated to a specific purpose, For example,
‘on the chosen hardware and delivers the combination they may want word processing software that formats
of hardware and software to the user. This iscalled a documents in the appropriate style automatically. There
turnkey solution or an end-to-end solution. are hundreds of specialized productivity software
applications available that cater to practically any
6.3.3. Downloading public domain software format one can imagine.
In this section, we will read about different productivity
Some software are available on the Internet that the users software such as the Microsoft Office package, graphics
can download free of cost. If such available software design software, multimedia software, and database
meets user's requirements, they can be casily downloaded. management software
The basic idea behind such software is that its creators
want their software to become popular among people
Such type of software is known as public domain software 6.4.1 Introduction to Microsoft Office
or freeware or shareware. It is also offen referred as Microsoft Office, released by Microsoft on 19 November
community-supported software as authors do not support 1990, is a suite of inter-related applications for the
the product directly but users of the software support and Microsoft Windows and Mac OS X operating systems.
help cach other. Initially, it included Microsoft Word, Microsoft Excel,
While some public domain software packages are and Microsoft PowerPoint. However, over the years,
available free of cost on the Internet with full set of the Microsoft Office suite has grown substantially with
supported features, others are cither available with only shared features, such as a common spell checker, OLE
limited features as the rest of the features can be purchased, data integration, and the Microsoft Visual Basic for
or with a full set of features but only for a limited time applications scripting language. Although the latest
period known as the trial period. version of Microsoft Office is MS Office 2013, in this
Some public domain software, also known as open chapter we will learn to use 2007 edition.
source software that is equally popular among user
community, allows its users to download, view, modify,
Microsoft Word
and distribute modified source codes to others, However,
there are special licensing systems for open source Word processors are software packages that enable users
software so that it can be promoted and at the same time to create, edit, print, and save documents for future
there are copyright protection schemes for the original and retrieval and reference. The key advantage of using a
subsequent authors of such software. word processor is that it allows users to make changes
to a document without retyping the entire document.
Microsoft Word is the world’s leading word processing
All open source software are not always free and not all application. Users can create a variety of documents such
free software are always open source. as letters, memos, resumes, forms, or any document that
+ Add macros so that users can attach specific functionsto
some function/special keys, a tool bar. or a menu,
* Provide online help on any command.
Before we discuss the functionalities of Microsoft
Word, let us first look at the different toolbars available in
the application window. Figure 6.5 shows the Menu bar.A
PY odeedeld seehchammetbarteseretadamediietacdeeredenkel
on click on any menu expands and lists various functions that
age Etcetera a ae mene age epee
ee oe neeeae een I a ee elbadbens ees aedhe are available within that menu.
Nem mes ae etn»
Whee menage Newt et may Oe poonens hapa
fle EGR Yow =Inwert Format Tools Table window Hel

Figure
6.5 Menu bar

The next is the standard toolbar, shown in Figure 6.6,


which contains shortcut buttons to perform functions that
Figure 6.4 Microsoft Word window are already available in some menu, but using them might
be a long winding process where one has to go to the
appropriate menu, expand it, and then click on the listed
can be typed and printed. A screenshot ofthis application function. With shortcut buttons available on the standard
is shown in Figure 6.4, toolbar, one can directly click them and perform the
Microsoft Word enables users to do the following: desired function.
Finally, the formatting toolbar, shown in Figure 6.7,
* Create documents and edit them later (if required) by contains shortcut buttons for formatting the text. It has
adding more text, modifying existing text, deleting’ buttons for choosing the font style, font name, font size;
moving some part of the text, ete. buttons to make the text bold, italicized, or underlined;
* Change the size of margins to reformat the text in the buttons for left, right, centre, or justified alignment;
document, buttons to number or bullet the paragraph; and buttons to
* Format documents by indenting or double-spacing the colour the font and its background.
text.
* Change the size and type of fonts. Creating afile If MS Word is already open, there are two
+ Insert page numbers, headers, and footers. ways to create a new document, Click the new button on
* Check spellings and correct them automatically if the standard toolbar, or click New on the File menu (see
required, Figure 6,8).
Display the word count and other statistics. Saving a file When one has completed working with a
Format the text in columnar style. document or just wants to store the work before continuing,
Insert tables in the text, it is necessary to save the file. This can be done by either
Find and replace text, choosing File —- Save from the Menu bar or clicking the
Cut, copy, and paste portions of text from one location Save button on the standard toolbar to open the Save As
in the document to another. dialog box, shown in Figure 6.9.
+ Insert graphs, pictures, and charts into the docment. The dialog box opens into the default folder (directory),
* Send the same letter to multiple recipients using the but clicking the Save in text box opens a drop-down list of
mail-merge facility. accessible drives, as shown in Figure 6.10.

Spelling&
Save Print grammar Format painter —insert hyperlink —Insert
Excel worksheet ©Zoom —Help

DSOu GRY HAS o-- SHORRBAT -Q.


Computer Software 99

Styles & formatting Font size Italics Align left Align right Bullets Decrease
&Increase indent

44 TimesNewRoman ~ 14 - BZ U (|= BB El eH O-A-

Font name Bold Underline Centre Justify Numbering Font colour

Figure 6.7 Formatting toolbar

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.

File names can be up to 256 characters long and can


contain uppercase and lowercase letters and spaces.
However, they cannot contain punctuation marks other
than underscores and hyphens.

Closing a file Removing a document from the document


window is achieved by choosing File —+ Close or clicking
the Close button (the cross sign on the upper right comer
of the document window) on the document window. If a
document that has been changed since it was last saved is
closed, a prompt appears to save the changes.
Opening an existing file To open an existing file, the
following steps are to be followed (Figure 6.11)
1. In the Microsoft Word program, click File —-» Open.
2. In the Look in list, click the drive, folder location that
contains the file to be opened.
3. In the folder list, locate and open the folder that contains
the file.
4. Click the file, and then click Open.

Figure 6.11 Opening an existing file in Microsoft Word

Printing a document Previewing the document before


printing gives one the chance to see how the pages break
and whether there are any layout problems that will make
Figure 6.10 Specifying
alocation for saving the file the document look less than its best. Microsoft Word
100 Computer Fundamentals and Programming in C

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.

Figure 6.13 Copying text in Microsoft Word

Working with fonts Saying what one wants to say in a


document is only half the battle, Making it look good
improves the odds that people will actually pick it up
and read it. All the fonts used by the Windows programs
are managed by Windows, so fonts available in one
Office application will be available in all the others, The
Formatting toolbar includes buttons and drop-down menus
that lets the user choose a font, font size, effects such as
Figure 6.12 Printing a file in Microsoft Word bold, italics, and underline, and font colour, If one needs
font options that are not available on the toolbar, open the
Editing a document Power users are those who use the Font dialog box shown in Figure 6.14, by choosing Format
minimum number of steps to complete a task. They are not — Font
just proficient, but also efficient, particularly with skills Microsoft Word's Font dialog box has three page tabs:
that are used frequently in Microsoft Word. Knowing Font, Character Spacing, and Text Effects. On the Font
several ways to select and replace text lets one streamline page, one can select font attributes and see how a font will
many of the other tasks that can be accomplished with the look by noting the changes in the preview as the desired
documents, styles, sizes, underlining, colours, and effects are applied
Selecting text To select a piece of text, press the Shift key There are 11 effects that one can apply from the Font
and, with the help of arrow keys select the text, or simply dialog box. The strikethrough and double strikethrough
Computer Software 101

margin and leaves a ragged edge at the left margin, Right


aligned text is the hardest to read.
& The paragraph isjustified or fully aligned. Justified text
appears formal because the text lines up evenly with the left
and night margins. It is often used in documents with columns
of text. Sometimes the paragraph looks unbalanced because
too much space has to be inserted between the characters.
To align text, select the text and click on one of the
alignment buttons on the Formatting toolbar,
Creating lists Microsoft Word makes it easy to create
bulleted and numbered lists. If a list begins with a number,
Microsoft Word will automatically number the following
paragraphs when Enter is pressed.
To apply numbering to existing text, select the paragraphs
and click the Numbering button |= on the Formatting toolbar,
Use the Bullets button $= to bullet existing paragraphs of
—]_ cms _J
text. To automatically number or bullet text as content is typed
Figure 6.14 Using the Font tab in Microsoft Word in, dothe following
* Type the number I and a period, followed by a
options can be used to show proposed deletions in a and then enter text for the item. For bullets, begin with
contract or bylaws, The user may apply superscript and an asterisk and a space
subscript styles to place special characters in formulac Press Enter. Microsoft Word will automatically number
(H,O or Tl), and use outline, emboss, and engrave to the next item 2, or bullet the next item.
stylize the text so that it stands out * Continue entering text and pressing the Enter key to
Character spacing Character spacing is used to adjust the create numbered or bulleted points.
distance between characters. For example, one can spread When the list is complete, press Enter twice to tum
4 title such as MEMORANDUM across a page without automatic numbering or bullets off
having to add two or three spaces between the characters
One can also begin numbering by clicking the Numbering
(MEMORANDUM), Character spacing is commonly
button before typing the first paragraph. To use letters
used in advanced desktop publishing when the characters
rather than numbers in automatic numbering, type A
are to be sized and scaled precisely
rather than 1 to begin. Word will number the second and
Animation Animation is a text enhancement feature succeeding paragraphs B, C, D, and so on. If the first
designed for documents that will be read onscreen. There paragraph is numbered ‘I’, Word will use Roman numerals
are six animation options that causes text to blink, sparkle, or to number the paragraphs.
shimmer, namely, Blinking Background, Las Vegas Lights,
Spelling and grammar Spell-checking software has
Marching Black Ants, Marching Red Ants, Shimmer, and
Sparkle Text. To apply these animutions, select the text to been in use for a long time, When one runs Spelling and
Grammar or has the Check spelling as you type option
be animated, choose Format — Font — Text Effects, and
tumed on, Microsoft Word checks each word against its
select one of the six options. To turn it off, select the text
again and select None from the list of options,
dictionaries. When a word is not found, it is flagged for
verification. As shown in Figure 6.15, right-clicking on
Aligning text Microsoft Word provides four options
for aligning paragraph text—left, centre, night, and full
(justify). These are denoted using the following icons:
E The paragraph is left-aligned, which is the most
common alignment type. It means that text lines up with
the left margin and leaves a ragged edge at the right
margin. Lefl-aligned text is considered the easiest to read.
= the paragraph is centred. This style is generally used
for headings and desktop publishing creations. Centred text
is equally positioned between the left and right margins.
3@ The paragraph is nght-aligned. Right alignment is
used in headers and footers and other text that needs to be
put off to the side. It means that text lines up with the right Figure 6.15 Using the AutoCorrect feature in Microsoft Word
02 Computer Fundamentals and Programming in C

‘red-underlined word provides options to select a word


from a list of choices, namely Ignore All,Add, or choosing
from a list ofAutoCorrect entries.
* Ignore this occurrence of the word.
* Ignore All occurrences of the word in this document.
+ Add the word to the custom dictionary, so that Microsoft
Office will recognize it the next time it is used.
* Change the word by choosing one of the suggested
corrections or by editing the word manually.
* Change all occurrences of the word in this document by
choosing one of the suggested corrections or by editing
the word manually.
* AutoCorrect the word (after choosing or entering a
correction) and add it to theAutoCorrect dictionary.
Finding and replacing text One of the fastest ways to Figure 6.17 Microsoft Excel window
make repetitive changes throughout a long document is
to use Find and Replace. Find helps the user to locate a
various fonts or colours, Microsoft Excel (see Figure 6.17)
text string, and Replace substitutes the new text for the
is an example of a spreadsheet software which is used to
existing string. The following steps are used to find and
store, organize, and manipulate data. The stored data can
replace text:
also be converted into graphs for analysis.
* Click Edit — Find to open the Find and Replace dialog It includes a number of simple as well as complex
box. formulae and functions to calculate variables in the data
* Enter the characters to be searched for in the Find What and is therefore widely used in finance to automatically
text box, Click Find Next. calculate variables such as profit, loss, or expenditure.
* Close the Find dialog box (see Figure 6.16) and click Microsoft Excel is widely used for the following
the Next Find/Go To button at the bottom of the vertical applications:
scroll bar. Browse through cach of the occurrences of
* Excel is used to manage data records and name lists in a
the text string.
tabular fashion, With Excel, users can casily sort the list
and filter it like a database tool,
* Excel is an excellent analytical wol, widely used in
business. Pivot table is one of the main features which is
used widely. Such tables can automatically sort, count,
and total the data stored in one table or spreadsheet and
create a second table displaying the summarized data.
With these tables, users can conveniently analyse huge
volumes ofdata.
+ Users can create simple as well as professional forms in
Excel. These forms can even include option buttons to
select answers and dropdown lists to select a particular
Figure 6.16 Finding and replacing text in Microsoft Word answer from a list of items, apart from the regular text
boxes in which the answers have to be typed. Together
Using Replace To replace text, open the Find dialog box with charts, Excel can be used to compile answers to
and click the Replace tab. Enter the text required to be tests or quizzes and analyse the results.
found in the Find What text box and the text to replace * Many small and large organizations use Excel as the
it with in the Replace With text box. One can choose to primary tool for corporate budgeting.
replace one occurrence al a time by clicking Find Next * Excel is widely used for managing inventories in many
and then Replace, or, if the user is very sure of what companies. Using well-designed forms, pre-defined
he/she is doing, choosing Replace All would complete functions and formulae, and pivot tables, users can get a
all the replacements in one step. When Microsoft Word good detailed analysis of stock movement and inventory
is finished, it opens a dialog box that indicates the total level at any point in time.
number of replacements made. * Finding the profit breakeven point is not simple.
However, with Excel, it can be calculated easily and
Microsoft Excel accurately in just a few seconds.
A spreadsheet software is one in which data is stored Excel application window The Excel application window
into rows and columns, or ‘cells’ that can be formatted in as shown in Figure 6.18 includes the standard title bar and
Computer Software Gos

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 ° ”

Worksheet components Each worksheet is divided


into columns, rows, and cells, separated by grid lines, as Figure 6.19 Point-and-click method in Microsoft Excel
shown in Figure 6.18. Columns are vertical divisions. The
first column is named A, and the letter A appears in the + Activate the cell where the result is required to appear,
column heading, The horizontal rows are numbered. Each * Type an equal sign (=). The formula elements will
worksheet has 256 columns and 65,536 rows. A cell is the begin appearing in the formula bar as they are typed or
intersection of a row and a column, Bach cell has a unique selected.
address composed of the cell’s column and row. For Click the first cell to be included in the formula.
example, the cell in the upper-left corner of the worksheet ‘Type an operator.
is cell Al, When data is entered, it is always placed in the Click the next cell in the formula.
active cell. Repeat Steps 4 and 5 until the entire formula is entered.
To enter data in a cell, first activate the cell, and then Finish the entry by pressing Enter.
begin typing the data. As soon characters are entered, an Filling formulae In the previous example, the formula for
insertion point appears in the cell, the text appears in the cach student's total marks is the same—marks obtained
cell and the formula bar, and the formula bar buttons are in Maths + Science + English + Computer. Since one
activated. working formula has already been created, all one needs
to do is fill it to the other cells,
There is a square box in the lower-right corner of the
cell called the fill handle. As the mouse is moved towards
env TTELE ES" the lower-right comer of cell, the mouse pointer changes
shape to a black cross to let the user know that the mouse
can be used for a fill operation,
" HortzontalVinescalledrowsarénumbered and vertical
lines called columnscaidentitied by alphabets Filling is a form of copying. Begin by activating the cell
that has the formula to be copied. Move the mouse pointer
i oOo Celt A cell isformed where a row and a
: column intersects
and is identified toward the fill handle until the mouse pointer changes to
: by thecombination of row name the fill pointer shape.
‘ plus the column name. The name Press the mouse button and drag the fill handle down
: s3Ee of theselected cell isC10
SE RESES
RSESNST
EA ESS
to select the cells to which the formula is to be copied.
Release the mouse button, and the formula will be filled
in the other cells. Figures 6.20(a) and (b) illustrate this
Navigational operation.
buttons
Excel can also fill the destination cells with a value from
Figure 6.18 Components of a Microsoft Excel worksheet a source cell and increase this value in each successive cell

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.

Options in the Formatting toolbar


Button [Style |Effect
$ Currency Displays the dollar sign—75.30 as
$75.30
% Percent Displays a number as a
percentage—45 as 45%
’ Comma Same as currency, but without the
dollar sign—12345.6 as 12,345.60
3B Increase Displays one more place after the
decimal decima!l—0.45 as 0.450
Ey Decrease Displays one less place after the
Figure 6.21 AutoFill feature in Microsoft Excel decimal decimal—0.450 as 0.45 J
Computer Software 105

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.

Merge, Shrink to Fit, and Wrap Text These actions can be


performed by following these steps:
* Select the title and several additional cells below the
title.
* Select Format Cells and check one or all of the following
options in the Format Cells dialog box:
Figure 6.22 Format Cells dialog box « Click the Merge Cells check box to merge the cells.
« Shrink to Pit reduces the size of the type within
Adjusting column width and row height By default, selected cells so the contents fit
Excel columns are slightly more than cight characters « Wrap Text wraps the contents of a cell if it exceeds
wide, Ifthe data in a worksheet is wider than the column, the cell’s boundaries.
the column width may need to be adjusted so that it
Borders and colour Effective use of fonts can help
becomes wide enough to contain the data. One can adjust
make worksheets casier to understand. Borders and
the column width manually by dragging the column
colour provide further ways to highlight information in a
border to AutoFit the column width to the existing data
worksheet. A border is a line drawn around a cell or group
The row height can be adjusted in a similar manner. If the
of cells. Fill colour is used to highlight the background of
pointer is moved to the lower edge of a row heading, it
part of a worksheet and font colour is applied to text
changes to an adjustment tool. Double-click to adjust the
row height to fit the font size or drag to manually inerease Using functions and references Excel includes hundreds
or decrease size. of other functions that one can use to calculate results used
Aligning text By default, Excel left-aligns text and right- in statistics, finance, engineering, math, and other fields.
aligns numbers. One can use the buttons on the Formatting Functions are formulae, so all functions begin with the
toolbar to override the defaults and align text and numbers equal sign (=). This is followed by the function name, one
at the left, centre, and right within the cells as follows of more arguments separated by commas, and this entire
expression is enclosed in parentheses.
Before entering a function, the cell in which the result
is to be displayed should be activated. The ‘+’ in the
Center formula bar is clicked to open the formula palette, The
Name box (to the left of the formula bar) changes to a
Function box, displaying the name of a last function that
was used (SUM).
The default settings reflect some standard rules for aligning A list of functions in the formula pa jette of Microsoft
text and numbers: Excel is shown in Figure 6.23.
* Columns of text should be left-aligned because we are If the required function is on the list, it is selected,
used to reading left-aligned text and Excel moves the function to the formula bar and the
* Columns of numbers should be kept in the default (right) formula palette. The formula palette (see Figure 6.24)
alignment and formatted so that the decimal points are expands to include a description of the function and one or
aligned more text boxes for the function's arguments.
Column labels should appear over the contents of Afier all the required arguments have been selected,
the column. If the column is filled with numbers, the OK is clicked to finish the entry and close the Formula
106 Computer Fundamentals and Programming in C

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

12 895, 8588 og = 7st


60 © Ramesh
40 © Mohan
20
0
Sf> Ffe

Figure 6.28 Column and bar charts Figure 6.29 Chart wizard in Microsoft Excel
108 ) Computer Fundamentals and Programming in C

| Acme | cetwe | rgwret | Cateatte | en tater|


[et tee we

——————

POINTERS

Figure 6.30 Specifying chart options in Microsoft Excel

« Axes: Display or hide axes ——— Ey


« Gridlines: Display gridlines and display or hide the Figure 6.31 Microsoft PowerPoint window
third dimension of a 3D chart
« Legend; Display and place a legend
* Data Labels; Display text or values as data labels
om
« Data Table: Show the selected range from the saw
worksheet as part of the chart
As the options are changed, the chart preview reflects
these changes, When the user has finished setting options,
Next is clicked to continue.
* In the last step of the Chart Wizard, the user can place
the chart on the current worksheet or on a new, blank
sheet in the same workbook. If the chart is placed on its
own sheet, it will print as a full-size, single-page chart
whenever printed. If it is added to the current worksheet
\
as an object, it will print as part of the worksheet, but it Se
can also be printed separately,
Figure 6.32 Microsoft Access window
Microsoft PowerPoint
Microsoft PowerPoint is used to create multimedia Microsoft Access
presentations and slide shows. Similar to Microsoft
Word, it also includes the tools to format text and Microsoft Access is a database application that is used
incorporate design templates. Users can create to store data that has been obtained cither from its own
presentations by using any design template that is interface or imported from other applications, The stored
available with the program, Many more free add-ins data can then be used for reporting and analysis. A
and templates are available online from Microsoft and a screenshot is shown in Figure 6.32
host of other websites. Figure 6.31 shows a screenshot Microsoft Access can be used as a front-end, with
of this tool. another application being used as the back-end tables,
When designingpresentations using Microsoft such as Microsoft SQL Server and non-Microsoft products
PowerPoint, users can add effects on slide transitions and such as Oracle and Sybase. Similarly, some products (such
add sound clips, images, animations, or video clips to as Visual Basic, ASP.NET) can act as the front-end and
make the presentation even more interesting for the target can use Microsoft Access tables as the back-end.
audience. Microsoft Access is equipped with a query interface,
In addition to slide shows, PowerPoint also offers forms to input and display data, and reports for printing
printing options to facilitate the users to provide handouts Tables designed in Access support a variety of standard
and outlines for the audience as well as notes pages for the field types, indices, record locking, and referential
speaker to refer to during presentations. integrity features. In addition to this, Access supports the
PowerPoint is a complete package for creating beautiful use of macros to automate repetitive tasks.
presentations for business and classrooms, It is also an Microsoft Access is equally popular among non-
effective tool for training purposes programmers as well as professional developers. While
Computer Software (109

non-programmers can create visually pleasing and


relatively advanced solutions with very little or no code, 3 muttimenia software
professional programmers, on the other hand, can create
complex databases and place them on the network to Multimedia is & comprehensive term that means different
enable multiple users to share and update data without types of media. It includes a combination of text, audio,
overwriting cach other's work still images, animation, video, and interactive content
Microsoft Access is particularly appropriate for forms.
meeting end-user database needs and for rapid application Multimedia content can be broadly divided into two
development. Access users enjoy its case of use to create groups, linear and non-linear. While the linear active
highly focused applications. content progresses without any navigational control for
the viewer (like in case of cinema presentation), non-linear
content, on the other hand, supports user's interaction to
control progress (as in case of computer games).
GE} GraAPHics SOFTWARE Multimedia presentations can be live or recorded. In a
recorded presentation, the user can interact via a navigation
Graphics software, or image editing software, is a program system but in a live multimedia presentation, interaction is
that allows users to create and edit digital images and possible only through the presenter or performer.
illustrations, Examples of such software include Adobe Nowadays, multimedia is widely applied in areas such
Photoshop, Adobe Illustrator, Paint Shop Pro, Microsoft as advertisements, education, entertainment, engincering,
Paint, etc medicine, mathematics, business, and scientific research,
Most graphics programs have the ability to import and Multimedia is used for creating exciting advertisements
export one or more graphics file formats. Some of the to attract the attention of the target audience, It is also
graphics applications are the following used in business to design training programs, In the
* Paint programs, which enable users to create rough entertainment industry, multimedia is used to create
frechand drawings. The images are stored as bitmaps special effects in movies and animations, It is also used in
and can casily be edited as and when required, computer games and some video games that are apopular
* Illustration/Design/Draw programs, which provide pastime
users more advanced features than paint programs. They Edutainment, which combines education —with
are particularly used for drawing curved lines. Such multimedia entertainment, is now emerging as a trend in
programs store images in vector-based formats. These school as well us higher education. This has made learning
programs also allow users to draw circles, ares, and theories simpler than ever before. Moreover, visually
other shapes smoothly and properly connected to cach impaired people or those with other kinds of disabilities
other, Moreover, the program enables the users to move, can pursue their careers by using training programs
copy, delete, rotate, tilt, flip horizontally/vertically, and specially designed for them.
increase/decrease the size of objects. Multimedia is used by engineers and researchers
* Presentation software, using which users can create bar for modelling and simulation. For example, a scientist
charts, pic charts, graphics, slide shows and reports, The can look at a molecular model of a particular substance
charts are usually based on numerical data imported and manipulate it to arrive at a new substance, Even in
from spreadsheet applications. Presentation software medicines, doctors are now trained by observing a virtual
is widely used by analysts and decision makers to gain surgery
a better understanding of the relationships, trends, and
changes that were otherwise buried in the data DATABASE MANAGEMENT SOFTWARE
* Animation software, which simulates movement by
displaying a sequence of images in a fraction of a Database management software (DBMS) is a collection
second, of programs which helps users to store, edit, and extract
* CAD software, which is used by architects and engincers data from a database. Today, different types of DBMSs
to create architectural drawings, product designs, are available in the market, such as Microsoft Access
landscaping plans, and engineering drawings. CAD FileMaker, DB2, SQL Server, and Oracle, to name a few.
software enables the designers to work much faster. The While some types of DBMS can run on personal computers,
drawings that used to be created in several days can now others run on huge systems such as mainframes.
be drawn in few hours. The use of a DBMS has become so common that it
* Desktop publishing, which facilitates its users with has now become a part of our everyday life. It is used in
a full set of word-processing features along with a computerized library systems, automated teller machine:
ne control over placement of text and graphics. flight reservation systems, computerized parts inventory
Using such an application, the users can easily create systems, etc. All these applications call for the creation of
newsletters, advertisements, books, and other types a series of rights or privileges that can be associated with
of documents, a specific user, This means that it is pos ible to designate
ae Computer Fundamentals and Programming in C

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

‘Types ofoperating systems

Batch ‘Single-user Single-user Multi-user


Multiprocessing —_—Real-time

Figure 6.33 Types of operating systems


Computer Software Mf

tasks simultaneously. This is the operating system that we


usually use in our desktop and laptop computers. These [windows |Linux |Sots |
Operating systems enhance the productivity of the users <> m5 a
as they can complete more than one job at the same time. L 7 if | ee |
For example, when we are typing a document in
Microsoft Word while listening to a song and downloading
a file from the Internet, we are actually doing three jobs at
the same time with the help of a multitasking operating
system, Microsoft's Windows and Apple's Mac OS
platforms are both examples of such operating systems.
Multi-user multitasking operating system A multi-user
operating tem enables multiple users on different
computers to access a single system (with one operating
system). In simple terms, it allows more users to connect
to the main computer (which has only one CPU and
one OS) to perform more than one job at a time, Hence,
users on multiple terminals can access the same data and
application programs that are stored on the main computer Figure 6.35 Virtual machine operating system
(Figure 6.34)
Similar to other operating systems, RTOS also manages
the hardware resources of a computer and host applications
that run on the computer. However, unlike other operating
systems, an RTOS is specially designed to run applications
with very precise timing and a high degree of reliability
This is particularly useful in measurement and automation
systems where downtime is costly or a program delay
could cause a safety hazard.
Figure 6.34 Main computer and its terminals Virtual machine operating system This type of operating
system enables several users of a computer to use it as if
Multi-user multitasking operating systems are quite they are using it individually, When using a virtual machine
complicated as they must efficiently manage the jobs and operating system, several operating system environments
resources required by the different users connected to it can co-exist on the same computer, For example, in
The users will typically be at terminals or computers that Figure 6.35, three operating system environments exist
access the main system through a network. In a multi-user on the same computer, These operating systems include
operating system, cach user is accessing the same OS at Windows, Linux, and Solaris.
different machines, This type of system is often used on
mainframes and similar machines. However, if the main 6.8.2 Command Interpretation
system fails, it can affect several users.
The command interpretation module or command
Multiprocessing Multiprocessing means using two or
interpreter of the operating system provides a set of
more processors (CPUs) within a single computer system. commands that users can execute, This set of commands
It refers to the coordinated processing of programs by more is often called system calls, When a user executes a system
than one processor. In 4 multiprocessing system, a complex
call, the command interpreter interprets the instructions
program can be divided into smaller parts and then executed
and allocates system's resources to handle user's request
concurrently by multiple processors in parallel. The command interpreter also provides an casy-to-us
However, the term multiprocessing should not be intuitive interface to the users, thereby hiding internal
confused with »rultiprogramming which means the
complexities and fulfilling operating system's objective of
interleaved execution of two or more programs by a single
case of use.
processor, Today, most of the modem computers support The user interface of command interpreter can be
multiprogramming. Moreover, a system can be both broadly classified into two groups—CLI and GUI which
multiprocessing and multiprogramming, only one of the are explained as follows:
two, or neither of the two.

Real-time operating system Areal-time operating system


(RTOS) is basically used to control machinery, scientific
instruments, and industrial systems, It has very little user- ‘Command interpreter is the interface between the user
interface capability and does not support end-user utilities and the operating system.
112 Computer Fundamentals and Programming in C

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.

Graphical user interface (GUI) is an interface that


makes use of the following graphical components to allow 6.9.1 Microsoft DOS
users 0 casily interact with the computer or system MicrosoftDOSis anon-graphical command line operating
system, which was releasedby Microsoft
in August 1981. It
Pointer A pointer is a small-angled arrow that enables the
users to select commands and objects on the screen. was the first widely installed operating system in personal
computers in the 1980s, MS-DOS was not only one of the
Pointing device A device such as mouse or trackball that most powerful operating systems of that time but was also
enables the user to select objects on the screen, easy to load and install. It requires neither much memory
Icons Icons are small pictures that represent commands, nor a very sophisticated computer to run on.
files, or windows. Users can execute commandsor open an Since MS-DOS supports a CLI (refer Figure 6,36),
application by moving the pointer to the icon and clicking users need to remember the commands and know where
the mouse button. Common examples of icons that we use
are small rectangles for files, file folders for directories, a
trash can to indicate a place where we dispose unwanted
file and direction buttons on web browsers that help
users to navigate to the previous page or next page
Menus Menu is a GUI element that displays a list of
available commands. Users can execute commands by
selecting a choice from the menu.
Window A window is a rectangular portion of the
screen that displays applications, menus, icons, files, etc
GUI facilitates the users to work in multiple windows
simultaneously where cach window displays a different
application, or each window can display different files that
have been opened or created by the same application.
The advantages of GUI are as follows.
* With well-designed GUIs, users can get rid of the
burden of learning complex commands to perform even
small operations.
* The interface is intuitive. Therefore, users take less time
to learn and work with the system. For example, it is far
simpler to move a file from one directory to another by
dragging its icon with the mouse than remembering and Figure 6.36 MS-DOS
Computer Software 113

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

Figure 6.37 Windows 8 Start screen

Search By clicking on the search option, users can search


Output of an app can be redirected to a projector by
through apps, files, and settings for items that match the
pressing the Window Key and the P key together
keyword
Share Users can share data from one app with another
Some of the features of Windows 8 are as follows: app. program, or service by clicking on this option. For
example, when using the Weather app users can take a
Windows Apps and the Microsoft Store Microsoft has screenshot and share it with others,
introduced a new Windows Store from where users can
cither download or purchase apps.
Start Start option displays the classic Windows desktop
on the computer's screen.
Devices This option helps users to specify on what
device he/she would like to play the app. For example,
When a user purchases an app he can install it on four users can select a device that a particular app will display
other computers running on Windows 8 its content on.
Settings Users can configure the settings of the app they
User’s settings travels with them In Windows 8, users are currently using by either clicking on the settings option
given an option to cither create a local account or a or by pressing the Windows + I key simultaneously. For
Microsoft account. With a local account, a user can only example, users can change the volume, shutdown or restart
logon to his/her local computer and his/her information the computer, change language, enable notifications, and
will not be synchronized with other computers he/she may monitor network connections.
use, On the other hand, with a Microsoft account,
Windows
8 will synchronize certain data, such as app settings,
profile pictures, and passwords to the Microsoft Cloud. To access the Start Menu, users must hover the mouse
This information will be automatically synchronized to
other computers that the user uses with the same Microsoft over the lower left corner of the desktop or by right
account, This gives a uniform experience that travels with clickingon Start Screen.
users from computer to computer.
Windows 10 is a new and an exciting operating system
for organizations and their employees which was released
To create a Microsoft account, you need to register your
in July 2015
Windows 10 was purposely developed to bridge the
email address
as aMicrosoft accountatLive.com gap between touch (tablets, smartphones) and non-touch
devices (laptops and desktops). With Windows 10, all the
The Charms Bar It is a small menu that appears when you apps that were designed to run on touch devices could also
hover mouse over the bottom right comer or the upper run on a desktop (Figure 6.38). Windows 10 combines
right of the screen or by pressing the Windows + C key the best features of old and new features into a cohesive
simultaneously. This menu contains five options ~Search, package, thereby correcting nearly all of the shortcomings
Share, Start, Devices, and Settings (see Figure 6.37) of Windows §.
Computer Software 115

Figure 6.38 Windows 10 Start screen

An open app store for business Windows 10 has a


The upgrade process of Windows 10 is almost free for single app store that is open for business. It also enables
most Windows 7 and 8 users. Organizations to create a customized store that includes
their choice of apps.
Live tiles Colourful and animated tiles were first
Some features of Windows 10 include
introduced in Windows 8, They included shorteuts for
One converged Windows platform Windows 10 has a various apps and informative widgets. The Start menu of
universal app platform with a single security model, and Windows 10 is a miniaturized version of the full screen
the same deployment and management approach to render Start menu of Windows 8. If you don't like tiles, you can
a unified experience across varied devices, ranging from unpin them and use them from your computer, leaving
smartphones to the industry devices only a narrow column of frequently used apps
Designed the way people work As the Start menu
of Windows 7 is back in Windows 10, the desktop of
Windows 10 is quite familiar to the users. Therefore, there
Windows 10 is a flexible, adaptable, and customizable
is virtually no learning curve required as the Start menu
Operating system. It is a good mix of menus of Windows
has been expanded to provide one-click access to the
functions and files that are used frequently
7 and customizable Live Tiles from Windows 8.

Secure Windows 10 has powerful security and identity


protection features that are casy to manage. For example, 6.9.3 UNIX
it allows users to crea ¢ identities for accessing devices,
apps, and sites lo protect the computer a: nst secunty
The UNIX operating system was first developed in
the 1960s, and since then it has been under constant
breach, data theft, or phishing
development. UNIX is a stable, multi-user, multi-tasking
Windows 10 not only secures data that is stored
in the computer but also protects it while it is being operating system for servers, desktops, and laptop
transferred — tablet or PC to USB drive, email, or cloud. computers.
For this, it provides an additional layer of protection at the Similar to Windows, UNIX also supports a GUI to
application and file level
provide an easy-to-use environment. UNIX is made up of
three parts the kernel, the shell, and the files/processes
Supports continuous innovation Windows 10 provides
great compatibility with all the existing apps. Moreover, Kernel The kemel of UNIX is the hub of the operating
Windows 10 is automatically updated whenever a new system as it allocates CPU time and memory to programs
update is available. Users can choose the way in which and handles communications when a system call is invoked.
their Windows is updated —through Windows Update or Shell The shell acts as an interface between the user
in a managed environment and the kernel. When a user logs in, the login program
116 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

and subtract. Although there were similarities between


GENERATION OF PROGRAMMING the machine languages, a computer could not understand
LANGUAGES programs written in another machine language.
In a machine language, all instructions, memory
We now know that programming languages are the locations, numbers, and characters are represented in
primary tools for creating a software. Today, hundreds of strings of 1s and 0s. Although machine language programs
programming languages exist in the market, some more are typically displayed with the binary numbers represented
used than others, and cach claiming to be the best. However, in octal (base-8)
or hexadecimal (base-1 6), these programs
back in the 1940s, when computers were being developed, are not easy for humans to read, write, or debug.
there was just one language—the machine language. The main advantage of the machine language is that the
The concept of generations of programming languages code can be executed very quickly and efficiently, since it
(also known as levels) is closely connected to the advances is directly executed by the CPU.
in technology that brought about the different generations of However, on the downside, the machine language is
computers. The four generations of programming languages difficult to learn and is far more difficult to correct if errors
include—machine language, assembly language, high- occur. Moreover, if you want to add some instructions into
level language (also known as third generation language or the memory at some location, then all the instructions after
3GL), and very high-level language (also known as fourth the insertion point would have to be moved down to make
generation language or 4GL). room in the memory to accommodate the new instructions.
Last but not the least, code written in machine language
6.12.1 First Generation: Machine Language is not portable and transferable to a different computer.
It needs to be completely rewritten since the machine
Programming of the first stored-program computer systems language for one computer could be significantly different
was performed in machine language (Figure 6.39). This is from that of another computer. Architectural considerations
the lowest level of programming language and also the only make portability a tough issue to resolve,
language that computers understand. All the commands and
data values are expressed using 1s and 0s, corresponding to
6.12.2 Second Generation: Assembly Language
the ‘on’ and ‘off electrical states in a computer.
The second generation programming languages (2GL)
MACHINE LANGUAGE include the assembly language. They are symbolic
programming languages that use symbolic notation to
This isan example of a machine language program that will represent machine language instructions. These languages
add two numbers and find their average. It is in hexadecimal are closely connected to the machine language and the
notation instead of binary notation because that is how the intemal architecture of the computer system on which
computer presented the code to the programmer. they are used. Since they are soclose to the machines, they
are also called low-level languages. Nearly all computer
systems have an assembly language available for use.
Assembly language, developed in the mid-1950s, was a
great leap forward. It used symbolic codes, also known as
mnemonic codes, which are easy-to-remember abbreviations,
rather than numbers. Examples of these codes include ADD
for addition, CMP for compare, MUL for multiply, etc.
Assembly language programs consist of a series
of individual statements or instructions to instruct the
computer what to do. Basically, an assembly language
statement consists of a label, an operation code (opcode),
and one or more operands,
Labels are used to identify and refer to instructions in
the program. The opcode is a mnemonic that specifies the
operation that has to be performed, such as move, add,
subtract, or compare. The operand specifics the register
013D or the location in main memory where the dala to be
processed is located.
Figure 6.39 A machine language program However, as with the machine language, the statement or
instruction in the assembly language will vary from machine
In the 1950s, each computer had its own native to machine, because the language is directly related to the
language, and programmers had primitive systems for internal architecture of the computer, and is not designed
combining numbers to represent instructions such as add to be machine independent. This makes the code written in
Computer Software | 119

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

computing devices, For example, in a computer lab, there


INTRODUCTION TO COMPUTER may be 30 computers but only one or two printers. In
NETWORKS order to allow every computer to use the printer, there are
two options. First, to buy an individual printer for every
A computer network, simply referred to as a network, is computer, so that cach computer has a printer attached to
a collection of computers and devices interconnected to it. The second and more viable option is to use the already
facilitate sharing of resources such as printers, information, available printers and connect all the computers and
and electronic documents. printers in the lab via a network, so that every computer
has access to the printer.
7.1.1 Advantages of Computer Networks
Increased Storage Capacity
The advantages of interconnecting computing devices are
discussed in the following subsections. Attaching a number of computers to the network enables
sharing of files. Files stored on one computer can casily
File Sharing be accessed by another computer, A standalone computer
may have limited storage capacity, but when several
The key benefit of a computer network is that it facilitates computers are connected together, the storage memory
its users to share files, and to access files that are stored of all these computers can be made available for cach
on a remote computer, Users can sit at their workstation computer.
and casily access files stored on other workstations that
are connected to the same network, provided they are Increased Cost Efficiency
authorized to do so, This saves the time required to copy a
file from one system to another by using a storage device The software packages available in the market are costly
such as a pen drive or a CD-ROM. Moreover, users can and take time for installation. Computer networks are a
access or update the information stored in a database, feasible cost-efficient solution as they allow software to
making it up-to-date and accurate. Hence, network file be stored or installed on one computer which can then
sharing
among computers gives more flexibility and allows be shared among other computers connected on the same
users 10 share photos, music files, and documents with network,
others working on other connected computers. However,
the most important advantage of network file sharing is Load Sharing
that it allows multiple users to collaborate on the same
project through the network. If one computer is designated to carry out all the jobs, then
it is very likely that the computer will slow down, thereby
Resource Sharing taking hours to complete all the jobs. Hence, abetter option
is to transfer the extra jobs to another machine (connected
Computer networks facilitate the users to share the limited on the same network) for execution. This greatly improves
and otherwise expensive resources among a number of the performance of the system.
Computer Networks and the Internet. | (125

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

7.2.3 Metropolitan Area Network


A MAN is a network that interconnects computers and
other devices in a geographical area or region larger than
that covered by even a large LAN, but smaller than the area
covered by a WAN. A MAN (Figure 7.3) may interconnect
networks in a city, a campus, or a community to form a
single larger network (which may then be connected to a
WAN). It may be formed by interconnecting several LANs
Figure 7.1 Local area network by bridging them with backbone lines with the help of
126 Computer Fundamentals and Programming in C

7.2.5 Personal Area Network


A PAN is a computer network designed for communication
between computer devices such as mobile computers and
cell phones that are close to one person. The scope or the
reach of aPAN is a few metres (less than 10 metres), PANs
are basically used to communicate with the personal devices
themselves or for connecting to a higher-level network
and the Intemet. PANs can cither be wired with computer
buses such as universal serial bus (USB) and FireWire or
be wireless with network technologies such as infrared and
Bluetooth. Bluctooth PANs are also called piconets.
Figure 7.3. Metropolitan area network PANs can be used to transfer files including e-mails,
calendar appointments, digital photos, and music. These
fibre optic cables. In areas where cabling is not possible to days, PANs are also used to enable wearable computer
connect all LANs to form a MAN, wireless alternatives such devices to communicate with other nearby computers
as microwave, radio, or infrared laser links can be used. and exchange digital information using the electrical
MANs use technologies adopted from both LANs and conductivity of the human body as a data network. For
WANs, A MAN can be distinguished from a LAN or WAN example, two people can wear business-card-sized
in the following ways: transmitters and receivers to exchange information by
* The size of the network lies in between that of a LAN shaking hands, We all know that the human body is a
and a WAN, A MAN typically covers an area of 5-50 good conductor of electricity. When two people shake
square km, Many MANs can cover an area the size of a hands, an clectric field passes tiny currents and the electric
city, although in some cases they may be as small as a circuit becomes complete, thereby enabling each person's
group of buildings. data, such as e-mail addresses and phone numbers, to be
* A MAN (as with a WAN) is usually not owned by a transferred to the other person's laptop computer or a
single individual or an organization. It is generally similar device, Interestingly, even the clothes of a person
owned by cither a consortium of users or by a network can be used to transfer data.
service provider who sells the service to the users.
+ AMAN is a high-speed network that allows sharing of 7.2.6 Peer-to-Peer Networks
regional resources.
Peer-to-peer or P2P network is a type of network in which
Though the MAN is not a very widely used network, it cach computer has the same capabilities and responsibilities.
has its own importance for some government bodies and This is in contrast to a client-server or master-slave
organizations on larger scale. architecture in which some computers have higher
capabilities (called server) than others (clients), Though
7.2.4 Campus/Corporate Area Network P2P networks are simple, they may give low performance
under heavy loads.
ACAN is a computer network created by interconnecting
In a P2P network (Figure 7.4), either party can initiate
LANs within a limited geographical area, The network
communication. These networks are widely used on the
is almost entirely owned by the campus of an enterprise,
Intemet to share files, printers, and other devices among
university, government, military bases, etc. The size of the
different users. To exchange files, users must first download
area that CANs covers is larger than that of LANs and
4 P2P networking program (e.g., Gnutellanet), Then they
smaller than that of MANs or WANs.
must enter the address of the computer to which they want
CANs are typically designed for the particular place
to connect. Once the connection is established, files can be
that hits the highest point level. For example, in case of
exchanged between the two computers. On the Internet,
a university having multiple labs, or multiple buildings,
P2P networks handle high volume of file sharing traffic
it is called the campus area network and in case of an
by distributing the load across many computers. Other
organization with multiple offices or multiple departments
benefits of distribution of resources across peers include the
in the buildings it is termed as the corporate area network.
Th days, CANs are mostly formed using the
following
wireless communication mediums rather than cables and * Higher storage and access capacity
wirings because wireless communication has become + Improved reliability due to the availability of multiple
more economical than the use of long wires and cables. peer systems
CANs are economical, beneficial, and casy to implement * Improved security by distributing partial secrets across
in the specific locality, Therefore, they are widely used peers
by universities and other corporate organizations to work Aclient~server system having a centralized server to manage
from any block and receive the same speed ofdata transfer. and control the network and to provide services to the clients
Computer Networks and the Internet 127

Figure 7.5 Twisted-pair cables

install and use, However, these cables easily pick up noise


signals, and thus become prone to error when their length
extends beyond 100 metres.
Figure 7.4 P2P network
7.4.2 Coaxial Cables
suffers from inefficient allocation of resources and limited
scalability, In future, if more clients want to connect to the Coaxial cables are a highly preferred connecting medium for
server, it will incur additional costs and consume more cable television systems and for connecting the computers
bandwidth from the system. This inefficiency is overcome within an office building or within short distances to form
in P2P systems. a network. The coaxial cable consists of a single copper
conductor at its centre,
encapsulated inside
PHYSICAL COMPONENTS a plastic layer that
OF A NETWORK provides
between the
insulation
conductor
Copper
The three primary physical components of a network —
cover fate ee
layer conductor and a braided metal
include the following shield (refer Figure 7.6)
Braided metal sheild The metal shield blocks
+ Connecting media—includes both wired and wireless any interference from
media through which the signals are sent from one Figure 7.6 Coaxial cable
the outside environment
computer to another and is again protected by an outer shield of plastic material.
Connecting devices—includes different devices such The coaxial cable is highly resistant to signal
4s switches, routers, hubs, bridges, which are used to interference and can support greater cable lengths between
connect the computers network devices than twisted-pair cables, Its transmission
* Network topologies—defines the layout of the network speed varies from 200 million to more than 500 million
bps. However, the downside of this cable is that it is
difficult to install.
WIRED MEDIA
Computers and other computing devices can be connected 7.4.3 Fibre Optic Cables
by different kinds of media such as twisted-pair cables, The fibre optic
coaxial cables, and optical fibres. cable (shown in
Figure 7.7) is
7.4.1 Twisted-pair Wires constructed in
several layers. The
Twisted-pair wires, which consist of copper wires that are
Core core is the actual
twisted into pairs, are the most widely used medium for
telecommunication. Figure 7.5 shows a bunch of twisted-
Cladding glass, or fibre
pair cables enclosed in plastic insulation. While ordinary
Con conductor, which
Figure 7.7 Fibre optic cable is covered with a
telephone wires consist of two insulated copper wires
refractive coating
twisted into pairs, computer networking cables, on the
called cladding that causes the light to travel in a controlled
other hand, consist of four pairs of copper cables that can
path along the entire length of the glass core. The next
be utilized for both voice and data transmission.
The twisted wires help to reduce crosstalk and layer is a protective covering or an insulating jacket made
of teflon or polyvinyl chloride (PVC) to protect the core
electromagnetic induction, The transmission speed of
twisted-pair cable varies from two million bits per second
and coating from any kind of damage. It also prevents
light from escaping the assembly.
(bps) to 100 million bps. They are cheap and easy to
(bs Computer Fundamentals and Programming in C

Optical fibre cables carry data aspulses of light. They


transmit light that can travel over extended distances.
Fibre optic cables are not affected by electromagnetic
radiation and are thus best suited for certain environments
that contain large amounts of electrical interference. The
transmission speed of an optical fibre cable is hundreds
of times more than that of coaxial cables, and thousands of
times more than that of twisted-pair wires. This capacity
has helped broaden communication possibilities by
including services such as videoconferencing and other
interactive services. Moreover, these days, the trend is
moving towards using coloured light rather than white
light. Initially, only one message could be carried in a
stream of white light impulses, but with this technology,
multiple signals can be carried simultaneously. Figure 7.9 Satellite communication

This means that all the transfer of signal happens in space.


WIRELESS MEDIA Satellites can be used to relay voice, data, and TV signals,

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

on the network receive accurate information. ise,


the signals become weaker as they travel, and a | sentby
the transmitting device may be interpreted as a 0 by the
receiving device.
A bridge reads the address of the receiving device
specified on the data packet to identify the destination ofthe
packet. It then forwards the packet only to the network to
which the receiving device is connected, thereby reducing

é
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

4, RouterA sends the packet to Router B so that


it can pass it to Network 4, which is directly connected NETWORK TOPOLOGIES
to it.
Topology refers to the schematic description of the
arrangement of a network. That is, network topology refers
7.6.6 Gateway to the actual geometric layout of computers and other
A gateway, shown in Figure 7.13, is a very complicated devices connected to the network. There are different
networking device that is basically used to connect two network topologies; cach suited to specific tasks and
or more dissimilar networks that use entirely different having its own advantages and disadvantages. Some of
protocols (a set of rules that must be followed to exchange these topologies are explained in this section.
information). For example, if you know only English but
want to talk to a person who knows only French, then 7.7.1 Bus Topology
you need a translator to facilitate your communication.
The gateway acts as a translator between two dissimilar In a bus topology (Figure 7.14), cach computer or server is
networks. It accepts data formatted by one network and connected toa single cable. Hence, all the nodes (computers
converts it into a format that can be accepted by the other and other devices) share the same communication channel.
network. When a node wants to send a message to another node, it
creates a message and adds the address of the recipient
to it. Then, it checks whether the line is free or not, If the
line is free, it places the message on the line (transmission
channel); else, it waits until the channel becomes available.

Figure 7.13 Gateway Nodes connected


to a single cable

A gateway can be implemented in cither software or


hardware. The other key role that a gateway performs is to
Figure 7.14 Bus topology
provide security to the network. It can be used to monitor
incoming/outgoing traffic to check for any malicious
activity within the network, which can be harmful to When the message is placed on the line, each and
network integrity. every node connected to it checks the destination address
mentioned on it. If the node's address does not match the
intended address, it ignores the message. The message is
7.6.7 Network Interface Card picked up and opened only by the addressee. The receiving
One can use the phone service through a telephone device. device also sends an acknowledgement to the sending
Similarly, one can use the network services through a device before it frees the line.
network interface card (NIC), also known as the network
adapter or the LAN card. That is, no computer can Advantages
communicate to other devices without a properly installed * Easy to install and to connect a new device to the
and configured LAN card, The communication cables that network
connect different devices to form a network are connected * Requires less cable length than the star topology
via this card. * Inexpensive as only one cable is required
An NIC acts as the liaison for the computer to send * Failure of a single node does not affect the network
and receive data on the LAN. Every LAN follows a set of
protocols, The most common protocol being used is the Disadvantages
ethemet and a lesser used protocol is token ring. Hence, * Failure in the cable results in shutting down ofthe entire
when forming a LAN, an NIC must be installed in each network.
computer on the network, and all NICs in the network * In case of network shutdown, it becomes very difficult
must support the same protocol. to identify the problem.
NICs are available in two varieties—wired and wireless. + As the number of nodes increases, the speed of the
While most modern desktop computers use a wired NIC, network slows down.
the laptops, on the other hand, come with both wired and
wireless LAN cards.
However, if your computer does not have an NIC, then
7.7.2 Star Topology
you may use a USB-based adaptor that can be plugged The star topology (Figure 7.15) is considered the easiest
into the USB port of the computer. This is a portable topology to design and implement. In this topology,
adaptor and is again available in two varicties—wired and each node is connected to a central hub (or server) with
wireless. @ point-to-point connection. All traffic that traverses the
Computer Networks and the Internet 131

network passes through the + Easy to install


central hub. That is, it is * Can span over larger distances
the host node that controls * Every node has equal chance to transmit data
communication between
other nodes. Disadvantages
The hub acts as a signal * Causes delay in communication which is directly
repeater. When a node has proportional to the number of nodes in the network, Hence,
Figure 7.15 Star topology to send a message to another adding new nodes will just increase the delay caused.
node connected to the + Incase of network failure, difficult to diagnose the fault
network, it will first have to send that message to the hub. + If one node fails, the entire network is shut down
The hub will regenerate the message (since signals become because the ring is not complete.
weak due to noise) and then send it to the destination node. Difficult to add or remove nodes from the network

Advantages 7.7.4 Mesh topology


to install
* New nodes can be connected casily In a mesh network (Figure 7.17), also known as a completely
* Network does not get disturbed when a device is added connected network, every node is connected to every other
or removed from it node on the network using a separate physical link. Mesh
2 to detect faults topology involves the concept of routes. Unlike other
* Failure of any other node (except the hub) does not topologies, in a mesh network, a message can take any of the
t the network several possible paths from
the source to the destination.
Disadvantages For example, if a message
has to be sent from A to B via
* Requires more cable length than bus topology
C, then if node C fails, then
* Ifthe central hub fails, the entire network is shut down
the message can be sent to
* More expensive than bus topology because of the cost
B via any other node in the
of hubs, cables, ete
Figure 7.17 Mesh topology network.

7.7.3 Ring Topology Advantages


In a ring topology (Figure 7.16), all the nodes are connected * Failure of a node does not affect the entire network; only
to cach other in the shape of a closed loop, so that every the communication with that particular node is affected.
node is connected directly to two other nodes, one on cither + Communication is fast as there is a direct link between
side of it. In a ring network, the nodes.
messages travel through the * Each connection can have its own data load, so the
ring in a circular fashion in traffic problem is eliminated.
the same direction (cither * Ensures security of data because every message travels
clockwise or — counter- along a dedicated link
clockwise), A failure in * Itis easy to detect network errors.
any cable or device breaks
Figure 7.16 Ring topology the loop and can cause the Disadvantages
network to shut down. * It is the most expensive network as, for n nodes, n
In a ring topology, each device acts as a repeater to keep (n-1)/2 physical links (cables) are required.
the signal strong as it travels, Each device incorporates a + Itis difficult to install
receiver for the incoming signal and a transmitter to send the
data to the next device connected to it in the ring. A node 7.7.5 Hybrid Topology
receives the data/message from any of its two adjacent nodes.
We have discussed the star, ring, bus, and mesh topologies.
Then, it checks the destination address. If the message is
addressed to it, it accepts the data and processes it; otherwise, Each of these has its own advantages and disadvants
Hence, in the real world, a pure star, pure ring, or pure
it just regenerates the signals and passes it to the next node
bus is rarely used. Rather, a combination of two or more
in sequence. In this topology, every computer takes tums to
topologies is preferred.
communicate with the other nodes connected to the network.
Hence, hybrid network topology (shown in Figure 7.18)
uses a combination of two or more topologies in such a
Advantages
way that the resulting network does not exhibit one of the
* Best suited for networks that do not have a hub standard topologies (c.g., bu and ring). Two very
* More reliable than star topology as the communication commonly used hybrid network topologies include the
does not depend on a single hub
33 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

Direction of data Number of bits transferred Synchronization between


flow simultaneously sender and receiver

Simplex Half-duplex Full-duplex Serial Parallel Synchronous Asynchronous

Figure 7.19 Data transmission modes

* It is used for controlling a hands-free headset from a


mobile phone.
DATA TRANSMISSION MODE
* It is used for controlling a Bluctooth-compatible car
Transmission of data on a communication channel
stereo system from a mobile phone,
between two machines can take place in several different
* Itis used for creating a network of PCs in a confined
ways as shown in Figure 7.19. This transmission can be
space where little bandwidth is required.
characterized by the following features:
* Itis used for enabling wireless communication between
the input and output devices ofacomputer. * Direction of data flow
+ It is used in the control of and communication between * Number of bits sent simultancously
devices where infrared system is used. * Synchronization between the sending and receiving
* It is used in low bandwidth applications that prefer devices
cable-free connection,
It is used for advertising products by using Bluctooth-
7.9.1 Simplex, Half-duplex, and Full-duplex
enabled hoardings to send advertisements to other
discoverable Bluctooth devices, Connections
* It is used for tracking and identifying the location of The data transmission mode refers to the direction of flow
objects in real-time location systems, The objects have of data. Based on this characteristic, a connection can be
an embedded tag, which sends wireless signals to further classified into three categories—simplex, half-
readers that receive and process those signals. duplex, and full-duplex.
In the simplex mode, data flows in only one direction,
Limitations of Wireless Networks from the sending device to the receiving device. A simplex
connection is often desirable where the data need not flow
The limitations of wireless networks are as follows. in both directions. For example, the computer can send a
Interference Electromagnetic interference is a common message to the printer, but the printer need not send any
problem in wireless networks which degrades a signal. data or message to the computer,
It can occur cither due to other networks or because of In the real world, simplex mode of data transmission
devices that generate radio waves that are within or close is not very popular because most of the communications
to the radio bands used for communication. require bi-directional exchange of data, However, this
mode of communication is used in business, at certain
Absorption Wircless networks suffer due to absorption point-of-sale terminals in which sales data is entered
of electromagnetic waves by some materials, thereby without the need for a corresponding reply, It is also used
preventing them from reaching the receiver. in radio and TV transmissions.
Reflection Materials that are either metallic orconductive In a simplex transmission, only one device transmits
cause reflection, which may prevent the signals from being data, and all other connected devices can only receive
properly received. data. Hence, this type of transmission is similar to a one-
way traffic, as data flows only in one direction. Note that
Multi-path fading Reflection can cause a signal to take
in simplex transmission, the roles of the sending and
different routes before reaching the receiver. At certain
receiving devices cannot be reversed. That is, the device
locations, the signal may get cancelled out, leading to
which has assumed the role of sending data can only send
multi-path fading.
and not receive. Similarly, the receiver can only receive
Hidden node problem This problem occurs whena data but can never send it. Figure 7.20 depicts the simplex
computer is visible from a wireless access point but seems transmission.
unavailable from other computers communicating with In the half-duplex mode, also known as an
that WAP. alternating connection or semi-duplex, there is only one
134 Computer Fundamentals and Programming in C
communication channels. Based on this definition,
Data/Signal connections can be classified as serial or parallel
Communication channel meoeiver connections. Since modern-day computers can proc
several bits of data at the same time, the basic connections
Figure 7.20 Simplex mode on a computer are parallel connections.

communication channel (a wire or a cable) to carry data. Parallel Connection


However, both the devices can be cither a transmitter or a
In a parallel connection, m bits are simultancously
receiver, That is, devices can share the channel but only
transmitted over the communication channels. Thes
one of them can transmit at a time, While one device is
n bits are concurrently transmitted through separate
transmitting the data/signals, the other will be in receiving
mode, and vice versa. This is shown in Figure 7.21 communication lines. As an analogy, parallel transmission
can be thought ofasa multi-lane highway where a number
of automobiles can travel at the same time
Direction of data flow at
time T, Ifone has seen the insideof a CPU, itmay beobserved that
the data bus has 32 lanes (in case of 32-bit computers). This
Device A Device B is because, in a computer, binary data flows from one unit
Direction of data flow at to another using the parallel mode. Hence, all the 32 bits of
time T, data are transferred simultaneously on 32-lane connections.
Similarly, in a networked environment, parallel transmission
Figure 7.21 Half-duplex mode may be used to transfer data from a computer to the printer.
In the half-duplex mode, the data is sent and received Parallel mode of transmission (shown in Figure 7,23) is
alternatively. Hence, it can be thought of as a one-lane undoubtedly a very fast data transmission mode.
bridge, where vehicles can come from both the directions, The communication channels in a parallel connection
but notat the same time. Vehicles on one side must wait until may contain cither of the following
traffic coming from the opposite direction has crossed the
bridge. In the real world, the half-duplex mode is utilized
in web browsing. The user sends a request to download
4 particular web page, then that page is downloaded and
displayed to the user.
In a full-duplex mode, data flows in both the directions
simultaneously as shown in Figure 7.22. That is, cach end of
the line can transmit and receive the data/signals at the same Computer A Computer B
time, The number of communication channels in a full-
duplex connection can cither be one or two. Two separate Figure 7.23 Parallel communication between computers
communication channels can carry data in both directions
and can be thought of as the combination of two simplex * nm physical lines so that cach bit is sent on a physical
lines, one in each direction. However, if there is only one line. Parallel cables are made up of several wires in a
single communication channel, then the bandwidth of single cable. However, closeness of conductive wires in
the channel is divided into two for each direction of data a single cable can result in interference, particularly at
transmission. A full-duplex connection can be thought of as high speeds, thereby degrading the signal quality.
a two-lane bridge where vehicles can simultaneously travel * One physical line that is divided into several sub-
in both the directions but only in their respective lanes channels. This is done by dividing the bandwidth of the
line so that each bit is sent at a different frequency.

Device A Device B Serial Connection


Data can flow in both the
directions simultaneously
In a serial connection, the data is sent one bit at a time over
Figure 7.22 Full-duplex mode the transmission channel. However, since most processors
process data in parallel, the device that sends the data mu:
In the real world, the full-duplex data transmission convert the parallel data into serial form before sending it
mode is widely applied in telephone systems, where both to the receiver. Similarly, on receiving the serial data, the
the caller and the receiver can talk at the same time. receiver must convert it into parallel data, so that it can be
processed further.
7.9.2 Serial and Parallel Transmissions In serial data transmission, bits of data are transmitted
The term transmission mode also refers to the number sequentially through a single communication channel as
of bits that can be simultaneously transmitted over the shown in Figure 7.24. An analogy would be the flow of
Computer Networks and the Internet | (135
Communication recognizes a character when it arrives. For this purpose,
cach character is preceded by some information indicating
the start of character transmission (the transmission-start
information is called a START bit) and ends by sending
the end-of-transmission information (called a STOP bit)
Figure 7.25 shows the asynchronous mode of transmission
Basically, an asynchronous line that is idle (not being
used) is identified with the value 1. The devices connected
to the network first check whether the line is idle or
Computer A converts the Computer B accepts serial disconnected. If the line is free or idle, the sending device
parallel data into serial data data from the channel and first sends a start bit that has a value 0, Thus, when the line
to transmit it on the converts it into parallel switches from a value of | to a value of 0, the receiver is
communication channel data for further processing alerted about the arrival of a character.
Figure 7.24 Serial communication between computers
Advantages
traffic on a one-lane residential street. Serial transmission + It is simple as it does not call for synchronization
is undoubtedly slower than parallel transmission because between the sending and receiving devices,
data is sent sequentially in a bit-by-bit manner. In the real * The hardware required to set up an asynchronous
world, serial transmission mode is used while working connection is inexpensive as timing is not critical,
with a serial mouse. An asynchronous connection can be set up very fast
and is therefore very well suited for applications where
7.9.3 Synchronous and Asynchronous Data messages are generated at irregular intervals like data
Transmission Modes entry from the keyboard

Parallel connections may result in interference, and hence Disadvantage


users may prefer a serial connection to a parallel onc. In
a serial connection, a single cable is used to transmit the Overhead is involved in sending the control bits (START
information, so the real challenge lies in synchronizing the bit, STOP bit), which actually do not carry any information.
sender and the receiver devices because the bits of data
are sent one after the other, There are two modes of data Synchronous Transmission
transmission that address this problem—asynchronous
In synchronous transmission, the sender and the receiver
transmission and synchronous transmission.
are synchronized with cach other using a clock. In this
transmission mode, characters or bytes are grouped
Asynchronous Transmission together to form a data block. Then, a header and trailer
In the asynchronous mode of transmission, the sender are added to the data block to form a frame.
transmits the data character by character (or byte by The header contains useful information that is needed by
byte) to the receiver at any point of time. This mode of the receiving device to synchronize its clock with the sender's
transmission is best suited for connecting input devices, clock. It is followed by the block of data containing a variable
printers, modems, fax machines, etc., to the computer, as number of bits, which is again followed by a trailer, The trailer
data is sent to the receiver at irregular intervals of time: is used fo terminate the message and contains an end-of-file
However, since the data arrives abruptly at any time, (EOF) character followed by a check character that helps
it is ver ‘y essential to ensure that the receiving device detect any transmission error. This is shown in Figure 7,26,

START bit STOP bit START bit STOP bit

-DOBGOOOO
Data for the first character
Opponano
Data for the second character

Figure 7.25 Asynchronous transmission

elalelsieieiel|»
Header
ojo

Figure 7.26 Synchronous transmission


136 Computer Fundamentals and Programming in C

Synchronous transmission is more efficient and faster Application layer


than its asynchronous counterpart. It is best suited for ¢ Message format, human-machine
interfaces
communication between two devices that have a buffer
Presentation layer
(small area of memory) to store the individual characters
Y Coding into 1s andOs:Encryption, compression
to form a data block of length 80 or 132 characters.

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

INTERCONNECTION MODEL DE wcvort tayer


GS ata link tayer
The Open System Intereonneetion (OS!) mode! given by |] GE) hy sicatayer
the International Standards Organization (ISO) in 1984 is
an abstract model that provides a networking framework Physical link
of standards to enable diverse equipment and applications
from different vendors to communicate with cach other. Figure 7.27 OSi model
When a vendor's device adheres to the standards set by
the OSI model, it can be casily connected to other devices Hence, the OSI mode! simplifies the entire process of
produced by other vendors. Correspondingly, the further a network communication by dividing it into logical smaller
vendor departs from those standards, higher is the difficulty pieces and makes network designs more extensible as new
in connecting its devices with devices of other vendors. services can casily be added in a layered architecture than
Incompatibility with set standards not only makes devices in a monolithic one.
difficult to connect but also makes them expensive to design
and less marketable than other devices following the norms. Layer 7—Application layer The application layer provides
The OSI model divides thecomplex task of computer-to- services to support end-user applications such as e-mail,
computer communication (also known as internetworking) file transfer, user interface, database access, remote printer
into a series of seven layers (Figure 7.27). These seven access, and so on. The commonly used protocols in this
layers are functionally independent of cach other. layer include HTTP, WWW, FTP, TELNET, and SMTP.
ore, any change made in one layer does not affect It is the responsibility of the application layer to hide the
the function of any other layer. While providing services underlying incompatibilities and complexities of network
to the layers above it, they receive services from the communication to enable a smooth transfer between
lay below it, During implementation, the upper layers systems, Web browser is an example of application layer
consisting of layers 7, 6, and S are implemented using that provides user's applications access to the network
software while the lower layers, that is, layers 4, 3, 2, and through the layers below it
1, are implemented using both hardware and software.
In the OSI model, data is transferred from one layer
to the next. It starts from the application layer of the The application
layer acts as a window for end-users’
sending device and goes until the physical layer. The data applications
to access network services.
then travels over the channel to the next computer and
moves back up the hierarchy. While the application layer Layer 6—Presentation layer The presentation layer, also
is closest to the end-user, the physical layer on the other called the syntax layer, acts as a translator between the
hand is closest to the physical network medium (wires). application program and the network format, This layer is
Computer Networks and the Internet 137

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,

The presentation layer at the sending computer


translates data from a common format. Theapplication The transport layer provides error control, flow control,
layer at the receiving computer translates the data in and reliable transfer ofdata.
common format into a format that is acceptable by the
receiver, Layer 3—Network layer The network layer is in charge of
all of the addressing issues. It accepts data packets (smaller
units of message), determines the best path or route, and
layer 5—Session layer The session layer enables
applications on the sender and the receiver to communicate sends the packets on that route so that it can either reach
the receiver or reach a device that is closer to the res
with cach other using a session. Sessions allow data
to be transmitted cither in one direction or in both the The network layer manages network problems like data
congestion, which occurs when there are too many packets
directions simultancously. For this, the layer establishes,
coordinates, manages, and terminates the connection present in a network.
between applications. The session layer also acts as a The network layer creates a logical path for transmitting
data from the sender to the receiver. It controls the
dialogue controller to decide which device will transmit
the information, Additionally, the layer synchronizes data
operation of the subnet (a part of the network) and decides
transmission and adds checkpoints in it. This is useful
the optimal path for the data based on network conditions,
especially when a large amount of data has to be transferred. priority of service, and other factors.
For example, if the user is downloading a file of SOOMB,
then the session layer may insert checkpoints after every
100MB of data. Now if the system crashes when already The main job of the network layer is routing and data
250MB of data is transferred, then the sender will send data transmission,
only after first 200MB, In the absence of this checkpoint,
the entire 250 MB of data has to be transferred again.
Layer 2—Data link layer The data link layer converts
data packets into a stream of Is and Os, It is also
responsible for error control, flow control, and reliable
The session layer establishes and terminates connection, data transfer, The data link layer is divided into two sub-
provides data synchronization, controls dialogues, and layers as follows:
inserts checkpoints. * Media access control (MAC) controls how a computer
on the network can access data and have permissions to
Layer4—Transportlayer The transport laycrisresponsible transmit it
for reliable data transfer between two systems. This layer Logical link control (LLC) performs error control and
not only transfers data but also provides error and flow flow control functions. In case of errors, the data link
contro! mechanisms to ensure complete and reliable data layer asks the sender to retransmit the data.
transfer. It enables the receiver to receive accurate data in Note that the transport layer also provides error and
the right sequence without any data loss or duplication. flow control. Generally, if the sender and the receiver are
The basic functionalities that the transport layer provides both on the same network, then error and flow control by
include the following the transport layer is not required, These features can be
* At the sender's site, it accepts data from the session supported by the data link layer itself. But when the two
layer, breaks it into smaller units (if there is a large devices are on different networks, then error and flow
138 Computer Fundamentals and Programming in C

Control must be implemented at the data link layer as well


as at the transport layer
TRANSMISSION CONTROL
PROTOCOL/INTERNET PROTOCOL
MODEL
The data link layer converts packets into a stream of bits
and provides error control and flow control mechanisms. The transmission control protocol/Internet protocol (TCP.
IP) is a suite of protocols used as the basic communication
language or protocol of the Internet. As shown in
Layer 1—Physical layer The physical layer converts the
Figure 7.28, each layer of the TCP/IP model corresponds
raw stream of bits into electric signals, optical signals,
to one or more layers of the OSI model, Table 7.1
or electromagnetic signals depending on whether the
underlying network uses a cable circuit (using coaxial
summarizes the types of services performed and protocols
used at cach layer within the TCP/IP model
cable), fibre-optic circuit, or a microwave circuit,
Note that at the application layer users access web
respectively
applications such as email or page download to generate
The physical layer is concerned with all the physical
aspects of data transmission. For this, it performs the
following tasks
* It establishes, maintains, and terminates physical
connections between computers.
It decides how many volts should be used to represent 0 Application layer
and 1
* It decides how many bits should be transmitted in a
second.
It decides the mode of data transmission (simplex, half-
duplex, or full-duplex). ‘Transport layer
* It defines physical and clectrical specifications for
devices to interface to the network, like the shape and Internet layer
layout of pins in connectors, broadcast frequencies, and ss
specifications of the cable
Network access layer

The physical layer transmits (on sender) and receives (on


Psa ae
receiver) data from the physical media. Figure 7.28 TCP/IP model

Function of layers in the TCP/IP mode!


Layer [Function Protocol
| Application Provides users with an interface to communicate, This interface could bethe web HTTP, TELNET, FTP, TETP,
browser. This layer sends and receives datafrom thetransport layer SNMP, DNS, SMTP
‘Transport Facilitates transport of data segments across the network, It is responsible for host- —TCP for connection-oriented
1o-host delivery. and reliable communication
‘While transmitting, transport layer receives data from application layer and sends ‘User datagram protocol
data
tothe Internet layer. But while receiving, itaccepts data from Internet layer and (UDP) forconnection-less
and
passes it to the application layer. unreliable communication
Internet Packages data into IP datagrams, which contain source and destination address. IP. ARP. RARP, ICMP
Forwards the datagrams on the best route available.
While receiving data, the Internet layer receives data from the network access Layer
and passes it tothe transportlayer. While sending data, it does theopposite.
Network Provides access to the physical network Ethernet, token ring, FDDI,
access Specifies details ofhow data isphysically sent through the network. Concemed —_frame relay
about electrical, mechanical, and physical details ofthe network interface.
While transmitting data, itsends data tothe physical network after receiving it
from the Internet layer, While receiving, it accepts data from the network and passes
itto the Internetlayer.
data. This data at the transport layer is chopped into smaller
units called segments. At the Internet layer. segments
Computer Networks and the Internet

INTERNET PROTOCOL ADDRESS


@ 2)
are packed into IP datagrams. These datagrams are then
chopped at the network access layer to form frames that When you have to send a letter toyour friend, you always
are transmitted across the networks. mention the residence address of your friend so that it can
reach her. This residence address is unique. If you want to talk
to your friend, you need to dial her telephone number, which
INTERNET is again unique. Similarly, if you have to send a message
over the Internet. you need some addressing mechanism so
The Internet is a global network that connects billions of that the message can reach the correct destination.
computers all over the world. It is a network of networks. Internet protocol address or IP address is, therefore,
The Internet links different organizations, academic a unique address allotted to computing devices such
institutions, government offices, and home users to share as computers, routers, printers, scanners, modems,
information among a large group of users. smartphones, tablets, and so on that are connected with
Each computer on the Internet is called a hast. To the Internet. This address facilitates unique identification
connect to the Internet, the user must gain access through a of devices for communication to take place,
commercial Internet service provider (ISP). The Internet,
sometimes known as the net, allows the users to: Features
* Connect casily through ordinary personal computers and The following are the features of IP address:
local phone numbers to share huge pool of information
+ Exchange e-mail with friends and colleagues. The * An IP address is divided into four parts where cach part
e-mail service has practically replaced the postal service is separated from the other using a dot.
for short written messages, It has undoubtedly become * Each part of the address contains a number ranging
the most widely used application on the Internet. from 0-255.
« Converse with other users. The conversation can be * For example, 79.121.10,190 is a valid IP address,
text-based, voice-based, video-based, or a combination + Without IP addresses, sending and receiving data over
of all these, the Internet would be impossible.
* Share important pieces of information in a timely
manner 7.13.1 Types of IP Addresses
* Access multimedia information that includes sound, There are two categories of IP addresses—static or
photographic images, and even video dynamic and public or private,
+ Browse through information and websites using a
Static and dynamic Internet protocol addresses As the
web browser, the most popular of which are Microsoft
Internet Explorer, Netscape Navigator, Opera, Google name suggests, static IP addresses never change and dynamic
IP addresses keep changing dynamically whenever users
Chrome, Mozilla Firefox, and Safari
log on to the network, Many a time, dynamic IP addresses
An additional feature of the Internet is that it lacks are issued using a leasing system. Therefore, the allocated
a central authority that controls it. Although there are IP address remains valid for a limited time. When the lease
dittetot governing
9 boards that work to establish policies expires, the computer automatically requests a new lease.
and standards, the Internet is bound by few rules and Similarly, when there is an IP address conflict, a request
answers to no single organization. for another IP address is sent to the ISP automatically, The
entire process of requesting IP addresses is automated and
7.12.1 History is therefore hidden from the users. Table 7.2 shows the
differences between static and dynamic IP addresses.
The roots of the Internet can be traced to the year 1969
when the Advanced Research Projects Agency (ARPA) of
the US government formed the very first network, which DOMAIN NAME SYSTEM
was widely known as the Advanced Research Projects
Agency Network (ARPANET). This network was initially When you want to talk to a friend, you do not type
created to interconnect computers so that the users in the his number. You may be having several friends and
research organizations and universities could communicate memorizing everyone’s number is just not possible.
with each other and share information. Therefore, you save all important phone numbers along
However, it was inthe year 1989 that the US government with their names in your phonebook. To connect with your
lifted restrictions on the use of the Intemet and allowed it friend, instead of dialling his 10-digit cell number, you
to be used for commercial purposes as well. Since then, the just search for his name in the phonebook and click the
Internet has grown rapidly to become the world’s largest Call button. Although you use the name, your call is not
network that connects thousands of networks, billions of connected based on name. The name is converted into a
computers, hundreds of countries across the world. number which is then used to establish the connection.
140 Computer Fundamentals and Programming in C

domain servers. Besides providing speedy mapping, this


cieee Differences between static and dynamic IP
authority delegation process ensures distributed and fault-
address
tolerant service to Internet users.
(Static IP address |Dynamic IP address In such a networked DNS environment, if one DNS server
‘This IP address ispermanent. This IPaddress is temporary does not know the IP address of a particular domain name, it
and changes dynamically. asks another server for the same, The process is repeated until
A computer retains its static A computer
isallotted anew
4 proper match between IP address and domain name is found.
address every time itis dynamic
IP address every time
connected tothe Internet, it is connected
tothe Internet.
Itis arcliable
way to facilitate —Itisnot a reliable
way to ONS is a service that automatically converts domain
communication between facilitate communication names into IP addresses.
remote devices. between remote devices.
‘This address reveals technical ©Dynamic
IP address does not Some commonly used domains are as follows:
information about the reveal
any such detail.
gov Government agencies
continent, country, and city in
which the computer islocated, edu Educational institutions
‘There are limited static It can support alarge number org Non-profit organizations
addresses. of users who do not require the
same IP address always. mil Military
Tris allotted todevices that It isallotted todevices using a com Commercial business
connect tothe Internet using a dial-up connection to connect
broadband connection. to the Internet, net Network organizations
Email servers and other web Itisnotsuitable for servers. int International organizations
servers must have a static IP
address, Some country domains are as follows:
Its preferable
for applications —Itispreferable for applications ca Canada
such asvoice over IP. online that work fine with temporary th Thailand
gaming, and other applications and one-time
IP addresses.
that need tolocate and connect fr France
to a particular computer onthe
Jp Japan
Internet.
It is less safe and requires Itissafe 10 use. in India
extra security mechanism. us Unites States of America
A user canconfigure
his static —Dynamic
IPaddress i allotted
AP address himself, by the ISP server. Thisallocation
uk United Kingdom
istransparent from the user. Other domain names include . museum (for museums),
info (informational websites), .name (personal websites),
pro (for professionals), .acro (for aeronautical companies),
Coming back to the Intemet, we have seen that every coops (for co-operative organizations), jobs (for job
device has a unique IP address. To connect with a particular posting), and .mobl (for mobile communication networks).
device you need to specify its address. However, we do Like our full names in which the general name or surname
not really type the IP address. For example, if we want comes on the right and our specific name comes on the left,
to connect to google.com, we just type www.google. domain names are also organized from right to left, with
com. Then where is the IP address and how are we able general domains to the right, and specific domains to the left
to access the website? The answer to this question is the For example, in the domain name www.google.com, there
Domain Name System (DNS). Similar to the phonebook are three domain names, each separated by a dot. Here, com
service, the Internet has a corresponding DNS service that és a general domain and google is a sub-domain, and www is
translates domain names into IP addresses (for example, a sub-domain prefix for the World Wide Web.
www.google.com into 74,125.224.72). This means that
every time we use the Internet, we always use the DNS
The DNS system works as a network of DNS servers.
As maintaining a central database of all the computers UNIFORM RESOURCE LOCATOR OR
on the Internet along with their names and IP address is UNIVERSAL RESOURCE LOCATOR
quite unpractical, the DNS distributes the responsibility of
storing domain names and their corresponding IP addresses A uniform resource locator (URL) specifies the unique
to authoritative name servers. These name servers are address for a file that is accessible on the Internet. It is
responsible for the domain they support. The authoritative provided by the user in the address bar. For example, when
name servers may even delegate authority to other sub- you type www.google.com, after pressing the Enter key,
Computer Networks and the Internet 141

hitpy/www davescomputertips. com/Newsketters/20070915,php


Protocol
World wide web
Domain name
Top level domain
Folder
File name
File extension

ure 7.29 Uniform resource locator

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

Figure 7.30 Types of URLs


specifies
complete
the
URL
GRD in TERNET SERVICES
containing all three fields (protocol, domain, and path), Today, the Internet has become a part of not only the big
relative URLs, on the other hand, contain only the one organizations, universities, and offices, but has become
field which is the domain name. the need of home users (like students) all over the
Many a time, you must have observed a complex URL world. In this era, life without the Internet has become
as the one given here, especially when you log in to your unimaginable. In this section, we will read in detail about
email account or search for a string on google. these services.
hitp://www.google.com/cgi-bin/search.
>
computer20fundamentals 7.16.1 Electronic Mail
Although it seems complex, it is actually very simple to An e-mail is a means of transmission of messages
interpret. In the query, http is the protocol, www.google. electronically overcommunication networks. These messages
com is the domain, and search.cgi is a file in the cgi-bin may vary from notes entered using the keyboard to electronic
142 Computer Fundamentals and Programming in C

Radhika will be able to see Goransh’s e-mail address, but


Goransh will not see Radhika’s e-mail address.
Moreover, there are also options for attachments and
forwards. The attachment option enables the users to attach
files to the e-mail. The forward option is used to forward
(make a copy) of a message received from someone and
mail it to someone else.
The messages are stored in electronic mailboxes until
the recipient fetches them. After reading the message, the
receiver may save it, delete it, forward it to someone else,
or reply to it. All in all, e-mail is a good alternative to the
traditional paper-based letters. It is much faster and easier
to use as there is no need to buy envelopes and stamps, and
involves no queuing in the post office.
ee
ne St a
7.16.2 File Transfer Protocol
Figure 7,31 E-mail File transfer protocol (FTP) is one of the oldest
applications of the Internet, which is basically used for
files stored on disk. Companies that are fully computerized transferring files from one computer to another, such 4
make extensive use of an e-mail because it is fast, flexible, from a user's personal computer to a web server. It is the
and reliable. Figure 7.31 shows an e-mail application. preferred method of exchanging files because it is faster
E-mail is one of the most widely used services on the and reliable. It is usually used to
Internet. Anyone who has an e-mail account can send an * enable the users to share files, computer programs, and/
e-mail (like a letter) to any other person who also has or data
an ¢-mail account (provided the c-mail address of the * enhance the use of remote computers
recipient is known), Usually, the structure of the e-mail * provide authentication and security to the stored files
can be given as: username@domain name. and programs
For example, if a user has created an e-mail account in * transfer data reliably and efficiently
Gmail, then the e-mail address is username@ gmail.com,
where username is his/her Gmail screen name The FTP program can be invoked cither by typing the
Using an c-mail is rather straightforward. If one has FTP commands on a simple command line interface (CLI)
an e-mail account, he/she can just click on the option such as the MS-DOS prompt window or with a commercial
“Compose e-mail’ (or similar options corresponding to the program that offers a graphical user interface (GUI), Even
browser being used). Thereafter, the user will be prompted the web browser can make FTP requests to download the
to enter the following fields selected programs
To In this field, the e-mail address of the recipient should 7.16.3 Chatting
be typed.
Chatting is a very popular service of the Internet that
Subject In this field, anything illustrating the content of allows two or more online users to come together to talk
the message can be keyed in. However, the length of this using an instant messenger. Chatting helps us 8 to stay
field is limited, connected with concerned people in busine: or family
who live many miles away
Body This ticld contains the content of the message. Most
To chat with users on the Internet, every user must
e-mail systems include a basic text editor for composing
have an account with a username and password to enter
messages, but uses may also edit messages using any other
the website. Chatting involves the exchange of typed-in
editor of their choi
messages between a group of users who take part from
CC and BCC Filling these fields is optional. However, anywhere on the Internet, The chatting program also
similar to the To field, these fields also contain e-mail enables the users to arrange a private chat between two
addresses of recipients, While CC stands for carbon copy, parties who meet initially in a group chat
BCC, on the other hand, means blind carbon copy. When These days, even the business organizations are using
a. user wishes to send the same e-mail message to multiple chatting services to host online business meetings, or to
recipicnts, he/she can add the extra e-mail addresses in answer any queries of customers or provide them online
the CC field, separating each address with a comma. BCC support and assistance.
works just like CC, except the e-mail addresses in BCC Whether a business chat or a personal chat, it can be
are not revealed to the other recipients. For example, if a ongoing or scheduled for a particular time and duration,
user sends an e-mail To: Goransh and BCC: Radhika, then Most chats are focused on a particular topic of interest and
Computer Networks and the Internet 143

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’.

7.16.7. Online Shopping


Online shopping means buying goods and/or services
Figure 7.32 Electronic newspaper
from merchants who sell on the Intemet. The popularity of
Source: Oleksiy Mark/Shutterstock/OUP Picture Bank the web gave an excellent opportunity to merchants to sell
their products to people who surf the Internet. Shoppers
With the online newspapers, users can read the can now visit web stores 24 * 7 as per their convenience,
full coverage of breaking news in a timely manner. that too while sitting in their home, office, or even while
The credibility and strong brand recognition of well-
travelling.
established newspapers, and the close relationships they Consumers buy a variety of products from online stores
have with advertisers, plus the savings in overhead costs ranging from books, clothing, household appliances, toys,
has led to the movement away from the printing process. hardware, software, and health insurance policies.
The number of people who want to shop online is
7.16.6 World Wide Web increasing day-by-day, This is mainly because when
The technical definition of the world wide web (WWW) a customer shops at a brick-and-mortar store, he or she
or simply web, can be given as ‘all the resources and has to drive to the store, find a parking place, and walk
144 Computer Fundamentals and Programming in C

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

4 for the same information using different search engines


gives better results.
= For getting better search results, while specifying
keywords users must keep in mind the following points:
Figure 7.33 Electronic shopping cart
+ Use AND: If you have to search for more than one
Source: Bloomua/Shutterstock/OUP Picture Bank
keyword and all of them do not form a phrase, then
specify the keywords using a ‘+’ sign or writing AND
7.16.8 Search Engine between them. This will instruct the search engine
to return web pages that contain all the keywords
The World Wide Web stores enormous amount of For example, if information on functions of kidneys
information on an amazing varicty of topics in hundreds is required, then the user must either type kidney +
of millions of pages. Finding information from this functions ot type kidney AND functions
huge source is extremely difficult, The information we * Use OR: Wf there is more than one keyword and
need is often stored in different names in different sites. users want information on any of the keywords, then
Therefore, a special site called a scarch engine (c.g., they must use OR in between the keywords given in
Google, Yahoo, MSN Search, and Bing) is used to help parentheses. For cxample, if a user wants information
people find information stored on various sites. Each of about Dethi or NCR, then he/she should type (De/hi OR
these search engines has its own abilities and features NCR). This would return web pages that contain cither
but they all help to minimize the time required to find keyword.
information, Search engines use automated software + Use NOT. If users want to limit the search result by
called robots, bots, or spiders that travel along the Web indicating keywords that should not be a part of result,
searching all documents and files to create a searchable then they must use the NOT or — symbol, For example,
index of the files and documents containing the keyword. if a user wants information about Delhi but not NCR,
The search engine then applies apredetermined algorithm then he/she must cither type Delhi NOT NCR or type
that ranks the pages according to their importance. Delhi — NCR.
It then displays the search results to users in the form * Use quotation marks; When there are multiple keywords
of a list commonly called hits. Most of the times, the that form a phrase, enclose the keywords in quotation
search results obtained from one search engine may marks. The search engine will then return the pages
not match those obtained from another search engine. that have the keywords in the exact order of the words
This is because cach search engine applics its own in quotations. For example, if the user is looking for a
technique to search and rank the pages; therefore, it is book on Computer Fundamentals and Programming in
always beneficial to use more than one search engine C, then he/she must type the complete title in quotation
on a regular bi Some sites such as Yahoo, Search, marks. This would give pages that contain the full
and EasySearcher not only use their search engine but phrase together. Otherwise, information on Computer
also give the results from simultaneous searches of other Fundamentals (only) and Programming in C (only) will
search indexes. The following are some useful tips to also be displayed.
search for information on the World Wide Web. * Combine symbols, if required: For example, if the user
* Use precise and specific keywords: For example, if you wants information about government universities in
want to know about kidneys, then do not type body Delhi but not in NCR, then he must type government
parts as the keyword as this would get too much general universities + Delhi - NCR.
Computer Networks and the Internet 145

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

8.1.1 Monolithic Programming


E33 PROGRAMMING PARADIGMS
Programs written
A programming paradigm is a fundamental style of using monolithic ADB 10
programming that defines how the structure and basic —— ng poesteet BDB 20 Global data
elements of a computer program will be built. The suc as assembly
n SUM DB?
style of writing programs and the set of capabilities language and BASIC
and limitations that a particular programming language consist of global MOV AX, A
has depends on the programming paradigm it supports. << =e agro ADD AX.B Soporte!
While some programming languages strictly follow a code. The glo! ta ew
single paradigm, others may draw concepts from more can be accessed and | MOVSUM,AX | "imp
than one. The sweeping trend in the evolution of high- modified (knowingly or | JMP STOP instruction
level programming languages has resulted in a shift in mistakenly) from any
programming paradigm. These paradigms, in sequence of part of the program,
their application, can be classified as follows: thereby posing a serious
Monolithic programming: emphasizes
H on finding
finding a threat to its integrity. A Figure 8.1 Structure of a
solution sequential code is one monolithic program
in which all instructions
Procedural programming—lays stress on algorithms
Structured programming—focuses on modules are executed in the specified sequence, In order to change the
Object-oriented programming—emphasizes on classes sequenceof instructions, jump statements or "goto’ statements
and objects are used. Figure 8.1 shows the structure of a monolithic
Logic-oriented programming focuses on goals usually program. As the name suggests, monolithic programs have
expressed in predicate calculus just one program module as such programming languages
* Rule-oriented programming—makes use of ‘if-then- do not support the concept of subroutines, Therefore, all the
else’ rules for computation actions required to complete a particular task are embedded
* Constraint-oriented programming—autilizes invariant within the same application itself. This not only makes the
relationships to solve a problem size of the program large but also makes it difficult to debug
and maintain. For all these reasons, monolithic programming
Each of these paradigms has its own strengths language is used only for very small and simple applications
and weaknesses and no single paradigm can suit all where reusability ts not a concer.
applications. For example, for designing computation-
intensive problems, procedure-oriented programming 8.1.2 Procedural Programming
is preferred; for designing a knowledge base, rule-
based programming would be the best option; and for In procedural languages, a program is divided into
hypothesis derivation, logic-oriented programming is subroutines that can access global data. To avoid repetition
used, In this book, we will discuss only the first four of code, cach subroutine performs a well-defined task
paradigms A subroutine that needs the service provided by another
asi Computer Fundamentals and Programming in C

subroutine can call


that —_subroutine.
Therefore, with
‘jump’. “goto’, and
‘call’ instructions,
the sequence
of execution of
instructions can be
Figure 8.2 Structure of a altered. Figure 8.2
procedural program shows the structure
of a procedural Figure 8.3 Structured program
language. FORTRAN and COBOL are two popular
procedural programming languages. of structured programming. In addition to the techniques
of structured programming for writing modules, it also
Advantages focuses on structuring its data. In structured programming,
* The only goal is to write correct programs the program flow follows a simple sequence and usually
* Programs are easier to write as compared to monolithic avoids the use of ‘goto’ statements. Besides sequential
programming flow, structured programming also supports selection and
repetition as mentioned here.
Disadvantages * Selection allows for choosing any one of a number of
statements to execute, based on the current status of the
No concept of reusability program. Selection statements contain keywords such
Requires more time and effort to write programs as ‘if’, ‘then’, “end if’, or ‘switch’ that help to identify
Programs are difficult to maintain the order as a logical executable.
Global data is shared and therefore may get altered * In repetition, a selected statement remains active until
(mistakenly) the program reaches a point where there is a need for
some other action to take place. It includes keywords
8.1.3 Structured Programming such as ‘repeat’, ‘for’, or ‘do... until’, Essentially,
repetition instructs the program as to how long it needs
Structured programming, also referred to as modular to continue the function before requesting further
programming, was first suggested by mathematicians, instructions.
Corrado Bohm and Guiseppe Jacopini in 1966. It was
specifically designed to enforce a logical structure on the
program to make it more efficient and easier to understand Advantages
and modify. Structured programming was basically * The goal of structured programming is to write correct
defined to be used in large programs that require large programs that are easy to understand and change.
development team to develop different parts of the same * Modules enhance programmers’ productivity by
program. Structured programming cmploys a top-down allowing them to look at the big picture first and focus
approach in which the overall program structure is broken on details later.
down into separate modules. This allows the code to be + With modules, many programmers can work on a
loaded into memory more efficiently and also be reused single, large program, with each working on a different
in other programs. Modules are coded separately and module.
once 4 module is written and tested individually, it is then + Astructured program takes less time to be written than
integrated with other modules to form the overall program other programs. Modules or procedures written for one
structure (refer to Fig. 8.3). Structured programming is, program can be reused in other programs as well.
therefore, based on modularization which groups related * Each module performs a specific task.
statements together into modules, Modularization makes it + Each module has its own local data.
easier to write, debug, and understand the program. Ideally, + A structured program is easy to debug because each
modules should not be longer than a page. It is always easy procedure is specialized to perform just one task and
to understand a series of 10 single-page modules than a every procedure can be checked individually for the
single 10-page program. For large and complex programs, presence of any error. In striking contrast, unstructured
the overall program structure may further require the programs consist of asequence ofinstructions that are
need to break the modules into subsidiary pieces. This not grouped for specific tasks. Their logic is cluttered
process continues until an individual piece of code can with details and, therefore, difficult to follow.
be written easily. Almost every modem programming * Individual procedures are casy to change as well as
language similar to C, Pascal, etce., supports the concepts understand. In a structured program, every procedure
Designing Efficient Programs 151

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

Main program tomaintain thename andaddress listofthestudents

‘Add the |{Save the ity |{Save the Process ; Display


w mit Lee ay list Z — 7 se list oo
entry fist list list catries

Figure 8.5 Layered program structure

or flowcharts, The design phase, therefore, specifies how


(EB DESIGN AND IMPLEMENTATION the program/software will be built
OF EFFICIENT PROGRAMS Implementation In this phase, the designed algorithms
are converted into program code using any of the high-
The design anddevelopment ofcorrect,
level languages. The particular choice of language will
efficient, and maintainable programs
depend on the type of program, such as whether it is 4
depend on the approach adopted by
system or an application program. While C is preferred for
the programmer to perform various
writing system programs, Visual Basic might be preferred
activities that need to be performed
for writing an application program. The program codes are
during the development process. The tested by the programmer to ensure their correctness,
entire program or software (collection
This phase is also called construction or code generation
of programs) development process
phase as the code of the software is generated in this
is divided into a number of phases,
phase. While constructing the code, the development
where cach phase performs a well-
team checks whether the software is compatible with
defined task. Moreover, the output of
the available hardware and other software components
one phase provides the input for its
that were mentioned in the Requirements Specification
subsequent phase.
Document created in the first phase
The phases in the software
development life cycle (SDLC) Testing In this phase, all the modules are tested together to
process is shown in Figure 8.6. ensure that the overall system works well as a whole product
The phases in the SDLC process Although individual pieces of codes are already tested by the
can be summarized as follows programmers in the implementation phase, there is always a
Requirements analysis In this phase, chance for bugs to ercep into the program when the individual
the user's expectations are gathered modules are integrated to form the overall program structure.
to know why the program/software In this phase, the software is tested using a large number
has to be built. Then, all the gathered of varied inputs, also known as test data, to ensure that the
requirements are analysed to arrive at software is working as expected by the user's requirements
the scope or the objectiveofthe overall that were identified in the requirements analysis phase,
software product. The last activity Software deployment, training, and support Afier the
Figure 8.6 Phases in this phase includes documenting code is tested and the software or the program has been
in software every identified requirement of the approved by the users, it is installed or deployed in the
development life Sets in order to avoid any doubts or production environment. This is a crucial phase that is
cycle uncertainty regarding the functionality often ignored by most developers. Program designers
of the programs and developers spend a lot of time to create software
The functionality, capability, performance, and but if nobody in an organization knows how to use it or
¢ and software components are all fix up certain problems, then no one would like to use
it, Moreover, people are often resistant to change and
Design The requirements documented in the previous avoid venturing into an unfamiliar area, so as a part of
phase acts as an input to the design phase, In the design the deployment phase, it has become very crucial to have
phase, a plan of actions is made before the actual training classes for the users of the software.
development process can start. This plan will be followed Maintenance Maintenance and enhancements are
throughout the development process. Moreover, in the ongoing activities that are done to cope with newly
design phase, the core structure of the software/program discovered problems or new requirements. Such activities
is broken down into modules. The solution of the program may take a long time to complete as the requirement may
is then specified for cach module in the form ofalgorithms call for the addition of new code that does not fit the
Designing Efficient Programs 153

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

PSEUDOCODES In the preceding example, the variable x can cither be


equal or not equal to y. However, it cannot be both true
This section will deal with different tools, which are used and false. If the condition is true then the proc is
to design solution(s) of a given problem at hand. executed.
A decision statement can also be stated in the following
8.4.1 Algorithms manner:
The typical meaning of an algorithm is a formally defined IF condition
procedure for performing some calculation. If a procedure then process1
is formally defined, then it must be implemented using ELSE process2
some formal language, and such languages are known as
programming languages. The algorithm gives the logic of This form is commonly known as the if-else construct
the program, that is, a step-by-step description of how to Here, if the condition is truc then process1 is executed,
arrive at a solution. else process2 is executed. An algorithm to cheek the
In general terms, an algorithm provides a blueprint equality of two numbers is shown in Figure 8.8.
to writing a program to solve a particular problem. It is
considered to be an effective procedure for solving a problem
in a finite number of steps. That is, a well-defined algorithm Step 1: Input first number as A
Step 2: Input second number as 8
always provides an answer, and is guaranteed to terminate. Step 3: IFA«B
Algorithms are mainly used to achieve software reuse Print “Equal”
Once we have an idea or a blueprint of a solution, we can ELSE
implement it in any high-level language, such as C, C++, Print “Not equal”
Java, and so on, In order to qualify as an algorithm, a sequence [END of IF]
Step 4: End
of instructions must possess the following characteristics
* Be precise Figure 8.8 Algorithm to test the equality of two numbers
* Be unambiguous
Not even a single instruction must be repeated infinitely
* After the algorithm gets terminated, the desired result Repetition Repetition, which involves executing one or
must be obtained. more steps for a number of times, can be implemented using
constructs such as the while, do-while, and for loops.
These loops execute one or more steps until some condition
Control Structures Used In Algorithms
is true. Figure 8.9 shows an algorithm that prints the first 10
An algorithm he 4 finite number of steps and some steps natural numbers,
may involve decis jon-making and repetition. Broadly
speaking, an algorithm may employ three control
structures, namely, sequence, decision, and repetition.
Step 1: [initialize] Set I = 1, N= 10
Step 2: Repeat Steps 3 and 4 while I <* N
Step 3: Print I
Sequence Sequence means that cach step of the
Step4: SET T=I¢1
algorithm is executed in the specified order. An algorithm [END OF LOOP]
to add two numbers is given in Figure 8.7. This algorithm Step S: End
performs the steps in a purely sequential order.
Figure 8.9 Algorithm to print the first 10 natural numbers
Decision Decision statements are used when the outcome
of the process depends on some condition. For example,
if x = y, then print “EQUAL”. Hence, the general form Example 8.1
of the if construct can be given as follows: Write an algorithm for interchanging/swapping two
IF condition then process values.
1 54 Computer Fundamentals and Programming in C

Solution Step 3: IF M >= 60 and M< 75

Step 1: Input first number as A Print "A"


Step 2: Input second number as B
Step 4: IF M >= 50 and M < 60
Step 3: Set temp = A Print "B”
Step 4: Set A=B Step 5: IF M >= 40 and M < 50
Step 5: Set B = temp Print "Cc"
Step 6: Print A, B ELSE
Step 7: End Print "o"
[END OF IF)
— Step 6: End

Example 8.2 ——

Write an algorithm to find the larger of two numbers.


Example 8.5
Solution
Step 1: Input first number as A Write an algorithm to find the sum of first N natural numbers.
Step 2: Input second number as B Solution
Step 3: IFA>8
Print A Step 1: Input N
ELSE IFA< 8 Step 2: Set I= 1, sum* 0
Print B Step 3: Repeat Steps 4 and 5 while I <# N
ELSE Step 4: Set sum = sum + I
Step5: Set
Te I¢1
Print “The numbers are equal”
[END OF IF) [END OF LOOP]
: End Step 6: Print sum
Step 7: End

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

| Arrows & Decision symbol

[7] Pressing step) Comestr


Figure 8.10 Symbols of flowchart

their execution will be carried out in the order of their


appearance.
Input/Output symbols are represented using a
parallelogram and are used to get inputs from the users
or display the results to them.
* A conditional or decision symbol is represented using
a diamond, It is basically used to depict a Yes’No
question or a True/False test. The two symbols coming
out of it, one from the bottom point and the other
from the right point, corresponds to Yes or Truc, and
No or False, respectively, The arrows should always
be labelled. A decision symbol in a flowchart can have
more than two arrows, which indicates that a complex
decision is being taken
Labelled connectors are represented by an identifying
label inside a cirele and are used in complex or multi-
sheet diagrams to substitute for arrows. For each label,
the ‘outflow’ connector must have one or more ‘inflow’
connectors. A pair of identically labelled connectors is
used to indicate a continued flow when the use of lines
becomes confusing Example 8.7

Significance of Flowcharts Draw a flowchart to add two numbers,


Solution
A flowchart is a diagrammatic representation that
illustrates the sequence of steps that must be performed
to solve a problem, It is usually drawn in the carly
stages of formulating computer solutions. It facilitates
communication between programmers and users. Once
a flowchart is drawn, programmers can make users
understand the solution easily and clearly
Flowcharts are very important in the programming of
a problem as they help the programmers to understand
the logic of complicated and lengthy problems. Once a
flowchart is drawn, it becomes easy for the programmers to
write the program in any high-level language. Hence, the
flowchart has become a necessity for better documentation
of complex programs.
A flowchart follows the top-down approach in solving
problems.

Example 8.6

Draw a flowchart to calculate the sum of the first 10 natural


numbers. Draw a flowchart to calculate the salary of a daily wager.
156 Computer Fundamentals and Programming in C

Solution * They are also used for program documentation. They


are even more helpful in the case of complex programs.
* They act as a guide or blueprint for the programmers
to code the solution in any programming language.
They direct the programmers to go from the starting
Input the no_of_hrs, point of the program to the ending point without
pay_per_hr, and missing any step in between. This results in error-free
travel_allowance programs.
* They can be used to debug programs that have
error(s). They help the programmers to easily detect,
Calculate SALARY=(no_of_hrs = locate, and remove mistakes in the program in a
pay_per_hr) + travel_allowance systematic manner,

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

Example 8.10 2. Set fail to 0


3. Set no of students to 1
Write a pseudocode for calculating the price of a product 4. WHILE no of students < 10
after adding the sales tax to its original price. a. input the marks
Solution b. IF marks >= SO then
Set pass = pass +1
1. Read the price of the product ELSE
2. Read the sales tax rate Set fail = fail +1
3. Calculate sales tax = price of the item x; ENDIF
sales tax rate ENDWHILE
4. Calculate total price = price of the product 5. Display pass
+ sales tax 6. Display fail
5. Print total price 7. End
6. End Variables: pass, fail, no of students, marks
Variables: price of the item, sales tax rate,
sales tax, total price

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

Let us take a problem, collect its requirement, design the

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

grade = Test Case 1D |Input | Expected Output | Actual Output


else
grade = ‘0’; 9 50 8 8
printf("\n GRADE = Xe", grade); 10 60 A A
} 1 7 ° te]
12 100 ° oO
Test Case ID|Input | Expected Output | Actual Output 13 0 Do L?)
| 1 ~12 Not Possible Not Possible
2 112 Not Possible Not Possible Test The above program is then tested with different test
data to ensure that the program gives correct output for
3 32 D D relevant and possible inputs. The test cases are shown in
| 4 46 c c the table given below
= oe 54 8 8 Note in the above table, we have identified test cases
for the following,
| 6 68 A A
ea 5 1 ° C) 1. “Not Possible” Combinations
A middle value from cach range
\ 8 40 c c 3. Boundary values for each range

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

| Programming paradigm A fundamental style of Structured programming Structured programming


Programming that defines how the structure and basic is a programming approach that employs a top-down
elements of a computer program will be built approach in such a way that the overall program structure
Pseudocode Pseudocode is a compact and informal high- is broken down into separate modules. This allows the
level description of an algorithm that uses the structural code to be loaded into the memory more efficiently and
conventions of a programming language. also be reused in other programs.
Runtime errors These are errors that occur when the Testing An activity performed to verify the correct
program is being executed. behaviour of a program. It is specifically carried out with
the intent to find errors.

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

Structure, Union, and Enumerated


Data Type

Files
Preprocessor Directives

Introduction to Data Structures


are
___ Introduction to C

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

89 intrRopuction of these languages, C also supports the concept of data


types. Since UNIX operating system was also developed at
The programming language C was developed in the early Bell Laboratories along with C language, C and UNIX are
1970s by Dennis Ritchie at Bell Laboratories to be used strongly associated with each other
by the UNIX operating system, It was named *C* because For many years, C was mainly used in academic
many of its features were derived from an ecarlicr language institutions, but with the release of different C compilers
called *B’. Although C was designed for implementing for commercial use and popularity of UNEX, C was widely
system software, it was later on widely used for developing accepted by computer professionals.
portable application software. C (also known as Traditional C) was documented and
C is one of the most popular programming languages. popularized in the book The C Programming Language by
It is being used on several different software platforms. Brian W. Kernighan and Dennis Ritchie in 1978. This book
In a nutshell, there are a few computer architectures for was so popular that the language came to be known as ‘K &
which a C compiler does not exist RC’. The tremendous growth of C language resulted in the
It is a good idea to learn C because few other development of different versions of the language that were
programming languages such as C++ and Java are also similar but incompatible with each other, Therefore, in the
based on C which means you will be able to lear them year 1983, the American National Standards Institute (ANSI)
more easily in the future. started working on defining the standard for C. This standard
was approved in December 1989 and came to be known as
ANSI C. In 1990, the International Standards Organization
9.1.1 Background (ISO) adopted the ANSI standard. This version of Ccame to
Like many other modern languages, C is derived from be known as C89. In 1995, some minor changes were made to
ALGOL (the first language to use a block structure). C89; the new modified version was known as C95, Figure 9.1
Although ALGOL was not accepted widely in the shows the taxonomy of C language, During 1990s, C++
United States, it was widely used in Europe. ALGOL's and Java programming languages became popular among
introduction in the 1960s led the way for the development the users so the Standardization Committee of C felt that a
of structured programming concepts. few features of C++/Java if added to C would enhance its
Before C, several other programming languages were usefulness. So, in 1999 when some significant changes were
developed. For example, in 1967 Martin Richards developed made to C95, the modified version came to be known as C99.
a language called BCPL (Basic Combined Programming Some of the changes made in the C99 version are as follows:
Language). BCPL was basically a type-less (had no concept + Extension to the character types, so that they can support
of data types) language which facilitated direct access of even non-English characters
memory. This made it useful for system programmers. Then Boolean data type
in 1970, Ken Thompson developed a language called B, + Extension to the integer data type
which was used to develop the first version of UNIX. C was * Inclusion of type definitions in the for statement
developed by Dennis Ritchie in 1972 that took concepts * Inclusion of imaginary and complex types
from ALGOL, BCPL, and B. In addition to the concepts * Addition of / , better known as C++ style line comment
166 Computer Fundamentals and Programming in C

ALGOL 0-15000 using BASIC would take 50 seconds whereas


a C program would do the same in just | second.
Facilitates low level (bitwise) programming.
* Supports pointers to refer computer memory, arrays,
structures, and functions.
* Core language. C is a core language as many other
programming languages (like C++, Java, Perl, etc.) are
based on C. If you know C, learning other computer
languages becomes much casicr,
* Cis a portable language, i.c., a C program written for
one computer can be run on another computer with little
or no modification.
+ Cis an extensible language as it enables the user to add
his own functions to the C library,
Cis often treated as the second best language for any given
programming task. While the best language depends
on the particular task to be performed, the second best
language, on the other hand, will always be C.

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.

ED wRitine THE FIRST C PROGRAM


To write a C program, we first need to write the code. For
this, open a text editor. If you are a Windows user you may
use Notepad and if you prefer working on UNIX/Linux
you can use emacs or vi, Once the text editor is opened on
your screen, type the following statements
®include <stdio.h>
Function 1()
int main()
{ {
Local declarations printf("\n Welcome to the world of C ");
Statements return 0;
}
Output
Welcome to the world of C

Function N() #include <stdio.h>


{ This is a preprocessor command that comes as the first
Local declarations statement in our code. All preprocessor commands start
with symbol hash (#). The #include statement tells the
‘Statements
compiler to include the standard inpuVoutput library or
} header file (stdio.h) in the program. This file has some
in-built functions. By simply including this file in our code
Figure 9.2 Structure of a C program
we can use these functions directly. The standard input/
In this section we will omit the global declaration part output header file contains functions for input and output
and will revisit it in the chapter on Functions. of data such as reading values from the keyboard and
A C program contains one or more functions, where printing the results on the screen.
a function is defined as a group of C statements that are
int main()
executed together. The statements in a C function are
written in a logical sequence to perform a specific task Every C program contains a main() function which is the
The main() function is the most important function and is starting point of the program. int is the return value of the
a part of every C program. The execution of a C program main() function. After all the statements in the program
begins at this function. have been written, the last
All functions (including main()) are divided into two Tip: statement of the program will
parts—the declaration section and the statement section. if you do not place return an integer value to the
The declaration section precedes the statement section @ parenthesis after operating system, The concepts
and is used to describe the data that will be used in the main, a compiler will be clear tous when we read
function. Note that data declared within a function are error will be the chapter on Functions. So
known as local declaration as that data will be visible only generated. even if you do not understand
within that function. Stated in other terms, the life-time of certain things, do not worry
the data will be only till the function ends, The statement {} The two curly brackets are used to group all the related
section in a function contains the code that manipulates statements of the main function. All the statements between
the data to perform a specified task. the braces form the function body. The function body
From the structure given above we can conclude that a contains a set of instructions to perform the given task,
C program can have any number of functions depending
printf("\n Welcome to the
world of C ");
Programmers can choose any name for functions. It is
The printf function is defined in the stdio.h file and is
not mandatory
to write Function1, Function2,
etc., but
with an exception that every program must contain one
used to print text on the screen, The message that has to be
function that has its name asmain().
displayed on the screen is enclosed within double quotes
and put inside brackets.
168 Computer Fundamentals and Programming in C

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

| Audible signal v Question mark


| ow Backspace “ Back slash
The printf and return statements have been indented
| \ Tab v Single quote or moved away from the left side. This is done to make
w Newline rv Double quote the code more readable.

w Vertical tab » Octal constant


Vv New page\ A Hexadecimal
2D FILes USED IN AC PROGRAM
Clear screen constant
Every C program has four kinds of files associated with it
7 Carriage (Figure 9.3). These include:
return

Files in a C program

Escape sequences are actually non-printing control


characters that begin with a backslash (\). Source Header Object Executable
file file file file

return 0; Figure 9.3 Files in a C program


This is a return command that is used to return the value 0 9.4.1 Source Code Files
to the operating system to give an indication that there
were no errors during the execution of the program The source code file contains the source code of the
program. The file extension of any C source code file is
*.¢'. This file contains C source code that defines the
main function and maybe other functions. The main()
Every statement in the main function ends with a semi- function is the starting point of execution when you
colon (;). successfully compile and run the program. A C program
in general may include even other source code files (with
Now that you have written all the statements using the file extension.c)
the text editor, save the text file as first.c. If you are a
Windows user then open the command prompt by clicking 9.4.2 Header Files
Start-<Run and typing ‘command’ and clicking Ok.
When working with large projects, it is often desirable to
Using the command prompt, change to the directory in separate out certain subroutines from the main() function
which you had saved your file and then type: of the program. There also may be a case that the same
C:\<te first.c subroutine has to be used in different programs. In the
latter case, one option is to copy the code of the desired
In case you are working on UNIX/Linux operating
subroutine from one program to another. But copying the
system, then exit the text editor and type
code is often tedious as well as error prone and makes
$cc first.c -ofirst maintainability more difficult
Introduction to C 169
So, another option is to make subroutines and store them compact binary code of the function definitions. Linker
in a different file known as header file. The advantages of uses these object files to produce an executable file (.exe
header files can be realized in the following cases file) by combining the object files together. Object files
* The programmer wants to use the same subroutines in have a *.o” extension, although some operating systems
different programs. For this. he simply has to compile including Windows and MS-DOS have a ‘.obj’ extension
the source code of the subroutines once, and then link to for the object file
the resulting object file in any other program in which
the functionalities of these subroutines are required. 9.4.4 Binary Executable Files
* The programmer wants to change or add subroutines, The binary executable file is generated by the linker. The
and have those changes reflected in all the other linker links the various object files to produce a binary
programs. In this case, he just file that can be directly executed. On Windows operating
Programming Tip: needs to change the source file system, the executable files have a ‘.exe’ extension.
Missing the inclusion for the subroutines, recompile
Ofappropriate header = its source code, and then re-
files ina C program link programs that use them. ©) COMPILING AND EXECUTING C
willgenerate anerror = This way time can be saved
Such @ program may as compared to editing the PROGRAMS
compile butthelinker subroutines in every individual C is a compiled language. So once a C program is written,
will give an error program that uses them
you must run it through a C compiler that can create an
inp Thus, we sce that using a executable file to be run by the computer, While the C
functions used inthe header file ‘produces the same program is human-readable, the executable file, on the
program. results as copying the header other hand, is a machine-readable file available in an
file into cach source file that executable form.
needs it, Also when a header file is included, the related The mechanical part of running a C program begins
declarations appear in only one place. If in future we with one or more program source files, and ends with an
need to modify the subroutines, we just need to make executable file, which can be run on a computer.
the changes in one place, and programs that include the The programming process starts with creating 4
header file will automatically use the new version when source file that consists of the statements of the program
recompiled later, There is no need to find and change all written in C language. This source file usually contains
the copies of the subroutine that has to be changed. ASCII characters and can be produced with a text editor,
Conventionally, header files names ends with a ‘.h’ such as Windows notepad, or in an Integrated Design
extension and names can use only letters, digits, dashes, Environment
and underscores. Although some standard header files are The source file is then processed by a special program
automatically available to C programmers, in addition to called a compiler,
those header files, the programmer may have his own user-
defined header files.
Standard Header Files In the program that we have Every programming language has its own compiler.
written till now, we used printf() function that has not
been written by us. We do not know the details of how this The compiler translates the source code into an object
function works. Such functions that are provided by all C code. The object code contains the machine instructions
compilers are included in standard header files. Examples
for the CPU, and calls to the operating system API
of these standard header files include: (Application Programming Interface)
* string.h for string handling functions However, even the object file is not an executable file.
* stdlib.h for some miscellancous functions Therefore, in the next step, the object file is processed with
* stdio.h for standardized input and output functions another special program called a linker. While there is a
* math.h for mathematical functions different compiler for every individual language, the same
* alloc.h for dynamic memory allocation linker is used for object files regardless of the original
* conio.h for clearing the screen language in which the new program was written, The
All the header files are referenced at the start of the source output of the linker is an executable or runnable file. The
code file that uses one or more functions from that file. process is shown in Figure 9.4
In C language programs, there are two kinds of source
files. In addition to the main (.c) source file, which
9.4.3 Object Files contains executable statements there are also header (.n)
Object files are generated by the compiler as a result source files. Since all input and output in C programs is
of processing the source code file. Object files contain done through library functions, every C program therefore
170 Computer Fundamentals and Programming in C

Source Object ‘ Executable E83 usinc comments


rat Compiler fa Linker ‘is
Many a time the meaning or the purpose of the program
code is not clear to the reader. Therefore, it is a good
Library
files
programming practice to place some comments in the code
to help the reader understand the code clearly. Comments
Figure 9.4 Overview of compilation and execution process are just a way of explaining what a program does. It is
merely an internal program documentation. The compiler
ignores the comments when forming the object file. This
uses standard header files. These header files should be means that the comments are non-executable statements.
written as part of the source code for modular C programs. C supports two types of comments.
The compilation process shown in Figure 9.5 is done
in two steps, In the first step, the preprocessor program * //isused to comment a single statement. This is known as
reads the source file as text, and produces another text a line comment. A line comment can be placed
file as output. Source code lines which begin with on the line and it does not require to be specif ally ended
the # symbol are actually not written in C but in the as the end of the line automatically ends the line.
preprocessor language. The output of the preprocessor * /*isusedtocommentmultiple
is a text file which docs not contain any preprocessor Programming ay statements. A /* is ended with
statements. This file is ready to be processed by the Not putting the +/ */ and all statements that lie
compiler. The linker combines the object file with library ‘ater thetermination within these char are
routines (supplied with the compiler) to produce the final ofthe block comment commented. This type of
executable file. is acompller error. comment is known as block
In modular programming, the source code is divided comment,
into two or more source files. All these source files are Note that commented statements are not executed by
compiled separately thereby producing multiple object the compiler. Rather, they are ignored by the compiler as
files, These object files are combined by the linker to they are simply added in the program to make the code
produce an executable file (Figure 9.6). understandable by the programmer to other people who

Source Pre- Object Executable


file processor coe files Unker files

Library Library
tiles files

Figure 9.5 Preprocessing before compilation

Source Pre- Object


file processor ris files

Library Library 5 Executable


files files abe files

Source Pre- Object


file processor conn files

Library
les

Figure 9.6 Modular programming—the complete compilation and execution process


Introduction to C 171

read it. It is a good habit to always put a comment at the


top of a program that tells you what the program does. GED CHARACTER SET INC
This will help in defining the usage of the program the
moment someone opens it
Like in natural languages, computer languages also use
Commented statements can be used anywhere in the a character set that defines the fundamental units used to
program. You can also use comments in between your represent information. In C, a character means any letter
code to explain a piece of code that is a bit complicated. from English alphabet, a digit or a special symbol used to
represent information. These characters when combined
The code given below shows the way in which we can
make use of comments in our first program. together form tokens that act as basic building blocks
of a C program. The character set of C can therefore be
/* Author: Reema Thareja given as
Description: To print ‘welcome to the a. English alphabet: Include both lower case (a - z) as
world of C’ on the screen */
well as upper case (A - 2) letters
#include <stdio.h>
Digits: Include numerical digits from 0 to 9
int main() c. Special characters: Include symbols such as ~, @, %,
{ 85 By Mle bs Se ee or te or HD GD ND
printf("\n Welcome to the world of C *
dato Le Dy fo "2 Pe oe Ly |
// prints message
d. White space characters: These characters are used to
return 0; // returns a value 0 to the
print a blank space on the screen. They are shown in
operating system
Figure 9.8,
} ¢. Escape sequence: Escape sequences have already been
Output discussed in Section 2.3
Welcome to the world of C

Since comments are not executed by the compiler, they


do not affect the execution speed and the size of the compiled
program, Therefore, using comments liberally in your
programs aids other users in understanding the operations
of the program as well as in debugging and testing

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

Table 9.2 Keywords in C language


Strings
auto break «case = char = const continue default
double cise enum extern float for goto
Special characters
int long register rem short — signed —xizeof
Operators struct switch typedef union unsigned void volatile
do if static = while
Figure 9.7 Tokens inc
172 Computer Fundamentals and Programming in C

CRD iventiriers CREB sasic DATA TYPES INC


Identifiers, as the name suggests, help us to identify data C language provides very few basic data types. Table 9.3
and other objects in the program. Identifiers are basically lists the basic data types. their size, range, and usage for
the names given to program clements such as variables, aC programmer on a 16-bit computer. In addition to this,
arrays, and functions. Identifiers may consist of sequence we also have variants of int and float data types.
of letters, numerals, or underscores.
__Table 9.3 Basic data types in C_

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

|unsigned int 2 0 65535


Convert the floating point number 5.32 into an IEEE
|signed int 2 -32768 to 32767 normalized form.
| short int 2 32768 10 32767 5|R 0.32 2=0.64/0 ‘Writethe |

unsigned short 2 0 65535 0.64 «


0.28«2 =0,56|0
1.28) 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

. the preprocessor reformats the program to be


compiled by the compiler, it replaces each defined name
(like pi, service_tax) in the source program with its
corresponding value. Hence, it just works like the Find-
and-Replace command available in a text editor.
Let us take a look at some rules that need to be applied
to a #define statement which defines a constant.
Rule 1: Constant names are usually written in capital Figure 9.12 Input and output streams in C
letters to visually distinguish them from other variable
names which are normally written in lower case characters.
Note that this is just a convention and not a rule, 9.14.2 Formatting Input/Output
Rule 2: No blank spaces are permitted between the # C language supports two formatting functions printf and
symbol and define keyword. scanf. printf is used to convert data stored in the program
into a text stream for output to the monitor, and scanf is
Rule 3: Blank space must be used between define and used to convert the text stream coming from the keyboard
constant name and between constant name and constant to data values and stores them in program variables. In this
value, section, we will discuss these functions,
Rule 4: #define is a pre-processor compiler directive and not
a statement. Therefore, it does not end with a semi-colon. Background
The most fundamental operation ina C program is to accept
INPUT/OUTPUT STATEMENTS IN C input values from a standard input device (keyboard) and
output the data produced by the program to a standard
Before performing input and output in C programs, output device (monitor). So far we had been assigning
let us first understand the concept from scratch. This values to variables using the assignment operator =. For
section deals with the basic understanding of the streams example,
involved in accepting input and printing output in C int a = 3;
programs.
But what if we want to assign value to variable that is
9.14.1 Streams inputted by the user at run-time? This is done by using the
scanf function that reads data from the keyboard. Similarly,
A stream is the source of data as well as the destination of for outputting results of the program, printf function is
data, Streams are associated with a physical device such used that sends results to a terminal, Like printf and scanf,
as a monitor or a file stored on the secondary memory. C there are different functions in C that can carry out the inpul/
uses two forms of streams—text and binary, as shown in output operations. These functions are collectively known
Figure 9.11, as Standard Input/Output Library. A program that uses
standard input/output functions must contain the following
statement at the beginning of the program:
Sueams ina
C Program #include <stdio.h>

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

Conversion specification Control characters Textual data

Data value’s Data value’s Specific format


type size information

Figure 9.13 printf() function in C


The syntax of printf function can be given as Note that when data is shorter than the specified width
then by default the data is right justified. To left justify the
printf ("control string", variable list);
data use minus sign (—) in the flags ficld.
The function accepts two parameters control string When the data value to be printed is smaller than the
and variable list, The control string may also contain the width specified, then padding is used to fill the unused
text to be printed like instructions to the user, captions, spaces, By default, the data is padded with blank spaces.
identifiers, or any other text to make the output readable. If zero is used in the flag field then the data is padded
In some printf statements you may find only a text with zeros, One thing to remember here is that zero flag is
string that has to be displayed on screen (as seen in the ignored when used with left justification because adding
first program in this chapter). The contro! characters can zeros after a number changes its value.
also be included in the printf statement. These control
Width is an optional argument which specifies the
characters include \n, \t, \r, \a, ete minimum number of positions in the output. If data needs
The parameter control string in the printf() function
more space than specified, then printf overrides the
is nothing but a C string that contains the text that has
width specified by the user. However, if the number of
to be written on to the standard output device. After the output characters is smaller than the specified width, then
control string, the function can have as many additional the output would be right justified with blank spaces to
arguments as specified in the control string
the left. Width is a very important field especially when
Note that there must be enough arguments, otherwise you have to align output in columns, However, if the user
the result will be completely unpredictable. However, if
does not mention any width then the output will take just
by mistake you specify more number of arguments, the
enough room for data.
excess arguments will simply be ignored, The prototype
of the control string can be given as follows. Precision is an optional argument which specifies the
maximum number of characters to print
%[flags}(width][.precision][length modifier)
type specifier * For integer specifiers (d, 4, 0, u, x, X): precision
flag specifies the minimum number of digits to be
Each control string must begin with a % sign. The written. However, if the value to be written is shorter
character specific: how the next variable in the list of than this number, the result is padded with leading zeros,
variables has to be printed. After % sign follows: Otherwise, if the value is longer, it is not truncated.
Flags is an optional argument which specifies output For character strings, precision specifies the maximum
justification such as numerical sign, trailing zeros or octal, number of characters to be printed.
decimal, or hexadecimal prefixes. Table 9.5 shows the For floating point numbers, the precision flag specifies
different types of flags with their description. the number of decimal places to be printed.
Its format can be given as .m, where m specifies the
Table 9.5 Flags in printf() function
number of decimal digits. When no precision modifier is
Flags | Description specified, printf prints six decimal positions.
| = Leftjustifywithin thegiven field width When both width and precision fields are used, width
| + Display thedata withitsnumeric sign (either + of—) must be large enough to contain the integral value of the
number, the decimal point and the number of digits after
Used to provide additional specifiers like o, x, X.0,Ox,
or OX for octal and hexadecimal values, respectively, for
the decimal point. Therefore, a conversion specification
values different
than zero %7.3f means print a floating point value of maximum 7
digits where 3 digits are allotted for the digits after the
0 "The number isleft-padded with zeros (0) instead ofspaces
decimal point
178 Computer Fundamentals and Programming in C

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!

|Note | 2. Write a program to demonstrate the ¢ of printf


In the print# statement, ‘\n’, iscalled the newline statement to print values of variables of different data
character and is used to print the succeeding text on types.
the new line. The following output will be generated on #include <stdio.h>
execution of the print#() function. int main()
{
// Declare and initialize variables
Enter the values int num = 7;
2 3456.443 a abcde 24.321E-2 1 12345678 float amt = 123.45;
num = 2 char code = ‘A’;
fnum = 3456.44 double pi = 3.1415926536;
chea long int population_of
str = abcde india = 10000000000;
dnum * 0.24321 char msg{] = "Hi";
snum * 1
lnum = 12345678 // Print the values of variables
Remember one thing that scanf terminates as soon as printf("\n NUM = Xd \n AMT = Xf \n CODE
it encounters a white space character so if you enter the = %c \n PI = Xe \n POPULATION OF INDIA
string as abe def, then only abc is assigned to str. = ld \n MESSAGE = Xs", num, amt, code,
pi, population_of_india, msg);
1. Find the output of the following program. return 0;
#include <stdio.h> }
int main()
Output
{
int a, b; NUM = 7
printf("\n Enter two four digit numbers : AMT = 123.450000
scanf("%2d %4d", &a, &b); CODE = A
printf("\n The two numbers are : %d and PI = 3.141590e+00
Xd", a, b); POPULATION OF INDIA = 10000000000
return 0; MESSAGE = Hi
} 3. Write a program to demonstrate the use of printf and
Output scanf statements to read and print values of variables
Enter two four digit numbers : 1234 5678 of different data types.
The two numbers are : 12 and 34 #include <stdio.h>
int main()
Here, variable a is assigned {
Programming
Tip:
Using an incorrect value 12 because it is specified int num;
specifier for the data as %2d, so it will accept only float amt;
type being read or the first two digits. The rest of char code;
Written willgenerate the number will be assigned double pi;
a run-time error, to b, The value 5678 that is long int population_of_india;
unread will be assigned to the char msg[10};
first variable in the next call to the scanf function.
printf("\n Enter the value of num; “);
scanf("%d", &num);
The %n specifier isused to assign the number of characters
printf("\n Enter the value of amt ; ");
scanf("%#", Bamt);
read till the point at which the %n is encountered to
printf("\n Enter the value of pi : ");
the variable pointed to by the corresponding argument.
scanf("Xe", &pi);
The following code fragment illustratesitsuse.
printf("\n Enter the population of
int count; India : “)
printf("Hello %n World!", &count); scanf("Xld", &population_of_india);
printf("%d", count); printf("\n Enter the value of code : ");
scanf(“%c", &code);
The output would be—Hello World! 6 because 6 isthe printf("\n Enter the message : “);
number of characters read before the Xn modifier. scanf("%s", msg);
sz Computer Fundamentals and Programming in C

printf("\n NUM = Xd \n AMT = ZF \n PI = Xe scanf("%d %d", &x1, &y1);


\n POPULATION OF INDIA = %ld \n CODE = printf("\n Enter the x and y coordinates of
%c \n MESSAGE = %s", num, amt, pi, the second point :");
population_of_india, code, msg); scanf("Xd 4d", &x2, &y2);
return 0;
} /* sqrt and pow are mathematical functions
Output defined in math.h header file */
distance = sart(pow((x2-x1), 2)
Enter the value of num : 5
+pow((y2-y1), 2));
Enter the value of amt : 123.45 printf("\n Distance = %f", distance);
Enter the value of pi : 3.14159
return 0;
Enter the population of India : 12345
}
Enter the value of code : c
Enter the message : Hello Output
NUM = 5 Enter the x and y coordinates of the first
AMT = 123.450000 point : 25
PI = 3,141590e+00 Enter the x and y coordinates of the second
POPULATION OF INDIA = 12345 point : 37
CODE = Distance = 2.236068
MESSAGE = Hello
4, Write a program to calculate the area of a triangle using 9.14.6 Detecting Errors During Data Input
Hero's formula.
When the scanf function completes reading all the data
#include <stdio.h>
values, it returns the numberof values that are successfully
#include <conio.h>
read. This return value can be used to determine whether
#include <math.h>
there was any error while reading the input. For example,
int main()
the statement,
{
float a, b, c, area, S; scanf("Xd %f Xc", Ba, &b, &c);
printf("\n Enter the length of the three
will return 3 if the user enters, say,
sides of the triangle : ");
scanf("Xf Xf Xf", Ba, Bb, &c); 12 12.34 A
S=(a¢b-¢c)/2;
It will return 1 if the user enters erroneous data like
/* sqet is a mathematical function defined 12 ABC 12.34
in math.h header file */
This is because a string was entered while the user was
area = sqrt(S*(S-a)*(S-b)*(S-c));
expecting a floating point value. So, the scanf function
printf("\n Area = Xf", area);
reads only first data value correctly and then terminates as
return 0;
soon as it encounters a mismatch between the type of data
} expected and the type of data entered.
Output
Enter the length of the three sides of the OPERATORS IN C
triangle : 12 16 20
Area = 96 An operator is a symbol that specifies the mathematical,
§. Write a program to calculate the distance between two logical, orrelational operation tobe performed. C language
points. supports different types of operators, which can be used with
#include <stdio.h>
variables and constants to form expressions. These operators
can be categorized into the following major groups:
#include <conio.h>
#include <math.h> + Arithmetic operators
* Relational operators
int main() + Equality operators
{ + Logical operators
int x1, x2, yl, y2; + Unary operators
float distance; * Conditional operators
printf("\n Enter the x and y coordinates of + Bitwise operators
the first point : “); + Assignment operators
Introduction to C 183

+ Comma operator result is always rounded-off by ignoring the remainder


* sizeof operator Therefore,
In this section, we will discuss all these operators. 9/4=2 and -9/4 = -3

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

printf("\n Xd - Xd = Xd", numl, num2, sub_


res); Operator Meaning
printf("\n Xd x Xd = Xd", numl, num2, mul_res);
printf("\n Xd / Xd = Xd (Integer Division)", < Less than
numl, num2, idiv_res);
> Greater than
printf("\n Xd XX Xd = %d (Moduluo Division)",
numl, num2, modiv_res); <= Less than ofequalto 100 <= 100 gives |
printf("\n Xd / Xd = %.2f (Normal Division)", cd Greater
than equal to 50 >= 100 gives0
fnuml, num2, fdiv_res);
return 0;
} number, Characters are considered valid operands since
they are represented by numeric values in the computer
Output
system. So, if we say, ‘A’ < ‘8’, where Ais 65 and B is 66
Enter the first number : 9 then the result would be 1 as 65 < 66.
Enter the second number : 7 When arithmetic expressions are used on cither side of
947 = 16 a relational operator, then first the arithmetic expression
9-782 will be evaluated and then the result will be compared
9*7 = 63 This is because arithmetic operators have a higher priority
9 / 7 = 1 (Integer Division) over relational operators.
9% 7 = 2 (Moduluo Division) However, relational operators should not be used for
9 / 7 = 1.29 (Normal Division) comparing strings as this will result in comparing the
address of the string and not their contents. You must
7. Write a program to subtract two long integers be wondering why so? The answer to this question will
tinclude <stdio.h> be clear to you in the later chapters. A few examples of
#include <conio.h> relational operators are as follows:
int main()
{ If x=1, ye2, and2 = 3, then
long int numi= 1234567, num2, diff-0;
clrser(); Expressions that evaluate to | Expressions that evaluate to
printf("\n Enter the number: “); TRUE FALSE
scanf("%1d", &num2);
Note that these expressions Note that these expressions
are true because their value is are false because their value
diff = num1 ~ num2; not zero. is zero,
printf("\n Difference = Xld", diff);
return 0; (x) (x - 1)
} (x + y) (12)
(z * 9) (0 * y)
Output (z2+10-5* x) (y == 1)
Enter the number: 1234
(z- x+y) (y % 2)
Difference = 1233333

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

printf("\n Xd <= Xd = Xd", x, y, x<=y); For example,


return 0; (a <b) 88 (b > c)
}
Output
The expression to the left is (a < b) and that on the
right is (b > c). The whole expression is true only if
10< 20-1 both expressions are true, i.c., if b is greater than both
10 == 20=0 aand
10 l= 20=1
10> 20-0 Logical OR
10 >= 20 = 0
10 <= 20=1 Logical OR returns a false value if both the operands are
false. Otherwise it returns a true value. The truth table of
logical OR operator is given in Table 9.12
9.15.3 Equality Operators
C language supports two kinds of equality operators to Table 9.12 Truth table of logical OR
compare their operands for strict equality or inequality A B | ANB
They are equal to (==) and not equal to (1«) operators. 0 0 0
The equality operators have lower precedence than the o 1 1
relational operators. 1 0 1
The equal-to operator (==) returns true (1) if operands
I 1 1
on both the sides of the operator have the same value;
otherwise, it returns false (0). On the contrary, the not-
equal-to operator (!*) returns teue(1) if the operands For example,
do not have the same value; else it returns false (0). (a <b) |] (b> c)
Table 9.10 summarizes equality operators.
The expression to the left is (a < b) and that on the
Table 9.10 Equality operators right is (b > c). The whole expression is true if either b is
Operator Meaning greater than a of b is greater thane or b is greater than
both a and c.
aS Retums | if both operands are equal, 0 otherwise

Returns | if operands do not have the same value, Logical NOT


O otherwise The logical NOT operator takes a single expression and
negates the value of the expression. That is, logical NOT
9.15.4 Logical Operators produces a 0 if the expression evaluates to a non-zero value
and produces a1 ifthe expression produces a zero, In other
C language supports three logical operators—logical
AND (88), logical OR (||), and logical NOT (1). As in words, it just reverses the value of the expression. The truth
case of arithmetic expressions, the logical expressions are
table of logical NOT operator is given in Table 9.13
evaluated from left to right
Table 9.13 Truth table of Logical NOT
Logical AND A 1A

Logical AND operator is a binary operator, which 0 1


simultaneously evaluates two values or relational ex- i 0
pressions. If both the operands are true, then the whole
expression evaluates to true. If both or one of the operands
is false, then the whole expression evaluates to false. The For example,
truth table of logical AND operator is given in Table 9.11 int a = 10, b;
b= la;
Table 9.11 Truth table of logical AND
Now the value of b = 0. This is because value of a =
A B A&&B
10. !a = 0. The value of !a is assigned to b, hence, the
0 0 0 result
Logical expressions operate in a short cut fashion and
0 1 0
the evaluation is stopped when it is known for sure what
1 0 0 the final outcome would be. For example, in a logical
expression involving logical AND, if the first operand is
1 1 1
false, then the second operand is not evaluated as it is for
186 Computer Fundamentals and Programming in C

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**;

Unary Minus The same principle applies to unary decrement


operators. The unary operators have a higher precedence
Unary minus (—) operator is strikingly different from the than the binary operators. If in an expression we have more
binary arithmetic operator that operates on two operands than one unary operator then unlike arithmetic operators,
and subtracts the second operand from the first operand. they are evaluated from right to left.
When an operand is preceded by a minus sign, the unary When applying the increment or decrement operator,
operator negates its value. For example, if a number is the operand must be a variable. This operator can never be
positive then it becomes negative when preceded with a applied to a constant or an expression.
unary minus operator. Similarly, if the number is negative,
it becomes positive after applying the unary minus
operator, For example, When postfix ++ or ~~ isused with a variable in an
int a, b = 10; expression, then the expression is evaluated first using
a= -(b)5 the original value of the variable and then the variable is
incremented or decremented by one.
The result of this expression is a « -10 because variable
Similarly, when prefix ++ or ~~ is used with a variable
b has a positive value. After applying unary minus operator
in an expression, then the variable isfirst incrementedor
(-) on the operand b, the value becomes —10, which
decremented and then the expression is evaluated using
indicates it as a negative value.
the new value of the variable.
Increment Operator (++) and Decrement
Operator (- -) 9. Write a program to illustrate the use of unary prefix
increment and decrement operators.
The increment operator is a unary operator that increases #include <stdio.h>
the value of its operand by 1. Similarly, the decrement int main()
operator decreases the value of its operand by 1. For {
example, --x is equivalent to writing x = x - 1 int num = 3;
The increment/decrement operators have two variants // Using unary prefix increment operator
prefix and postfix, In a prefix expression (++x or --x), printf("\n The value of num = Xd", num);
the operator is applied before an operand is fetched for printf("\n The value of ++num = Xd", ++num);
computation and, thus, the altered value is used for the printf("\n The new value of num = %d", num);
computation of the expression in which it occurs. On the
// Using unary prefix decrement operator
contrary, in a postfix expression (x++ or x--) an operator
is applied after an operand is fetched for computation. printf("\n\n The value of num = Xd", num);
Introduction toC | (187
printf("\n The value of --num = %d", --num); Hence. conditional operator is used in certain situations,
printf("\n The new value of num = Xd", num); replacing if-else condition phrases. Conditional operator
return 0; makes the program code more compact, more readable,
} and safer to use, as it is casier to check any error (if
Output present) in one single line itself. Conditional operator is
also known as ternary operator as it is neither a unary nor
The value of num = 3
a binary operator, it takes three operands.
The value of ++num = 4
An expression using conditional operator can be
The new value of num = 4 used as an operand of another conditional operation
The value of num = 4 That means C allows you to have nested conditional
The value of --num = 3 expressions, Consider the expression given below which
The new value of num = 3 illustrates this concept
int a= 5, b = 3, c= 7, small;
10. Write a program to illustrate the use of unary postfix small=(acb?(acc?a:ic):
increment and decrement operators. (bec? b: c));
#include <stdio.h>
int main() 11. Write a program to find the largest of three numbers
{ using ternary operator.
int num = #include <stdio.h>
// Using unary postfix increment operator include <conio.h>
int main()
printf("\n The value of num = Xd", num); {
printf("\n The value of nume+ = Xd", nume+); int numl, num2, num3, large;
printf("\n The new value of num = Xd", num); clrscr();
// Using unary postfix decrement operator
printf("\n Enter the first number: ");
printf("\n\n The value of num = Xd", num); scanf("%d", &num1);
printf("\n The value of num = Xd", num--);
printf("\n Enter the second number: “);
printf("\n The new value of num = Xd", num); scanf("Xd", &num2);
return 0;
printf("\n Enter the third number; “);
} scanf("%d", &num3);
Output large = numl>num2?(num1>num3?num1:num3) :
The value of num = 3 (num2>num3?num2: num3) ;
The value of num++ = 3 printf("\n The largest number is: Xd", large);
The new value of num = 4 return 0;
The value of num = 4 }
The value of num-- = 4
Output
The new value of num = 3
Enter the first number: 12
Enter the second number: 34
9.15.6 Conditional Operator Enter the third number: 23
The conditional operator or the temary (?:) is just like The largest number is: 34
an if-else statement that can be used within expressions.
Such an operator is useful in situations in which there are 9.15.7 Bitwise Operators
two or more alternatives for an expression. The syntax of As the name suggests, bitwise operators are those operators
the conditional operator is that perform operations at bit level. These operators
expl ? exp2 : exp3 include: bitwise AND, bitwise OR, bitwise XOR, and
shift operators. The bitwise operators expect their operands
exp! is evaluated first. If it is truc, then exp2 is evaluated
to be integers and treat them as a sequence of bits.
and becomes the result of the expression, otherwise exp3
is evaluated and becomes the result of the expression. For
Bitwise AND
example,
large = (a> b) 2?a:b
Like boolean AND (&8) bitwise AND operator (8) performs
operation on bits instead of bytes, chars, integers, ete
The conditional operator is used to find the larger of two When we use the bitwise AND operator, the bit in the first
given numbers. First exp1, that is (a > b) is evaluated. Ifa operand is ANDed with the corresponding bit in the second
is greater than b, then large = a, clse large = b. Hence, operand. The truth table is same as we had seen in logical
large is equal to cither a or b but not both AND operation. The bitwise AND operator compares cach
188 Computer Fundamentals and Programming in C

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

In aC program, the & operator is used as follows. ~10101011 = 01010100

int a = 10, b = 20, c=0;


c = a&b;
Bitwise operators are used for testing the bits or shifting
Bitwise OR them left or right. Always remember that bitwise
operators cannot be applied to float or double variables.
When we use the bitwise OR operator ([), the bit in the
first operand is ORed with the corresponding bit in the
second operand, The truth table is same as we had seen in Shift Operator
logical OR operation. The bitwise-OR operator compares C supports two bitwise shift operators. They are shift-left
each bit of its first operand with the corresponding bit of its
(<<) and shift-right (>>). These operations are simple and
second operand. If one or both bits are |, the corresponding
are responsible for shifting bits cither to the left or to the
bit in the result is 1 and 0 otherwise. Por example,
right. The syntax for a shift operation can be given as
10101010 & 01010101 « 11121111
operand op num
In aC program, the | operator is used as follows.
where the bits in operand are shifted left or right depending
int a = 10, b = 20, c=0; on the operator (left if the operator is << and right if the
c= alb operator is >>) by the number of places denoted by num.
For example, if we have x = 0001 1101, then
Bitwise XOR x << 1 produces 0011 1010
The bitwise XOR operator (*) performs operation on When we apply a left-shift, every bit in x is shifted to
individual bits of the operands. When we use the bitwise the left by one place. So, the MSB (most significant bit) of
XOR operator, the bit in the first operand is XORed with x is lost, and the LSB of x is set to 0.
the corresponding bit in the second operand. The truth Therefore, if we have x = 0001 1101, then
table of bitwise XOR operator is shown in Table 9.14
x << 4 produces 1101 0000.

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

printf("\n a & b = Xd", a8); Other Assignment Operators


printf("\n a | b = Xd", afb);
printf("\n ~a = Xd", ~a); C language supports a set of shorthand assignment
printf("\n ~b = %d", ~b); operators of the form
printf("\n a * b = Xd", a%b); variable op = expression
printf("\n a << 1 = Xd", acct); where op is a binary arithmetic operator. Table 9.15 shows
printf("\n b >> 1 = %d", b»>3); the list of other assignment operators that are supported
} by C.
Output The advantage of using shorthand assignment operators
are as follows
a&be«3
a| be 63 Shorthand expressions are easier to write as the
~a= -28 expression on the left side need not be repeated.
~b
«= -40 * The statements involving shorthand operators are casier
a*b-=60 to read as they are more concise.
acl S4
* The statements involving shorthand operators are more
bor 119 efficient and easy to understand

13. Write a program to demonstrate the use of assignment


9.15.8 Assignment Operators operators.
In C, the assignment operator is responsible for assigning include <stdio.h>
int main()
values to the variables.While the equal sign («) is the
fundamental assignment operator, C language also supports {
other assignment operators that provide shorthand ways to int numl = 3, num2 = 5;
printf("\n Initial value of numl = %d and
represent common variable assignments,
When an cqual sign is encountered in an expression, the
num2 = Xd", num, num2);
numl += num2 * 4 - 7;
compiler processes the statement on the right side of the
sign and assigns the result to the variable on the left side. printf("\n After the evaluation of the
expression numl = %d and num2 = %d",
For example,
numl, num2);
int x; return 0;
x = 10; }
assigns the value 10 to variable x. If we have, Output
int x = 2, y = 3, sum = 0; Initial value of numl = 3 and num2 = 5
sum =x+y; After the evaluation of the expression num1
then sum» 5. = 16 and num2 = 5

The assignment operator has right-to-left associativity,


so the expression 9.15.9 Comma Operator
a=sb«c«= 10; The comma operator in C takes two operands. It works
by evaluating the first and discarding its value, and then
is evaluated as evaluates the second and returns the value as the result of
the expression. Comma separated operands when chained
(a = (b = (c = 10)))5
together are evaluated in left-to-right sequence with the
First 10 is assigned to c, then the value of c is assigned right most value yielding the result of the expression
to b. Finally, the value of b is assigned to a. Among all the operators, the comma operator has the
The operand to the left of the assignment operator lowest precedence.
must always be a variable name. C does not allow any Therefore, when a comma operator is used, the entire
expression, constant, or function to be placed to the left of expression evaluates to the value of the right expression
the assignment operator. Therefore, the statement a + b = 0; For example, the following statement first increments a,
is invalid in C language then increments b and then assigns the value of b to x
To the right of the assignment operator you may have
int a=2, b=3, x=0;
an arbitrary expression. In that case, the expression would
x = (++a, be=a
be evaluated and the result would be stored in the location
denoted by the variable name. Now, the value of x = 6
190 Computer Fundamentals and Programming in C

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

AAEUEN OUOFYEG IPNSOF OMT


axp
© JO SAsUN
JO
anya
SLE

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

INOUE << opqeueA = 2qeu


on
/yqeUeA = aIQuUTEN

wopsroudyes

9]qeues
aqeuts
|wowssaudyo
= 9AFEURA
IqeLEN
»Uorsaudes
= ®aqeLEN
opGeUEA
+voto
= ~ajqeuey
vorssandx>
9,qeues
= 2yqeurs
2IqeuE
3puotwandeo
= PGEUTA
aqEUEA
HiNOKe
>>
=
wotssaul way ajeqnura

Wun oure >> ayqenner


pepe
=>

ksxem

=/
x2
91qeum
uotssand x9
a}qqrtneA
=uowssoud 9}qeuma
wyoyssando opps
uomsandys
= uma
94g
ayworssaxdyo OWE
ayqrtMA
Jun
=<<
=>

= = ~
soyes3dQ
Introduction to C 191

9.15.10 sizeof Operator Table 9.16 Operato. recedence

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.

9.15.11 Operator Precedence Chart


C operators have two properties: priority and axsociativity
When an expression has more than one operator then it is =i left-to-right {comma) left-to-right
the relative priorities of the operators with respect to cach
other that determine the order in which the expression will
be evaluated. Associativity defines the direction in which the x=3* (445) *6
=3°*9°¢6
operator acts on the operands. It can be either left-to-right or
=27°6
right-to-lefl. Priority is given precedence over associativity to
= 162
determine the order in which the expressions are evaluated.
xe3*4%5/2
Associativity is then applied, if the need arises.
=12%5/2
Table 9,16 lists the operators that C language supports
=2/2
in the order of their precedence (highest to lowest).
=1
Associativity indicates the order in which the operators of
x=3* (4%5)/2
equal precedence in an expression are evaluated.
=3*4/2
You must be wondering why the priority of the
*=12/2
assignment operator is so low, This is because the action of
=6
assignment is performed only when the entire computation
x=3*4% (5 / 2)
is done, It is not uncommon for a programmer to forget the
priority of the operators while writing any program. So =3*4%2
=12%2
it is recommended that you use the parentheses operator
-0
to override default priorities. From Table 9.16 you can
3° ((4% 5) / 2)
see that the parenthesis operator has the highest priority
=3* (4 / 2)
So any operator placed within the parenthesis will be
=3°*2
evaluated before any other operator.
*6
Take the following variable declarations,
Example 9.3 inta=0, bel, c=
float x = 2.5, y = 0.0;
Evaluating expressions using the precedence chart If wewrite,
oxn3*4+5°6 asbec=7;
=12+5*6 Since the assignment operator works from right-to-left,
= 12+ 30 c = 7. Then since b = c, therefore b = 7. Now
= 42 a=b, soa=7.
192 Computer Fundamentals and Programming in C

7 a += b-= c *= 10 int main()


This is expanded as {
a=a+(b=b- (c =c * 10)) float radius;
=a+(b=1- (-10)) double area, circumference;
= a+ (b= 11) clrser();
-O+11 printf("\n Enter the radius of the
ell circle: ");
%--a* (54b)/2- cH ed scanf(°Xf", &radius);
= --a*6/2-cH*d area = 3.14 * radius * radius;
= --a*6/2--1+b circumference = 2 * 3.14 * radius;
printf ("AREA = %.2le", area);
(Value of c has been incremented but its altered value will
printf("\n CIRCUMFERENCE = %.2e",
not be visible for the evaluation of this expression)
circumference) ;
e-l*6/2-+-1¢1 return 0;
(Value of a has been incremented and its altered value will }
be used for the evaluation of this expression) Output
e-1°3--1¢1
Enter the radius of the circle: 7
#-3--201
AREA = 153.86
2 -3--1 CIRCUMFERENCE = 4.40e+01
= +2
®Rarbec
15. Write a program to print the ASCII value of a character
= (a * b) * ¢ (because associativity of * include <stdio.h>
is from left-to-right) include <conio.h>
=O int main()
10,2 && b {
0 char ch;
Ia <b B&e<b elrser();
=1 printf("\n Enter any character: ");
Inb+c lta scanf("Xe", &ch);
= (b+) |] (ta) printf("\n The ASCII value of %c is:
= 0 |{2 %6", ch, ch);
*1 return 0;
1.x * 5 88S || (b/c) }
= ((x * 5) 8&8 5) || (b/c)
* (12.5 8& 5) || (2/-2) Output
«1 Enter any character: A
14.2 <= 10 && x >" 1 BB b The ASCII value of A is: 65
= ((a <= 10) && (x >= 1)) && b
= (1 8&8 1) 8&1 16. Write a program to read a character in upper case and
=1 then print it in lower case.
IS.Ix |f le [J bec @include <stdio.h>
= (Ctx) |] (te)) I] (b+ ©) @include <conio.h>
= (0 || 0) || 0 int main()
=0 {
lox *ycared
ic char ch;
= ((x * y) < (a+ b)) Ic elrser();
= (0 <4) || -3 printf("\n Enter any character in upper
=1 case: ");
17.(x > y) + fa || cer scanf("%c", &ch);
= ((x > y) + (1a)) I] (ere) printf("\n The character in lower case is:
*(1+1) [| 0 %c", che32);
=1 return 0;
}
14. Write a program to calculate the area of a circle.
#include <stdio.h> Output
#include <conio.h>
Introduction to C 193

Enter any character: A scant


("%d" ,&num1);
The character in lower case is: a printf("\n Enter the second number:
scanf("Xd" ,&num2);
17. Write a program to print the digit at ones place of a
number, fnuml = numi + num2;
#include <stdio.h> num2 = numi - num2;
#include <conio.h> numl = numi - num2;
int main() print€("\n The first number is %d", num1);
{ print€("\n The second number is Xd", num2);
int num, digit_at_ones_ place; return 0;
clrser(); }
printf("\n Enter any number: gh Output
scanf("%d", &num);
digit_at_ones_place = num % 10; Enter the first number: 3
printf("\n The digit at ones place of Xd is Enter the second number: 5
Xd", num, digit_at_ones_place); The first number is 5
return 0; The second number is 3
}
20. Write a program to convert degrees Fahrenheit into
Output degrees celsius
Enter any number: 123 #include <stdio.h>
The digit at ones place of 123 is 3 ®include <conio.h>
int main()
18. Write a program to swap two numbers using a {
temporary variable. float fahrenheit, celsius;
#include <stdio.h> printf("\n Enter the temperature in
include <conio.h> fahrenheit: ");
int main() scanf("%#", &fahrenheit);
{ celsius = (0.56) * (fahrenheit - 32);
int numl, num2, temp; printf("\n Temperature in degrees celsius
clrser(); = %f", celsius);
printf("\n Enter the first number: ")3 return 0;
scanf("%d", &num1) ; }
printf("\n Enter the second number: 3
scanf("%d", &num2) ;
Output
temp = numl; Enter the temperature in fahrenheit: 32
numl » num, Temperature in degree celsius = 0
num2 = temp;
2 . Write 4 program that displays the size of every data
printf("\n The first number is %d", num);
printf("\n The second number is Xd", num2); type.
#include <stdio.h>
return 0;
@include <conio.h>
} int main()
Output {
clrser();
Enter the first number : 3
printf("\n The size of short integer is:
Enter the second number : 5
The first number is 5
Xd", sizeof(short int));
printf("\n The size of unsigned integer is:
The second number is 3
Xd", sizeof(unsigned int));
19, Write a program to swap two numbers without using a printf("\n The size of signed integer is:
temporary variable. Xd", sizeof(signed int));
#include <stdio.h> printf("\n The size of integer is: Xd",
#include <conio.h> sizeof(int));
int main() printf("\n The size of long integer is:
{ %d", sizeof(long int));
int numl, num2;
clrser(); printf("\n The size of character is: Xd",
sizeof(char));
printf("\n Enter the first number: “);
194 Computer Fundamentals and Programming in C

printf("\n The size of unsigned character is: return 0;


Xd", sizeof(unsigned char)); }
printf("\n The size of signed character is:
Xd", sizeof(signed char)); Output
Enter the number of Rs10 coins in the
printf("\n The size of floating point number Piggybank: 10
is: Xd", sizeof(float)); Enter the number of RsS coins in the
printf("\n The size of double number is: piggybank: 23
Nd", sizeof(double)); Enter the number of Rs2 coins in the
return 0; piggybank: 43
} Enter the number of Rel coins in the
piggybank: 6
Output
Total amount in the piggybank = 307
The size of short integer is: 2
The size of unsigned integer is: 2 23. Write a program to calculate the bill amount for an
The size of signed integer is: 2 item given its quantity sold, value, discount, and tax.
The size of integer is: 2 include <stdio.h>
The size of long integer is: 2 #include <conio.h>
int main()
The size of character is: 1 {
The size of unsigned character is: 1 float total_amt, amt, sub_total, discount_amt,
The size of signed character is: 1 tax_amt, qty, val, discount, tax;
printf("\n Enter the quantity of item
The size of floating point number is: 4 sold: ");
The size of double number is: 8 scanf("X#", &qty);
printf("\n Enter the value of item: ");
22. Write a program to calculate the total amount of money scanf("X#", &val);
in the piggybank, given the coins of Rs 10, Rs 5, Rs printé("\n Enter the discount percentage: ");
and Re 1 scanf("X#", &discount);
#include <stdio.h> printf("\n Enter the tax: ");
#include <conio.h> scanf(°X#", &tax);
int main()
amt = qty * val;
{ discount_amt « (amt * discount)/100.0;
int num_of_10 coins, num_of_5 coins,
sub_total = amt - discount_amt;
num_of_2 coins, num_of_1_ coins; tax_amt = (sub_total « tax) /100.0;
float total_amt = 0.0;
total_amt = sub_total + tax_amt;
clrser();
printf("\n Enter the number of Rs10 coins printf("\n\n\n ******eeeeee* BILL
in the piggybank: "); Ae eeeweneewee):
scanf("%d", &num_of_10_coins); printf("\n Quantity Sold: xf", qty);
printf("\n Enter the number of RsS coins printf("\n Price per item: %f", val)
in the piggybank: "); printf("\n - ;
scanf("%d", &num_of_5 coins); printf("\n
printf("\n Enter the number of Rs2 coins printf("\n Discount: - Xf", discount_amt);
in the piggybank: "); printf("\n Discounted Total: %f", sub_total);
scanf("Xd", &num_of_2 coins); peintf("\n Tax: + Xf", tax_amt);
printf("\n Enter the number of Rel coins printf("\n ------------~ ");
in the piggybank: "); printf("\n Total Amount Xf", total_amt);
scanf("%d", &num_of_1 coins); return 0;
}
total_amt = num_of_10_coins * 10 + num_of_
S_coins * 5 + num_of_2 coins * 2 + num_of
Output
1_coins; Enter the quantity of item sold: 20
Enter the value of item: 300
printf("\n Total amount in the piggybank = Enter the discount percentage: 10
xf", total_amt); Enter the tax: 12

getch(); © BILL e*
Introduction to C 195

Quantity Sold : 20 Now, x = 3.0, as automatically integer value 1%


Price per item : 300 converted into its equivalent floating point representation.
In some cases, when an integer is converted into a floating
Amount = point number, the resulting floating point number may
Discount : - 600 not exactly match the integer value. This is because the
Discounted Total : 5400 floating point number format used internally by the
Tax : + 648 computer cannot accurately represent every possible
integer number. So even if the value of x = 2.99999995,
Total Amount you must not worry. The loss of accuracy because of this
feature would be always insignificant for the final result.
Let us summarize how promotion is done
RTP TPE CONVERSION AND * float operands are converted to double.
TYPECASTING * char or short operands whether signed or unsigned are
converted to int.
Till now we haye assumed that all the expressions involved * Ifany one operand is double, the other operand is also
data of the same type. But what happens when expressions converted to double. Hence, the result is also of type
involve two different data types, like multiplying a floating double.
point number and an integer. Such type of situations are * If any one operand is long, the other operand is also
handled either through type conversion or typecasting converted to Long. Hence, the result is also of type long.
Type conversion or typecasting of variables refers to Figure 9.15 exhibits type conversions in an expression
changing a variable of one data type into another. Type
conversion is done implicitly, whereas typecasting has to
char ch;
be done explicitly by the programmer. We will discuss i ‘When
achar type is
both of them here. aot ss operated with aninttype
float f ; char ispromoted
to int.
9.16.1 Type Conversion double d, res;
Type conversion is done when the expression has variables
of different data types. To evaluate the expression, the data ra(ch # 4) (£/4)+(d - £) Whena float type datais
type is promoted from lower to higher level where the ‘ ‘ ‘ ‘operated with anint,then
hierarchy of data types (from higher to lower) can be given ivis float|double
read — inti ispromoted tofloat.
int
as; double, float, long, int, short, and char, Figure 9.14
shows the conversion hicrarchy of data types. int float double
Type conversion is automatically done when we assign ’

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

result can be of long int. So to get correct precision value,


typecasting can be done. For instance
No compile time warning message is generated when
information tslost while demoting the type of data. int a = 500, b = 70 ;
float res;
res = (float) a/b;
charch; —— - - Let us look at some more examples of typecasting
int 4; 00000100 11010010 11010010
res = (int)9.5;
41234; Contents ofi (binary Contents 9.5 is converted to 9 by truncation and then assigned to
equivalentof 1234) ofch res.
che
* res = (int)12.3 / (int)4.2;
It is evaluated as 12/4 and the value 3 is assigned to
Figure 9.16 implicit conversion example
res.
* res = (double)total/n;
Thus we can observe the following changes are
total is converted to double and then division is done
unavoidable when performing type conversions. in floating point mode.
* When a float value is converted to an int valuc, the * res = (int)(a+b);
fractional part is truncated. The value of a+b is converted to integer and then
When a double value is converted to a float valuc, assigned to res.
rounding of digits is done. * res = (int)a + b;
When a long int is converted into int, the excess a is converted to int and then added with b.
higher order bits are dropped. * res = cos((double)x);
These changes may cause incorrect results. It converts x to double before finding its cosine value,
24. Write a program to convert a floating point number
9.16.2 Typecasting into the corresponding integer.
Typecasting is also known as forced conversion. Type- include <stdio.h>
casting an arithmetic expression tells the compiler to #include <conio.h>
represent the value of the expression in a certain way int main()
It is done when the value of a higher data type has to be {
converted into the value of a lower data type. But this float #_num;
casting is under the programmer's control and not under int i_num;
compiler’s control. For example, if we need to explicitly clrser();
typecast a floating point variable into an integer variable, printf("\n Enter any floating point number: ");
then the code to perform typecasting can be given as: scanf("Xf", &f_num);
i_num = (int)#_num;
float salary = 10000.00; printf("\n The integer variant of %f is =
int sal; Xd", #_num, 4_num);
sal « (int) salary; return 0;
When floating point numbers are converted to integers }
(as in type conversion), the digits after the decimal are Output
truncated, Therefore, data is lost when floating-point
representations are converted to integral representations. Enter any floating point number: 23.45
So in order to avoid such type of inaccuracies, int type The integer variant of 23.45 is = 23
variables must be typecast to float type
As we se in the code above, typecasting can be
25. Write a program to convert an integer into the
corresponding floating point number.
done by placing the destination data type in parentheses
#include <stdio.h>
followed by the variable name that has to be converted.
®@include <conio.h>
Hence, we conclude that typecasting is done to make
a variable of one data type to act like a variable of int main()

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

f_num = (float)i_num; exam_total = exam_scorel + exam_score2;


printf("\n The floating point variant of activities total = activities _scorel +
Xd is = Xf", i_num, #_num); activities score2 + activities score3;
return 0; exam_percent = (float)exam_total * EXAMS_
} WEIGHTAGE / EXAMS_TOTAL;
Output sports_percent = (float)sports_score *
Enter any integer: 12 SPORTS WEIGHTAGE / SPORTS_TOTAL;
activities percent = (float)activities
total
The floating point variant of 12 is = 12.00000
* ACTIVITIES _WEIGHTAGE / ACTIVITIES_TOTAL;
26. Write a program to calculate a student's result based on
two examinations, one sports event, and three activities total_percent = exam_percent + sports.
conducted. The weightage of activities = 30%, sports = percent + activities percent;
20%, and examination © 50%.
#include <stdio.h>
printf("\n\n *
#include <conio.h> RESULT *****
tdefine ACTIVITIES WEIGHTAGE 30 print€("\n Total percent in examintaion :
tidefine SPORTS _WEIGHTAGE 20 Xf", exam_percent);
tidefine EXAMS _WEIGHTAGE SO printf("\n Total percent in activities :
tidefine EXAMS TOTAL 200 xf", activities_percent);
tidefine ACTIVITIES TOTAL 60 printf("\n Total percent in sports :
tdefine SPORTS _TOTAL SO Xf", sports_percent);
int main() printf("\n

{
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

scanf("Xd Xd %d", &activities scorel,


&activities_score2, &activities_score3); Total percentage

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?

11 __ function prints data on the monitor. (a) 20 (b) -4.5


12 establishes the original value for a variable {c) ‘a’ (d) pi
13, Character constants are quoted using _ Identify the valid variable name
14, AC program ends witha (a) Initial.Name (b) A+B
15) file contains mathematical functions. (c} Samt (d) Floats
16 causes the cursor to move to the next line. Which operator cannot be used with float operands?
17. Floating point valuesdenote__———_—values by default (a) + (b) -
18. A variable can be made constant by declaring it with the
(c) % {d) *
qualifier at the time of initialization.
11 Identify the erroneous expression.
19, The sign of the result is positive in modulo division if
(a) x=y=2, 4; (b) res=++a* 5;
20. Associativity of operators defines (c) res = /4; (d) res = a++—b #2
21, ___ can be used to change the order of evaluation
expressions. State True or False
: Operator returns the number of bytes 1 We can have only one function in a C program
occupied by the operand Header files are used to store program’s source code
23, The specification is used to read/write a short Keywords are case sensitive
integer. Variable first is same as First
24, The specification is used to read/write a An identifier
VPwn can contain any valid printable ASCII
hexadecimal integer. character.
25, To print the data left-justified, __ specification is Signed variables can increase the maximum positive
used. range
Commented statements are not executed by the
Multiple-choice Questions compiler.
1, The operator which compares two values is Samount is a valid identifier in C
(a) assignment (b) relational Comments cannot be nested.
(c) unary (d) equal
The equality operators have higher precedence than the

2. Which operator is used to simultaneously evaluate two


relational operators.
expressions with relational operators? Shifting once to the left multiplies the number by 2

(a) AND (b) OR print#("%d", scanf(“%d", &num)); is a valid C statement.


1,234 is a valid integer constant.
(c) NOT {d) Allofthese
A printf statement can generate only one line of output.
3. Ternary operator operates on how many operands? stdio.h is used to store the source code of the program.
(a) 1 (b) 2 The closing brace of main() is the logical end of the
(c) 3 (d) 4 program.
4, Which operator produces the 1s complement of the The declaration section gives instructions to the computer.
given binary value? Declaration of variables can be done anywhere in the
(a) Logical AND (b) Bitwise AND program,
200 ‘Computer Fundamentals and Programming in C

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

printf("\n a = %d", a); res=a-=c || a¢b;


return 0; printf("\n Xd", res);
} res = b 210 || b &&c <0 || a> 0;
3, #include <stdio.h> printf("\n Xd", res);
int main() res = (a/2.0 == 0.0 88 b/2.0 I=
{ 0.0) || ¢ < 0.0;
int a; printf("\n Xd", res);
printf("\n Xd", 1/3 + 1/3); return 0;
printf("\n Xf", 1.0/3.0 + 1.0/3.0); }
a = 15/10.0 + 3/2; 9, Binclude <stdio.h>
printf("\n Xd", a); int main()
return 0; {
} int a = 20, b = 5, result;
4. #include <stdio.h> float ¢ = 20.0, d= 5.0;
int main() printf("\n 10+a/4* b= Xd",
{ 10+a/4* bd);
int
a = 4; printf("\nc /d*bea-b-= Xd",
printf("\n Xd", 10 + are); c/d*b+a-b);
printf("\n Xd", 10 + ++); return 0;
return 0; }
} 10. #include <stdio.h>
5, #include <stdio.h> int main()
int main() {
{ int a, b;
int a= 4, b= 5, ce 6; printf("\n a= Xd \t b= %d \taeb-=
a=be==¢; XA", a, b, arb);
printf("\n a = Xd", a); return 0;
return 0; }
} 11. #include <stdio.h>
6, #include <stdio.h> int main()
#include <conio.h> {
int main() printf("\n Xd", ‘F’);
{ return 0;
int a=, be2, c#3, d=4, e=5, res; }
clrser(); 12. #include <stdio.h>
res=a+b/e-d*e; int main()
printf("\n Result = Xd" res); {
res = (a+b) /c-d* @; int n = 2;
printf("\n Result = Xd",res); n= In;
res a+(b/ (c -d)) * @; printf("\n n = %d", n);
printf("\n Result = Xd",res); return 0;
return 0; }
} 13, #include <stdio.h>
7, #include <stdio.h> int main()
int main() {
{ int a = 100, b = 3;
inta=4, b= 5; float c;
printf("\n %d", (a > b)? a: b); c = a/b;
return 0; printf("\n c = %f", c);
}
8, #include <stdio.h> return 0;
int main() }
{ 14. finclude <stdio.h>
int a= 4, b = 12, c= -3, res; int main()
res=a>b &&a< c; {
printf("\n Xd", res); int n = -2;
202 Computer Fundamentals and ProgramminginC

printf("\n n = %d", -n); a = a + Bate;


return 0; printf("\n a= %d", a);
} return 0;
15 include <stdio.h> }
int main() 22. include <stdio.h>
{ int main()
inta=2, b= {
c = att; int result;
d = ++b; result = 3 +5 - 1 17 % -13;
printf("\n c = Xd d = Xd", c, d); printf("Xd", result);
return 0; result = 3 * 2+ (15 /4%7);
} printf("%d", result);
16. Hinclude <stdio.h> result =18/9/3*2*3¢
int main() 5%10/4
{ printf("xd", result);
int = 30; return 0;
printf("\n _ = Xd", _); }
return 0; 23. Hinclude <stdio.h>
} int main()
17 #include <stdio.h> {
int main() int n = 2;
{ printf(“\n Xd Xd Xd", nee, n, +4n)
int a= 2, b= 3, c, d; return 0;
ate; }
++b; 24. Hinclude <stdio.h>
printf("\n a = Xd b = Xd", a, b); int main()
return 0; {
} int a= 2, b= 3, #4;
18. #include <stdio.h> aeb
int main() printf("\n a = %d",a);
{ return 0;
int a= 2, b= 3; }
printf("\n Xd", ++(a - b)); 25. include <stdio.h>
return 0; int main()
} {
19. Hinclude <stdio.h> int num = 070;

int main() printf("\n num = Xd", num);


{ print€("\n num = %o", num);
inta=2, b= 3; print€("\n num = Xx", num);
printf("\n Xd", ++a - b); return 0;
return 0; }
} 26. Hinclude <stdio.h>
20. include <stdio.h> int main()
int main() {
{ printf("\n %40.27s Welcome to
inta= 2,6 C programming”);
printf("\n a printf("\n %40.20s Welcome to
printf("\n a C programming");
printf("\n a “eeu
ocow printf("\n %40.14s Welcome to
printf("\n a 8& b = Xd", 2 &&b); C programming");
return 0; printf("\n %-40.27s Welcome to
} C programming”);
21 Winclude <stdio.h> printf("\n %-40.20s Welcome to
int main() C programming”);
{ printf("\n %-40.14s Welcome to
int a = 2; C programming”);
introduction to C 203

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)

S vim firstprog.c include <stdio.h>


void main()
Now when the editor gets opened type the program given below.
{
#include <stdio.h> printf(“Welcome to the World of
void main() Programming”);
{ }
printf("Welcome to the World of
Programming”);
Step 3: Compile the program using gee, which is a compiler
that is installed by default in Ubuntu. For compiling, write the
}
following command
Step 2: Compile the program using cc or gcc command. The
command will create the aout file. gee firstprog.c —ofirstprogram
In the above command, gee is the compiler; firsiprog.c is the
S$ ce firstprog.c name of the file to be compiled and the name following -o
Step 3: Execute the C program. The program can be executed specifies the filename of the output. When you execute this
in two ways. First, by executing the aout to see the output command, the compiler will generate an executable file in
Second, by renaming it to another file and executing it as case there are no syntax or semantic errors in the program. If
shown below there are errors, the compiler will notify you about the errors
and you will then have to fix them before re-compiling the
S /aout code.

or Step 4: Exccute the program by typing the command given


below
$ my a.out firstprogram
ffirstprogram
$ Sfirstprogram
Decision Control and
¢ ‘Looping Statements
TAKEAWAYS
* Decision control statements * Iterative statements * Nested loops
* Conditional branching statements * For, while, do-while loops * Break, continue, and goto statements

ETB INTRODUCTION TO DECISION Selection/Branching


CONTROL STATEMENTS statement

Till now we know that the code in a C program is executed


sequentially from the first line of the program to its last Conditional Unconditional
line, i.c., the second statement is executed after the first, type type
the third statement is executed after the second, and so on.
Although this is true, but in some cases we want only
sclected statements tobe executed. Such type of conditional
if if-else if-else-if switeh
processing extends the usefulness of programs. It allows
the programmers to build programs that determine which Figure 10.1 Decision control statements
statements of the code should be executed and which
should be ignored.
The if block may include one statement or n statements
C supports two types of decision control statements
enclosed within curly brackets. First, the test expression is
that can alter the flow of a sequence of instructions. These
evaluated. If the test expression is true, the statement of
include conditional type branching and unconditional
type branching. Figure 10.1 shows the categorization of if block (statement | to ) are executed otherwise these
statements will be skipped and the execution will jump to
decision control statements in C language.
statement x
The statement in an
CONDITIONAL BRANCHING Lib
ana i
f : any va .

STATEMENTS Properiindentthe ace statement and. the


Aebtoss tee eaprbatiss is any valid Cc
dependent on the <. _ language
: SEER
expression that may
The conditional branching statements help to jump from
one part of the program to another depending on whether include logical operators. Note
@ particular condition is satisfied or not. These decision
control statements include
* ifstatement
* if-else statement Test FALSE
SYNTAX OF IF STATEMENT
* if-else-if statement Expression
* switch statement if (test expression)
TRUE
statement 1;
10.2.1 if Statement Statement Block |
statement n;
The if statement is the simplest form of decision control
statement x;
statements that is frequently used in dec ion-making, Statement x
The general form of a simple if statement $s shown in
Figure 10.2 Figure 10.2 if statement construct
206 Computer Fundamentals and Programming in 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

the value of x is incremented and is printed on the screen. space character");


The output of this program is getch();
return 0;
xell
}
Observe that the printf statement will be executed
Output
even if the test expression is false
Press any key: 3
1. Write a program to determine whether a person is The user has entered a digit
cligible to vote or not
Now let us write a program to detect errors during data
#include <stdio.h> input. But before doing this we must remember that when
#include <conio.h> the scanf() function completes its action, it returns the
int main() number of items that are successfully read. We can use
{ this retumed value to test if any error has occurred during
int age; data input. For example, consider the following function:
printf("\n Enter the age: “);
scanf("Xd", &age); scanf("Xd Sf %c", &a, &b, &c);
if(age >= 18) If the user enters
printf("\n You are eligible to vote");
getch(); 11.2A
return 0; then the scanf() function will return 3, since three values
} have been successfully read. But had the user entered,
Output
l abc A
Enter the age: 28
You are eligible to vote then the scanf() function will immediately terminate when
it encounters abe as it was expecting a floating point value
and will print an error message. So after understanding
this concept, let us write a program code to detect an error
In case the statement block contains only one statement, in data input.
putting curly brackets becomes optional. Ifthere is more include <stdio.h>
than one statement in the statement block, putting curly main()
brackets becomes mandatory, {
int num;

2. Write a program to determine the character entered by


char ch;
the user.
printf("\n Enter an int and a char value:
"3
#include <stdio.h> // Check the return value of scanf()
#include <ctype.h> if(scanf ("Xd Xe", &num, &ch)==2)
Decision Control and Looping Statements 207

printf("\n Data read successfully");


else int num;
printf("\n Error in data input"); clrser();
} printf("\n Enter any number: “);
Output scanf( "Xd", &num) ;
if(num&2 == 0)
Enter an int and a char value: 2A
printf("\n %d is an even number", num);
Data read successfully else
printf("\n %d is an odd number", num);
10.2.2 if-else Statement return 0;
We have studied that the if statement plays a vital role }
in conditional branching. Its usage is very simple. The Output
test expression is evaluated. If the result is true, the Enter any number: 11
statement(s) followed by the expression is executed else if 11 is an odd number
the expression is false, the statement is skipped by the
compiler 4. Write a program to enter any character. If the entered
But what if you want a character is in lower case then convert it into upper case
Programming Tip: Separate set of statements to and if it is a lower case character then convert it into
Align the matching be executed if the expression upper case.
if-else clauses returns a zero value? In such
include <stdio.h>
vertically. cases, we use an if-else
statement rather than using
#include <conio.h>
int main()
simple if statement. The general form of a simple if- {
else statement is shown in Figure 10.3
char ch;
In the syntax shown, we have written statement block
A statement block may include one or more statements. elrser();
printf("\n Enter any character: ");
According to the if-else construct, first the test expression
is evaluated. If the expression is true, statement block 1is scanf("%c", &ch);
executed and statement block 2 is skipped. Otherwise, if if(ch >e'A’ BB chew'Z')
the expression is false, statement block 2 is executed and
printf("\n The entered character is in upper
statement block | is ignored. Now in any case after the
case. In lower case it is: %c", (ch+32))
statement block | or 2 gets executed, the control will pass
else
to statement x, Therefore, statement x is executed in every
printf("\n The entered character is in lower
Case.
case. In upper case it is: %c", (ch-32));
return 0;
3. Write a program to find whether the given number is }
even or odd. Output
#include <stdio.h> Enter any character: a
#include <conio.h> The entered character is in lower case, In
int main() upper case it is: A

SYNTAX OF IF-ELSE STATEMENT Test FALSE

if (test expression) TRUE


{
statement block 1;

else Statement Block 2

statement block 2;

statement x;

‘Statementx

Figure 10.3 if-else statement construct


208 Computer Fundamentals and Programming in C

§. Write a program to enter a character and then determine return 0;


whether it is a yowel or not }
#include <stdio.h> Output
#include <conio.h>
Enter any year: 1996
int main() Leap Year
{
char ch;
clrser(); Pitfall A very common pitfall while using if statements
is fo use assignment operator (=) instead of comparison
printf("\n Enter any character: “); operator (==). For example, consider the statement
scanf("%e", &ch);
if(a = 10)
if(ch ='a* ||ch =="e' [|ch=="i' ||ch=="o’ printf("xd", a);
[|che=*u’ || chee'A’ |[che='E* || che«
||che="0" ||che=tu’ ) Here, the statement does not test whether a is equal to
printf("\n %c is a vowel", ch); 10 or not. Rather the value 10 is assigned to a and then the
else value is returned to the if construct for testing. Since the
printf("\n %c is not a vowel"); value of a is non-zero, the if construct returns a 1.
getch(); The compiler cannot detect
return 0; Programming Tip: such kinds of errors and
} Do not use floating thus the programmer should
Output point numbers for carefully use the operators.
checking for equality The program code given
Enter any character: v ina test expression. below shows the outcome of
v is not a vowel mishandling the assignment
and the comparison operators,
6. Write a program to find whether a given year is a leap
year or not #include <stdio.h>
#include <stdio.h> main()
#include <conio.h> {
int main() int x = 2, y = 3;
{ if(x = y)
int year; printf("\n EQUAL");
clrser(); else
printf("\n Enter any year: ); printf("\n NOT EQUAL");
scanf("%d", &year); }
if(((year%4 == 0) && ((year%100 !=0)) ||
Output
(year%400 == 0))
printf("\n Leap Year"); EQUAL
else #include <stdio.h>
printf("\n Not a Leap Year"); main()

Test FALSE
SYNTAX OF IF-ELSE-IF STATEMENT Expression
if ( test expression 1) TRUE

statement block 1; State Block 1 Test FALSE


Expression2
else if ( test expression 2)
TRUE
statement block 2;
‘Statement Block 2 ‘Statement Block x

statement block x;
}
statement y; ‘Statementy

Figure 10.4 if-else-if statement construct


Decision Control and Looping Statements | (209
scanf("Xd", Sum);
Programming Tip: =
int x = 2, y = 3; if (num==0)
if(x == y) Keep thelogical printf("\n The number is
printf("\n EQUAL"); expressions simple equal to zero");
else and short. Forthis, else if(num>0) ‘
print#("\n NOT EQUAL"); Vesros beinebiare print#("\n The number is
statements. positive");
}
Output else
printf("\n The number is
NOT EQUAL negative");
return 0;
10.2.3 if-else-if Statement }
C language supports if-else-if statements to test Output
additional conditions apart from the initial test expression.
The if-else-if construct works in the same way as a Enter any number: 0
normal if statement, if-else-if construct is also known The number is equal to zero
as nested if construct, Its construct is given in Figure 10.4 In the above program to test whether a number is
It is not necessary that positive or negative, if the first test expression evaluates
Programming Tip: every if statement should to a true value then rest of the statements in the code will
Braces must be have an else block as C be ignored and after executing the printf statement which
placed onseparate supports simple if statements. displays “The number is equal to zero”, the control
linessothatthe Block = After the first test expression will jump to return 0 statement
Ofstatements canbe or the first if branch, the
easily identified. programmer can have as many2
9. Acompany decides to give bonus to all its employees on
else-if branches as he wants Diwali. A 5% bonus on salary is given to the male workers
depending on the expressions that have to be tested. For and 10% bonus on salary to the female workers, Write a
example, the following code tests whether a number program to enter the salary and sex of the employee. If
ent dd by the user is negative, positive, or equal to zero. the salary of the employee is less than Rs 10,000 then the
employee gets an extra 2% bonus on salary, Calculate the
7. Write a program to demonstrate the use of nested if bonus that has to be given to the employee and display
structure the salary that the employee will get
#include <stdio.h>
include <stdio.h>
int main()
include <conio.h>
{
int main()
int x, y;
printf("\n Enter two numbers: “); {
char ch;
scanf("%d Xd", &x, &y);
float sal, bonus, amt_to_be paid;
if(x == y)
printf("\n Enter the sex of the employee
printf("\n The two numbers are equal”);
(m or f): ")5
else if(x > y)
printf("\n %d is greater than Xd", x, y); scanf("%c", Bch);
printf("\n Enter the salary of the
else
employee: “);
printf("\n Xd is smaller than Xd", x, y);
scanf("Xf", &sal);
return 0;
if(ch = ‘m')
} bonus = 0.05 * sal;
Output else
Enter two numbers: 12 23 bonus = 0.10 * sal;
12 is smaller than 23 if (sal < 10000)
bonus += 0.20 * sal;
8. Write a program to test whether a number entered is amt_to_be_paid = sal + bonus;
positive, negative, or equal to zero. printf("\n Salary = xf", sal);
#include <stdio.h> printf("\n Bonus = Xf", bonus);
int main() printf("\n teeeeeeneeweres seneeweeeny:
{ printf("\n Amount to be paid: %f", amt_to_
int num; be_paid);
printf("\n Enter any number: getch();
210 Computer Fundamentals and Programming in C

return 0; * iftaxable income is above 5,00,001 then charge 30% tax


} ®include <stdio.h>
Output include <conio.h>
Sdefine MIN1 150001
Enter the sex of the employee (m or f): f
Sdefine MAX1 300000
Enter the salary of the employee: 12000
Sdefine RATE1 0.10
Salary = 12000
define MIN2 300001
Bonus = 1200
define MAX2 500000
define RATE2 0.20
Amount to be paid: 13200
define MIN3 500001

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

else int main()


printf("\n %d is greater than Xd and Xd", {
num3, num1, num2); int marksi, marks2, marks3, marks4,
total = 0;
} float avg =0.0;
else if(num2>num3) clrser();
printf("\n %d is greater than %d and Xa", printf("\n Enter the marks in
fnum2, uml, num3); Mathematics: *);
else scanf("Xd", &marks1);
printf("\n Xd is greater than Xd and Xd", printf("\n Enter the marks in Science: ");
num3, numi, mum2); scanf("%d", &marks2);
return 0; printf("\n Enter the marks in Social
Programming Tip: } Science: ");
scanf("Xd", &marks3);
sented aT Osspat printf("\n Enter the marks in Computer
the
ind statements
ent [ter the first umber: 12 Science: ");
int byatleast
blockhe Enter the second number: scanf("%d", &marks4);
three spaces tothe 23 total = marksl + marks2 + marks3 + marks4;
Enter the third number: 9
right ofthe braces. avg = (float) total/4;
23 is greater than 12 and 9
printf("\n TOTAL « Xd", total);
printf("\n AGGREGATE » %.2", avg);
13. Write a program to input three numbers and then find
largest of them using && operator
if(avg >= 75)
printf("\n DISTINCTION");
#include <stdio.h> else if(avg>=60 8& avg<75)
#include <conio.h> peintf("\n FIRST DIVISION");
int main() else if(avg>=50 8& avg<60)
{ printf("\n SECOND DIVISION");
int num1, num2, num3; else if(avg>=40 && avg<50)
clrser(); printf("\n THIRD DIVISION");
printf("\n Enter the first number: “); else
scanf("%d", &num1); printf("\n FAIL");
printf("\n Enter the second number: “); return 0;
scanf("%d", &num2); }
printf("\n Enter the third number: “); Output
scanf("%d", &num3);
if(numl>num2 && numi>num3) Enter the marks in Mathematics: 90
printf("\n Xd is the largest number”, num); Enter the marks in Science: 91
if(num2>num1 && num2>num3) Enter the marks in Social Science: 92
printf("\n Xd is the largest number”, Enter the marks in Computer Science: 93
num2) ; TOTAL = 366
else AGGREGATE = 91.00
printf("\n Xd is the largest number™, num3); DISTINCTION
getch(); 15. Write a program to calculate the roots of a quadratic
return 0;
equation.
}
Output #include <stdio.h>
#include <math.h>
Enter the first number: 12 #include <conio.h>
Enter the second number: 23 void main()
Enter the third number: 9 {
23 is the largest number int a, b, cj

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

deno = 2 * a; clause. So the programmer must always see that every if


if(D > 0) statement is paired with an appropriate else statement.
{
printf("\n REAL ROOTS"); Comparing Floating Point Numbers
rooti = (-b + sqrt(D)) / deno;
root2 = (-b - sqrt(D)) / deno; We should never use floating point numbers for testing
printf("\n ROOT1 = Xf \t ROOT 2 = Xf",
equality. This is because floating point numbers are just
rooti, root2); approximations, so it is always better to use floating point
numbers for testing ‘approximately equal’ rather than
}
else if(D == 0) testing for exactly equal.
We can test for approximate equality by subtracting
{
print#("\n EQUAL ROOTS”); the two floating point numbers (that are to be tested) and
rootl « -b/deno; comparing their absolute value of the difference against a
printf("\n ROOT] = %f \t ROOT 2 = X#", very small number, epsilon. For example, consider the code
rootl, rootl); given below which compares two floating point numbers.
Note that epsilon is chosen by the programmer to be small
}
else enough so that the two numbers can be considered equal.
printf("\n IMAGINARY ROOTS”); #include <stdio.h>
getch(); #include <math.h>
} define EPSILON 1.0e-5
Output int main()
Enter the values of a, b, andc : 345 {
double numi = 10.0, num2 = 9.5;
IMAGINARY ROOTS
double resi, res2;
resi = num2 / numl * numl;
Let us now summarize the rules for using if, if-else, res2 = num2;
and if-else~if statements. /* fabs() is a € Library function that
Rule 1: The expression must be enclosed in parentheses. returns the floating point absolute value */
if(fabs(res2 - resl) < EPSILON)
Rule 2: No semicolon is placed afler the if/if-else/ print# (“EQUAL”);
if-else-if statement. Semicolon is placed only at the end else
of statements in the statement block. print#("NOT EQUAL");
Rule 3: A statement block begins and ends with a curly return 0;
brace. No semicolon is placed after the opening/closing }
braces.
Also note that adding a very small floating point value
to 4 very large floating point value or subtracting floating
Dangling Else Problem point numbers of widely differing magnitudes may not
have any effect. This is because adding/subtracting two
With nesting of if-else statements, we often encounter floating point numbers that differ in magnitude by more
a problem known as dangling than the precision of the data type used will not affect the
Programming Tip: else problem, This problem larger number.
While forming is created when there is no
the conditional matching else for every if 10.2.4 switch case
expression, try to use statement. In such cases, C
A switch case statement is a multi-way decision statement
positive statements always pairs an else statement
that is a simplified version of an if-else block that evaluates
rather than using to the most recent unpaired if
only one variable. The general form ofa switch statement
compound negative statement in the current block.
is shown in Figure 10.5,
statements. Consider the following code
which shows such a scenario.
Programming Tip: Table 10.1 compares
tisalways general form of a switch
if(a > b) recommended to statement with that of an
if(a > c)
printf("\n a is greater than b and c”); usedefauttlabeling =i ¢e1se statement,
switch statement. Here, statement blocks refer
else
to statement lists that may
printf("\n a is not greater than b and c"); contain zero or more statements, These statements in the
The problem is that both the outer if statement and block are not enclosed within opening and closing braces.
the inner if statement might conceivably own the else
Decision Control and Looping Statements 213

TRUE
Value |

Statement Block | FALSE

Syntax of Switch Statement = Value 2


switch ( variable ) FALSE

case valuel: Statement Block2


Statement Block 1;
break; en
case value2: FALSE
Statement Block 2;
break; TRUE
ot a Value N
case value N:;
Statement Block N;
Statement Block N FALSE
Statement Block D;
break; Statement Block D
}
Statement x;
Statement X

Figure 10.5 The switch statement construct

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

int option = 1; #include <stdio.h>


switch(option) int main()
{ {
case 1: printf(“\n In case 17); char ch;
case 2: printf("\n In case 2"); printf("\n Enter any character: “);
default: printf("\n In case default”); scanf("Xe", &ch);
} switch(ch)
return 0; {
} case ‘A’:
Output case, ‘8+
printf("\n % c is vowel”, ch);
In case 1 break;
In case 2 case 'E’:
In case default case ‘e':
printf("\n % c is vowel”, ch);
Had the value of option been 2, then the output would break;
have been dese: oY"
In case 2 case ‘i’:
In case default printf("\n % c is vowel”, ch);
Decision Control and Looping Statements 215
break; 19, Write a program that accepts a number from 1 to TO!
case ‘0 Print whether the number is even or odd using a switch
case 'o case construct
printf("\n % c is vowel”, ch);
#include <stdio.h>
break;
case ‘U
void main()
case ‘u': {
printf("\n % c is vowel", ch); int num;
printf("\n Enter any number (1 to 10)
break;
default: printf("Kc is not a vowel”, ch);
scanf("%", &num);
switch(num)
return 0;
case 1
} case 3:
Output case 5:
Enter any character: E case 7:
E is vowel case 9:
printf("\n 000");
Note that there is no break statement after case A, so if break;
the character ‘A’ is entered, then the control will execute case 2:
the statements given in case ‘a' case 4:
18. Write a program to enter a number from 1-7 and
case 6:
display the corresponding day of the week using case 8:
case 10:
switch case statement
printf("\n EVEN");
#include <stdio.h> default
#include <conio.h> printf("\n INVALID INPUT");
int main() break;
{
int day;
clrser(); OR
printf("\n Enter any number from 1 to 7: “);
scanf("%d", &day) ; #include <stdio.h>
void main()
switch(day) {
{ int num, rem;
case 1: printf(“\n SUNDAY"); printf("\n Enter any number (1 to 10): ");
break;
scanf("%", &num);
case 2: printf("\n MONDAY"); rem = num%2;
break; switch(rem)
case 3: printf("\n TUESDAY"); {
break; case 0:
case 4: printf("\n WEDNESDAY"); printf("\n EVEN");
break; break;
case 5: printf("\n THURSDAY"); case 1:
break; printf("\n 000");
case 6: printf("\n FRIDAY"); break;
breakjw }
case 7: printf("\n SATURDAY"); }
break; Output
default: printf("\n Wrong Number”); Enter any number from 1 to 10: 7
} oop
return 0;
}
Output
Advantages of Using a switch case Statement
Enter any number from 1 to 7: 5 Switch case statement is preferred by programmers due
THURSDAY to the following reasons
216 Computer Fundamentals and Programming in C

* Easy to debug false then the computer will


Easy to read and understand Programming Tip: run into an infinite loop which.
* Ease of maintenance as compared with its equivalent crcteateroators is never desirable
if-else statements nee nsec
Yossi Awhile loop is also referred
* Like if-else statements, switch statements can also be Seater Sob to as a top-checking loop since
nested control condition is placed as
+ Executes faster than its equivalent if-else construct the first line of the code. If the control condition evaluates
to false, then the statements enclosed in the loop are never
GUE) ITERATIVE STATEMENTS executed.
For example, look at the following code which prints
first 10 numbers using a while loop.
Iterative statements are used to repeat the execution of a
list of statements, depending on the value of an integer include <stdio.h>
expression, C language supports three types of iterative int main()
statements also known as looping statements. They are: {
* while loop inti=1; // initialize loop variable

* do-while loop while(ic=10) // test the condition


* for loop { // execute the loop statements
printf(" %d", i);
In this section, we will discuss all these statements. i=i+¢1; // condition updated
}
10.3.1 while Loop getch();
The while loop provide: amechanism to repeat one or more return 0;
statements while a particular condition is true. Figure 10.6 }
shows the syntax and general form of representation of a Output
while loop. 12345678910
In the while loop, the condition is tested before any of
the statements in the statement block is executed, If the Initially i * 1 and is less than 10, ic, the condition
condition is true, only then the statements will be executed is true, so in the while loop the value of 4 is printed and
otherwise if the condition is false, the control will jump to the condition is updated so that with every execution of
statement y, which is the immediate statement outside the the loop, the terminating condition becomes approachable.
while loop block Let us look at some more programming examples that
From the flowchart, it is illustrate the use of while loop.
Programming Tip: clear that we need to constantly
Iterative statements update the condition of the 20. Write a program to calculate the sum of first 10
are used to repeat while loop. It is this condition numbers.
the execution ofa which determines when the #include <stdio.h>
listofstatements, loop will end, The while loop int main()
depending onthe will execute as long as the {
value ofan integer condition is true. Note if the int i = 1, sum = 0;
expression, condition is never updated and while(ic#10)
the condition never becomes {

‘Statementx

Syntax of While Loop


statement x;
while (condition) Update the
{
statement block; condition expression Condition
statement y;
Statement Block us FALSE
Statementy
The while loop construct
Decision Control and Looping Statements | (217
sum = sum + i; int main()
i=i+1; // condition updated {
} int i=1, large = -32768, num;
printf("\n SUM = Xd", sum); clrser();
return 0;
} while(ic=5)
{
Output printf("\n Enter the number: ")
SUM = 55 scanf("Xd" num) ;
large = num>large?num: large;
21, Write a program to print 20 horizontal asterisks (*) itt;

#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,

#include <stdio.h> @include <stdio.h>


int main() #include <conio.h>

{ 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+;

Output printf("\n\n Enter any number: ");


scanf("%d" ,&num) ;
Enter the value of m: 7
}
Enter the value of n: 11
printf("\n Count of positive numbers entered
SUM = 45
= Xd", positives);
printf("\n Count of negative numbers entered
23. Write a program to display the largest of S numbers
= Xd", negatives);
using ternary operator
printf("\n Count of zeros entered = xa",
#include <stdio.h> zeros);
#include <conio.h> getch();
218 Computer Fundamentals and Programming in C

return 0; statements in the loop have to be executed is not known in


} advance. The program will execute until the user wants to
Output stop by entering -1
Now look at the code given below which results in an
Enter -1 to exit infinite loop. The code given below is supposed to calculate
Enter any number: -12 the average of first 10 numbers, but since the condition
Enter any number: 108 never becomes false, the output will not be generated and
Enter any number: -24 the intended task will not be performed.
Enter any number: 99
Enter any number: -23 include <stdio.h>
Enter any number: 101 int main()
Enter any number: -1 {
Count of positive numbers entered = 3 int i = 0, sum #0;
Count of negative numbers entered = 3 float avg = 0.0;
Count of zeros entered = 0
while(ic<#10)
25. Write a program to calculate the average of numbers
{
entered by the user
sum = sum + i;
#include <stdio.h> }
int main() avg = (float) sum/10;
{ printf("\n The sum of first 10 numbers = Xd",
int num, sum = 0, count = 0; sum);
float avg; printf("\n The average of first 10 numbers «
printf("\n Enter any number. Enter -1 to xf", avg);
STOP: “); return 0;
scanf("%d", &num);
while(num t= -1)
10.3.2 do-while Loop
Programming Tip: aks
ees sericolon sum = sun + num; The do-while loop is similar to the while loop. The only
enrecnes print#("\n Enter any difference is that in a do-while loop, the test condition is
bedak ree apie number. Enter -1 to evaluted at the end of the loop, Now that the test condition
STOP; “); is evaluted at the end, this clearly means that the body
culnonlprni scanf("%d", &num); of the loop gets executed at least one time (even if the
. However, } condition is false), Figure 10,7 shows the syntax and
A diaipenbehats avg = (float)sum/count; general form of representation of a do-while loop,
on Stroe as printf("\n SUM = Xd", sum); Note that the test condition is enclosed in parentheses
Sa ada print#("\n AVERAGE = %.2f", and followed by a semicolon, The statements in the
the program. a statement block are enclosed within curly brackets, The
return 0; curly brackets are optional if there is only one statement in
} the body of the do-while loop.
Output Like the while loop, the do-while loop continues to
execute whilst the condition is true. There is no choice
Enter -1 to exit whether to enter the loop or not because the loop will be
Enter any number. Enter -1 to STOP: 23 executed at least once irrespective of whether the condition
Enter any number. Enter -1 to STOP: 13 is true or false. Henee, entry in the loop is automatic
Enter any number. Enter -1 to STOP: 3 There is only one choice: to continue or to exit. The do-
Enter any number. Enter -1 to STOP: 53 while loop will continue to execute while the condition
Enter any number. Enter -1 to STOP: 4 is true and when the condition becomes false, the control
Enter any number. Enter -1 to STOP: 63 will jump to statement following the do-while loop.
Enter any number. Enter -1 to STOP: -23 Similar to the while loop, the do-while is an indefinite
Enter any number. Enter -1 to STOP: -6 loop as the loop can execute until the user wants to stop.
Enter any number. Enter -1 to STOP: -1 The number of times the loop has to be executed can thus
SUM = 130 be determined at the run time. However, unlike the while
AVERAGE = 16.25 loop, the do-while loop is a bottom-checking loop, since
the control expression is placed after the body of the loop,
Thus, we see that while loop is very useful for designing The major disadvantage of using a do-while loop is
interactive programs in which the number of times the that it always executes at least once, even ifthe user enters
Decision Control and Looping Statements 219

‘Statement x

Syntax of do-while Loop


Statement block
statement x;
do
{
statement block; Update the
}while (condition); condition expression

statement y;

TRUE Condition

FALSE
Statement y

Figure 10.7 do-while construct

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++;

Enter the value of n: 5


fflush(stdin);
/* The function is used to clear the
standard input file. */
printf("\n Enter another character. Enter *
to exit.");
scanf(“%c", &ch.
} while(ch I= '* 3

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

Syntax of for Loop

for (initialization; condition; Controling FALSE


increment/decrement/update) condition for
{ loop variable
statement block;
} TRUE
statement y;
Statement block

Update the
loop variable

‘Statement y

Figure 10.8 for loop construct


222 Computer Fundamentals and Programming in C

In the syntax of the for loop, initialization of the include <stdio.h>


loop variable allows the programmer to give it a value. int main()
Second, the condition specifies that while the conditional {
expression is true the loop should continue to repeat int i;
itself. With every iteration, the condition when the loop for (i=0;i<10;i++);
would terminate should be approachable. So, with every print#(" xd", i);
iteration, the loop variable must be updated. Updating the return 0;
loop variable may include incrementing the loop variable, }
decrementing the loop variable or setting it to some other
value like, 4 +=2, where 4 is the loop variable. In this code, the loop initializes 1 to 0 and increments
Note that every section of the for loop is separated its value. Since a semicolon is placed after the loop, it
means that loop does not contain any statement. So even
from the other with a semicolon. It is possible that one
of the sections may be empty, though the semicolons still if the condition is truc, no statement is executed. The loop
have to be there. However, if the condition is empty, it is continues till 4 becomes 10 and the moment i#10, the
evaluated as true and the loop will repeat until something statement following the for loop is executed and the value
of i (10) is printed on the screen.
else stops it
The for loop is widely used to execute a single or a When we place a semicolon after the for statement,
group of statements a limited number of times. Another then the compiler will not generate any error me: ge.
Rather it will treat the statement as a null statement,
point to consider is that in a for loop, condition is tested
before the statements contained in the body are executed.
Usually such type of null statement is used to generate
So if the condition does not hold true, then the body of the time delays. For example, the following code produces no
for loop is not executed output and simply delays further processing,
Look at the following code which prints the first 1 include <stdio.h>
numbers using a for loop. int main()
#include <stdio.h> {
int main() int 4;
{ for(i=10000; 1>0;1-
int i, nj printf(" Xd", 4);
printf("\n Enter the value of n :"); return 0;
scanf("%d", &n); }
* Multiple initializations must be separated with a oOmma
for(detjicenjit+) operator as shown in the following code segment.
printf(“\n Xd", 4);
return 0; #include <stdio.h>
} int main()
In the code, i is the {
lanemnrnlng Tie loop variable. Initially, it int i, sum;
to ane theloop is initialized with valuc 1 for(i=0, sum=0;1<10;i++)
sum «= i;
ch leinthe Suppose the user enters 10
ta iplial ek as the value for n. Then the printf(" Xd", sum);
condition is checked, since the return 0;
renathcal odd condition is truc as i is less }
than n, the statement in the If there is no initialization to be done, then the
for loop is executed and the initialization statement can be skipped by giving only
value ofi is printed. After every iteration, the value of i is a semicolon. This is shown in
incremented. When i=n, the control jumps to the return Programming Tip: the following code.
0 statement,
erated #include <stdio.h>
nip int main()
Points to Remember About for Loop
* Ina for loop, any or all the expressions can be omitted.
reeaipeareybiy ftint i=0;
In case all the expressions are omitted, then there must paaaatig talecead for(;i<10;i++)
be two semicolons in the for statement oe oe fs printf("xd", i);
* There must be no semicolon after a for statement. If ashes dati return 0;
avoid itas mi as }
you do that, then you are sure to get some unexpected
results, Consider the following code.
Decision Control and Looping Statements 223

* Multiple conditions in the test expression can be tested #include <stdio.h>


by using logical operators (88 or | |). int main()
* If the loop controlling variable is updated within the {
statement block, then the third part can be skipped. This float i;
is shown in the code given below for (i=100;i>=10;)
{
#include <stdio.h> printf(" Xf", i);
int main() i = (float)i/10;
{ }
int i=0;
return 0;
for(;1<10;)
}
{
printf(" Xd", 4); Selecting an appropriate loop Loops can be entry-
i\i+; controlled (also known as pre-test) or exit-controlled (also
} known as post-test), While in an entry-controlled loop,
return 0;
condition is tested before the loop starts, an exit-controlled
} loop, on the other hand, tests the condition after the loop
* Multiple statements can be included in the third part is executed, If the condition is not met in entry-controlled
of the for statement by using the comma operator. For loop, then the loop will never execute, However, in case of
example, the for statement given below is valid in C. post-test, the body of the loop is executed unconditionally
for(inO, jwl0j;icj; ist, j--) for the first time.
If your requirement is to have a pre-test loop, then
* The controlling variable can also be incremented choose cither for loop or while loop, In case, you need to
decremented by values other than 1. This is shown in the have # post-test loop then choose a do-while loop.
code below which prints all odd numbers from 1 to 10. Look at Table 10.2 which shows a comparison between
#include <stdio.h> 4 pre-test loop and a post-test loop.
int main()
{ [Table 10.2}Comparison of pre-test and post-test loops
int 4;
for (il; i<@l10;ie=2) Feature Pre-test loop | Post-test loop
printf(" Xd", 4); |Initialization 1 1
return 0; Number oftests Nel N
} | Statements executed N N
* If the for loop contains nothing but two semicolons, Loop control variable N N
that is no initialization, condition testing, and updating update
of the loop control variable
Minimum iterations 0 '
Programming Tip: then the for loop may become
Although placingan an infinite loop if no stopping
arithmeticexpression = condition is specified in the When we know in advance the number of times the
in initialization
and body of the loop. For example, loop should be executed, we use a counter-controlled loop.
updating section the following code will The counter is a variable that must be initialized, tested,
of the for loop is infinitely print C Program- and updated for performing the loop operations. Such a
permissible, tryto ming on the computer screen counter-controlled loop in which the counter is assigned
avoid them as they @ constant or a value is also known as a definite repetition
may cause some #include <stdio.h> loop
round-off and/or int main()
When we do not know in advance the number of times
truncation errors, the loop will be executed, we use a sentinel-controlled
for(;5) loop. In such a loop, a special value called the sentinel
printf(" C Programming”);
value is used to change the loop control expression from
return 0;
truc to false. For example, when data is read from the
} user, the user may be notified that when they want the
* Never use a floating point variable as the loop control execution to stop, they may enter -1. This value is called
variable. This is because floating point values are just a sentinel value. A sentinel-controlled loop is often useful
approximations and therefore may result in imprecise for indefinite repetition loops.
values and thus inaccurate test for termination. For If your requirement is to have a counter-controlled
example, the following code will result in an infinite loop, then choose for loop, else if you need to have a
loop because of inaccuracies of floating point numbers. sentinel-controlled loop, then go for either a while loop
et Computer Fundamentals and Programming in C

“OF a do-while loop. Although a sentinel-controlled loop }


canbe implemented using for loop. while, and do-while return 0;
loops offer better option. }
33. Write a program to print the following pattern.
NESTED LOOPS .
7
C allows its users to have nested loops, i.c., loops that can tee
be placed inside other loops. Although this feature will tee
work with any loop such as while, do-while, and for, sewer
it is most commonly used with the for loop, because this
is easiest to control. A for loop can be used to control the #include <stdio.h>
int main()
number of times that a particular set of statements will be
executed. Another outer loop could be used to control the {
number of times that a whole loop is repeated. int i, Jj;
for(i=l;i<=S;it+)
In C, loops can be nested to any desired level. However,
loops should be properly indented so that a reader can {
easily determine which statements are contained within printf("\n");
cach for statement. To sec the benefit of nesting loops, for(j=15j<=i;
j++)
printf("*");
we will see some programs that exhibit the use of nested
loops. }
return 0;
}
31. Write a program to print the following pattern.
Pass 1-12345 34. Write a program to print the following pattern,
Pass 2-12345 1
Pass 3-12345 12
Pass 4-12345 123
Pass 5-12345 1234
tinclude <stdio.h> 12345
int main() include <stdio.h>
{ int main()
int 4, J;
for(i=ljiceS;
ive) int i, jj;
| for(i=ljic#S;i++)
printf("\n Pass %d- “,1i); {
for(j=1;j<55 j++) printf("\n");
printf(" %d", 3)5 for(j=1;j<wi;jr+)
} printf("%d", 3)
return 0; }
} return 0;
}
32. Write a program to print the following pattem.
ARE 35. Write a program to print the following pattern,
eee 1
Pere eer eer 22
nae 333
kee thee coal
#include <stdio.h> 55555
int main() #include <stdio.h>
{ int main()
int i, j; {
for(i=1;i<=5;i++) int i, j;
{ for(i=1;ic=5;i++)
printf("\n"); {
for(j=1; j<=10; j++) printf("\n");
printf("*"); for(j=1;j<=i; j++)
Decision Control and Looping Statements 225

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

41. Write a program to print the multiplication table of n, int main()


where n is entered by the user. {
#include <stdio.h> int n, i, sum =0;
int main() float avg = 0.0;
clrser();
{
int n, i;
printf("\n Enter the value of n: “);
printf("\n Enter any number: scanf("Xd", &n);
scanf("Xd", &n); for(isl;icen;ite)
sum = sum + i;

printf("\n Multiplication table of Xd” avg = (float) sum/n;


printf("\n The sum of first n natural numbers
Printh(“\n *eeeeecesercesececouses®);
for(in0;ic#20;i+) = Xd", sum);
printf("\n %d X Xd = Xd", n, i, (mn * 4)); printf("\n The average of first n natural
return 0; numbers = %.2*", avg);
return 0;
}
Output
}
Output
Enter any number: 2
Multiplication table of 2 Enter the value of n: 10
The sum of first n natural numbers = 55
2X0#0 The average of first n natural numbers = 5.50
2X1"2
44, Write a program using for loop to calculate factorial
of a number,
2X 20 = 40

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

scanf("%d", &num); return 0;


for(i=2; icnum/2;i++) }
{ Output
if(numXi == 0)
Enter -1 to exit
{
flag =1; Enter any number: 5
break; Enter any number: 10
} Enter any number: 7
} Enter any number: -1
if(flag <= 1) Count of prime numbers entered = 2
printf("\n %d is a composite number”, num); Count of composite numbers entered = 1
else
47. Write a program to calculate pow(xy1) ic., to calculate x"
printf("\n %d is a prime number", num);
return 0; #include <stdio.h>
} #include <conio.h>
Output
#include <math.h>
int main()
Enter the number: 5
{
5 is a prime number int i, num, n;
long int result 1;
46. Write a program using do-while loop to read the
clrser();
numbers until —1 is encountered. Also count the
printf("\n Enter the number: ");
number of prime numbers and composite numbers
scanf("Xd", Snum);
entered by the user
printf("\n Till which power to
#include <stdio.h> calculate: *);
#include <conio.h> scanf("Xd", &n);
int main() for(iwl;icenjire)
{ result = result * num;
int num, 4; printf("\n pow(Xd, Xd) = %ld", num, n,
int primes«O, composites#0, flag~O; result);
clrser(); return 0;
printf("\n Enter -1 to exit"); }
printf("\n\n Enter any number:"); Output
scanf("%d" ,&num);
do Enter the number: 2
Till which power to calculate: 5
for (1=2;i<=num/2;
i++) pow(2, 5) = 32
{ 48. Write 4 program to print the reverse of a number,
if (numXi==0)
{ #include <stdio.h>
flage1; #include <conio.h>
break; int main()
{
}
} int num, temp;
if(flage=0) clrser();
primes++
else printf("\n Enter the number: ");
composites++; scanf("Xd", &num) ;
printf("\n The reversed number is: “);
flage0; while(num != 0)
printf("\n\n Enter any number: ");
scanf("%d", &num) ; temp = num&10;
} while(num |= -1); printf ("%d", temp) ;
printf("\n Count of prime numbers entered = num = num/10;
%d", primes); }
printf("\n Count of composite numbers entered return 0;
= Xd", composites); }
228 Computer Fundamentals and Programming in C

Output $1. Write a program to enter a decimal number. Calculate


and display the octal equivalent of this number
Enter the number: 123
The reversed number is: 321 include <stdio.h>
#include <conio.h>
49, Write a program to enter a number and then calculate
@include <math.h>
the sum of its digits,
#include <stdio.h> int main()
#include <conio.h>
{
int main() int decimal_num, remainder, octal_num = 0,
{ i= 0;
int num, temp, sumofdigits «
cleser();
clrscr(); printf("\n Enter the decimal number:
printf("\n Enter the number: "); scanf("%d", &decimal_num);
scanf("%d", &num); while(decimal
num |= 0)
{
while(num |= 0) remainder = decimal_num%8;
octal_num += remainder*pow(10,i);
temp = numX10; decimal_num = decimal_num/8;
sumofdigits += temp; ie;
num = num/10;
}
} printf("\n The octal equivalent = Xd", octal_
printf("\n The sum of digits = %d", num);
sumofdigits); return 0;
return 0;
}
}
Output
Output
Enter the decimal number: 18
Enter the number: 123 The octal equivalent = 22
The sum of digits » 6
$2. Write a program to enter a binary number, Calculate
50. Write a program to enter a decimal number. Calculate
and display the decimal equivalent of this number,
and display the binary equivalent of this number
#include <stdio.h>
#include <stdio.h>
#include <conio.h>
#include <conio.h>
#include <math.h>
#include <math.h>

int main() int main()


{ {
int decimal _num = 0, remainder, binary_num,
int decimal_num, remainder, binary_num = 0,
i= 0; i= 0;
clrscr(); clrser();
printf("\n Enter the decimal number:
printf("\n Enter the binary number: ");
scanf("%d", &decimal_num); scanf("Xd", &binary_num);
while(decimal_num != 0) while(binary_num |= 0)
{ {
remainder = decimal_numX2; remainder = binary_numX10;
binary_num += remainder*pow(10,i); decimal_num += remainder*pow(2,i);
decimal_num = decimal_num/2; binary_num = binary_num/10;
itt; itt;
} }
printf("\n The binary equivalent = Xd", printf(“\n The decimal equivalent = Xd",
binary_num); decimal_num);
return 0; return 0;
} }
Output Output
Enter the decimal number: 7 Enter the binary number : 111
The binary equivalent = 111 The decimal equivalent = 7
Decision Control and Looping Statements 229

$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

lis syntax is quite simple, just type keyword continue


do
followed with a semicolon. {
continue; if (condition)
* continue ;
Again like the break statement, the continue statement
cannot be used without an enclosing for, while, ordo-while }while( Pere
statement, When the continue statement is encountered in
the while and do-while loops, the control is transferred Transfers control Transfers control
to the code that tests the controlling expression. However, to the condition to the condition
if placed within a for loop, the continue statement causes expression of the expression of the
while loop do-while loop
a branch to the code that updates the loop variable. For
example, look at the following code.
include <stdio.h>
int main() for(...)
{ {
int i; if (condition) for(:
for(iwl; ic# 10; i++) continue ; {
{ iF(condition)
if (ie=5)
}
continue;
continue;
printf("\t Xd", 4); Transfers control
to the condition
} expression of the
return 0; for loop Transfers control
} to the condition
expression of the
The code given here is meant to print numbers from 1 to inner for loop
10. But as soon as i becomes
Programming Tip: equal to 5, the continue Figure 10.10 continue statement
As far as possible, statement is encountered,
try not touse so rest of the statements in
do
goto, break, and the for loop are skipped
continue statements = and the control passes to the {
as they violate the expression that increments the printf("\n Enter any number. Enter 999 to
rules ofstructured value of 4. The output of this stop: ");
programming. program would thus be
scanf("Xd", Shum);
if(num == 999)
22RSHaA?
FF break; // quits the loop
if (num < 0)
(Note that there is no $ in the series. It could not be printed,
as continue causes skipping of the statement that printed {
printf(“\n Square root of negative numbers is
the value of 4on screen).
not defined");
Figure 10.10 illustrates the use of continue statement
continue; // skips the following statements
in loops.
Hence, we conclude that the continue statement is }
printf(“\n The square root of Xd is Xf", num,
somewhat the opposite of the break statement. It forees
sqrt(num));
the next iteration of the loop to take place, skipping
any code in between itself and the test condition of the
Jwhile(1);
return 0;
loop. The continue statement is usually used to restart
a statement sequence when an error occurs, Look at the }
program code given below that demonstrates the use of
break and continue statements.
65, Write a program to calculate square root of a number.
goto STATEMENT
#include <stdio.h> The goto statement is used to transfer control to a
#include <math.h> specified label. However, the label must reside in the
int main() same function and can appear only before one statement in
{ the same function. The syntax of goto statement is shown
int num; in Figure 10.11
234 Computer Fundamentals and Programming in C
int num, sum=0;
goto Label read: // label for goto statement
printf("\n Enter the number. Enter 999 to end:
or)
scanf(“Xd", &num);
if (num t= 999)
{
if(num < 0)
goto read; // jump to label- read
sum += num;
goto read; // jump to label- read
}
goto Label printf(“\n Sum of the numbers entered by the
user is = Xd", sum);
Backward jump return 0;
Figure 10.11 goto statement }

Here, label is an identifier that specifics the place


Conclusion
where the branch is to be made, Label can be any valid * Itis not necessary to use goto statement as it can always
variable name that is followed by a colon (;). The label be eliminated by rearranging the code.
is placed immediately before the statement where the Using the goto statement violates the rules of structured
control has to be transferred. programming.
The label can be placed anywhere in the program * It is a good programming practice to use break,
cither before or after the goto statement. Whenever the continue, and return statements in preference to goto
goto statement is encountered the control is immediately whenever possible.
transferred to the staterm following the label. * Goto statements make the program code complicated
Therefore, goto statement breaks the normal sequential and render the program unreadable
execution of the program. If the Label is placed after the
goto statement, then it is called a forward jump and in
case it is located before the goto statement, it is said to be One must avoid the use of break, continue, and goto
a backward jump statements as much as possible as they are techniques
The goto statement is often combined with the if used in unstructured programming.
statement to cause a conditional transfer of control.
IF condition THEN goto Label In structured programming, you must prefer to use
In this book, we will not use the goto statement because if and if-else constructs to avoid such statements. For
computer scientists usually avoid this statement in favour example, look at the following code which calculates the
of the ‘structured programming’ paradigm. Some scientists sum of numbers entered by the user. The first version u:
think that the goto statement should be abolished from the break statement. The second version replaces break
higher-level languages because they complicate the task by if-else construct
of analysing and verifying the correctness of programs // Uses break statement
(particularly those involving loops). #include <stdio.h>
Moreover, structured program theory proves that the int main()
availability of the goto statement is not necessary to {
write programs, as combination of sequence, selection, int num, sum=0;
and repetition constructs is while(1)
Programming Tip: sufficient to perform any {
Follow proper computation, The code given printf("\n Enter any number. Enter -1 to
indentation forbetter below demonstrates the use of stop: ");
clarity, readability, a goto statement. The program scanf("%d", &num);
and understanding of the sum of all if (num==-1)
the loops. positive numbers entered by break; // quit the loop
the user. sume=num;
#include <stdio.h> }
int main() printf("\n SUM = %d", sum);
{ return 0;
Decision Control and Looping Statements 235

} 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.

type. 7 statements help to jump from one part of


3. Ina do-while loop, if the body of the loop is executed n the program to another depending on whether a
times, the test condition is evaluated _ times. particular condition is satisfied or not.
4, The statement is used to skip statements 8 _ statements are used to repeat the
in a loop. execution of a list of statements
5. Aloop that always satisfies the test condition is known as 9. In _ loop, the entry is automatic and there
a loop. is only a choice to continue it further or not.
Decision Control and Looping Statements 237

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

16. Can we use a for loop when the number of iterations is }


not known in advance? If yes, give a program that
illustrates how this can be done. Programming Exercises
17. Change the following for loop into a while loop. Also 1 Write a program to read a floating point number and an
integer. If the value of the floating point number is
convert the for loop into a do-while loop.
greater than 3.14 then add 10 to the integer.
int Write a program to print the prime factors of a number.
for (i10;1>0;i--) Write a program to test if a given number Is a power of 2
printf("xd", 1); Hint: A number x is a power of 2 if x I= 0 and
18. Change the following do-while loop into a for loop. Also x & (x 1)) 0
rewrite the code by changing the do-while loop into a for Write a program to print the Floyd's triangle.
loop. Write a program to read two numbers. Then find out
whether the first number is a multiple of the second
int num;
number.
printf("\n Enter any number. Enter 999 to Write 3 program using switch case to display a menu
stop : ");
that offers 5 options: read three numbers, calculate
scanf("Xd", &num); total, calculate average, display the smallest, and display
do the largest value.
{
printf("%d", x); Write a program to display the sin(x) value where x
printf("\n Enter any number, Enter 999 to stop ranges from 0 to 360 in steps of 15.
Write a program to display the cos(x) and tan(x) values
")5
scanf("Xd", &num); where x ranges from 0 to 360 in steps of 15
}while(num |» 999); Write a program to calculate electricity bill based on the
following information
19. Change the following while loop into a do-while loop.
Also convert the while loop into a for loop Consumption unit Rate of charge
int num; [o-1s0 Rs 3 per unit |
printf("\n Enter any number. Enter 999 to stop 151-350 Rs 100 plus Rs 3.75 per unit
ys i |_ exceeding 150 units
scanf("%d", &num);
| 351-450 Rs 250 plus Rs 4 per unit
while(num |= 999)
| |_exceeding 350 units |
{
printf("X%d", x); 451-600 Rs 300 plus Rs 4.25 per unit
printf("\n Enter any number. Enter 999 to stop | |_ exceeding 450 units
er Above 600 Rs 400 plus Rs 5 per unit
scanf("Xd", &num); exceeding 600 units
}
Decision Control and Looping Statements 239

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! +

29. Write a program to print the following pattern.


Vehicle name | Rate till 3 hours | Rate after 3 hours
1
[Teuck/Bus | __-20 I 30
Car | 10 | 20
Cycle/ Motor 5 10
cycle/ Scooter |

18 Write a program to read month of the year as an integer


Then display the name of the month.
19, Write a program to print the sum of all odd numbers 30. Write a program to print the following pattern.
from 1 to 100. 1
20. Write an interactive program to read an integer. If it is 212
positive then display the corresponding binary 32123
representation of that number. The user must enter 999
31 Write a program to read a 5 digit number and then
to stop. In case the user enters a negative number then display the number in the following format. For example
ignore that input and ask the user to re-enter any
the user entered 12345, the result should be
different number.
12345 1
21 Write a program to print 20 asterisks. 2345 12
22. Write a program that accepts any number and prints the 345
number of digits in that number. 4s 1234
s 12345
240 Computer Fundamentals and Programming in C

Find the output of the following codes.


1. include <stdio.h>
int main()
{
inta=2,b=3, c= 4;
if( cl= 100)
a = 10;
else
b = 10; c);
if(a +b > 10) return 0;
c = 12; }
a = 20; include <stdio.h>
b = +c; int main()
printf(" \n a= Xd \t b= Xd \t c= Xd", {
c); int a= 2, b= 3, = 4;
return 0; if(a © || b >= « && « > 0)
} if(a && b)
2. #include <stdio.h> ¢=10;
int main() else
{ c#20;
intaes2,b#3,c#4 printf(" \n a = Xd \t b = Xd \t c = Xd", a, b
if(be=2) °)5
a0; return 0;
else }
#10; include <stdio.h>
printf("\n a = %d \t b = Xd \t c = Xd", a, b int main()
c); {
return 0; int a= 2,b=3,c#4;
} if( a= b)
cH
3, #include <stdio.h> printf(" \n a = Xd \t b = Xd \t c = Xd", a, bd,

int main() ©);


return 0;
{
inta=2,b=3,c=4; }
if (a&&b) #include <stdio.h>

#10; int main()


else {
=20; inta«2,
b= 3, c = 4;

printf(“\n a= %d \t b= Xd \t c= Xd", 2, b, if(a = b< c)


©);
return 0;
}
4, #include <stdio.h>
int main() ++b;
printf(" \n a = Xd \t b = Md \t c = Xd", a, b
©)3
return 0;
}
switch(ch)
c=20; {
printf("\n a = %d \t b = Xd \t c = Xd", a, BD case ‘a

c); case ‘A’

return 0; printf("\n A");


} case 'b':
5. #include <stdio.h> case 'B"
int main() printf("\n B");
Decision Control
and Looping Statements 241

default: if( ¢ < d)


printf("\n DEFAULT"); if (¢ <b)
} printf("\n c");
10. switch(ch) else if(a < c)
{ printf("\n a");
case ‘a if(a > b)
case ‘A’: printf("\n b");
printf("\n An); else
case 'b’ print€("\n d");
case 'B }
printf("\n B"); #include <stdio.h>
break; void main()
default: {
printf("\n DEFAULT"); char ch = 'Y';
} switch(ch)
11 switch(ch) {
{ default:
case ‘a printf("\n YES OR NO");
case ‘A’: case ‘Y’
printf("\n a"); print#("VES");
break; break;
case ‘b case 'N’
case 'B print#("NO");
printf("\n B"); break;
break; }
default: }
printf("\n DEFAULT"); #include <stdio.h>
} int main()
12 #include <stdio.h> {
void main() int num«10;

{ 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");

27. #include <stdio.h>


if(n<10) void main()
break; {
nes5 char ch = -63;
} int num = -36;
printf("\n ieXd and n=Xd", i,n); unsigned int unum = -18;
} if(ch > num)
22 include <stdio.h> {
void main() printf("A");
{ if(ch > unum)
int i#0; printf("B");
do else
{ printf("C");
printf("\n %d",i); }
its; else
}while(ice0); {
printf("\n STOP"); print#("D");
} if(num < unum)
23 #include <stdio.h> printf("E");
void main() else
{ printf("F");
int i, J; }
for(iw0;i<#10;i++) }
{ 28. #include <stdio.h>
printf("\n"); int main()
for(j=0;j<=i0;j++) {
printf(" "); int num=10;
printf("\n %d", 3)5 for (;++num;num-=2)
} printf(" Xd", num);
} urn 0;
24 #include <stdio.h>
void main() 29. #include <stdio.h>
{ int main()
int num = 10; {
printf("\n Xd", a>10); int num=10;
} for(;5)
printf("HI!!");
25. #include <stdio.h> return 0;
void main() }
{ 30. #include <stdio.h>
printf("HELLO") ; int main()
if (11) {
printf ("WORLD") ; int num=10;
Decision Control and Looping Statements 24. a

for(num++ num<=100; num=100) Find errors in the following codes.


printf ("%d", num); (a) #include <stdio.h>
return 0; void main()
} {
31, #include <stdio.h> int i=1;
int main() while(ic=10)
{ {
while(1); isi;
printf("Hi"); print#("%d", i);
return 0; ite;
} }
32. #include <stdio.h>
int main() (b) include <stdio.h>
{ void main()
int i=0; {
char c ='0'; int i;
while(i<10) for(i=0,ic#10;
i++)
{ printf("%d", i);
printf("%e", ¢ + 4);
itt; (c) #include <stdio.h>
} void main()
return 0; {
} int il;
33, #include <stdio.h> do
void main() {
{ printf("xd", i);
int i0; ive;
do }while(i#10)
{ }
if(i>10) (d) #include <stdio.h>
continue; void main()
iets {
}while(i<20); int i,j;
printf("\n iexd", i); for(in1,j=O;i+jcu10; i++)
} printf("Xd", i);
34, Hinclude <stdio.h> jen2
void main() }
{
int ie; Give the functionality of the following loops.
for(j;i<#ljier) (a) int i=1, sum=0;
{ while(i!l=10)
printf("\n &d",4); {
printf("\n STOP"); sum ¢=i;
} i = ie2;
} }
35. #include <stdio.h> (b) int 4, sum=0;
void main () for (i=1;i<=10)
{ sum=
Ant 45,95 (c) int 4;
for(i=10;i>=0;i--) for ( pic=l0;ite)

q
i--;
printé("\n*) (d) int i=10;
for(j=i;j>=0;j--)
do
printf("%d", j)5 { printf(“%d", i);
}
} while(i>0);
}
(e) int i=10;
244 ‘Computer Fundamentals and Programming in C

do (h) int i=10;


{ printf("xd", i); while(i-->0)
} while(i<5); printf("Xd", i);
(f int is1, n=10, sum=0; ) int i;
while(icen) for (i=10;i>5;i-=2)
{ printf("Xd", i);
sum+=d; ti int 4;
ite for (i=10;1>5;)
} print#(“Xd", i);
(g) int i, sum=0;
for (i#1;;i++)
sum+=i;
Decision Control and Looping Statements 245

CASE STUDY 1: Chapters 9 and 10


We have learnt the basics of programming in C language and scanf(“Xd"
,number);
concepts to write decision-making programs. bet us now apply
our learning to write some useful programs if (number==0| |number>3000)
ROMAN NUMERALS
printf ("\n INVALID NUMBER");
thousand = number/1000;
Roman numerals are written as combinations of seven letters.
hundreds = ((number/100)%10) ;
These letters include tens = ((number/10)%10) ;
ones = ((number/1)%10) ;
if (thousand ==1)
printf("M");
else if (thousand ==2)
printé("MM");
If smaller numbers follow larger numbers, the numbers are
added, Otherwise, if a smaller number precedes a larger number
else if (thousand ==3)
printf("MaM");
the smaller number is subtracted from the larger. For example, to
convert 1,100 in Roman numerals, you would write M for 1000
and then a C after it for 100, Therefore, 1100 = MC in Roman
if (hundreds == 1)
printf("c");
numerals. Some more examples include
else if (hundreds «= 2)
© Vil=$+2=7 printf("CC");
* Xel0-1=9 else if (hundreds «= 3)
* XL=50-10=40 print#("ccc");
* CX= 1004021 else if (hundreds «= 4)
* MCMLXXXIV = 1000 + (1000 ~ 100) + 50 + 30 +(S~ l= printf("CbD");
else if (hundreds ==5)
1984
printf("0");
else if (hundreds «= 6)
printf("0C");
else if (hundreds == 7)
eA
Wl printf("DCC");
else if (hundreds ==8)
4 |v printf("OCCC”);
s|v [is] xvii |31| xxxt_ | S00 | D else if (hundreds == 9)
6 | vi 19 |_XIX_| 40 XL 600 | be | printf("CM");
7 | Vil | 20 50 _700 | Dec |
rs |vin |20 “60 “g00 |pece | if (tens =» 1)
9 | 1x | 2 70 900 | cM | printf("x");
io | x | 23 80 1000 | M else if (tens 2)
i XI | 24 0 1600 | MDC printf("xX");
else if (tens == 3)
12 | XM | 25 100 c 1700 |MDCC | printf ("Xxx");
13 | XIN | 26 | XXVI} 101) Cl 1900 |MCM | else if (tens == 4)
printf("XL");
1, Write a program to show the Roman number representation
of a given number. else if (tens ==5)
#include <stdio.h>
printf("L");
#include <conio.h>
else if (tens == 6)
printf ("LX");
main()
else if (tens == 7)
{ printf ("LXx");
int number;
else if (tens ==8)
int ones, tens, hundreds, thousand;
clrser();
printf ("Lx");
printf("\n Enter any number else if (tens == 9)
(1-3000): ");
printf ("XC");
246 Computer Fundamentals and Programming in C

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

Centuries table Months table Days table


1700-1799 | 4 January I (in leap year 6) Sunday 1
1800-1899 | 2 February _| 4 (in leap year 2) Monday _|2
1900 ~ 1999 0 March 4 Tuesday 3
2000-2099 | 6 April Wednesday |4
| May [Thursday [5
June 5 Friday 16
July 10 Saturday |7
pAsget _ |3__
gust 3
A
2500 | 6
2600 —2699 October t

} 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

year = year/4; switch(day)


year = year+yy-1900; {
switch(mm) case 0:
{ // Since 7%7 = 0, case O means it's a
case 1: Saturday
case 10; printf("\n SATURDAY");
month = 1; break;
break; case 1:
case 2: printf("\n SUNDAY") ;
case 3: break;
case 11: case 2:
month = 4; printf("\n MONDAY") ;
break; break;
case 7: case 3:
case 4: printf("\n TUESDAY");
month = 0; break;
break; case 4:
case 5: printf("\n WEDNESDAY");
month = 2; break;
break; case 5:
case 6: printf("\n THURSDAY");
month = 5; break;
break; case 6:
case 8: printf("\n FRIDAY");
month = 3; break;
break; }
case 9: getch();
case 12: return 0;
month = 6; }
} breaks Output

year = year+month; Enter the date: 29 10 1981


year = yearedd; THURSDAY
day = year%7;
Functions

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

INTRODUCTION It is not necessary that the main() function can call


only one function, it can call as many functions as it wants
C enables programmers to break up a program into and as many times as it wants. For cxample, a function
call placed within a for loop, while loop, or do-while
segments commonly known as functions, cach of which
can be written more or less independently of the others. loop can call the same function multiple times until the
Every function in the program is supposed to perform a condition holds true.
well-defined task, Therefore, the code of one function is Another point is that it is not only the main() function
completely insulated from the other functions. that can call other functions. A function can call any other
Every function interfaces to the outside world in terms function. For example, look at Figure 11.2 which shows
of how information is transferred to it and how results one function calling another, and this function in tum
generated by it are transmitted back. This interface is calling some other function. From this we see that every
specified by the flinction name. For example, look at function encapsulates a set of operations and when called
Figure 11.1 which explains how the main() function calls it returns information to the calling function
another function to perform a well-defined task
11.1.1 Why are Functions Needed?

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

Figure 11.2 Functions calling another functions

Main function USING FUNCTIONS


In the second chapter, we have discussed that when we
Function A Function B Function C execute a C program, the operating system calls the main()
function of the program which marks the entry point for
the execution. When the program is executed, the main()
Function BL Function B2 function returns some value to the operating system
Any function (including main()) can be compared
Figure 11.3 Top-down approach of solving a problem to a black box that takes in input, processes it, and then
produces the result. However, we may also have a function
that does not take any inputs at all, or the one that does not
functions have been pre-written and pre-tested, so the
programmers can use them without worrying about their return anything at all.
code details, This speeds up program development, by While using functions we will be using the following
terminologies:
allowing the programmer to concentrate only on the
code that he has to write. A function /that uses another function g is known as the
* When a big program is broken into comparatively calling function and g is known as the called function
smaller functions, then different programmers working The inputs that a function takes are known as arguments
on that project can divide the workload by writing parameters,
different functions. + When a called function returns some result back to the
* Like C libraries, programmers can also write their calling function, it is said to return that result
functions and use them at different points in the * The calling function may or may not pass parameters
main program or in any other program that needs its to the called function. If the called function accepts
functionalities, arguments, the calling function will pass parameters,
Consider a program that executes 4 set of instructions else it will not do so.
* Function declaration is a declaration statement that
repeatedly » times, though not continuously. In case the
identifies a function with its name, a list of arguments
instructions had to be repeated continuously for n times,
they can be placed within a loop. But if these instructions that it accepts, and the type of data it returns.
have to be executed abruptly from anywhere within the * Function definition consists of a function header that
program code, then instead of writing these instructions
identifies the function, followed by the body of the
function containing the executable code for that function.
wherever they are required, a better idea is to place these
instructions in a function and call that function wherever
required. Figure 11.4 explains this concept
GERD FUNCTION DECLARATION/
FUNCTION PROTOTYPE
cen funci()
Before using a function, the compiler must know about
the number of parameters and the type of parameters that
the function expects to receive and the data type of the
value that it will return to the calling function. Placing
funci(); } the function declaration statement prior to its use enables
the compiler to make a check on the arguments used while
return 0; calling that function.
} The general format for declaring a function that accepts
some arguments and returns some value as a result can be
Figure 11.4 Function func1() called twice from main() given as:
250 Computer Fundamentals and Programming in C
peturn_data_type function_name(data_type + The function declaration
variablel, data_type variable2,...); Prograsaming Tip: is global. Therefore, the
eT ceteea declared function can be
Here, function_name is a valid name for the function.
Sand, coer eho called from any point in the
Naming a function follows the same rules as naming in the function espa
variables. A function should have a meaningful name that declaration, 5
+ Use of argument names in
must specify the task that the function will perform. The
function name is used to call it for execution in a program. the function declaration
Every function must have a different name that indicates statement is optional. So both declaration statements are
valid in C
the particular job that the function does.
return_data_type specifies the data type of the value int func(int, char, float);
that will be returned to the calling function as a result of
or
the processing performed by the called function.
data_type variablei, data_type variable2, — is int func(int num, char ch, float fnum);
a list of variables of specified data types. These variables
A function cannot be declared within the body of another
are passed from the calling function to the called function.
function,
They are also known as arguments or parameters that
A function having void as its return type cannot return
the called function accepts to perform its task. Table 11.1
shows examples of valid function declarations in C any value
A function having void as its parameter list cannot
accept any value. So the function declared as
LLL CRee® Valid function declarations
void print(void);
Function declaration | Use of the function
or
Retura data type Converts a character toupper case.
‘The function receives a character void print();
as an argument, converts itinto does not accept any input/arguments from the calling
char convert_to_ upper case and returns theconverted function.
uppercase (char ch); characterback tothecalling function,
If the function declaration does not specify any return
Calculates
average oftwo integer type, then by default, the function returns an integer
Funcom rease numbers a and b received as value. Therefore, when a function is declared as
arguments. The function retums a
float avg (inta,intby, floating point value. sum(int a, int b);
int findlargest (int Finds thelargest ofthreenumbers— Then the function sum accepts two integer values from
a int, inter, a,b, and ¢ received asarguments,An the calling function and in turn returns an integer value
integer value which isthe largest of to the caller,
Data typeof the three numbers is returned tothe * Some compilers make it compulsory to declare the
variable calling function, function before its usage while other compilers make
it optional. However, it is a good practice to always
double multiply Multiplies two floating point numbers declare the function before its use as it allows error
(float a,float by; aand b that are received asanguments checking on the arguments in the function call
Variable and returns a double value.

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()

Function definitions are often placed in separate header {


files which can be included in other C source files that int numl, num2, total = 0;
wish to use these functions. For example, the header printf("\n Enter the first number: “);
252 Computer Fundamentals and Programming in C
scanf("Xd", &numi); following the function call
Programming A
printf("\n Enter the second number: ieee dhe Refer Figure 11.2 in which the
scanf("Xd", &num2) ; Ina control passes from the called
total = sum(num1, num2); function to the calling function
function that has void
// FUNCTION CALL os itsreturn when the return statement is
printf("\n Total = %d", total); encountered.
return 0; A return statement may or may not return a value to
the calling function. The syntax of return statement can
be given as
// FUNCTION DEFINITION
int sum (int a, int b) // FUNCTION HEADER return <expression>;
{ // FUNCTION BODY Here expression is placed in between angular brackets
int result; because specifying an expression is optional. The value of
result = a + b; expression, if present, is returned to the calling function
return result; However, in case expression is omitted, the return value
} of the function is undefined.
The expression, if present, is converted to the type
Output
returned by the function. A function that has void as its
Enter the first number; 20 return type cannot return any value to the calling function.
Enter the second number; 30 So in a function that has been declared with return type
Total = SO void, a return statement containing an expression
generates a warning and the expression is not evaluated,
The variables declared within the function and its Por functions that have no return statement, the control
parameters are local to that automatically returns to the calling function after the last
incite as function. The programmer statement of the called function is executed. In other words
void aethe retary may use same names for an implicit return takes place upon execution of the last
type when the variables in other functions. statement of the called function, and control automatically
function is This climinates the need for returns to the calling function
is faluens Noliie thinking and keeping unique
thecalling function. names for variables declared
in all the functions in the The programmer may or may not place the expression in
program.
2 return statement within parentheses.
In the sum() function, we have declared a variable
By default, the return type of a function is int.
result just like any other variable. Variables declared
within a function are called automatic local variables
A function may have more

Whentbevave ‘humans retusa


because of two reasons.
* First, they are local to the function.So, their effect (in
terms of scope, lifetime, or accessibility) is limited to rab given below
the function, Any change made to these variables is function is assigned 8
visible only in that function. toa variable, then #include <stdio.h>
Sccond, they are automatically created whenever the the returned value #include <conio.h>
function is called and cease to exist after control exits is converted to the int check_relation(int a,
the function. type of the variable int b);
receiving it. int main()
{
A function cannot be used on the left side of an int a=3, b=5, res;
assignment statement. Therefore writing, func(10) = clrser();
100; isinvalid in C, where func isa function that accepts res = check_relation(a, b);
if(res==0) // Test the returned value
an integer value,
printf("\n EQUAL(");
if(res==1)
return STATEMENT printf("\n a is greater than b(");
if(res==-1)
The return statement terminates the execution of the called printf("\n a is less than b(");
function and returns control to the calling function. When getch();
the return statement is encountered, the program execution return 0;
resumes in the calling function at the point immediately
Functions 253

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

variables in the calling function. int num = 2;


Functions ess

printf("\n The value of num before printf("\n In main(), ¢ = Xd and d =


calling the function = %d", num); x", c, 4);
add(&num) ; return 0;
printf("\n The value of num after calling }
the function = %d", num); void swap_call_by val(int a, int b)
return 0; {
} int temp;
temp = a;
void add(int *n) a-b;
{ b = temp;
*n = *n + 10; printf("\n In function (Call By Value
printf("\n The value of num in the called Method) a = %d and b = Xd", a, b);
function = Xd", *n); }
} void swap_call
by _ref(int *c, int *d)

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: }

* Since arguments are not copied into new variables, it


Output
provides greater time and space efficiency. In main(), 3 = 1 and b = 2
The called function can change the value of the argument In function (Call By Value Method) a = 2 and
and the change is reflected in the calling function. b=1
* Areturn statement can return only one value. In case In main(), a= 1 and b= 2
we need to return multiple values, pass those arguments
by reference In main(), c« 3 and d= 4
In function (Call By Reference Method) c = 4
Disadvantages andd=3
In main(), ¢ = 4 and d « 3
However, the side-effect of using this technique is that
when an argument is passed using call by address, it 3. Write a program to find biggest of three integers using
becomes difficult to tell whether that argument is meant functions.
for input, output, or both. include <stdio.h>
Now let us write a few programs that use both the call- int greater(int a, int b, int c);
by-value and the call-by-reference mechanisms.
int main()
2. Write a function to swap the value of two variables. {

#include <stdio.h> int numl, num2, num3, large;


void swap_call_by val(int, int); printf("\n Enter the first number: ");
void swap_call_by_ref(int *, int *); scanf("%d", &num1);
int main() peintf("\n Enter the second number: ");
{ scanf("Xd", &num2);
int a=1, be2, c#3, d=4; printf("\n Enter the third number:
printf(“\n In main(), a = Xd and b = Xa", scanf("%d", &num3);
a, b);
swap_call
by val(a, 6); large = greater(num1, num2, num3);
printf("\n In main(), a = Xd and b = Xd", printf("\n Largest number = %d", large);
a, b); return 0;
printf("\n\n In main(), ¢ = %d and d = }
xd", c, d)5
swap_call_by_ref(&c, &d); int greater(int a, int b, int c)
// address of the variables is passed {
256 Computer Fundamentals and Programming in C
if(a>b && a>c) mins = hrs*60 + mins;
return a; return mins;
if(b>a && b>c) }
return b; Output
else
return ¢; Enter hours and minutes: 4 30
} Total minutes = 270

Output 6. Write a program to calculate P/n/r).


Enter the first number : 45 include <stdio.h>
Enter the second number: 23 #include <conio.h>
Enter the third number : 34 int Fact(int);
Largest number = 45 int main()
{
4, Write a program to calculate area of a circle using int n, ¢;
function, float result;
#include <stdio.h> elrser();
float cal_area(float r); printf("\n Enter the value of n: “);
int main() scanf("Xd", &n);
{ printf("\n Enter the value of r: ");
float area, radius; scanf("Xd", &r);
printf("\n Enter the radius of the result = (float)Fact(n)/Fact(r);
circle: "); printf("\n P(n/r): P(%d)/(%d) = %.2", 1
scanf("Xf", &radius); r, result);
area « cal_area(radius); getch();
printf("\n Area of the circle with radius return 0;
Xf = Xf", radius, area); }
return 0; int Fact(int num)
}
float cal_area(float radius) int fel, 4;
{ for(isnum;ire1;i--)
return (3.14 * radius * radius); f = f*i;
} return f;
Output }
Output
Enter the radius of the circle: 7
Area of the circle with radius 7 = 153.83 Enter the value of n: 4
Enter the value of r: 2
§. Write a program to convert time to minutes. P(n/r): P(4)/(2) = 12.00
#include <stdio.h>
#include <conio.h> 7. Write a program to calculate C/n/r)
int convert_time_in_mins(int hrs, int #include <stdio.h>
minutes); #include <conio.h>
int main() int Fact(int);
{ int main()
int hrs, minutes, total mins; {
printf("\n Enter hours and minutes: “); int n, 5
scanf("Xd Xd", &hrs, &minutes); float result;
total_mins = convert_time_in_mins(hrs, clrscr();
minutes); printf("\n Enter the value of n:
printf("\n Total minutes = Xd", total_ scanf("Xd", &n);
mins); printf("\n Enter the value of r:
getch(); scanf("Xd", &r);
return 0; result = (float)Fact(n)/(Fact(r)*Fact(n-r));
} print€("\n C(n/r) : C(%d)/(Xd) = %.2#",
r, result);
int convert_time_in_mins(int hrs, int mins) getch();
{ return 0;
Functions 257

} 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 */

printf("\n The value of x outside the


while loop is %d", x); return 0;
return 0; }
} In this example, the label Loop is visible from the beginning
to the end of the main() function. Therefore, there should
Output
not be more than one label having the same name within
The value of x outside the while loop is 10 the main() function.
The value of x inside the while loop is 0
The value of x inside the while loop is 1 11.8.3 Program Scope
The value of x inside the while loop is 2 Till now we have studied that variables declared within
The value of x outside the while loop is 10 a function are local variables. These local variables (also
You may get an error known as internal variables) are automatically created
capper insta message while executing this when they are declared in the function and are usable only
Try to avoid variable ha bung cies
code. This is because some C within that function. The local variables are unknown to
cteplypatesse compilers make it mandatory other functions in the program, Such variables cease to
beadtartal
scope.
eleaeaa! to declare all the variables first exist after the function in which they are declared is exited
before you use them, i.c., they and are re-created each time the function is called
permit declaration of variables However, if pu want
right after the curly brackets of main() starts. a function t access some
Hence, we can conclude two things A global variable variables which are not passed
Variables declared with same names as those in outer can be used from to it as arguments, then declare
block mask the outer block variables while executing anywhere in the those variables outside any
the inner block. program whereasthe function blocks, Such variables
In nested blocks, variables declared outside the inner local variable ceases are commonly known as global
blocks are accessible to the nested blocks, provided these to exist outside the variables and can be aceessed
variables are not re-declared within the inner block function in which it is from any point in the program.
declared.
Ufetime Global variables are
created at the beginning of program execution and remain
In order to avoid error, a programmer must use different in existence throughout the period of execution of the
names for variables not common to inner as well asouter program. These variables are known to all the functions in
blocks, the program and are accessible to them for usage. Global
variables are not limited to a particular function so they
exist even when a function calls another function. These
11.8.2 Function Scope variables retain their value so that they can be used from
Function scope mdicates that a variable is active and every function in the program.
visible from the beginning to the end of a function. In C, Place of Declaration The global variables are declared
only the goto label has function scope. In other words outside all the functions including main(). Although there
Functions | (259

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;

then x is an integer that has automatic storage. It is deleted


Functions are considered tobeself-contained
and when the block in which x is declared is exited
independent modules. So they need to be isolated from The auto storage class can be used to declare variables
the rest of the code, but using global variables goes in a block or the names of function parameters. However,
against this idea behind creating independent functions. since the variable names or names of function parameters
by default have automatic storage, the auto storage class
specifier is therefore treated as redundant while declaring
11.8.4 File Scope data.
When a global variable is accessible until the end of the Important things to remember about variables declared
file, the variable is said to have file scope. To allow a with auto storage class are as follows:
260 Computer Fundamentals and Programming in C

* 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

External variables may be declared outside any function


in a source code file as any other variable is declared. But
The extern specifier tells the compiler that the variable
usually external variables are declared and defined at the
has already been declared elsewhere and therefore
beginning of a source file.
it should not allocate storage space for that variable
Memory is allocated for external variables when the
program begins execution, and remains allocated until the again. During compilation of the program, the linker will
program terminates, External variables may be initialized automatically resolve the reference problem.
while they are declared. However, the initializer must be a
constant expression. The compiler will initialize its value In a multi-file program, the global variable must
only once during the compiler time. In case the extern be declared only once (in any one of the files) without
variable is not initialized, it will be initialized to zero by using the extern keyword. This is because otherwise the
default linker will have a conflict as to which variable to use and
External variables have global scope, ic. these therefore in such a situation it raises a warning message.
variables are visible and accessible from all the functions
in the program, However, if any function has a local 11.9.4 static Storage Class
variable with the same name and type as that of the global While auto is the default storage class for all local variables,
or extern variable, then references to the name will access static is the default storage class for all global variables.
the local variable rather than the extern variable. Hence Static variables have a lifetime over the entire program,
extern variables are overwritten by local variables. i.e., memory for the static variables is allocated when
Let us now write a program in which we will use the the program begins running and is freed when the program
extern keyword. terminates, To declare an integer x as static, write
// FILE 1.€ static int x = 10;
Here x is a local static variable, Static local variables when
#include <stdio.h>
defined within a function are initialized at the runtime, The
#include <FILE2.C>
difference between an auto variable and a static variable is
// Programmer’s own header file
that the static variable when defined within a function is not
int x;
re-initialized when the function is called again and again. It
void print(void);
is initialized just once and further calls of the function share
int main()
the value of the static variable. Hence, the static variable
{ inside a function retains its value during various calls.
x = 10;
When a static variable is not explicitly initialized
printf("\n x in FILEL = Xd", x);
by the programmer, then it is automatically initialized to
print();
zero when memory is allocated for it. Although static
return 0;
automatic variables exist even after the block in which
} they are defined terminates, their scope is local to the
// END OF FILE1.C
block in which they are defined,
// FILE2.C
Static storage class can be specified for auto as well as
#include <stdio.h>
extern variables. For example we can write,
extern int x;
void print() static extern int x;
{ When we declare a variable as extern static variable,
printf("\n x in FILE 2 = Xd", x); then that variable is accessible from all the functions in
} this source file.
main()
{
// Statements
static variables can be initialized while they are being
}
// END OF FILE2.C declared, But this initialization isdone only once at the
compile time when memory isbeing allocated for the
Output static variable. Further, the value with which the static
x in FILE1 = 10 variable
isinitialized must be a constant expression.
x in FILE2 = 10

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

Table 11.2 Comparison of storage classes

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

int main() 11.9.5 Comparison of Storage Classes


{
printf("\n First call of print()("); Table 11.2 compares the key features of all the storage
print(); classes
printf("\n\n Second call of print()(");
print();
print("\n\n Third call of print()(*); GEERT) RECURSIVE FUNCTIONS
print(); .
return 0; A recursive function is defined as a function that calls
} itself to solve a smaller version of its task until a final
call is made which does not require a call to itself, Every
void print() recursive solution has two major cases;
{ + Base case, in which the problem is simple enough to be
static int x; solved directly without making any further calls to the
int y = 0; same function.
printf("\n Static integer variable, x = * Recursive case, in which first the problemat hand is
Ra", x)5 divided into simpler sub-parts, Second the function
printf("\n Integer variable, y = %d", y); calls itself but with sub-parts of the problem obtained in
xt} the first step. Third, the result is obtained by combining
yres the solutions of simpler sub-parts.
} Therefore, recursion is defining a large and complex
Output problem in terms of smaller and more casily solvable
problems. In recursive function, a complex problem is
First call of print() defined in terms of simpler problems and the simplest
Static integer variable, x = 0 problem is given explicitly.
Integer variable, y = 0
To understand recursive functions, let us take an
example of calculating factorial of a number. To calculate
Second call of print() n!, we multiply the number with factorial of the number
Static integer variable, x = 1 that is | less than that number. In other words, a! =n *
Integer variable, y = 0 (n-1)!
Let us say we need to find the value of 5!
Third call of print()
Static integer variable, x = 2 S1=Sx4x3%2x1
Integer variable, y = 0 = 120
Functions 263

This can be written as


5!=5 * 4! , where 4!
int Fact(int n)
{
Therefore, if(n==1)
St=5*x 4x3! return 1;

Similarly, we can also write,


else
return (n * Fact(n-1));
S!=5x4x3x2!
}
Expanding further
From the aforegiven example, let us analyse the basic
Sl=Sx 4x3 2x1! steps of a recursive program.
We know, I! = 1 Step 1: Specify the base case which will stop the function
Therefore, the serics of problems and solutions can be from making a call to itself
given as shown in Figure 11.6, Step 2: Check to see whether the current value being
processed matches with the value of the base
case. If yes, process and return the value
PROBLEM SOLUTION Step 3: Divide the problem into smaller or simpler sub-
s! $x4x3 x2 x11 problems.
=Sx 4! = Sx 4x3xK2x1
=5x4x31 © Sx 4x3x2 Step 4: Call the function from the sub-problems.
=Sx4x3x2! «Sea x6 Step 5: Combine the results of the sub-problems.
#SK 4x 3X21! «5x24 Step 6: Return the result of the entire problem
- 128

Figure 11.6 Recursive factorial function


The base case of a recursive function acts as the
terminating condition. So, in the absence of an explicitly
Now if you look at the defined base case, a recursive function would call itself
td ingTip: problem carefully, you can see indefinitely.
Every recursive .
that we can write 4 recursive
irae loneind function to calculate the
at least one base i
factorial of a number, Every 11.10.1 Greatest Common Divisor
oblodaheen recursive function must have a
recursive function will
infinite :
base case ‘
and a recursive fcase. The greatest common divisor (GCD) of two numbers
sunive eeofcalls
sequence
For the factorial function, (integers) is the largest integer that divides both the
numbers. We can find the GCD of two numbers recursively
thereby resulting in * Base case is when n = 1, by using the Euclid's algorithm that states
an error condition because if m= 1, the result
known asan
infinite will be Las I! = 1 {b, if b divides a
stack. * Recursive case of the GCD(a, b)
factorial function will call
|GCD (6, a mod b), otherwise
itself but with a smaller value of n, this case can be GCD can be implemented as a recursive function
given as because if b does not divide a, then we call the same
function (GCD) with another set of parameters that
factorial(n) =n * factorial(n —1) are smaller and simpler than the original ones. Here we
Look at the following code which calculates the assume that a > 6, However if a < b, then interchange a
factorial of a number recursively and + in the aforegiven formula.
#include <stdio.h>
int Fact(int);
Working
int main() Assume a 62 and b= 8
{ GCD(62, 8)
int num, factorial; rem = 62% 8=6
printf(“\n Enter the number: “); GCD(8, 6)
scanf("Xd", &num); rem=8 %6=2
factorial = Fact(num); GCD(6, 2)
printf("\n Factorial of %d = Xd", num, rem = 6 %
factorial); Return 2
return 0; Return 2
Return 2
264 Computer Fundamentals and Programming in C

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 GCD(int x, int y)


That is, the third term of the series is the sum of the
first and second terms. Similarly, fourth term is the sum
{
int rem; of second and third terms, and so on. Now we will design
rem = xXy; a recursive solution to find the n term of the Fibonacci
if(rem==0) series. The general formula to do so can be given as:
return y; 0, ifn=0
else
return (GCD(y, rem)); FIB(n) is n=1
} (PIB (n 1) + FIB (n — 2), otherwise
As per the formula, FIB(O) « 0 and FIB(1) @ | and,
11.10.2 Finding Exponents
FIB(2) = FIB(1) + FIB(O) = 1 +0 = 1, So we have
two base
We can find exponent of a number using recursion. To find cases. This is necessary because every problem is divided
x’, the base case would be when y = 0, as we know that any into two smaller problems,
number raised to the power 0 is 1. Therefore, the general
formula to find x’ can be given as 12. Write a program to print the Fibonacci series using
recursion,
{lifye=0 #include <stdio.h>
EXP(x,9»)= 4 int Fibonacci(int);
|x x EXP(x!"'), otherwise
int main()
{
Working int n, i = 0, res;
exp_ree(2,4) =2 * exp_ree( 2, 3) printf("Enter the number of terms\n(");
exp_ree(2, 3) = 2 * exp_ree( 2, 2) scanf("%d",&n);
exp_ree(2, 2) 2 x exp_reef 2, 1) printf("Fibonaced series\n(");
exp_ree(2, 1) = 2 x exp_ree{ 2, 0) for(i = 0; i <n; it+ )
exp_ree( 2, 0)=1 {
exp_ree( 2, 1) =2 2 res = Fibonacci(i);
exp_ree( 2, 2 x2=4 printf ("Xd\t", res);
exp_ree(2,3)=2x4=8 }
exp_ree( 2,4) = 2x 8 = 16 return 0;
}
11. Write a program to calculate exp(x.y) using recursive int Fibonacci(int n)
functions, {
#include <stdio.h> if (n==0)
int exp_rec(int, int); return 0;
int main() else if (n==1)
{ return 1;
int num1, num2, res; else
printf("\n Enter the two numbers: “); return ( Fibonacci(n-1) +
scanf("Xd %d", &numi, &num2); Fibonacci(n-2) );
res = exp_rec(num1, num2); }
Functions 265

Output 11.11.3 Tail Recursion


Enter the number of terms 5 A recursive function is said to be fail recursive if no
Fibonacci series operations are pending to be performed when the recursive
Sti 2 & function returns to its caller. When the called function
returns, the returned value is immediately returned from
the calling function. Tail recursive functions are highly
GERBER tyres OF RECURSION desirable because they are much more efficient to use as the
amount of information that has to be stored on the system
Recursion is a technique that breaks a problem into one or stack is independent of the number of recursive calls
more sub-problems that are similar to the original problem. For example, the factorial function that we have written
Any recursive function can be characterized based on is anon-tail-recursive function (Figure 11.9), because there
is a pending operation of multiplication to be performed
+ whether the function calls itself directly or indirectly on return from cach recursive call
(direct or indirect recursion),
whether any operation is pending at each recursive call
(tail-recursive or not), and int Fact(int n)
* the structure of the calling pattern (/inear or tree {
recursive) if (ne=1)
In this section, we will discuss all these types of return 1;
recursions.
else
return (n * Fact(n-1));
11.11.1 Direct Recursion
}
A function is said to be directly recursive if it explicitly
calls itself. For example, consider Figure 11.7 Figure 11.9 Non-tail recursive function

int Func(int n) Whenever there is a pending operation to be performed,


the function becomes non-tail recursive. In such a non-
if (new)
return nj; tail recursive function (Figure 11,10), information about
else cach pending operation must be stored, so the amount of
eturn(Func(n-2)); information directly depends on the number of calls
However, the same factorial function can be written in
Figure 11.7 Direct recursion
a tail-recursive manner as shown in Figure 11.10.
In the code, Fact1 function preserves the syntax of
Fact(n). Here the recursion occurs in the Fact function
Here, Func() calls itself for all positive values of n, so and not in Fact function. Carefully observe that Fact1
it is said to be a directly recursive function has no pending operation to be performed on return from
recursive calls.The value computed by the recursive call is
11.11.2 Indirect Recursion simply returned without any modification. So in this
A function is said to be indirectly recursive if it contains a
call to another function which ultimately calls it. Look at int Fact(n)
the functions given in Pigure 11.8. These two functions are {
indirectly recursive as they both call each other return Facti(n, 1);

}
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);
}

Figure 11.8 Indirect recursion Figure 11.10 Tail-recursive function


266 Computer Fundamentals and Programming in C

int Fibonacci(int num)

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

Fibonacci(7) = Fibonacci (6) + Fibonaced (5)


Fibonacci(6) + Fibonacci (S) + Fibonacci (4)
Fibonacci(S) = Fibonacci (4) + Fibonaced (3)
Fibonacci(4) = Fibonacci (3) + Fibonacci (2)
Fibonacci(3) = Fibonacci (2) + Fibonace’ (1)
Fibonacci(2) = Fibonacci (1) + Fibonacci (@)
Now we have, Fibonacci(2) = 1+ @ «1
Fibonacci(3) «1¢1"2
Fibonacci(4) =2¢1«3
Fibonacci(S) «3¢2=5
Fibonacci(6) «3+5«8
Fibonacci(7) « S + 8 = 13

Figure 11.11 Tree recursion

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

main issue is that the smaller disk must always come {


above the larger disk int n;
We will be doing this using a spare pole. In our case, printf("\n Enter the number of rings: “);
Ais the source pole, C is the destination pole, and B is the scanf("Xd", &n);
spare pole. To transfer all the three rings from A to C, we move(n, ‘A’, ‘C’, ‘BY);
will first shift the upper two rings (n — | rings) from the return 0;
source pole to the spare pole. We move the first two rings }
from pole A to B using C as the spare pole as shown in
Figure 11.13. void move(int n, char source, char dest, char
spare)
{
if (me=1)
printf("\n Move from %c to
mm Xc",source,dest);

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.

a BB GEBED RECURSION Vs ITERATION


Figure 11.14 Move rings from A to C
Recursion is more of a top-down approach to problem-
The final step is to move the n — | rings from B to C solving in which the original problem is divided into
using A as the spare pole, This is shown in Figure 11.15, smaller sub-problems. On the contrary, iteration follows
a bottom-up approach that begins with what is known and
then constructing the solution step by step.
Recursion is an excellent way of solving complex
problems especially when the problem can be defined in
recursive terms. For such problems, a recursive code can be
o @ @ written and modified in a much simpler and clearer manner,
However, recursive solutions are not always the best
Figure 11.15 Move rings from B to C solutions, In some cases, recursive programs may require
substantial amount of run-time overhead, Therefore,
To summarize, the solution to our problem of moving 1
when implementing a recursive solution, there is a trade~
rings from A to C using B as spare can be given as: off involved between the time spent in constructing and
Base case: ifn = | maintaining the program and the cost incurred in running-
* Move the ring from A to C using B as spare time and memory space required for the execution of the
program.
Whenever a recursive function is called, some amount
Recursive case: of overhead in the form of a run time stack is always
* Move #— 1 rings fromA to B using C as spare involved. Before jumping to the function with a smaller
* Move the one ring left on A to C using B as spare parameter, the original parameters, the local variables, and
* Move n— 1 rings from B to C using A as spare the return address of the calling function are all stored on
The following code implements the solution of the the system stack. Therefore, while using recursion a lot of
Tower of Hanoi problem time is needed to first push all the information on the stack
when the function is called and then time is again involved
#include <stdio.h> in retrieving the information stored on the stack once the
void move(int, char, char, char); control passes back to the calling function.
int main()
268 Computer Fundamentals and Programming in C

= 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

Marks2 Marks Marks 10 Marks14 Marks 18 GERD DECLARATION OF ARRAYS


We have already seen that every variable must be declared
Marks3 Marks? Marks 11 Marks! Marks19 before it is used. The same concept is true in case of array
variables also. An array must be declared before being
used. Declaring an array means specifying three things:
Marks4 Marks8 Marks 12 Marks20 + Data type—what kind ofvalues
itcan store, for example
int, char, float, double
* Name—to identify the array
Figure 12.1 Twenty variables for 20 students * Size—the maximum number of values that the array
can hold
Now to read values for these 20 different variables, we Armays are declared using the following syntax
must have 20 read statements. Similarly, to print the value
of these variables, we need 20 write statements. If it is just type name[size];
a matter of 20 variables, then it might be acceptable for Here the type can be either
the user to follow this approach. But would it be possible propemense 1 int, float, double, char, or
to follow this approach if we have to read and print marks fodedareandGehine) a other valid data type
of the students an array, you must The number within brackets
* in the entire course (say 100 students) -seuldewliy indicates the size of the array,
+ in the entire college (say 500 students) ie. the maximum number of
* in the entire university (say 10000 students) elements that can be stored in
The answer is no, definitely not! To process large the array. The size of the array is a constant and must have
amount of data, we need a data structure known as array a value at compilation time. For example, if we write,
An array is a collection of similar data elements. These int marks[10];
276 Computer Fundamentals and Programming in C

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]

Figure 12.2 Memory representation of an array of 10 elements

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;

Figure 12.3 Code to initialize each element of the array to-1


The code accesses every individual element of the array
C array indices start from 0. So for an array with N
and sets its value to —1. In the for loop, first the value of
elements, the index of the last element is N — 1.
marks[0) is set to —1, then the value of the index (i) is
incremented and the next value, i.¢., marks[1] is set to —1. Example 12.2
ico (i
The procedure is continued until all the 10 elements ofthe
array are set to —1. Given an array,
float avg[] = {99.0, 67.0, 78.0, 56.0,
88.0, 90.0, 34.0, 85.0}. Calculate the address of avg
[4] if base address= 1000.
No

we ff) 1 2) Gl Oo OS)
1000 1004 1008 1012 1016 1020 1024 1028

We know that storing a floating point number requires 4


12.3.1 Calculating the Address of Array bytes, therefore, word size is 4 bytes.
Elements Address(Avg[4]) = 1000 + 4(4 ~ 0)
= 1000 + 4(4) = 1016
You must be wondering that how C knows where an
individual element of the array is located in the memory.
The answer is that the array name is a symbolic reference
to the address ofthe first byte of the array. When we use
the array name, we are actually referring to the first byte
of the array.
The subscript or the index represents the offset from
the beginning of the array to the clement being referenced.
With just the array name and the index, C can calculate the
address of any element in the array,
Since an array stores all its data elements in consecutive 12.3.2 Calculating the Length of an Array
memory locations, storing just the base address, ic, the
address of the first element in the array is sufficient. The Length of the array is given by the number of elements
address of other data elements can simply be calculated stored in it. The general formula to calculate the length of
the array is:
using the base address. The formula for doing this
calculation is: Length = upper_bound - lower_bound + 1
Address of data element, A[k] = BA(A) + w(k - where upper_bound is the index of the last element and
lower_bound) lower_bound is the index of the first clement in the
Here, A is the array, k is the index of the clement for
array.
which we have to calculate the address, BA is the base Usually, Lower_bound is zero but this is nota compulsion
address of the array A, w is the word size of one clement in as we can have an array whose index may start from any
memory (for example, size of int is 2), and lower_bound non-zero value.
is the index ofthe first element in the array.
Example 12.3

Example 12.1 Let Age[S] be an array ofintegers such that


Age[(O] = 2 Age[1] = 5 Age[2] = 3
Given an array int marks[{] = {99, 67, 78, 56, 88, 90,
Age[3] = 2 Age[4] = 7
34, 85}. Calculate the address of marks[4] if base address
= 1000. Solution
Show the memory representation of the array and calculate
Solution its length.
Memory representation of the array Age is as given

marks (0) [1] (2) BS)


1000 1002 1004 1006 1008 1010 1012 1014
Age[O] Age{!] Agef2] Age[3] Agel4]
We know that storing an integer value requires 2 bytes,
therefore, word size is 2 bytes.
Length = upper_bound - lower_bound + 1
Address(Marks[4]) 1000 + 2(4 - 0) Here, lower_bound = 0, upper_bound = 4
1000 + 2(4) = 1008 Therefore, length=4-0+1-=5
278 Computer Fundamentals and Programming in C

int marks [5S] = (90,45, 67, 85, 78};


STORING VALUES IN ARRAYS
Lv [4s [o |2s|7 |
When we declare an array, we are just allocating space for io tt 6 BO
the elements; no values are stored in the array. There are
three ways to store values in an array—first, to initialize int marks [5] «{ 90,45); Rest of the
the array clement at the time of declaration; second, to elements are
input value for every individual clement at the run time; io 6 6 6B OA filled with 0,
third to assign values to the individual elements. This is
shown in Figure 12.4. int marks [] ={ 90,4 5, 72,8 1, 63,54);
9 4s 72 aI 63 4
Initialize the elements io tt BF BB OS)
during declaration
int marks [S]* (0);
Input values for [LeoToTelfofo]o]
ae ney the elements from.
oO om 2 8
the keyboard
Figure 12.5 Initialization of array elements
Assign values to
individual elements
If we have more initializersthan the declared size ofthe
Figure 12.4 Storing values in an array array, then a compile time error will be generated. For
example, the following statement will result in a compiler
error.
12.4.1 Initializing Arrays during Declaration
int marks [3] = {1,2,3,4};
Elements of the array can also be initialized at the time of
declaration as other variables. When an array is initialized,
we need to provide a value for every element in the array 12.4.2 inputting Values from the Keyboard
Armays are initialized by writing,
An array can be filled by inputting values from the
Visioning a type array_name(size) = keyboard. In this method, a while/do-while ora for loop
By default, the {list of values}; is executed to input the value for cach element of the array.
elements ofthearray - For example, look at the code shown in Figure 12.6
are not initialized, The values are written within
They may contain curly brackets and every value
some garbage is separated by a comma. It // Input value of each element of the array
value, so before is a compiler error to specify int 1, marks{10};
using the array you more number of values than For(1=0;1<10; i++)
must initialize the the number of elements in the scanf("%d", &marks[1});
array or read some array, When we write,
nee oara geeine int marks(5] = (90, 82, Figure 12.6 Code for inputting each element of the array
78, 95, 88};
In the code, we start with the index 4 at 0 and input
an array with name marks is declared that has enough space the value for the first element of the array. Since the array
to store 5 clements. The first element, i.¢., marks{0) is can have 10 elements, we must input values for elements
assigned with the value 90. Similarly, the second element whose index varies from 0 to 9. Therefore, in the for loop,
of the array, i.c., marks[1) is assigned 82, and so on. we test for condition (i<10) which means the number of
While initializing the array at the time of declaration, the elements in the array
programmer may omit the size of the array. For example,
int marks(] = (98, 97, 90}; 12.4.3 Assigning Values to Individual Elements
The third way is fo assign values to individual clements
The above statement is absolutely legal. Here, the
of the array by using the assignment operator. Any value
compiler will allocate enough space for all initialized
that evaluates to the data type of the array can be assigned
¢lements. Ifthe number of values provided is less than the
to the individual array clement. A simple assignment
number of elements in the array, the un-assigned elements
statement can be written as:
are filled with zeros. Figure 12,5 illustrates initialization
of arrays. marks[3] = 100;
Arrays 279

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.

GEE OPERATIONS ON ARRAYS Solution


{a) Step 1: [Initialization] Set Count = 0, I =
There are a number of operations that can be preformed on lower_bound
arrays. These operations include the following Step2: Repeat for I = lower_bound to upper_
x Traversing an array
bound
* Inserting an element in an array IF Marks[I] >= 80, then: Set Count =
* Deleting an clement from an array Count + 1
* Merging two arrays [End of IF}
* Searching an clement in an array SetI=I+1
* Sorting an array in ascending or descending order (END OF LOOP]
We will study all these operations in detail in this
Step3:Exit
section. (b) Step 1: [Initialization] Set I = lower_bound
2380 Computer Fundamentals and Programming in C

Step 2: Repeat for I = lower_bound to upper_ RandNo = rand() % MAX;


bound // vand() is a pre-defined function
IF Marks[{I] >= 75, Write: I, arr[i] = RandNo;
Marks[I] }
[End of IF} printf("\n The contents of the array are:
Set Il=e=Ie«1 \n")5
[END OF LOOP] for(i=0;i<MAX;i++)
Step 3: Exit printf("\t Xd", arr[i]);
getch();
return 0;
1. Write a program to read and display n numbers using an
array, }
Output
#include <stdio.h>
#include <conio.h> The contents of the array are:
int main() 60634720273
{ 3. Write a program to print the position of the smallest of
int i#0, n, arr[20}; n numbers using arrays.
clrser(
printf("\n Enter the number of elements: #include <stdio.h>
#include <conio.h>
scanf("Xd", &n);
int main()
printf("\n Enter the elements”); {
for(i=0;icn;i++) int 4, n, arr[20], small, pos;
clrscr();
{
printf("\n Arr[%d] = ", 4); printf("\n Enter the number of elements in
scanf("Xd", &arr[i]); the array: ");
} scanf("%d", &n);
printf("\n The array elements are\n"); printf("\n Enter the elements:");
for(i#0;icn; i++) for(i=O;ic<n;i++)
printf("Are(Xd] = Xd\t", 4, arr[i)); scanf("Xd" ,Barr[i});
return 0; smallearr[0]; pos*0;
} for(in1;icn;ir+)
Output {
if(are[i}<small)
Enter the number of elements: 5 {
Enter the elements small = arr[i};
Arr[O) «1 pos * i;
Arr[1] = 2 }
Arr(2] = 3 }
Are(3] = 4 printf("\n The smallest element is : %d",
Are[4] = 5 small);
The array elements are printf("\n The position of the smallest
Are[(O]) = 1 = Are[{1] = 2 Arr[2] = 3 element in the array is: %d", pos);
Arr(3) = 4 Arr[4) = 5 return 0;
2. Write a pro; am to read and display n random numbers }
using an arr Output
#include <stdio.h>
#include <conio.h>
Enter the number of elements in the array: 5
Enter the elements: 12345
#include <stdlib.h>
The smallest element is: 1
#define MAX 10
The position of the smallest element in the
int main()
array is: 0
{
int arr[MAX], i,RandNo; 4. Write a program to interchange the largest and the
for(i=0;i¢ MAX;i++) smallest number in the array
{ #include <stdio.h>
/* Scale the random number in the range
@include <conio.h>
0 to MAX-1 */
Arrays 281

int main() Enter the value of element 4:5


{ The smallest of these numbers is : 1
int i, n, arr{20), temp; The position of the smallest number in the
int small, small_pos; array is: 0
int large, large_pos; The largest of these numbers is: 5
clrscr(); The position of the largest number in the
printf("\n Enter the number of elements :* array is: 4
scanf("%d", &n); The new array is:
52341
for(is0;icnjit+)
{ §. Write a program to find the second largest number using
printf("\n Enter the value of element an array of n numbers
%d: ", 1); include <stdio.h>
scanf("%d" ,&arr(i)); #include <conio.h>
} int main()
smallearr(0);
{
small_pos*0;
int i, n, arr[20], pos, large, second
largesarr[0);
large;
large_pos=0;
clrser();
for(iwl;icn;
ite)
{ printf("\n Enter the number of elements
if(are[i}<small)
in the array: *);
{ scanf("%d", &n);
small = arr[i);
small_pos = 4; for(ieO;icn;ir+)
} {
if(arr{i)}>large) printf("\n Enter the number: ");
{ scanf("Xd",&arr[i});
large = arr[i)};
}
large_pos » 4; large-arr[0];pos*0;
} for(iwl;icnjie+)
} {
printf("\n The smallest of these numbers if(are(i]>large)
is : %d", small);
{
printf("\n The position of the smallest
large = arr[i);
number in the array is: Xd",small_ pos = i;
pos); }
printf("\n The largest of these numbers }
is: %d", large);
second_large-arr[n-pos-1];
printf("\n The position of the largest for(isO;icn;ie+)
number in the array is: Xd",large_ {
pos); if(i t= pos)
temp = arr[large_pos);
{
are[large_pos] =arr[small_pos]; if(arr[i]}>second_large)
arr[{small_pos] = temp; second_large = arr[i];
printf("\n The new array is: “); }
for(ie0;icnjit+)
}
printf(" \n Xd“, arrfi)); peintf("\n The numbers you entered are:
return 0; for(i=O;i<n;
i++)
} printf("Xd ", arr[i});
Output printf("\n The largest of these numbers is:
Xd", large);
Enter the number of elements: 5 printf("\n The second largest of these
Enter the value of element 0:1 numbers is: %d",second_large);
Enter the value of element 1:2 return 0;
Enter the value of element 2:3
Enter the value of element 3:4
282 Computer Fundamentals and Programming in C

Output printf("\n Enter the size of the array:");


scanf("%d", &n);
Enter the number of elements in the array: 5 printf("\n Enter the elements:");
Enter the number: 1 for(i=O;icn;it+)
Enter the number: 2
Enter the number: 3 {
scanf("Xd", S&array[i});
Enter the number: 4
Enter the number: S }
for(i=O;icn;it+)
The numbers you entered are
12345 {
for(j= itt; jen; j++)
The largest of these numbers is: 5
{
The second largest of these numbers is: 4 if(array[i] == array[j) && i!-j)
6. Write a program to enter n number of digits. Form a {
number using these digits. flage1;
printf("\n Duplicate numbers found
#include <stdio.h>
at location %d and %d",
#include <conio.h>
i, 2);
#include <math.h>
}
int main()
{
int number#O, digit[(10], numofdigits,i
}
clrser();
if(flage=0)
printf("\n No Duplicate");
printf("\n Enter the number of digits: *)
return 0;
scanf("Xd", &numofdigits) ;
}
for(i90; icnumofdigits; i++) Outpu
{ Enter the size of the array: 5
printf("\n Enter the Xdth digit: “, 1);
Enter the elements: 12345
scanf("Xd", &digit[i]); No Duplicate
}
i=0; 8. Write a program to read marks of 10 students in the
while(icnumofdigits) range of 0-100. Then make 10 groups; 0-10, 10-20,
{ 20-30, ete. Count the number of values that falls in each
number = number + digit[i] * pow(10,i); group and display the result
itt;
#include <stdio.h>
} #include <conio.h>
printf("\n The number is: Xd", number);
int main()
return 0;
{
int marks[50], i;
int group[10]={0);
Output printf("\n Enter the marks of 10 students
: \n");
Enter the number of digits: 3 for(i=0;i¢10; i++)
Enter the Oth digit: 3
Enter the 1th digit: 4 {
printf("\n MARKS[Xd} = ", i)
Enter the 2th digit: 5 scanf("Xd", Smarks{i});
The number is: $43 ++group[ (int) (marks[i])/10];
7. Write @ program to find whether the array of integers }
contains a duplicate number. Printf("\n teeeeeeeeeweeeeeeneenennen):
printf("\n GROUP \t\t FREQUENCY");
#include <stdio.h>
for(i=0;1<10;i++)
ttinclude <conio.h>
printf("\n %d \t\t Xd", i, group[i]);
int main()
getch();
{ return 0;
int array[10], i, n, j, flag=0;
clrscr();
Arrays 283

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 |

10. Write a program to read a sorted list of floating point


wBunanawunHto values and then calculate and display the median of the
9 wnrneeeoocodn values.
9. Modify the above program to display frequency include <stdio.h>
histograms of each group, finclude <conio.h>
#include <stdio.h> int main()
#include <conio.h> {
int main() int i, j, 15
float median, values[10];
{
int marks[10], i, index; printf("\n Enter the size of the array:
int group[10]}={0); scanf("%d", &n);
printf("\n Enter the marks of 10 students printf("\n Enter the values: “);
: \n")5
for(inO;icnzire)
for(i#0;1<10;
i++) scanf("%F", Svalues[i});
if (n%2=90)
{
print#("\n MARKS[Xd] = ", 4); median = (values({n/2} + values(n/2+1})/2.0;
scanf("Xd", Smarks[i}); else
++group[ (int) (marks{i]})/210); median = values[{n/2 + 1);
printf("\n MEDIAN = %.2f", median);
}
Printf("\n tteeeeeneeeeeeereweeneeeet): getch();
return 0;
is0;
printf(“\n FREQUENCY HISTOGRAM"); }
for (indexe0; index<10; index++) Output
{
Enter the size of the array: 5
printf("\n GROUP Xd | “,index);
for (i=0;i<group[index];i++) Enter the values:

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)

The array is declared to store marks of all the students


in the class, Now suppose there are 54 students and a new
student comes and is asked to give the same test. The Algorithm to Insert an Element in the Middle
marks of this new student would be stored in marks [55]. of an Array
Assuming that the student secured 68 marks, we will
assign the value as, The algorithm INSERT will be declared as INSERT (A, N,
POS, VAL). The arguments are
marks[55] = 68;
(a) A, the array in which the clement has to be inserted
However, if we have to insert an element in the middle (c) N, the number of elements in the array
of the array, then this is not a trivial task. On an average, (d) POS, the position at which the clement has to be
we might have to move as much as half of the elements inserted and
from their position in order to accommodate space for the (c) VAL, the value that has to be inserted,
new clement.
For example, consider an array whose elements are In the algorithm given in Figure 12.11, in Step 1, we
first initialize I with the total number of elements in the
arranged in ascending order. Now, if anew element has
to be added, it will have to be added probably somewhere array
in the middle of the array. To do this, we will have to In Step 2, a while loop is executed which will move all
first find the location where the new clement will be
the elements that have index greater than POS one position
towards right to create space for the new clement, In Step 5,
inserted and then move all the elements (that have a
value greater than that of the new element) one space to we increment the total number of elements in the array by |
the right so that space can be created to store the new
value.
Step 1: [INITIALIZATION] SET I = N
Step 2: Reapeat Steps 3 and 4 while I > = POS
Example 12.5 Step 3: SET A [1 +1] = A[I]
SET A [I #1] = A(t]
Data[] is an array that is declared as int Data[20); and [END OF LOOP)
contains the following values; Step4: SETN «Ne 2
Data{] = {12, 23, 34, 45, 56, 67, 78, 89, 90,
Step 6: SET A [POS] = VAL
Step 7: EXIT
100};
{a) Calculate the length of the array. Figure 12.11 Algorithm to insert a new element ata
(b) Find the upper bound and lower bound. specified position
and finally in Step 6, the new value is inserted atthe desired for(i=0;i<n; i++)
woe LE
position. printf("\t Xd", arr[i));
Now, let us visualize this algorithm by taking an getch();
example. Initial Data[ )is given asshown in Figure 12.12. return 0;
Calling INSERT (Data, 6, 3, 100) will lead to the }
following processing in the array:
Output
Enter the number of elements in the array: 5
Enter the values: 12345
Enter the number to be inserted: 7
Data{O] Data{!] Data[2] Data[3] Dataf4] Data[S] Dataf6]
Enter the position at which the number has
to be added: 3
The array after insertion of 7 is:
123745
Data[O] Data[1] Data[2] Data[3] Data[4] Data[S] Dataf6]
12. Write a program to insert a number in an array that is
[4s [atu fete] | 2| already sorted in ascending order.
Data[O] Data{t] Data[2] Data[3] Datal4] Data[s] Datal6} #include <stdio.h>
#include <conio.h>
int main()
{
Data[O] Datal1] Data[2} Data[3] Data[4] Data[S] Dataf6] int i, n, j, num, are[10];
clrscr();
Figure 12.12 inserting a new value in an existing array
printf("\n Enter the number of elements
in the array: ");
11. Write a program to insert a number at a given location
scanf("X%d", &n);
in an array.
printf("\n Enter the array elements:");
#include <stdio.h>
for(i=O;icn;ier)
#include <conio.h>
scanf("%d", &arr[i]);
int main()
printf("\n Enter the number to be inserted: “);
{ scanf("%d", &num);
int i, n, num, pos, arr[10];
for(isO;icn;iee)
clrser();
if(arr[i] > num)
printf(“\n Enter the number of elements in
the array: "); {
scanf("%d", &n); for(j = n-1; j>=i; j--)
printf(“\n Enter the values:”); arr{j+1) = arr{j);
arr[i] = num;
for(i=0;icn;i++)
break;
|
scanf("%d", &arr[i)); }
} }
printf("\n Enter the number to be ner;
printf("\n The array after insertion of
inserted: ");
Xd is: ", num);
scanf("X%d",&num);
for(i=O;icn;it+)
printf(“\n Enter the position at which the
printf("\t %d", arr[i]);
number has to be added: “);
scanf("%d", &pos); getch();
return 0;

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

The array after insertion of 6 is:


123456
aE
12.5.3 Deleting an Element from an Array (a) Since the elements of the array are stored in ascending
Deleting an clement from an array means removing order, we will compare the value that has to be deleted
a data clement from an already existing array. If the with the value of every element in the array. As soon
as VAL = Data[1I], where I is the index or subscript
clement has to be deleted from the end of the existing
of the array, we will get the position from which the
array, then the task of deletion is quite simple. We just
have to subtract | from the upper_bound. Figure 12.13 element has to be deleted. For example, if we see this
shows an algorithm to delete an clement from the end array, here VAL = 56. Data[0] = 12 which is not
equal to 56. Like this, we will compare and finally get
of the array
the value of POS = 4.
{b) [12 [23 [34 [4s |67 |78| 9 [90| 100]
Step 1: SET upper_bound « upper_bound -1
Step 2: EXIT Daa lOl 1) (21 Bt Mt IS) (6) EM) E8t

Figure 12,13 Algorithm to delete the last element of an


array
Algorithm to Delete an Element From the
Middle of an Array
For example, if we have an array that is declared as
The algorithm DELETE will be declared as DELETE(A, N,
int marks[];
Pos). The arguments are as follows:
The array is declared to store marks of all the students
in the class. Now suppose there are 54 students and the (a) A, the array from which the clement has to be deleted
student with roll number $4 leaves the course. The marks (b) N, the number of elements in the array
of this student was therefore stored in marks[54]. We just (c) POS, the position from which the element has to be
have to decrement the upper_bound. Subtracting | from deleted
the upper_bound will indicate that there are 53 valid data
in the array,
Figure 12.14 shows the algorithm in which we first
initialize I with the position from which the element has
However, if we have to delete the clement from the
middle of the array, then this task is not trivial, On an
to be deleted. In Step 2, a while loop is executed which
will move all the elements that have index greater than
average, we might have to move as much as half of the
POS one location towards left to occupy the location
clements from their position in order to occupy the space
vacated by the deleted element. When we say that we
of the deleted clement
For example, consider an array whose elements are are deleting an clement, we are actually overwriting
the element with the value of its successive clement, In
arranged in ascending order. Now, if an clement has to be
Step 5, we decrement the total number of elements in
deleted from somewhere middle of the array. To do this,
the array by |
we will first find the location from where the element has
to be deleted and then move all the elements (that have a
value greater than that of the clement) one location towards Step 1: [INITIALIZATION] SETI = POS
the left so that location vacated by the deleted clement is Step 2: Repeat Steps 3 and4 while I<=N-1
occupied by the next clement and so on. Step 3: SET A [I] =A [I + 1]
Step 4: SETI «I+
[ENDOF LOOP]
Step S: SETN#N-2
Example 12.6 Step 6: EXIT
Data[) Is an array that is declared as int Data[10); and
Figure 12.14 Algorithm to delete an element from the
contains the following values:
middie of an array
Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};
Now, let us visualize this algorithm by taking an
{a) If a data element with value 56 has to be deleted, find example and haying a look at Figure 12.15
its position. Initial Data} is given as shown in Figure 12.15
(b) Delete the data element and give the memory Calling DELETE (Data, 6, 2) will lead to the following
representation of the array. processing in the array
wre
es
Data{O] Dataf1] Dataj2) Dataj3] Data[4] Dataj5] The array
se after deletion is:
fa) Arr{0) =1
Are[1] = 2
fs
| a fet | «© | me] vri-s
Data{O] Data{1] Dataj2} Datal3] Dataf4} —Dataj3j saSac dleali
(b) 14, Write a program to delete a number from an array that

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

BINARY_SEARCH(A, lower_bound, upper_bound, VAL)

Step 1: [INITIALIZE] SET BEG = lower_bound, END = upper_bound, POS « -2


Step 2: Repeat Steps 3 and 4 while BEG <= END
Step 3: SET MID = (BEG + END)/2
Step 4: IF A[MID) = VAL, then
POS = MID
PRINT POS
Go to Step 6
ELSE IF A[MID] > VAL, then
SET END = MID - 1
ELSE
SET BEG « MID +1
[ENDOF IF}
[END OF LOOP}
Step 5: IF POS = -1, then
PRINT “VAL IS NOT PRESENT IN THE ARRAY”
{END OF IF]
Step 6: EXIT

Figure 12.20 Algorithm for binary search

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

scanf("%d", &n); One-dimensional arrays for


printf("\n Enter the elements: “); inter-function communication
for(i=0;icnji++)
{
scanf("Xd", &arr[i]);
} Passing Passing an
printf("\n Enter the number that has to be individual elements entire array
searched: ");
scanf("Xd", &num);
beg » 0, end = n-1; Passing Passing
while(beg £ end) data values addresses
{
mid = (beg + end)/2; Figure 12.21 One-dimensional arrays for inter-function
if (arr[mid] == num) communication

{
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 Individual Elements


Figure 12.22 Passing value of individual array elements to
The individual elements of an array can be passed to a
a function
function by passing cither their data values or their addresses.

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

‘Calling 19. Write a program to read and print an array of n


function numbers.
#include <stdio.h>
main()
include <conio.h>
. void read_array( int arr[], int);
int are{S} (1, 2, 3, 4, 5);
func(arr[3]); void display array( int arr{], int);
Called
function int main()
void func(int *num) {
int num[10], n;
printf("xd", *num); clrser();
printf("\n Enter the size of the array:");
scanf("%d", &n);
Figure 12.23 Passing address of individual array elements read_array(num, n);
to function display_array(num, );
getch();
return 0;
}
Passing the Entire Array void read_array(int arr[10], int n)
We have studied that in C the array name refers to the {
first byte of the array in memory. The address of rest of int 4;
the elements in the array can be calculated using the array printf("\n Enter the elements of the
name and the index value of array:");
Programming Tip: the clement. Therefore, when for(i=O;icn;ite)
When an entire array we need to pass an entire array {
is to besent to the to a function, we can simply scanf("Xd", &arr[i]);
called function, the pass the name of the array }
calling function just Figure 12.24 illustrates the }
needs to pass the code which passes the entire void display array(int arr[10], int n)
name of the array. array to the called function. {
In cases where we do not printf("\n The elements of the array are :");
want the called function to make any changes to the for(int isO;icn;i++)
array, the array must be reccived as a constant array printf("\t Xd", arr(i]);
by the called function. This prevents any type of }
unintentional modifications of the array elements. To
declare the array as a constant array, simply add the Output
keyword const before the data type of the array Enter the size of the array: 5
Enter the elements of the array: 1234 5
The elements of the array are: 12345
20. Write a program to merge two integer arrays. Also
display the merged array in reverse order.
®include <stdio.h>
main() #include <conio.h>
{ void read_array(int my_array[], int);
int arr[S] ={1, 2, 3, 4, 5};
func(are);
void display_array(int my_array[], int);
Called void merge_array(int my_array3[{], int, int
function my_array1[{], int, int my_array2[], int);
void reverse_array(int my_array[], int);
void func(int arr[S]) int main()
{
int i, {
for(is0;i<S;i++) int arri{10], arr2[10], arr3{20], n, m, t;
printf("%d", arr[i}); clrser();
}
printf("\n Enter the number of elements in
Figure 12.24 Passing entire array to function the first array: “);
294 Computer Fundamentals and Programming in C

scanf("Ad", &m); Output


abe !
rrays, x a;
read_arr y(arri, m);: Enter the number of elements in the first
tipspbaatie printf(“\n Enter the array: 3
number of elements in the
Vldiiatibe nce
validity ofthe index second array: *); 10 20 30
Enter the number of elements in the second
eens te scanf(“Kd", &n); array: 3
compiler. Aninvalid rhscrelse ala n); 1S 25 35
index when used merge_array(arr3, t, arri, The merged array is:
with an assignment a ae, wr Arr(O) = 10 Arr{i] = 20 Arr[2] = 30
; Are(3] = 15 Are[4] = 25 Are(5] = 35
‘operator may destroy
the data of another r" The merged array in reverse order is:
progra printf(“\n The merged Arr[O] = 35 9 Arr{1] = 25 = Arr[2] = 15
pedptoon ‘is array is: “); Arr[3} = 30 Arr[4] = 20 Arr[5] = 10
ialie aha display_array(arr3, t);
ee print#("\n The merged 21. Write a program to interchange the largest and the
smallest number in an array
initia e
bytthe
Ali lizers than array
*); in reverse order is:
#include <stdio.h>
a se_array(arr3,
reverch t); #include <conio.h>
Li ca
in the array, 3 wat
void read_array(int my_array{], int);
wee return 0; void display_array(int my_array[{], int);
generated. ; void interchange(int arr[], int);
void read_array(int my_array[10], int n) int find_biggest_pos(int my_array[10], int n);
int find_smallest_pos(int my_array[10], int n);
{
int 1;
for(iwO;icnjiee) int main()
scanf("Xd", &my_array[i)); {
} int arr[10], nj;
void merge_array(int my_array3[], int t, int clrser();
my_arrayi[], int m, int my_array2{], int n)
{ printf("\n Enter the size of the array: vu
int i, j*0; scanf("%d", &n);
for(iwO; icm; i+) read_array(arr, n);
{ printf("\n The elements of the array
my_array3[j] © my_arrayi[i}; are\n");
haat display_array(arr, n);
} interchange(arr, n);
for(is0; icn; i+) printf("\n The elements of the array after
{ interchange are\n");
my_array3(j] = my_array2{i]; display_array(arr, n);
i+t5 getch();
return 0;
}
} }
void display array(int my_array[], int n) void read_array(int my_array[10], int n)
{ {
int i; int i;
for(ieO;icn;
i++) printf("\n Enter the elements”);
printf("\n Arr[Xd] = Xd", i, for(i=O;icn;it+)
my_array(i}); scanf("Xd", Smy_array[i});
} z
void reverse_array(int my_array[{], int m) void display_array(int my_array[10], int n)
{ {
int i, 4; int i;

for(iem-1, j=0;i>=0;i--, j++) printf("n");


printf(“\n arr[%d) = %d", j, for(i=O;i<n;it+)
my_array{i]); printf("\t Arr[%d] = %d", i, my_array[i]);
Arrays 295

void interchange(int my_array[10], int n)


{
TWO-DIMENSIONAL ARRAYS
int temp, big_pos, small_pos;
big_pos = find_biggest_pos(my_arr, n); Till now we have read only about one-dimensional arrays. A
small_pos = find_smallest_pos(my_arr,n); one-dimensional array is organized linearly and only in one
temp = my_array[big_pos]; direction. But at times, we need to store data in the form of
my_array[big_pos] = my_array[small_pos]; matrices or tables. Here the concept of one-dimensional array
my_array[small_pos] = temp; is extended to incorporate two-dimensional data structures, A
two-dimensional array is specified using two subscripts where
}
int find_biggest_pos(int my_array[10}, int n) one subscript denotes row and the other denotes column.
C considers the two-dimensional array as an array of one-
{
int i, large = my_array[0}, pos=0; dimensional arrays. Figure 12.25 shows a two-dimensional
for(iel;icnjir+) array which can be viewed as an array of arrays.
{
if (my_array[i] > large)
{
large = my_array[i];
posed;
}
}
return pos;
} Second dimension
int find_smallest_pos(int my_array[10], int n)
Figure 12.25 Two-dimensional array
{
int 1, small = my_array[0], pos=0;
for(iwl;icnjire) 12.7.1 Declaring Two-dimensional Arrays
{ Similar to one-dimensional arrays, two-dimensional
if (my_array[4] < small) arrays must be declared before being used. The declaration
{ statement tells the compiler the name of the array, the data
small = my_array[i);
type of cach element in the array, and the size of each
posei;
dimension. A two-dimensional array is declared
}
} data_type array_name[row_size][column_size];
return pos; Therefore, a two-dimensional m « n array is an array that
} contains m * data elements and cach clement is accessed
Output using two subscripts, i and j where ic= mand j<= n.
For example, if we want to store the marks obtained by
Enter the size of the array: 5 3 students in $ different subjects, then we can declare a
Enter the elements 12345 two-dimensional array as
The elements of the array are
Arr[O] = 1 Arr{1] = 2 Arr{2] = 3 int marks[3}[5];
Are[3] = 4 Arr[4) = 5 A two-dimensional array called marks is declared that
The elements of the array after interchange are
has m(3) rows and n(5) columns, The first clement of the
Are[O) = 5 Arr{1] = 2 Arr[2] = 3 array is denoted by marks(0)[0), the second element as
Arr[3] = 4 Arr[4] = 12 marks[0}[1], and so on. Here, marks[0}(0] stores the
marks obtained by the first student in the first subject,
marks[{1}[0} stores the marks obtained by the second
student in the first subject, and so on
If a function receives an array that docs not change
it, then the array should be received as a constant
array. This would ensure that the contents of the array Each dimension of thetwo-dimensional array isindexed
are not accidentally changed, To declare an array as from zero to its maximum size minus one. The first
constant, prefix its type with the const keyword, as index selects the row and the second selects the column,
shown below.
int sum(const int arr[ }, int n); The pictorial form of a two-dimensional array is given
in Figure 12.26,
296 Computer Fundamentals and Programming in C

marks[O][0} marks[O}[2} | marks{0\{3} | marks{O][4]


marks{ 10] marks[1}[2] marks{1}[3) marks{1}[4]

Row 2 marks[2}{0} marks[2){1] marks[2)[2} marks{2][3} marks[2][4]

Figure 12.26 Two-dimensional array

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++)

Two-dimensional Arrays printf("\t Xd", arrfiJ[j]);


}
The clements of a 2D array are stored in contiguous getch();
memory locations. While accessing the elements, return 0;
remember that the last subscript varies most rapidly }
whereas the first varies least rapidly
Output
In case of one-dimensional arrays we used a single
for loop to vary the index i in every pass, so that all the
¢lements could be scanned. Since a two-dimensional array
contains two subscripts, we will use two for loops to scan
the clements, The first for loop will scan cach row in the ee wne
ee we
298 Computer Fundamentals and Programming in C

Enter the sales of 3 items sold by salesman


4: 32 45 64
Total Sales By Salesman 0 = 91
Total Sales By Salesman 1 = 142
24.1n a small company there are 5 salesmen. Each Total Sales By Salesman 2 = 112
salesman is supposed to sell 3 products. Write a Total Sales By Salesman 3 = 120
program using a two-dimensional array to print (i) the Total Sales By Salesman 4 = 141
total sales by each salesman and (ii) total sales of each Total sales of item 0 = 158
item, Total sales of item 1 = 198
#include <stdio.h> Total sales of item 2 = 250
#include <conio.h>
25. In a class there are 10 students. Each student is
int main()
supposed to appear in 3 tests. Write a program using
{ two-dimensional arrays to print
int sales(S](3], i, j, total_sales=0;
(i) the marks obtained by cach student in different
//INPUT DATA
subjects.
printf("\n ENTER THE DATA");
printf("\n t#eeeeeeeeseeeeee): (ii) total. marks and average obtained by cach
student
for(in0;icS;
i++)
(iii) store the average of cach student in a separate 1D
{ array so that it can be used to calculate the class
printf("\n Enter the sales of 3 items
average.
sold by salesman Xd: ", i);
for(j=0;j<3; J++) #include <stdio.h>
scanf("Md", &sales{i}(4}); ®@include <conio.h>
} int main()
// PRINT TOTAL SALES BY EACH SALESMAN {
for(ieO;icS;ite) int marks[{10}(3), 4, 43
{ int total_marks[10)={0};
total sales = 0; float class_avg-0.0, total_avg = 0.0;
for(j~0;5<3;
j++) float avg[10];
total_sales += sales(i}({4];
printf("\n Total Sales By Salesman Xd / INPUT DATA
= %d",i, total_sales); printf("\n ENTER THE DATA");
) for(inO;i<lO;ite)
// TOTAL SALES OF EACH ITEM {
for(isO;i<3;i++) // for each item printf("\n Enter the marks of student %d
{ in 3 subjects ; “, 1);
total_sales*0; for(j90;j<3;
j++)
for(j=0;j<5;j++) // for each salesman scanf("Xd", &marks({i}(j]);
total_sales += sales{j){4];
printf("\n Total sales of item Xa
= xd", i, total_sales); // CALCULATE TOTAL MARKS OF EACH STUDENT
} for(i=0;i<10;i++)
getch(); {
return 0; for(j=0;j<3;
j++)
} total_marks[i] += marks[iJ][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

printf("\n\n STUD NO.\t MARKS IN 3 SUBJECTS int main()


\t TOTAL MARKS \t AVERAGE”); {
for(i=0;1<10;i++) int marks[5)[3], 4, j, max_marks;
{ printf("\n X4d", 4); for(i=0;i<S;it+)
for(j=0;5<3;j++) {
printf(" Xd", marks{i}{4]); printf("\n Enter the marks obtained by
printf("X4d \t%.2*", total_marks[i), student Xd", 4);
avgeli}); for(j=0;j<3;j++)
} {
printf("\n\n CLASS AVERAGE = %.2f", class_ printf("\n marks[{Xd][Xd] = *, 4, 4)5
ave); scanf("%d", &marks[i][4]);
getch(); }
return 0; }
} for(j=0;4<355++)
Output
{
max_marks = marks[{0}[4};
ENTER THE DATA for(iwl;icS;ie+)
Enter the marks of student 0 in 3 subjects {
78 89 90 if (marks[i}[j]>max_marks)
Enter the marks of student 1 in 3 subjects: max_marks = marks[i}[4);
98 87 76 }
Enter the marks of student 2 in 3 subjects: printf("\n The highest marks obtained
67 78 89 in the subject Xd= Xd", j,
Enter the marks of student 3 in 3 subjects: max_marks);
90 87 65 }
Enter the marks of student 4 in 3 subjects: getch();
56 87 97 return 0;
Enter the marks of student 5 in 3 subjects: }
45 67 89 Output
Enter the marks of student 6 in 3 subjects:
66 77 88 Enter the marks obtained by student 0
Enter the marks of student 7 in 3 subjects: marks[{0}[0} = 89
76 87 98 marks[O}[1] = 76
Enter the marks of student 8 in 3 subjects: marks{0}[{2] = 100
67 88 66 Enter the marks obtained by student
Enter the marks of student 9 in 3 subjects: marks{1}[0) = 99
66 75 78 marks{1}[1] = 90
STUD NO MARKS IN 3 TOTAL AVERAGE marks[{1}(2] = 89
SUBJECTS MARKS Enter the marks obtained by student 2
o 78 89 90 257 85.67 marks[2}[0) = 67
1 98 87 76 261 87.00 marks[2}(1] = 76
2 67 78 89 234 78.00 marks[2](2] = 56
3 90 87 65 242 80.67 Enter the marks obtained by student 3
a 56 87 97 240 80.00 marks[3}(0] = 88
5 45 67 89 201 67.00 marks[3}(1] = 77
6 66 77 88 231 77.00 marks(3}(2] = 66
7 76 87 98 261 87.00 Enter the marks obtained by student 4
8 67 88 66 221 73.67 marks(4}(0] = 67
9 66 75 78 210 73.00 marks[4][1] = 78
marks(4}(2] = 89
CLASS AVERAGE = 78.90 The highest marks obtained in the subject 0
= 99
26. Write a program to read a two-dimensional array marks The highest marks obtained in the subject 1
Which stores marks of5students in 3 subjects. Write a = 90
program to display the highest marks in each subject The highest marks obtained in the subject 2
#include <stdio.h> = 100
#include <conio.h>
God Computer Fundamentals and Programming in C

{
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

printf("\t %d",transposed_ mat[i}[j}); cols_sum = colsi;


}
return 0; printf("\n Enter the elements of the first
} matrix");
Printf("\n t#eteweeeneeweeenwenneanen):
Output
Enter the elements of the matrix for(i=0;icrows1;i++)
sane wee eeeedeeneeeee {
123456789 for(j=0;j<colsi;
j++)
The elements of the matrix are scanf("Xd", &mati(i}[4]);
}
123 printf("\n Enter the elements of the second
456 matrix");
789 Printf("\n *#teeeeeeeeeeesaeneenwawen):
The elements of the transposed matrix are
for(i=0;i<rows2;i++)
147 {
258 for(j=0;j<cols2; j++)
789 scanf("Xd" ,&mat2(i}[4]);
}
29. Write a program to input two m * n matrices and then for(i=0;icrows_sum;
i++)
calculate the sum of their corresponding clements and {
store it ina third m * nmmatrix, for(j=0;4<cols_sum, j++)
#include <stdio.h>
sum(i}(j] = mata(i}(j) + mat2(i)[);
#include <conio.h>
}
printf("\n The elements of the resultant
int main()
matrix are”);
{ printf("\n vewewneneenys
int 4, 4;
int rows1, colsi, rows2, cols2, rows_sum, for(ixO;ic<rows_sum;i++)
cols_sum;
{
int mati(5]{5], mat2[5]{S], sum(S)[5] print#("\n");
clrscr();
for(j»0;j<cols_sum;j++)
printf("\n Enter the number of rows in the printf("\t Xd", sum[i}[j])5
first matrix: "); }
return 0;
scanf("%d", Brows) ;
}
printf("\n Enter the number of columns in Output
the first matrix: "); Enter the number of rows in the first
scanf("%d",&cols1); matrix: 2
Enter the number of columns in the first
printf("\n Enter the number of rows in the matrix: 2
second matrix: “); Enter the number of rows in the second
scanf("%d",&rows2) 5 matrix: 2
printf("\n Enter the number of columns in Enter the number of columns in the second
the second matrix:"); matrix: 2
scanf("%d",&cols2); Enter the elements of the first matrix

if(rows1 != rows2 || colsi != cols2) 1234


{ Enter the elements of the second matrix
printf("\n The number of rows and columns
of both the matrices must be equal”); 5678
getch(); The elements of the resultant matrix are
exit();
} 6 8
rows_sum = rowsl;
10 12
G02 Computer Fundamentals and Programming in C

a program to multiply two m * n matrices. }


for(i = 0; i < res_rows;i++)
#include <stdio.h>
#include <conio.h>
{
int main()
3-0;
for(j= 0; j < res_cols;j++)
{ {
inti; j,k
int rows1, colsi, rows2, cols2, res_rows,
res(i}[3j}=0;
for(k = 0; k < res_cols; k++)
res_cols;
res{iJ]{j] += mati[i][{k] * mat2[(k]
int mati(5][(5], mat2[{5)[S], res(5)[5];
clrser();
15
}
printf("\n Enter the number of rows in the
}
printf("\n The elements of the product
first matrix: ");
matrix are");
scanf("Xd" ,&rows1); Printf("\n t#eeeweeeeeeeneewerenwanen):

printf("\n Enter the number of columns in


for(i=0;icres_rows;
i++)
the first matrix: ");
{
scanf("%d",&colsi);
printf("\n");
for(j = 0; j < res_cols; j++)
printf("\n Enter the number of rows in the
printf("\t Xd",res{i}[j]});
second matrix: “);
scanf("%d" ,&rows2);
M
return 0;
}
printf("\n Enter the number of columns in
the second matrix:"); Output
scanf("%d",&cols2);
Enter the number of rows in the first
matrix: 2
if(cols1 != rows2)
Enter the number of columns in the first
{ matrix: 2
printf(“\n The number of columns in
Enter the number of rows in the second
the first matrix must be equal
matrix: 2
to the number of rows in the
Enter the number of columns in the second
second matrix");
matrix: 2
getch(); Enter the elements of the first matrix
exit(); Penne
nee eneeeeneeeenene
} 1234
res_rows = rows1; Enter the elements of the second matrix
res_cols = cols2; Aten eee eee eneeeeeeeeenene
$678
printf("\n Enter the elements of the first
The elements of the product matrix are
matrix"); Ween eeeeeeeeeneeeneneenns
printf("\n +++ a
19 22
4 50
for(i=0;i<rows1;i++)
&
for(j=0; j<cols1; j++)
scanf("%d", &mat1[i}[3]}); PASSING TWO-DIMENSIONAL
}
printf("\n Enter the elements of the second
ARRAYS TO FUNCTIONS
matrix"); There are three ways of passing two-dimensional arrays
printf("\n *##eseeeeeeeeweeweeewwene”):
to functions. First, we can pass individual elements of the
array. This is exactly same as passing elements of a one-
for(i = 0; i < rows2;i++) dimensional array. Second, we can pass a single row of
{ the two-dimensional array. This is equivalent to passing
for(j = 0; j < cols2;j++)
the entire one-dimensional array to a function. This has
scanf("%d", &mat2(i}[5]); already been discussed in the previous section. Third, we
Arrays 303

2D arrays for inter-


void read_matrix(int mat[2]
function communication Wi genre (2], int, int);
serpent void summatrix(int mati[2}
will begenerated {2], int mat2[2}[2], int,
ifyou omit the int);

Passing . Passing an bday void mul_matrix(int mati(2)


individual elements PSEAFOW catice 20) array 3 aber cha (2),anemat2[2)(2], int,
Figure 12.30 Two-dimensional arrays for inter-function ita trapneguinaes void transpose_matrix(int
communication mat2[2}(2], int, int);
void display_matrix(int
can pass the entire two-dimensional array to the function. mat(2)[{2], int r, int ¢);
Refer Figure 12,30 which shows the three ways of using int main()
two-dimensional arrays for inter-function communication. {
int option, row, col;
12.9.1 Passing a Row int mati(2][2], mat2(2}[2};
clrscr();
A row of a two-dimensional array can be passed by
indexing the array name with the row number. When we
do
send a single row of a two-dimensional array, then the
called function receives a one-dimensional array. Figure {
12.31 illustrates how a single row ofa two-dimensional print€("\n **#***** MAIN MENU *#*eeee");
array is passed to the called function.
printf("\n 1. Read the two matrices");
printf("\n 2. Add the matrices”);
printf("\n 3. Multiply the matrices");
printf("\n 4. Transpose the matrix");
Calling function
printf("\n 5S. EXIT");
main()
printf("\n\n Enter your option: ");
{ scanf("Xd", Soption);
int arr(2}[3]}* ({1, 2, 3), (4, 5, 6))5 switch(option)
func(are{1]); {
) case 1:
Called function printf("\n Enter the number of
rows and columns of
void func(int arr{])
the matrix: ");
scanf("%d %d", &row, &col);
{ printf("\n Enter the first
int 4;
matrix: “);
for (in@;i<3;i¢+) read_matrix(mati, row, col);
printf("%d", are[i) * 14 printf("\n Enter the second
) matrix: “);
read_matrix(mat2, row, col);
Figure 12.31 Passing a single row of a 2D array break;
case 2:
12.9.2 Passing an Entire 2D Array sum_matrix(mati, mat2, row,
col);
To pass a two-dimensional array to a function, we use
break;
the array name as the actual parameter. However, the
case 3:
parameter in the called function must indicate that the
if(col == row)
array has two dimensions.
mul_matrix(mati, mat2, row,
col);
31. Write a menu-driven program to read and display an m
else
x n matrix, Also find the sum, transpose, and product
printf("\n To multiply two
of two m * n matrices.
matrices, number of
#include <stdio.h> columns in the first
#include <conio.h> matrix must be equal to
304 Computer Fundamentals and Programming in C
number of rows in the }
second matrix”); display_matrix(tp_mat, r, ¢);
break; }
case 4;
transpose_matrix(mati, row, col); void display_matrix(int mat(2][2], int r
break; int c)
} {
} int i, 3;
while(option t= 5); for(isO;icr;
i++)
getch(); {
return 0; printf("\n");
} for(j-0;j<ci
jer)
void read_matrix(int mat(2)(2], int r, int c) printf("\t mat(Xd][%d] = Xd", i, j
{ mat(i}(3])3
int i, 3;
for(i = O;i < rjise) }
{ print#("\n");
Output
for(j = 0;4 < cjj++)
{ seeeee® MAIN MENU * #88
printé("\t mat[%d](%d] = ",4,4); 1. Read the two matrices
scanf("Xd", &mat{i}(4]); 2. Add the matrices
} 3. Multiply the matrices
4. Transpose the matrix
} 5. EXIT
void sum_matrix(int mati[2}[2], int mat2[2] Enter your option: 2
(2], int r, int c) Enter the number of rows and columns of the
{ matrix: 22
int 1, j, sum[2)[2); Enter the first matrix:
for(i#0;icrjive) mat(O)[O] = 2 mat(0)[1)
{ mat(1)(O] « 3 mat(1)[1) an
for(j=0;j<c;jer) Enter the second matrix :
sum(i}[j) = mati[i}(j] + mat2[i}[3]; mat(0}[0] = 2 mat{0)}[1] = 3
} mat(1)(0] = 4 mat({1}[1] = 5
display_matrix(sum, r, ¢); eee MAIN MENU *¥eeeeee
} « Read the two matrices
void mul_matrix(int mat1[2][2], int mat2(2] . Add the matrices
(2], int r, int c) . Multiply the matrices
. Transpose the matrix
int 4, j, k, prod{2)[2); . EXIT
vawne
for(ie0;i<rjite) Enter your option: 2
{ mat(O}(0) = 3 mat(O}(1) = 5
for(j=0;j<c; j++) mat(1)[0) = 7 mat({1][1) = 9
{
prod{i}[j} = 0; 32. Write a program to fill a square matrix with value zero
For(k=O0;k<c;ke+) on the diagonals, | on the upper right triangle, and ~1
prod[i}[j) += mata(ij(k] * mat2(k}(3]; on the lower left triangle.
}
} include <stdio.h>
display_matrix(prod, r, ¢); include <conio.h>
} void read_matrix(int mat[5}[5], int);
void transpose_matrix(int mat[2][2], int r, void display_matrix(int mat[5][5], int);
int c) int main()
{ {
int i, j, tp_mat(2)[2); int row;
for(is0;icrjit+) int mat{5][5];
{ clrscr();
for(j=0;j<cj
j++) printf("\n Enter the number of rows and
tp_mat(j][i] = mat[i}[3); columns of the matrix ");
scanf("Xd", &row); else return 0;
read_matrix(mat, row); }
display_matrix(mat, row);
getch(); void main()
return 0; {
int arr{3][(3], i, j, m, flag;
printf("\n Enter the number of rows and
void read_matrix(int mat[5}[S], int r) columns: ");
{ scanf("Xd", &n);
int i, Jj; printf(“\n Enter the elements of the array: “);
for(i = O;4 < rjite) for(i = 0; i < nj it)
{ {
for(j = O55 < rjje+) for(j = 0; j < nj jee)
{ { printf("arr[%d}[%d] = ", i, 5);
if(ie=j) scanf("xd", & arr{i}[4]);
mat(i}[j] = 0; }
else if(i>j) }
mat(i}{j] = -2; flag = isSymmetric(arr, n);
else if(flag= =1)
mat(i}(j] = 1; peintf("\n The array is symmetric”);
} else
} printf("\n The array is not symmetric”);
}
void display matrix(int mat(S][5], int r)
{
int i, 3; GEERT) MuttivIMENSIONAL ARRAYS
for(inO;icrj;ite)
{ A multidimensional array in simple terms is an array of
printf("\n"); arrays. Like we have one index in a one-dimensional array,
for(j=0;
jer; j++) two indices in a two-dimensional array, in the same way we
printé("\t Xd", mat{i}[4]); have n indices in ann-dimensional array or multidimensional
array. Conversely, an n-dimensional array is specified using
} n indices. An n-dimensional m, * m * my * .. m, array a
collectionm,* p*m* *m, clements, Ina multidimensional
Output
array, a particular element is specified by using n subscripts
Enter the number of rows and columns of the as A[I, ]{12][15]—[1q]. where,
matrix; 2
I, <= My I =m, Icom — Icon
° 1
1 0
A multidimensional array can contain as many indices
as needed and the requirement of the memory increases
33. Write a program to check whether a matrix is with the number of indices used. However, practically
symmetric or not speaking we will hardly use more than three indices in
Hint: A matrixissymmetric if itisequal to its transpose. any program. Figure 12.32 shows a three-dimensional
#include <stdio.h>
#include <conio.h>
int isSymmetric(int a[3)(3], int n)
{ dimension “”
int i, j, flag;
(Columns)
for(i = 0; i < nj it) First 3 +5 |
dimension |
A]&||x |0 | Page 3
om (ietieay) (lined
{
for(j = 0; J <n; j++)
{
if(il = j 88 a{i}[j) = = a(j}[4}) [6 | Page 2

}
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

ERED sparse MaTRICES


Sparse matrix is a matrix that has large number of
(10,2)(14,2)
elements with a zero value. In order to efficiently utilize
the memory, specialized algorithms and data structures
that take advantage of the sparse structure of the matrix
The three dimensional array will contain 2 x 2 x 3 = 12 should be used. If we apply operations using standard
elements. matrix structures and algorithms to sparse matrices, then
ns
execution will slow down and the matrix will consume
large amounts of memory. Sparse data can be easily
34. Write a program to read and display a 2 « 2 * 2 array. compressed which in turn can significantly reduce memory
#include <stdio.h> usage.
#include <conio.h> There are two types ofsparse matrices, In the first type
int main() of sparse matrix, all elements above the main diagonal
{ have a zero value. This type of sparse matrix is also called
int array(2}(2}[2), i, 3, ks a lower triangular matrix because if you see it pictorially,
clrser(); all the elements with a non-zero value appear below the
diagonal. In a lower tnangular matrix, A,,; = 0 where
printf("\n Enter the elements of the i<j. Ann *n lower triangular matrix A has one non zero
matrix"); clement in the first row, two non-zero clements, in the
for(i = O;i < 2;i++) second row and likewise, n non-zero clements in the n™
{ row. Figure 12.33 shows a lower triangular matrix.
for(j = 03] < 2;j++)
{
for(k = O;k < 2;k++) i
{ 5 3
scanf("%d", Sarray[i]}[j][k]);
2 7 -1
t
} 3 1 4 2
} 3 2 8 1 7
printf("\n The matrix is: ");
for(i = O;i < 2;i++) Figure 12.33 Lower triangular matrix
Arrays 307

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}

Like a lower triangular matrix, we also have an upper


triangular matrix in which A; @ 0 where i>j. Ann * n 12.11.1 Array Representation of Sparse Matrices
upper triangular matrix A has n non-zero elements in the Let us sce how we can represent a sparse matrix. Consider
first row, n-1 non-zero elements in the second row and the sparse matrix given below
likewise, 1 non-zero clement in the nth row. Figure 12.34
shows an upper triangular matrix. fo 20
004
jo 0 0
Out of 9 clements, the matrix has only two non-zero
elements. This sparse matrix can be represented using the
a matrix given below
eowrve
Mwrow

Figure 12.34 Upper triangular matrix


* The first row gives the number of rows (3), number of
In the second variant of a sparse matrix, clements columns (3), and number of non-zero elements (2) in
with a non-zero value can appear only on the diagonal the sparse matrix.
or immediately above or below the diagonal. This type * The second row specifies the location and value of first
of matrix is also called a tridiagonal matrix. Hence in a non-zero element. The first non-zero value 2 is at (0, 1)
tridiagonal matrix, Aj; = 0 where |i ~ j]> 1. location.
In a tridiagonal matrix, if clements are present on Similarly, third row specifies the location and value of
(a) the main diagonal, it contains non-zero elements for the next non-zero element, i.e. value 4 at (1, 2) location.
ij. In all, there will be n elements
This means that in the array representation of the sparse
(b) below the main diagonal, it contains non-zero matrix, number of rows will be one more than the number
elements for i*j+1, In all, there will be n-1 elements. of non-zero values.
(c) above the main diagonal, it contains non-zero
elements for i=j-1. In all, there will be n-2 elements. 35. Write a program that shows the array representation of
Figure 12.35 shows a tridiagonal matrix a sparse matrix.
include <stdio.h>
#include <conio.h>

void sparse_mat(int mat[3][3], int, int, int);


void sain()
2 2 { int i, j, rows, cols, num_values = 0;
5 1 9 int mat({3][3];
8 clrscr();
printf("\n Enter the number of rows : ");
Figure 12.35 Tridiagonal! matrix scanf("%d",&rows) ;
printf("\n Enter the number of columns:”);
To store the tridiagonal matrix efficiently in memory, scanf(“Xd",&cols);
we can use a one-dimensional array which stores only printf("\n Enter the elements of array:");
the non-zero elements. The mapping between a two- for(i=0;icrows;i++)
308 Computer Fundamentals and Programming in C

{ 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

CASE STUDY 2: Chapter 12


INTRODUCTION TO SORTING (b) Compare 52 and 29. Since $2 > 29, swapping is done. 30,
The term sorting means arranging the elements of the array 29, 52. 87. 63, 27. 19, 54
in some relevant order which may be either ascending or Compare $2 nd! 87. Since $2 < 87, no swapping is done
descending, Le., if A is an array, then the elements of A are (d) Compare, 87 and 63. Since, 87 > 63, swapping is done. 30,
arranged in sorted order (ascending order) in such a way that, 29, 52, 63, 87, 27, 19, 54
A[O) < A[2] < A[2] < ... < A[N-1] (e) Compare 87 and 27. Since 87 > 27, swapping is done. 30,
For example, if we have an array that is declared and 29, . 63, 27, 87, 19, 54
initialized as,
(1) Compare 87 and 19. Since 87 > 19, swapping is done. 30,
int A[] = {21, 34, 11, 9, 1, 0, 22}; 29, 52.63,27, 19, 87, 54
Then the sorted array (ascending order) can be given as, A{} (g) Compare 87 and $4. Since 87 > 54, swapping is done. 30,
= {0, 1, 9, 11, 21, 22, 34}
29, 52, 63, 27, 19, $4,87
A sorting algorithm is defined as an algorithm that puts Observe that after the end of the first pass, the largest
clements of a list in a certain order (that can be cither numerical, element is placed at the highest index of the array. All the
lexicographical, or any user-defined order), Efficient sorting other elements are still unsorted.
algorithms are widely used to optimize the use of other algorithms
like search and merge algorithms which require sorted lists to Pass 2:
work correctly. There are two types of sorting (a) Compare 30and 29. Since 30 > 29, swapping is done.
* Internal sorting which deals with sorting the data stored in 29,30, $2, 63, 27, 19, 54, 87
computer's memory. (b) Compare 30 and $2. Since 30<$2, no swapping is done
* Extemal sorting which deals with sorting the data stored in files. (c) Compare 52 and 63, Since $2 < 63, no swapping is done
External sorting ix applied when there is voluminous data that (d) Compare 63 and 27. Since63> 27, swapping is done.
cannot be stored in computer's memory 29, 30, 52, 27, 63, 19, 54, 87
In this section we will discuss only about internal sorting
te Compare 63 and 19. Since 63 > 19, swapping is done.
BUBBLE SORT 29, 30, 52. 27, 19, 63, 54, 87
Bubble sort is a very simple method that sorts the array elements
Compare 63 and $4. Since 63 > $4, swapping is done
by repeatedly moving the largest clement to the highest index
29, 30, 52, 27, 19, $4, 63, 87
position of the array (in case of arranging elements in ascending
Observe that after the end of the second pass, the second
order). In bubble sorting, consecutive adjacent pairs of elements
largest clement is placed at the second highest index of the array
in the array are compared with each other, If the clement at the
All the other elements are still unsorted.
lower index is gr ter than the element at the higher index, the
two elements are interchanged so that the smaller clement is Pass 3:
placed before the bigger one. This process is continued till the (a) Compare 29 and 30, Since 29 <30, no swapping is done
list of unsorted elements gets exhausted
This procedure of sorting is called bubble sorting because the
(b) Compare 30 and $2. Since 30 <$2, no swapping is done
smaller elements ‘bubble’ to the top of the list. At the end of the
(c) Compare 52 and 27. Since 52 > 2 . swapping is done.
first pass, the largest element in the list will be placed at the end 29, W, 27, $2, 19, 54, 63, 87
of the list. Bubble sort is also referred to as sinking sort (d) Compare 52 and 19, Since 52 > 19, swapping is done
29, 30, 27, 19, $2, 54, 63, 87
(e) Compare 52 and 54. Since 52 < 54, no swapping is done.
If the elements are to be sorted in descending order,
Observe that after the end of the third pass, the third largest
then with each pass the smallest element is moved to
element is placed at the third highest index of the array. All the
the highest index of the array.
other elements are still unsorted.

Bubble Sort Example Pass 4:


To discuss bubble sor, let us consider an array that has the (a) Compare 29 and 30. Since 29 < 30, no swapping is done
following elements: (b) Compare 30 and 27. Since 30 > 2 . swapping is done
A(] = {30, 52, 29, 87, 63, 27, 19, 54} 29, 27,W, 19, 52, 54, 63, 87

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();

void insertion_sort(int arr[], int n)


{
int i, j, temp;
for(i = 1;i < njit+)
{
temp = arr[i)};
j = i-1;
while((temp < arr[j]) && (j>=0))
pass9:|9 [18[36]39]45|54]63|72[31[ron {
are(j+1) = are{j);
Jo5
Initially, A[O) is the only clement in the sorted set. In Pass 1, .
A(1) will be placed either before or after A[0], sothat the array are[j+l1) = temp;
A is sorted, Inpass 2,A[2] will beplaced either before A[O], in- }
between A[O) and A[ 1] or after A[ 1], so that the array is sorted. }
In pass 3, A[ 3) will beplaced in its proper
place sothat the array
Ais sorted, InPass N-1, A[N~1] will beplaced in its proper place Output
so that the array A is sorted. Enter the number of elements in the array: 6
To insert the element A[K] in the sorted list A[O), A[1], Enter the elements of the array 27 72 36 63
seeey A[K-1], we need to compare A[K] with A[K-1], then 45 54
with A[K-2), then with A[K-3] until we meet an element A[{3) The sorted array is:
such that A[3] <= A[K]. 27 36 45 54 63 72
In order to insert
A[K) in its correct position,
we need to
SELECTION SORT
move cach element A[K-1], A[K-2], —., A[3+1] by one
position and then A[K] is inserted at the (3+1)" location. Selection sort is generally the preferred choice for sorting files
with very large objects (records) and small keys. Although
selection sort performs worse than insertion sort algorithm it ix
2. Write a program to sort an array using insertion sort
noted for its simplicity, and also has performance advantages
algorithm,
over more complicated algorithms in certain situations,
#include <stdio.h>
#include <conio.h> Technique
void insertion_sort(int arr[],int n); Consider an array ARR with N elements. The selection sort
void main() makes N-1 passes to sort the entire array and works as follows,
{ First find the smallest value in the array and place it in the first
int arr[10], 4, 1; position, Then find the second smallest value in the array and
clrscr(); place it in the second position. Repeat this procedure until the
printf("\n Enter the number of elements in entire array is sorted. Therefore,
the array: “); In pass 1. find the position POS of the smallest value in the
scanf("%d", &n); array and then swap ARR[POS] and ARR[O], Thus, ARR[O] is
printf("\n Enter the elements of the sorted.
array"); In pass 2, find the position POS of the smallest value in sub-
for(i = O;i < njite) array of N-1 elements. Swap ARR[POS] with ARR[1]. Now,
{ A[O) and
A{1) is sorted.
scanf("Xd", &arr[i)}); In pass 3, find the position POS of the smallest value insub-
} array of N-2 elements. Swap ARR[POS] with ARR[2]. Now
insertion_sort(arr,n); ARR[O]. ARR[1] and ARR[2] is sorted.
printf("\n The sorted array is: \n"); In pass N-1, find the position POS of the smaller
of the
for(i = O;i < njit+) elements ARR[N-2} and ARR[N-1]. Swap ARR[POS] and
printf("%d\t", arr[i]); ARR[N-2] sothat ARR[O], ARR[1], .. , ARR[N-1) is sorted,
Ge Computer Fundamentals and Programming in C

Sort Example

‘The advantages of the selection sort algorithm are as follows;


* Simple and easy toimplement
* Can be used for small data sets
* 60 per cent more efficient than bubble sort algorithm
The disadvantage is that it is inefficient for lange data sets. Insertion sort is considered to be better than selection sort and bubble
sort.

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

of the string. So, the internal representation of the string


GER intRopuction becomes HELLO’ \0". To store a string of length 5, we need
$+ I locations (1 extra for the null character). The name
Nowadays, computers are widely used for word processing of the character array (or the string) is a pointer to the
applications such 4s creating, inserting, updating, and beginning of the string. Figure 13.1 shows the difference
Programming Tip: es ere er between character storage and string storage.
Character constants r esides this we nce < io iba n
If we declare str as,
‘areenciosed in for a particular pattern within
Single quotes. String a text, delete it, or replace it char str[S] = "HELLO";
sacs ;
with another pattern. So there Then the null character will not be appended
in double quotes. is actually a lot we as users do automatically to the character array. This is because str
to manipulate the textual data.
can hold only $ characters and the characters in HELLO
In C language, a string is a null-terminated character have already filled the locations allocated to it
array. This means that after the last character, a null
¢ ter ('\0') is stored to signify the end of the
character array. For example, if we write
When the compiler assigns a character string to a
char str[] = "HELLO"; character array, it automatically appends a null character
We are declaring a character array that has five usable to the end of the string. Therefore, the size of the string
characters namely, H, E, L, L, and 0. Apart from these should be equal to maximum number of characters in
characters, a null character (‘\0") is stored at the end the string plus one.

char che";
Here H is a character not a string. The

Here H is a string not a character. The string


H requires two memory locations,
One
to store the character H and another tostore Although
C permits empty string,
itdoes
the nullcharacter. ‘not allow an empty character.

Figure 13.1 Difference between character storage and string storage


318 Computer Fundamentals and Programming in C

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.

1. Write a program to display a string using printf()


#include <stdio.h> eerrereeer
#include <conio.h> mm
mmm
int main() se
=S
22s
Sees
{
char str[] = “Introduction to C*; #include <stdio.h>
clrser(); include <conio.h>
printf("\n |%s|", str); int main()
printf("\n |%20s|", str); {
printf("\n |%-20s|", str); int i, w, p;
printf("\n |%.4s|", str); char str[] = "HELLO";
printf("\n |%20.4s|", str); printf("\n");
printf("\n |%-20.4s|", str); for(iO;icS;ie+)
getch(); {
return 0; p= itl;
} printf("\n X-5.*s", p, str);
}
Output printf("\n");
[Introduction to ¢| for(i=4;i>=0;i--)
| Introduction to c| {
[Introduction to C | p = isl;
[Inte] printf("\n %-S.*s", p, str);
| Intr | }
|Intr | getch();
return 0;

LCL CRER I Functions to read and write characters

Function Joperation sprintf() Function


petchar() Used toread a character from the keyboard; waits
The library function sprintf() is similar to printf()
for carriage return (enter key), It returns an integer,
The only difference is that the formatted output is written
in which the low-order byte contains the character.
getchar() can be used toinput any key, including
to a memory area rather than directly to a standard
RETURN, TAB, and ESC. output (screen). sprint#() is useful in situations when
potch() Ts un alternative
forgetchar(), Unlike getchar(), the formatted strings in memory have to be transmitted over a
getch() function waits for a keypress, after which it communication channel or to a special device.
returns immediately. The syntax of sprint#() can be given ny
petehe() Similar togetch(). Theonly difference isthat int sprintf( char * buffer, const char *
getche() echoes the character on screen. format [ , argument , ...] );
Used towrite a character tothe screen. Itaccepts
an integer parameter of which only the low-order Here, buffer is the place where string needs to be
byte isoutput tothescreen. Returns thecharacter stored. The arguments command is an ellipsis so you
Written,
ofEOF (~1) ifanerror occurs. can put as many types of arguments as you want, Finally,
format is the string that contains the text to be printed, The
string may contain format tags.
The printf() function in UNIX supports specification
of variable field width or precision, i.c., if we write, ®include < stdio.h>
main()
printf("\n %*.s*, w, p, str);
{
Then the print#() statement will print first p characters of char buf[100};
str in the field width ofw. int num = 10;
sprintf(buf, “num = %3d", num); scanf("%[0123456789.“[ ]()_+-$%&*]",
} In the given example, str can accept any character
enclosed in the opening and closing square brackets
(including * and [).
SUPPRESSING INPUT The user can also specify a range of acceptable
characters using a hyphen. This is shown in the statement
The scanf() function can be used to read a field without given below:
assigning it to any variable. This is done by preceeding
that field’s format code with a *. For example, consider scanf("%[a-z)", str );
the example below: Here, str will accept any character from small a to
scanf("Xd*cXd", &hr, &min); small z. Always remember that scansets are case sensitive.
However, if you want to accept a hyphen then it must
The time can be read as 9:05. Here the colon would be cither be the first or the last character in the set.
read but not assigned to anything. Therefore, assignment
suppression is particularly useful when part of what is
input needs to be suppressed. Example 13.1

To better understand scanset, try the following code with


13.2.1 Using a Scanset different inputs
The ANSI standard added the new scanset feature to the #include <stdio.h>
C language. Scanset is used to define a set of characters int main()
which may be read and assigned to the corresponding {
string. Scanset is defined by placing the characters inside char str[10};
square brackets prefixed with a %, as shown in the example printf("\n Enter string: " );
below: scanf("%[A-Z]", str );
X["aeiou"]} // Reads only upper case characters
printf( “The string is : %s", str);
When we use the above scanset, scanf() will continue return 0;
to read characters and put them into the string until it
encounters a character that is not specified in the scanset.
For example, consider the code given below.
#include <stdio.h> A major difference between scanset and the string
int main() conversion codes is that scanset does not skip leading
{ white spaces, If the white space is a part of the scanset,
char str[10)}; then scanset accepts any white space character, otherwise
printf("\n Enter string: “ ); it terminates if a white space character is entered without
scanf("X{aeiou]", str ); being specified in the scanset.
printf( “The string is: Xs", str); Scanset may also terminate ifa field width specification
return 0; is included and the maximum number of characters that
) can be read has been reached. For example, the statement
given below will read maximum 10 vowels. So the scanf
The code will stop accepting a character as soon as the statement will terminate if 10 characters have been read or
user enters a character that is not a vowel. if anon-vowel character is entered.
However, if the first character in the set is a * (caret
symbol), then scanf() will accept any character that is not scanf("%10[aeiou)", str );
defined by the scanset. For example, if you write
scanf("%[*aeiou)", str); sscanf() Function
Then, str will accept characters other than those The sscanf function accepts a string from which to read
specified in the scanset, ic, it will accept any non-vowel input. It accepts a template string and a series of related
character. However, the caret and the opening bracket arguments. The sscanf function is similar to scanf
can be included in the scanset anywhere. They have a function except that the first argument of sscanf specifies
predefined meaning only when they are included as the a string from which to read, whereas scanf can only read
first character of the scanset. So if you want to accept a from standard input. Its syntax is given as
text from the user that contains caret and opening bracket
sscanf(const char *str, const char
then make sure that they are not the first charactersin the
scanset. This is shown in the following example. *format,(pl, p2, ...])5
322 Computer Fundamentals and Programming in C

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

Length in C, a string is a variable length array of characters that


controlled = is delimited by the null character,
Figure 13.4 String taxonomy

Fixed-length strings When storing a string in a fixed- GED OPERATIONS ON STRINGS


length format, you need to specify an appropriate size for
the string variable, If the size is too small, then you will In this section, we will learn about different operations
not be able to store all the elements in the string. On the that can be performed on character arrays. But before we
other hand, if the string size is large, then unnecessarily start with these operations, we must understand the way
memory space will be wasted. arithmetic operators can be applied to characters.
In C, characters can be manipulated in the same way as
Variable-length strings A better option is to use a variable
we do with numbers. When we use a character constant or
length format in which the string can be expanded or
4 character variable in an expression, it is automatically
contracted to accommodate the elements in it. For example,
converted into an integer value, where the value depends
if you declare a string variable to store the name of a
on the local character set of the system. For example, if
student, If a student has a long name of say 20 characters,
we write
then the string can be expanded to accommodate 20
characters, On the other hand, a student name has only int i;
5 characters, then the string variable can be contracted to char ch =
store only 5 characters. However, to use a variable-length i= ch;
string format you need a technique to indicate the end of printf("Xd", i);
clements that are a part of the string. This can be done
either by using length-controlled string or a delimiter. // Prints 65, ASCII value of ch is ‘A*
Strings 323

C also enables programmers to perform arithmetic clrscr();


operations on character variables and character constants. printf("\n Enter the string :");
So, if we write gets(str);
while(str[i] t= "\0")
int i;
itt;
char ch = ‘A’;
length = i;
i = ch + 10;
printf("\n The length of the string is
printf("%d", 1); Xd", length);
getch();
// Prints 75, ASCII value of ch that is ‘A’ + 10
return 0;
Character variables and character constants can be }
used with relational operators as shown in the example Output
below,
Enter the string : HELLO
char ch» ‘C'
The length of the string is ; 5
if(ch >= 'A' && ch <# ‘Z*)
printf("The character is in upper case");
13.4.2 Converting Characters of a String into
13.4.1 Finding the Length of a String Upper Case
The number of characters in the string constitutes the We have already seen that in memory the ASCII codes are
length of the string. For example, LENGTH("C PROGRAMMING stored instead of the real value, The ASCII code for A-Z
IS FUN") will return 19. Note that even blank spaces are varies from 65 to 91 and the ASCII code for a-z ranges from
counted as characters in the string 97 to 123. So if we have to convert a lower case character to
LENGTH("\O") = O and LENGTH("") = 0 because both upper case, then we just need to subtract 32 from the ASCII
the strings do not contain any character. Therefore, both value of the character, Figure 13.7 shows an algorithm that
the strings are empty and of zero length. Figure 13.6 converts characters of a string into upper case.
shows an algorithm that calculates the length of a string
Stepi: [INITIALIZE] SET I « 0
Step 2: Repeat Step 3 while STR[I) |= NULL
Step 1: [INITIALIZE] SET I = 0 Step 3: IF STR[I] >= ‘a’ AND STR[I] <= ‘2°
Step 2: Repeat Step 3 while STR [I]! = NULL SET Upperstr[I] = STR [I]-32
Step 3: SETIe tea ELSE
[END OF Loop} SET Upperstr[I] = STR[I)
Step 4: SET LENGTH « I [END OF IF]
Step 5: END SETI = Ie2
[ENO OF Loop)
Step 4: SET Upperstr{I] = NULL
Figure 13.6 Algorithm to calculate the length of a string Step 5: EXIT

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 the algorithm, we initialize I to zero. Using 1 as the


There is a library function strien(s1) that returns the index of STR, we traverse each character from Step 2 to 3.
length of s1. It is defined in string.h. If the character is already in upper case, then it is copied
in Upperstr else the lower case character is converted into
3. Write a program to find the length of a string upper case by subtracting 32 from its ASCII value. The
upper case character is then stored in Upperstr. Finally,
#include <stdio.h> when all the characters have been traversed a null character
#tinclude <conio.h> is appended to Upperstr (as done in Step 4)
int main()
{ 4. Write a program to convert characters of a string to
char str[100], i = 0, length; upper case.
324 Computer Fundamentals and Programming in C
#include <stdio.h> If the character is already in lower case, then it is copied
#include <conio.h> in Lowerstr clse the upper case character is converted into
int main() lower case by adding 32 to its ASCII value, The lower
{ case character is then stored in Lowerstr. Finally, when
char str[100], upper_str [100]; all the characters have been traversed a null character is
int is0, j-0; appended to Lowerstr (as done in Step 4).
clrser();
printf("\n Enter the string: §. Write a program to convert characters of a string into
gets (str); lower case.
while(str[i] l= "\o") #include <stdio.h>
{ include <conio.h>
if(str[i]>='a && str[i}<="z") int main()
upper_str{j] « str[i] -32 {
else char str[100], lower_str [100];
upper_str[j]} = str{i}; int i 0, j = 0;
ite; Jee; clrser();
} printf("\n Enter the string :");
upper_str[j] = *\0*; gets(str);
printf("\n The string converted into upper while(str{i) I= ‘\O")
case is : "); {
puts(upper_str); if(str[i}>='A" && str[i]<='2Z')
return 0; lower_str{j) = str{i] + 32;
} else
Output lower_str[j] = str[i);
dee; joe;
Enter the string: hello }
lower_str[j] = ‘\0';
printf("\n The string converted into lower
13.4.3 Converting Characters of a String Into case is : “);
puts(lower_str);
Lower Case
return 0;
If we have to convert an upper case character into lower }
case, then we just need to add 32 to its ASCH value. Output
Figure 13.8 shows an algorithm that converts characters
of a string into lower case. Enter the string : Hello
The string converted into lower case is: hello

13.4.4 Concatenating Two Strings to Forma


In C, there is a library function tolower() that converts a New String
character into lower case. It is defined in ctype.h
If $1 and $2 are two strings, then concatenation operation
produces a string which contains characters of $1 followed
Step 1: [INITIALIZE] SET I = 0 by the characters of $2. Figure 13.9 shows an algorithm
Step 2: Repeat Step 3 while STR[I) !* NULL that concatenates two strings.
Step 3: IF STR[I] >= 'A’ AND STR[I] <= 'Z
SET Lowerstr[I] = STR [1] + 32 Step 1: [INITIALIZE] I « 0 and
3«0
ELSE Step 2: Repeat Steps 3 to 4 while stri [1]! = NULL
SET Lowerstr[I] « STR [1]
[END OF IF] Step 3: SET new_str[}) = str1[1)
Step 4: Set I= I¢l and 3 = Jel
SET IeIed
[END OF LOOP} [END of Loop]
Step 4: SET Lowerstr[I] » NULL
Step S: SET I0
Step S: EXIT Step 6: Repeat Steps 6 to 7 while str2[i]! = NULL
Step 7: SET new_str{}] « str2 [I]
Step 8: Set I» Ip] and 3 = Jel
Figure 13.8 Algorithm to convert characters of a string [EN of LOOP]
into lower case Step 9: SET new_str[3) = NULL
Step 16: EXIT
In the algorithm, we initialize I to zero. Using I as the
index of STR, we traverse each character from Step 2 to 3 Figure 13.9 Algorithm to concatenate two strings
Strings 325

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

After appending, the destination string is: @include <string.h>


Hi, How are you? int main()
{
char stri[so}, str2[so];
13.4.6 Comparing Two Strings
int i=0, leni = 0, len2 = 0, same = 0;
If $1 and S2 are two strings then comparing two strings clrscr();
will give either of these results printf("\n Enter the first string : “);
gets(str1);
(a) $1 and S2 are equal printf("\n Enter the second string : ");
(b) $1 > $2, when in dictionary order $1 will come after $2 gets(str2);
(c) $1 < $2, when in dictionary order $1 precedes $2 leni = strlen(str1);
len2 = strlen(str2);
To compare the two strings, cach and every character
if(leni == len2)
is compared from both the strings. If all the characters are
{
same then the two strings are said to beequal, Figure 13.11
while(i<leni)
shows an algorithm that compares two strings.
{
if(strifi] == str2{i])
ite;
There is a library function strcmp (s1, 52) that compares else break;
2 with s1. It is defined in string.h. }
if(iwwlen1)

Step 1: [INITIALIZE] SET I = 0,SAME = 0 samewl;


Step 2: SET Leni» Length(STR1), Len2= Length(STR2) printf("\n The two strings are equal");
Step 3: IF lend ! len2, then }
Write “Strings Are Not Equal” }
ELSE
if(leni!*len2)
Repeat while I<Len1
IF STRI[I] = STR2(T} printf("\n The two strings are not
SET Ie Iea equal");
ELSE if(same «= 0)
Go to Step 4 {
{END OF IF] if(stri[i]}>str2[i})
[END OF LOOP] printf("\n String] is greater than
TF I = Lend
SET SAME « 1 string2");
Write “Strings are equal” else if(stri[i}<str2[i]})
{END OF IF} printf("\n String2 is greater than
Step 4: IF SAME «§ 0 string1");
IF STRI[I] > STR2{I], then
Write “String 1 is greaterthan String2” }
ELSE IF STRI[I] < STR2{[I], then getch();
Write “String 2 is greater than String3™ return 0;
{END OF IF} }
[END OF IF}
Step $: EXIT Output

Figure 13.11 Algorithm to compare two strings


Enter the first string: Hello
Enter the second string: Hello
The two strings are equal
In this algorithm, we first check whether the two strings
are of same length. If not, then there is no point in moving
ahead as it straightaway means that the two strings are not 13.4.7 Reversing a String
same, However, if the two strings are of the same length, IfSi= "HELLO", then reverse of SL = “OLLEH". To reverse
then we compare character by character to check if all the a string wejust need to swap the first character with the last,
characters are same. If yes, then variable SAME is set to | else second character with the second last character, so on and so
if SAME = 0, then we check which string precedes the other forth, Figure 13.12 shows an algorithm that reverses a string,
in dictionary order and print the corresponding message.

8. Write a program to compare two strings


There is a library function strrev(s1) that reverses all the
#include <stdio.h> characters in the string except the null character. It is
#include <conio.h> defined
in string _h.
Strings 327

For example, if S1 = “Hello World", then Substr_


Step 1: [INITIALIZE] SET I=, JeLength(STR)-1 Left(Si, 7) = Hello W
Step Repeat Steps 3 and 4 while I< 2
Step SWAP (STR(I), STR(3)) Figure 13.13 shows an algorithm that extracts the first 1
Step 4: SET I=I4+1,383-1 characters from a string.
[END OF LOOP}
Step 5: EXIT
Step 1: [INITIALIZE] SETI « 0
Figure 13.12 Algorithm to reverse a string Step2:Repeat Steps 3 to 4 while STR[I]! » NULL AND
I<
Step 3: SET Substr{I] = STR[T]
In Step 1, I is initialized to zero and 3 is initialized Step 4: SETIT*Ie1
to the length of the string - 1. In Step 2, a while loop is
[ENO OFLOOP)
Step 5: SET Substr[I] = NULL
executed until all the characters of the string are accessed. Step 6: EXIT
In Step 3, we swap the i" character of STR with its 3
character. (As a result, the first character of STR will be Figure 13.13 Algorithm to extract first m characters from
interchanged with the last character, the second character a string
will be interchanged with the second last character of STR,
and so on). In Step 4, the value of I is incremented and 2 is In Step 1, we initialize the index variable I with zero,
decremented to traverse STR in the forward and backward In Step 2, a while loop is executed until all the characters
direction, respectively. of STR have been accessed and I is less than N. In Step 3,
the 1" character of STR is copied in the 1'" character of
9. Write a program to reverse the given string Substr. In Step 4, the value of I is incremented to access
#include <stdio.h> the next character in STR. In Step 5, Substr is appended
#include <conio.h> with a null character,
#include <string.h>
10. Write a program to extract the first » characters ofa
int main()
string
{
char str[100], reverse _str[100], temp #include <stdio.h>
int i= 0, j= 0; #include <conio.h>
clrser(); int main()
printf("\n Enter the string: {
gets (str); char str[100], substr[100};
jestrlen(str)-1; int is0, n;
while(icj) clrser();
{ printf("\n Enter the string: ");
temp « str(j]; gets(str);
str[j] = str[i)}; printf("\n Enter the number of characters to
str[i] « temp; be copied: ");
ive; scanf("Xd", &n);
on i=0;
} while(str[i] f= '\O" 8& ic n)
printf("\n The reversed string is: %
{
puts(str); substr[i] = str[i];
getch(); ite;
return 0;
}
} substr [i] = "\0';
Output printf("\n The substring is: *);
Enter the string: Hi there puts(substr);
The reversed string is: ereht iH getch();
return 0;
}
13.4.8 Extracting a Substring from Left Output
In order to extract a substring from the main string we Enter the string: Hi there
need to copy the content of the string starting from the Enter the number of characters to be copied: 2
first position to the n" position where n is the number of The substring is: Hi
characters to be extracted.
328 Computer Fundamentals and Programming in C

13.4.9 Extracting a Substring from Right of the substr [i] = "\0';


printf("\n The substring is : ");
String
puts(substr);
In order to extract a substring from the right side of getch();
the main string we need to first calculate the position return 0;
from the left. For example, ifS1 = “Hello World” and }
we have to copy 7 characters starting from the right,
Output
then we have to actually start extracting characters from
the 4th position, This is calculated by total number of Enter the string : Hi there
characters ~ 1 Enter the number of characters to be copied : 5
For example, if S1 = “Hello world", then Substr_ The substring is : there
Right(S1, 7) = o World
Figure 13.14 shows an algorithm that extracts n 13.4.10 Extracting a Substring from the Middle
characters from the right ofa string,
of a String
To extract a substring from a given string requires
Step 1: [INITIALIZE] SET I = 0, 3 = Length(STR) - N information about three things. The main string, the
Step 2: Repeat Steps 3 to 4 while STR(J]!= NULL position of the first character of the substring in the given
Step 3: SET Substr [1] = STR[3]
Step 4: SETI =1¢1, 38301 string, and the numberof characters/length of the substring,
[END OF LOOP) For cxample, if we have a string,
Step 5: SET Substr [I] * NULL
Step 6: EXIT str[] = “Welcome to the world of programming”;

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

clrser(); This algorithm —first


printf("\n Enter the main string: “); Pbactosscrac ag initializes the indexes in the
gets(str); prog) string to zero. From Steps 3
printf("\n Enter the position from which to besser to 4, the contents of new_str
start the substring: "); eeypeh are built. If I is exactly equal
scanf("%d", &m); pagsoieated : fo the position at which the
printf("\n Enter the length of the pele substring has to be inserted
substring: "); anes into the text, then the inner
scanf("%d", &n); aia ite loop copies the contents of the
ism; substring into the new_str.
while(str[i] l= ‘\O' && n>0) Ptah cag utility Otherwise, the contents of the
{ text are copied into it
substr[j] * str[i];
its; 13. Write a program to insert a string in the main text
hae] #include <stdio.h>
ne=5 #include <conio.h>
} int main()
substr[j] = "\0'; {
printf("\n The substring is : “); char text(100], str[20], ins_text[100]}
puts (str); int is0, j=0, k=0,pos;
getch(); clrscr();
return 0; printf("\n Enter the main text : ");
} gets(text);
Output printf("\n Enter the string to be inserted
7 ")5
Enter the main string : Hi there gets(str);
Enter the position from which to start the printf("\n Enter the position at which the
substring: 1 string has to be inserted: ");
Enter the length of the substring: 7 scanf("Xd", &pos);
The substring is : i there while(text[i]!="\o")
{
13.4,11 Inserting a String in Another String if (i==pos)
{
The insertion operation inserts a string $ in the main text while(ste[k]!="\o")
T at k” position. The general syntax of this operation {
is: INSERT(text, position, string). For example, ins_text[j]estr[k];
INSERT("XYZXYZ", 3, “AAA") = "XYZAAAXYZ"
Je*5
Figure 13.16 shows an algorithm to insert a string in a kee;
given text at the specified position.
}
}
Step 1: [INITIALIZE] SET I*0,3«0 and KeO else
Step 2: Repeat Step 3 while text{I] ! = MULL
Step 3: IF I « pos,then {
Repeat while str[K] ! = NULL ins_text[j]»text(i);
new_str[4] = str[k] Pa)
SET J» Jed
SET K = Kel
}
{END OF INNER LOOP} ite;
ELSE }
new_str[[}] = text[I] ins_text[j]="\0';
SET J = Jel printf("\n The new string is:
{END OF IF} puts(ins_text);
SET I Ivd
[END OF OUTER LOOP] getch();
Step 4: SET new_str[{3} = NULL return 0;
Step $: EXIT }
Output
Figure 13.16 Algorithm to insert a string in a given text
at the specified position Enter the main text: How you?
330 Computer Fundamentals and Programming in C

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

pos = strchr(str, ‘n'); int main()


if(pos) {
printf("\n mn is found in str at position char stri{10] = "HELLO";
Xd", pos); char str2{10] = "HEY";
else if(stremp(stri,str2)==0)
printf("\n n is not present in the printf("\n The two strings are
string”); identical");
return 0; else
} printf("\n The two strings are not
identical");
Output
return 0;
nis found in str at position 9

strrchr Function Output


Syntax: The two strings are not identical
char *strrchr(const char *str, int c);
strncmp Function
The strrchr ( ) function searches for the first
occurrence of the character ¢ (an unsigned char) beginning Syntax
at the rear end and working towards the front in the string int strncmp(const char *str1, const char
pointed to by the argument str, i.c., the function searches
*str2, size_t n);
for the last occurrence of the character ¢ and returns a
pointer pointing to the last matching character, or NULL if This function compares at most the first n bytes of str1
no match is found and str2. The process stops comparing after the null
character is encountered. The function returns zero if the
#include <stdio.h>
first n bytes of the strings are equal. Otherwise, it returns a
#include <string.h>
value less than Zero or greater than zero if str1 is less than
int main()
or greater than str2, respectively
{
char str[50] = “Programming In C"; #include <stdio.h>
char *pos; #include <string.h>
pos « strrchr(str, ‘n'); int main()
if (pos) {
printf("\n The last position of n is: char str1[{10] = "HELLO";
Xd", pos); char str2[10] = "HEY";
else if(strncmp(stri1,str2,2)#*0)
printf("\n n is not present in the printf("\n The two strings are
string"); identical");
return 0; else
} printf("\n The two strings are not
identical”);
Output
return 0;
The last position of n is: 13 }
Output
strcmp Function
The two strings are identical
Syntax
int stremp(const char *stri, const char strcpy Function
*str2); Syntax:
The strcmp function compares the string pointed to by char *strepy(char *st rl, const char *str2);
str1 to the string pointed to by str2. The function returns
cro if the strings are equal. Otherwise, it returns a value This function copies the string pointed to by str2 to
less than zero or greater than zero if stri is less than or stri including the null character of str2. It returns the
greater than str2 respectively argument str. Here stri should be big enough to store
the contents of str2
#include <stdio.h>
#include <string.h> include <stdio.h>
334 Computer Fundamentals and Programming in C
#include <string.h> #include <stdio.h>
int main() #include <string.h>
{ int main()
char stri{10], str2[10] = "HELLO"; {
strepy(stri,str2); char str[] = "HELLO";
printf("\n ste1; Xs", stri); printf("\n Length of str is: %d",
return 0; strlen(str));
} return 0;
Output }
Output
HELLO
Length of str is: 5
strncpy Function
strstr Function
Syntax
char *stencpy(char *stel, const char *str2, Syntax
size_t n); char *strstr(const char *str1, const char
This function copies up to n characters from the string *str2);
pointed to by str2 to str, Copying stops when n characters This function is used to find the first occurrence of string
are copied, However, if the null character in str2 is reached str2 (not including the terminating null character) in the
then the null character is string str. It returns a pointer to the first occurrence of str2
Programing Tip:
Do not use string
continually= copied to. stri in ste1. If no match is found, then a null pointer is returned.
until n characters have been
functions ona » i #include <stdio.h>
copied. Finally, a null character
Character array S is appended to str1. However #include <string.h>
sae withs if n is zero or negative then int main()
null character, nothing is copied.
. {
char stri{] = "HAPPY BIRTHDAY TO YOU";
#include <stdio.h> char str2[] = “OAY";
#include <string.h> char *ptr;
int main() ptr = strstr(stri, str2);
{ if(ptr)
char stri(10), str2[10] = "HELLO"; printf("\n Substring Found");
strncpy(str1,str2, 2); else
printf("\n strl: Xs", stra); printf("\n Substring Not Found");
return 0; return 0;
} }
Output Output
HE Substring Found
strspn Function
To copy the string str2 in stri, a better way is towrite Syntax.
strncpy(stri, str2, sizeof(str1)-1); size_t strspn(const char *str1, const char *str2);
This would enforce the copying of only that many The function returns the index of the first character in str1
characters for which stri has space to accommodate. that doesn’t match any character in str2.
#include <stdio.h>
#include <string.h>
strlen Function
int main()
Syntax: {
char stri[] = “HAPPY BIRTHDAY TO YOU";
size_t strlen(const char *str); char str2[{] “HAPPY BIRTHDAY JOE";
This function calculates the length of the string str up printf("\n The position of first character in
to but not including the null character, i.c., the function str2 that does not match with that in stri
returns the number of characters in the string. is %d", strspn(stri,str2));
Strings 33: Oy

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

strcspn Function Syntax:


char *strtok( char *str1, const char
Syntax
‘delimiter );
size_t strespn(const char *stri, const char
The strtok() function is used to isolate sequential tokens
*str2);
ina null-terminated string, str. These tokens are separated
The function returns the index of the first character in ste1 in the string using delimiters. The first time that strtok is
that matches any of the characters in str2 called, str should be specified; subsequent calls, wishing
to obtain further tokens from the same string, should pass
#include <stdio.h>
a null pointer instead. However, the delimiter must be
#include <string.h>
supplied each time, though it may change between culls
int main()
The strtok() function returns a pointer to the beginning
{ of cach subsequent token in the string, after replacing the
char stri[] = “PROGRAMMING IN C";
token itself with a null character. When all tokens are left,
char ste2[] = "IN";
a null pointer is returned.
printf("\n The position of first character in
str2 that matches with that in stri is xa", include <stdio.h>
strespn(str1,str2)); @include <string.h>
return 0; main ()
} {
char str[] = "Hello, to, the, world of,
Output
programming”;
The position of first character in str2 that char delim[{] = *,";
matches with that in stri is 8 char result(20);
result = strtok(str, delim);
strpbrk Function while(result! NULL)
{
Syntax: printf("\n Xs", result);
char *strpbrk(const char *str1, const char result « strtok(NULL, delim);
*str2); }
getch();
The function strpbrk() returns a pointer to the first return 0;
occurrence in ste of any character in str2, or NULL if
}
none are present, The only difference between strpbrk()
and strespn is that strcspn() retums the index of the Output
character and strpbrk() retums a pointer to the first Hello
occurrence of acharacter in str2 to
#include <stdio.h> the
#include <string.h> world of
int main() programming
{
char stri{] = “PROGRAMMING IN C"; strtol Function
char str2{] = “AB”
Syntax:
char *ptr = strpbrk(stri,str2));
if(ptr==NULL) long strtol(const char *str, char **end, int
printf("\n No character matches in the two base);
strings");
The strtol function converts the string pointed by str
else
to a long value, The function skips leading white space
printf("\n Character in str2 matches with
characters and stops when it encounters the first non-
that in stri");
numeric character. strtol stores the address of the first
return 0;
336 Computer Fundamentals and Programming in C

fhvalid character in str in *end. If there were no digits at printf("%1f", num);


all, then the strtol function will store the original value getch();
of str in *end. You may pass NULL instead of * end if you return 0;
do not want to store the invalid characters anywhere. }
Finally, the third argument base specifics whether
Output
the number is in hexadecimal, octal, binary, or decimal
representation. 123. 345000

#include <stdio.h> atoi() Function


#include <stdlib.h>
main () Till now you must have understood that the value | is an
{ integer and ‘1° is a character. So there is a huge difference
long num; when we write the two statements given below
num = strtol("12345 Decimal Value", NULL, 10);
printf("xld", num); int is1; // here i #1
num * strtol("65432 Octal Value”, NULL, 8); int is'1"; /* here i =49, the ASCII value
printf("Xld", num); of character 1*/
num = strtol("10110101 Binary Value”, NULL, 2); Similarly, 123 is an integer number but '123' is a
printf("Sld", num); string of digits, What if you want to operate some integer
num = strtol("A7CB4 Hexadecimal Value”, NULL, operations on the string '123'? For this, C provides
16); a function atoi that converts a given string into its
printf("%ld", num); corresponding integer,
getch(); The atoi() function converts a given string passed
return 0; to it as an argument into an integer, The atoi() function
} returns that integer to the calling function, However, the
Output string should start with a number. atoi() will stop reading
from the string as soon as it encounters 4 non-numerical
12348 character, atoi()isincluded in the stdlib.h file. So before
27418 using this function in your program, you must include this
181 header file. The syntax of atoi() can be given as,
687284
int atoi(const char *str);
strtod Function Example i = atoi("123.456");
RESULT: i = 123.
Syntax:
double strtod(const char *str, char **end); atof() Function
The function accepts a string str that has an optional plus The atof() function converts the string that it a
(’+') or minus sign ("-") followed by either: an argument into a double value and then returns that ilue
* a decimal number containing a sequence of decimal to the calling function. However, the string must start with
digits optionally consisting of adecimal point, or a valid number. One point to remember is that the string
* a hexadecimal number consisting of a "Ox" or “Ox” can be terminated with any non-numerical character, other
followed by asequence of hexadecimal digits optionally than “E" or “e". The syntax of atof() can be given as,
containing a decimal point double atof(const char *str);
In both cases, the number may be optionally followed Example x = atof("12.39 is the answer");
by an exponent ('E’ or ‘e* for decimal constants or a RESULT: x = 12.39
‘P' or ‘p’ for hexadecimal constants), followed by an
optional plus or minus sign, followed by a sequence of atol() Function
decimal digits. For decimal and hexadecimal constants,
the exponent indicates the power of 10 and 2, respectively, The atol() function converts the string into a long int
by which the number should be scaled. value. The atol function returns the converted long value
to the calling function, Like atoi, the atol() function will
#include <stdio.h>
read from a string until it finds any character that should
#include <stdlib.h> not be in a long. Its syntax can be given as,
main ()
{ long atol(const char *str);
double num; Example x = atol("12345.6789");
num = strtod("123.345abcdefg™, NULL); RESULT: x = 12345L.
Strings 337

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

Name|0] Enter the number of students: 3


Name|1] Enter the name of student 1: Aditya
Name[2] Enter the name of student 2: Goransh
Name[3] Enter the name of student 3: Sarthak
Name|4] Names of the students are: Aditya Goransh
Sarthak
Figure 13.20 Memory representation of a 2D character array
17. Write a program to sort names of students.
By declaring the array names, we allocate 50 bytes. #include <stdio.h>
But the actual memory occupied is 27 bytes. Thus we Sinclude <conio.h>
see, more than half of the memory allocated lies wasted. int main()
Figure 13.21 shows an algorithm to process an individual
{
string from an array of strings. char names[5][10], temp[10];
int i, n, 3;
Step 1: [Initialize] SET I-0 clrscr();
Step 2: Repeat Step
3while I<N printf("\n Enter the number of students: ");
Step 3: Apply Process to NAMES[I] scanf("%d", &n);
[END OF LOOP} for(i=0;icn;ir+)
Step 4: EXIT {
printf("\n Enter the name of the student
Figure 13.21 Algorithm to process an Md: “, ivi);
individual string from an array of strings gets(names[i});
338 Computer Fundamentals and Programming in C

} 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

Enter the number of characters to be copied; 5


if(str[i] == ‘\n* || i==79) The copied text is: w are
line_count++;
if(str{i] == * B& str[iei] I= * *) 22. Write a program to enter a text that has commas.
word_count++; Replace all the commas with semi colons and then
char_counte+; display the text.
itt; include <stdio.h>
} #include <conio.h>
printf("\n The total count of words is: xd", int main()
word _count+1);
{
printf("\n The total count of lines is: %¢é", char str[1000], copy_str[1000];
line_count+1); int i=0;
printf("\n The total count of characters is: clrscr();
xd", char_count); printf("\n Enter the text: ");
return 0; gets(str);
} while(str[i] t= ‘\0")
Output {
if(str[i] ==',")
Enter the text: Hi there copy_str[i] =
The total count of words is: 2 else
The total count of lines is: 1 copy_str[i] = str[i];
The total count of characters is: 8 ite;
21. Write a program to copy n characters of a string from
}
copy_str[i] = ‘\0";
the m" position in another string
printf("\n The copied text is: “);
#include <stdio.h> i=0;
#include <conio.h> while(copy_str[i] != '\0")
int main() {
{ printf("Xc", copy_str[i]);
char str[1000), copy_str[1000); iets
int ie0, jwO, m, nj }
clrser( return 0;
printf("\n Enter the text: “); }
gets(str);
Output
printf("\n Enter the position from which to
start: "); Enter the text: Hello, How are you
scanf("Xd", &m); The copied text is: Hello; How are you
printf("\n Enter the number of characters to
be copied: "); 23. Write a program to enter a text that contains multiple
scanf("%d", &n); lines. Rewrite this text by printing line numbers before
i=m; the text of the line starts.
while(str[i] != ‘\O" && n>0) #include <stdio.h>
{ include <conio.h>
copy_str[j] = str{i]; int main()
{
char str[1000);
int is0, linecount = 1;
clrser();
}
copy_str[j]) = ‘\0"; printf("\n Enter a * to end”);
printf("\n The copied text is: *); Printf("\n #eeeeeeneewene):
puts(copy_str); printf("\n Enter the text: ");
return 0; scanf("%c", &str[i]);

} 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

found=1; 27. Write a program to implement a quiz program.


count++;
include <stdio.h>
} #include <string.h>
itt;
#include <conio.h>
:
if (found==1) main()
printf("\n PATTERN FOUND Xd TIMES", {
count);
char quest(5 (100);
else
char option1 3}[20}], option2[3]}[20],
option3[3]}[20],option4[3}][20],
printf("\n PATTERN NOT FOUND");
return 0; option5[3][20];
int response[5], correct_ans[5], option, i,
}
marks;
Output elrser();
strcpy(quest[0), "Name the capital of
Enter the string: She sells sea shells on the
India”);
sea shore
Enter the pattern: sea strcpy(option1[0],
“1. Mumbai”) ;
PATTERN FOUND 2 TIMES
strcpy(option1[1],"2. New Delhi");
strcpy(option1[2],"3. Chennai");
26. Write a program to find whether a given string is a correct_ans[0] = 1;
palindrome or not strepy(quest(1), "Name the national bird of
India”);
#include <stdio.h> strepy(option2(0],"1. Peacock");
t#include <conio.h> strcpy(option2(1],"2. Sparrow");
int main() strcpy(option2(2],"3. Parrot");
{ correct_ans(1]=0;
char str[100]; stecpy(quest(2], "Name the first Prime
int i= 0, j, length = 0; Minister of India”);
clrser(); strcpy(option3[0], "1. M D Gandhi");
printf("\n Enter the string: “); strcpy(option3(1],"2. $ D Sharma");
gets(str); strepy(option3[2],"3. J L Nehru");
while(str[i] !* *\o") correct_ans({2]=2;
{ strcpy(quest([3], "Name the first female
length++;
President of India");
itt; strcepy(option4[0],"1. Pratibha Patil");
} strepy(option4[1],"2. Sonia Gandhi");
iO; strepy(option4[2],"3. Indira Gandhi");
j = length - 1; correct_ans(3] = 0;
while(i <= length/2) strepy(quest[4],"Name the youngest Prime
{ Minister of India");
if(str(i] == str{j)) strcpy(optionS[0],"1. Rajiv Gandhi"
{ strepy(optionS[1],"2. Sanjay Gandhi");
Let; strcpy(optionS[2],"3. Rahul Gandhi");
hae) correct_ans[4] = 0;
} do
else {
break; printf("\n\n\n\n QUIZ PROGRAM");
a printf ("\neeeeeeeereeeees ");
Af(4>=9) printf("\n 1. Display Questions")
printf("\n PALINDROME" ); printf("\n 2. Display Correct Answers”);
else printf("\n 3. Display Result")
printf("\n NOT A PALINDROME"); printf("\n 4. EXIT");
return 0; Printf("\n tte eeeweeeewweeewwewenee):
} printf("\n\n\n Enter your option: ");
Output scanf("%d", Boption);
switch(option)
Enter the string: madam {
PALINDROME
342 Computer Fundamentals and Programming in C

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

Fill in the Blanks 3. Insert("XXXYYYZZ2", 1, “PPP”) =


1, Strings are (a) PPPXxxyYYZzz (b) XPPPXXYYYZZ2
2. Every string is terminated witha (c) XxxvvvzzzPPP
3. If a string is given as “AB CD”, the length of this string is 4, Delete(“XXXYYYZZ2”, 4,3) =
(a) xyz (b) XXxYYZZ
4. The subscript of a string starts with
(c) xxxvZz
5, Characters ofastringarestoredin ss memory
locations.
5. If str[] = "Welcome to the world of programming”, then
SUBSTRING(str, 15, 5) =
6, char mesg{i00}; can store maximum ___ -
characters. (a) world (b) programming
7. function terminates as soon as it finds a (c) welcome (d) none of these
blank space. 6. streat() is defined in which of the header files?
8, LENGTH("") = (a) ctype.h (b) stdio.h
9, The ASCII code for A-Z varies from _ (c) string.h (d) mathh
10. toupper()is used to 7. Astring can be read using which function?
11, $1>S2, means (a) gets() (b) scant()
12, The function to reverse a string is = at (c) getehar() (d) All of these
13, IfS1 = "GOOD MORNING”, then Substr_Left (S1, 7) = 8. Replace(“XXXYYYZZ2", “XY", “AB") =
14. INDEX("Welcome to the world of programming”,
“world”) = _ (a) XXABYYZZZ (b) XABYYYZZZ
(c) ABXXXYYYZZ
15. returns the position in the string where
the string pattern first occurs. 9. The index of U in Oxford University Press is?
16, The atoi() function is present in _ header (a) 5 {b) 6
file, (c) 7 (d) 8
17, strncat(str1, str2,n) is used to 10. s1 = “HI, s2 = “HELLO”, s3 = “BYE”, How can we
18, strcmp(stri, str2) returns 1if_ concatenate the three strings?
19, function computes the length of a string. (a) strcat(si,s2,s3)
20. Besides printf(), function can be used to (b) streat(s1(streat(s2,s3)))
print a line of text on the screen. (c) strepy(s1, streat(s2,s3))
11. strlen("Oxford University Press”) is ?
Multiple-choice Questions
fa) 22 {b) 23
1, LENGTH("\0") =
(c) 24 (d) 25
(a) -1 (b) 0
12. Which function adds a string to the end of another
() 2 (d) None of these string?
2. ASCII code for a~z ranges from
(a) stradd() {b) streat()
(a) 0-26 (b) 35-81
(c) strtok() (d) strepy()
(c) 97-123 (d) None ofthese
344 ‘Computer Fundamentals
and Programming in C

State True or False 14. Write a short note on arrays of strings.


2 A string “Hello World” can be read using scanf(). 15. How is an array of strings represented in the memory?
2. Initializing a string as char str[}="HELLO”; is incorrect as 16. Explain with an example how an array of strings is stored
a null character has not been explicitly added. in main memory.
. A string when read using scanf() needs an ampersand 17. If Substring function is given as SUBSTRING(string,
character. position, length) then, find S(5,9) if S = “Welcome to
gets() takes the starting address of the string which will world of C Programming”
hold the input 18. If Index function is given as INDEX(text, pattern), then
. gets() and scanf() automatically append a null find the index(T, P) where T = “Welcome to world of C
character at the end of the string read from the keyboard. Programming” and P = “of”.
. The scanf() function can be used to read a line of text
that includes white space characters. Programming Exercises
The tolower() function is defined in ctype.h header file. 1. Write a program in C to concatenate first n characters of
. Arithmetic operators can be applied to string variables. a string to another string
String variables can be present either on the left or on 2. Write a program in C that compares first n characters of
the right side of the assignment operator. one string with first n characters of another string
10, if $1 and $2 are two strings, then concatenation 3. Write a program that reads your name and then displays
operation produces a string which contains characters of the ASCII value of each character in your name on a
$2 followed by the characters of $1. separate line.
ll Appending one string to another string involves copying 4. Write a program in C that removes leading and trailing
the contents of the source string at the end of the spaces from a string.
destination string. 5. Write a program to read a word and re-write its
12 $1<S2, when in dictionary order $1 precedes $2 characters in alphabetical order.
13 if $1 = “GOOD MORNING", then Substr_Right(S1, 5) = 6. Write a program that accepts an integer value from 0 to
MORNING. 999, Display the value of the number read in words. That
14, Replace ("AAABBBCCC”, “X", “YYY")= AAABBBCC is, if the user enters 753, then print Seven Hundred Fifty

15. When a string is initialized during its declaration, the Three.


string must be explicitly terminated with a null character. 7. Write a program to insert a word before a given word in
the text
16, stremp(“and”, “ant”) will return a positive value.
8. Write a program to (a) read a name and then display itin
17 Assignment operator can be used to copy the contents
of one string into another. abbreviated form, (b) Janak Raj Thareja should be
displayed as JRT; (c) Janak Raj Thareja should be
Review Questions
displayed as J.R. Thareja
9. Write a program in C that replaces a given character
1. What are strings? Discuss some operations that can be
with another character in the string
performed on strings.
10, Write a program to display the word Hello in the
. Explain how strings are represented in main memory.
following format
How are strings read from the standard input device?
Explain the different functions used to perform string
E
input operation
EL
. Explain how strings can be displayed on the screen ELL
. Explain the syntax of printf() and scanf() ELLO
Write a short note on operations that can be performed 11. Write a program to display the given string array in
‘on strings. reverse order.
Differentiate between gets() and scanf(). 12. Write a program to count the number of characters,
Give the drawbacks of getchar() and scanf(). Which words, and lines in the given text
function can be used to overcome the shortcomings of 13. Write a program to count the number of digits, upper
getchar() and scanf()? case characters, lower case characters, and special
How can putchar() be used to print a string? characters in a given string
Differentiate between a character and a string. 14. Write a program to count the total number of
. Differentiate between a character array and a string occurrences of a given character in the string.
List all the substrings that can be formed from the string 15. Write a program to accept a text. Count and display the
“ABCD”. number of times the word “the” appears in the text.
What do you understand by pattern matching? Give an 16. Write a program to find the last instance of occurrence
algorithm for it. of a sub-string within a string.
Strings 345

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

Heap It is a contiguous block of memory that is available


UNDERSTANDING THE for use by programs when the need s. A fixed size
COMPUTER'S MEMORY heap is allocated by the system and is used by the system
in a random fashion.
Every computer has a primary memory. All data and The addresses of the memory locations in heap that are
programs need to be placed in the primary memory for not currently allocated to any program for use are stored
execution. RAM (Random Access Memory), which is a ina free list. When a program requests a block of memor
part of the primary memory, is a collection of memory the dynamic allocation technique (discussed at the end
locations (often known as cells) and cach location has of this chapter) takes a block from the heap and assigns
a specific address. Each memory location is capable of it to the program. When the program has finished using
storing | byte of data (though new computers are able the block, it returns the memory block to the heap and the
to store 2 bytes of data but in this book we have been addresses of the memory locations in that block are added
talking about locations storing | byte of data). Therefore, to the free list
a char type data needs just | memory location, an int Compared to heaps, stacks are faster but smaller and
type data needs 2 memory locations. Similarly, float expensive. When a program begins execution with the
and double type data need 4 and 8 memory locations, main() function, all variables declared within main() are
respectively. allocated space on the stack. Moreover, all the parametres
In general, the computer has three areas of memory passed to a called function are stored on the stack.
each of which is used for a specific task. These areas of Global memory The block of code that is the main()
memory include—stack, heap, and global memory
program (along with other functions in the program) is
Stack A fixed size of memory called system stack is stored in the global memory. The memory in the global
allocated by the system and is filled as needed from the area is allocated randomly to store the code of different
bottom to the top, one element at a time. These clements functions in the program in such a way that one function
can be removed from the top to the bottom by removing is not contiguous to another function. Besides the function
one clement at a time, i.c., the last clement added to the code, all global variables declared in the program are
stack is removed first stored in the global memory area.
When a program has used the variables or data stored in Other memory layouts C provides some more memory
the stack, it can be discarded to enable the stack to be used areas such as text segment, BSS, and shared library
by other programs to store their data, We have already segment
read a little bit on the system stack in Chapter 11 when we
discussed recursion. * The text segment is used to store the machine
instructions corresponding to the compiled program.
This is generally a read-only memory segment.
* BSS (Block Started by Symbol) is used to store un-
System stack is the section of memory that isallocated initialized global variables.
for automatic variables within functions. * Shared library segment contuins the executable image
of shared libraries that are being used by the program.
348 Computer Fundamentals and Programming in C

When this statement executes, the compiler sets aside


INTRODUCTION TO POINTERS 2 bytes of memory to hold the value 10. It also sets up
a symbol table in which it adds the symbol x and the
Every variable in C language has a name and a value relative address in memory where those 2 bytes are set
associated with it. When a variable is declared, a specific aside.
block of memory within the computer is allocated to hold Thus, every variable in C has a value and a memory
the value of that variable. The size of the allocated block location (commonly known as address) associated with it
depends on the type of the data. Let us write a program Some texts use the term rvalue and value for the value
to find the size of the various data types on your system. and the address of the variable, respectively
(Note the size of integer may vary from one system to The rvalue appears on the right side of the assignment
another. In 32 bit systems, integer variable is allocated 4 statement (10 in the above statement) and cannot be used
bytes while on 16 bit systems it is allocated 2 bytes.) on the left side of the assignment statement, Therefore,
1. Write a program to find the size of various data types on writing 10 = k; is illegal. If we write
your system. int x, ys
#include <stdio.h> x = 10;
int main() yuu
{ then in this code we have two integer variables x and
printf("\n The size of short integer is : y. Compiler reserves memory for integer variable x
Xd", sizeof(short int)); and stores rvalue 10 in it. When we say y = x, then x
printf("\n The size of unsigned integer is: is interpreted as its rvalue (since it is on the right hand
Xd", sizeof(unsigned int)); side of the assignment operator **'). Here x refers to the
printf("\n The size of signed integer is: value stored at the memory location set aside for x, in this
%d", sizeof(signed int)); case 10. After this statement is executed, the rvalue ofy
printf("\n The size of integer is: Xd", is also 10.
sizeof(int)); You must be wondering why we are discussing
printf("\n The size of long integer is: Xd", addresses and Ivalues? Actually pointers are nothing but
sizeof(long int)); memory addresses. A pointer is a variable that contains
the memory location of another variable, Therefore, 4
printf("\n The size of character is: Xd", pointer is a variable that represents the location of a data
sizeof(char)); item, such as a variable or an array clement, Pointers are
printf("\n The size of unsigned character frequently used in C language as they have a number of
is: Xd", sizeof(unsigned char)); useful applications. These applications include:
printf("\n The size of signed character is:
* to pass information back and forth between a function
Xd", sizeof(signed char));
and its reference point
* enable programmers to return multiple data items from
printf("\n The size of floating point number
a function via function arguments
is: %d", sizeof(float));
* provide an alternate way to access individual elements
printf("\n The size of double number is:
of the array
Xd", sizeof(double));
* to pass arrays and strings as function arguments
return 0;
* enable references to functions, So with pointers,
} programmers can even pass functions as argument to
Output another function
* to create complex data structures such as tre 3, linked
The size of short integer is: 2
lists, linked stacks, linked queues, and graphs
The size of unsigned integer is: 2
+ for dynamic memory allocation of a variable
The size of signed integer is: 2
The size of integer is: 2
The size of long integer is: 4 DECLARING POINTER VARIABLES
The size of character is: 1
The size of unsigned character is: 1 Programming Tip: A pointer provides access to a
The size of signed character is: 1
The data type of the variable by using the address
The size of 5 floating point number is: 4
pointer variable and of that variable. A pointer
The size of double number is: 8 the variable to which variable is therefore a variable
it points must be the that stores the address of
Consider the statement below: same. another variable, The general
int x = 10;
Pointers (349
syntax of declaring pointer variables can be given as An integer pointer variable, therefore, points to ai
below: integer variable. In the last statement, ptr is assigned the
address of x. The & operator retrieves the Ivalue (address)
data_type *ptr_name; of x, and assigns it to the pointer ptr.
Here, data_type is the data type of the value that the Consider the memory cells given in Figure 14,1
pointer will point to, For example,
int *pnum; LES)CE
char *pch; 1000 1001 1002 1003 10041005 1006 1007 1008 1009
float *pfnum;
Figure 14.1. Memory representation
In cach of the aforegiven statements, a pointer variable
Now, since x is an integer variable, it will be allocated
is declared to point to a variable of the specified data type
Although all these pointers, pnum, pch, and pfnum point 2 bytes. Assuming that the compiler assigns it memory
to different data types, they will occupy the same amount locations 1003 and 1004, we say the value of x = 10 and
of space in memory. But how much space they occupy will the address of x (written as &x) is equal to 1003, i.c., the
starting address of x in the memory. When we write, ptr =
depend on the platform where the code is going to run.
To verify this, execute the following code and observe the &x, then ptr = 1003.
result
#include <stdio.h> in C,pointers are not allowed to store actual memory
main()
addresses, but only the addresses of variables of a given
{ type. Therefore writing a statement like int * ptr = 1000;
int *pnum; is absolutely illegal inC.
char *peh;
float *pfnum;
We can dereference a pointer, i.c., refer to the value of the
double *pdnum;
variable to which it points, by using unary ‘** operator
long *plnum;
(also known as indirection
printf("\n Size of integer pointer = Xd",
Programming Tip: operator)as*ptr,i.c., *ptr =
sizeof (pnum));
printf("\n Size of character pointer = Xd",
As theaddress ofa 10, since 10 is value of x
sizeof(pch));
memory location is Therefore, * is equivalent to
printf("\n Size of float pointer = Xd",
Sconstant,ieannot writing value at address. Look
sizeof(pfnum));
be changed inthe at the code below which shows
printf("\n Size of double pointer = Xd",
program code. the use of pointer variable
sizeof(pdnum)); include <stdio.h>
printf("\n Size of long pointer = Xd", int main()
sizeof(plnum)); {
} int num, *pnum;
pnum = &num;
Output
printf("\n Enter the number: ");
Size of integer pointer = 2 scanf("Xd", &num);
Size of character pointer « 2 printf("\n The number that was entered is:
Size of float pointer = 2 Xd", *pnum);
Size of double pointer = 2 printf("\n The address of number in memory
Size of long pointer = 2 is: Xp", &num);
return 0;
Now let us declare an integer pointer variable and start
using it in our program code. }
Output
int x= 10;
int *ptr; Enter the number: 10
ptr = &x; The number that was entered is: 10
The address of number in memory is: FFDC
In the above statement, ptr is the name of pointer
variable. The ‘*" informs the
Howat Shsae compiler that ptr is a pointer
‘%p control string prints the argument as a memory
4 variable and the int specifies
address in hexadecimal form. %u prints memory address
sorecol es
ine that it will store the address of
an integer variable.
in decimal form,
350 Computer Fundamentals and Programming in C

Can you tell what will be The address of a variable is the


iadeetnien ds the value of *(&num)? Yes it is Programming Tip: address of the first byte occupied
cannot beassigned equivalent tonum. The indirection bob ltteirbrreng by that variable. Basically,
‘Ubiuie bf thevariate and the address operators are es aacihasVariable: address of the variable is the
to.whichit 3 inverse of cach other, so when ofthe sametype relative location of the variable
combined in an expression, they The riable towhich with respect to the program's
cancel each other. por s memory space. Although the
We can also assign values to variables using pointer ti address of a variable cannot be
variables and modify their values. The code given below a . ‘an changed, the variable’s address
shows this, le. P may change during different
program runs, ic. if you try to
#include <stdio.h>
print the address of num today, it may print 4010. Next time
int main()
when you run the program, it may print the address as FA12.
{ One point to remember always is that both the data type
int num, *pnum;
of the pointer variable and the variable whose address it
pnum = &num;
will store must be of the same type, Therefore, the
*pnum = 10;
following code is not valid.
printf("\n *pnum = Xd", *pnum);
printf("\n num = %d", num); int x = 10;
*pnum = *pnum + 1; float y = 2.0;
// increments the value of num int *px;
printf("\n After increment *pnum = Xd", float *py;
*pnum) ; px = &y; //INVALID
printf("\n After increment num = Xd", num); py = &x;//INVALID
return 0;
Also note that it is not necessary that the pointer variable
} will point to the same variable throughout the program, It
Output can point to any variable as long as the data type of the
pointer variable is same as that of the variable it points to.
*“pnum = 10 The following code illustrates this concept
num = 10
After increment *pnum = 12 @include <stdio.h>
After increment num = 11 int main()
Now can you predict the output of the following code? {
int a=3, b=5;
#include <stdio.h> int *pnum;
int main() pnum = &a;
{ printf("\n a © Xd", *pnum);
int num, *pnuml, *pnum2; pnum = &b;
pnuml = &num; printf("\n b = Xd", *pnum);
*pnuml = 10; return 0;
pnum2 = pnuml; }
printf("\n Value of num using all three
variables (num, *pnuml, *pnum2) = Xd Xd
Output
Xd", num, *pnumi, *pnum2); a-3
printf("\n Address of num using all three be S
variables (&num, pnuml, pnum2) = %x Xx Xx",
num, pnuml, pnum2);
return 0; Using an un-initialized pointer can cause unpredictable
} results.
While the first printf statement will print the value of
num, the second printf statement will print the address
of num, These are just three different ways to refer to the
EZR) POINTER EXPRESSIONS AND
value and address of the same variable. POINTER ARITHMETIC
Like other variables, pointer variables can also be used in
Any number of pointers can point to the same address. expressions. For example, if ptr1 and ptr2 are pointers,
then the following statements are valid.
Pointers — (351

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);

int numle2, num2=3; return 0;


int *p = &numi, *qe&num2; }
*pte = "gee; Output
What will *p++ = *q++ do? Because ++ has a higher Enter the two numbers: 2.5 3.4
precedence than *, both p and q are increased, but because 2.5 ¢ 3.4 = 5.90
p ing Tip: the increment operators (++)
are used as postfix and not 4. Write a program to calculate area of a circle
katie ote cfix, thethe value value assigned
prefix, assigned toto @include <stdio.h>
roseabepgaal aad *p is *q before both p and q @include <conio.h>
are increased. Then both are int main()
increased, So the statement is equivalent to writing
{
*p = "43 double radius, area = 0.0;
tps t4q5 double *pradius = &radius, *parea = &area;
printf("\n Enter the radius of the circle; ");
Let us now summarize the rules for pointer operations: scanf("X1", pradius);
* Apointer variable can be assigned the address of another *parea = 3.14 * (*pradius) * (*pradius);
variable (of the same type). printf("\n The area of the circle with
* A pointer variable can be assigned the value of another radius %.21f = %.21f", *pradius, *parea);
pointer variable (of the same type).
352 Computer Fundamentals and Programming in C

return 0; int main()


} {
char ch, *pch = &ch;
Output
int upper = 0, lower = 0;
Enter the radius of the circle: 7 clrscr();
The area of the circle with radius 7.00 = 153.83 printf("\n Enter the character: ");
scanf("%e", pch);
5. Write a program to convert a floating point number into while(*pch I= ‘*")
an integer,
{
#include <stdio.h> if(*pch >= ‘A’ && *pch <= *Z')
int main() {
{ *peh += 32;
float fnum, *pfnum = &fnum; uppere+;

int num, *pnum = &num; }


printf("\n Enter the floating point no.: "); if(*pch >» ‘a’ 8% *pch cw *z')
scanf("X#", &fnum); {
*pnum = (int)*pfnum; *pch == 32;
printf("\n The integer equivalent of %.2f lower++;
= Xd", *pfnum, *pnum); }
return 0; printf("%e", *pch);
printf("\n Enter the character: “);
}
scanf("%c", pch);
Output
}
Enter the floating point no.: 3.4 printf("\n Total number of upper case
The integer equivalent of 3.40 = 3 characters = %4", upper);
printf("\n Total number of lower case
6. Write a program to print a character, Also print its AS characters = %d", lower);
value and rewrite the character in upper case getch();
return 0;
#include <stdio.h>
#include <conio.h> }
int main() Output
{ Enter the character: A
int ch, *pch = &ch;
a
clrser();
Enter the character: b
printf("\n Enter the character: “);
8
scanf("%e", &ch);
Enter the character
printf("\n The char entered is: X%c", *pch);
c
printf("\n ASCII value of the char is: Xd",
Enter the character: *
*pch); Total number of upper case characters = 1
printf("\n The char in upper case is: %c"
Total number of lower case characters = 2
*pch ~ 32);
Betch(); 8. Write a program to test whether a number is positive,
return 0; negative, or equal to zero,
}
#include <stdio.h>
Output int main()
Enter the character: {
The char entered is: int num, *pnum = &num;
ASCII value of the char is: 122 printf("\n Enter any number: “);
The char in upper case is: Z scanf("%d", pnum);
if(*pnum>0)
7. Write a program using pointer variables to read a printf("\n The number is positive");
character until * is entered, If the character is in upper else
case, print it in lower case and vice versa. Also count the {
number of upper and lower case characters entered. if(*pnum<0)
printf("\n The number is negative”);
#include <stdio.h>
else
#include <conio.h>
Pointers weanoe

printf("\n The number is equal to zero”); return 0;


} }
return 0; Output
}
Output
Enter the starting and ending limit of the
numbers: 0 10
Enter any number: -1 0 is even
The number is negative 2 is even
4 is even
9, Write a program to display the sum and average of 6 is even
numbers from m to n 8 is even
#include <stdio.h> 10 is even
int main()
Il. Write a program to read numbers until -1 is
{
entered. Also display whether the number is prime or
int range;
composite.
int m, “pm = &m;
int n, *pn = &n; #include <stdio.h>
int sum = 0, *psum = &sum; int main()
float avg, *pavg = &avg; {
printf("\n Enter the starting and ending int num, *pnum = &num;
limit of the numbers to be summed:"); int i, flag = 0
scanf("%d Xd", pm, pn); printf("\n ***** ENTER -1 TO EXIT **+*
range =n - m5 printf("\n Enter any number: *);
while(*pm <= *pn) scanf("Xd", pnum) ;
{ while(*pnum |= -2)
*psum = *psum + *pm; {
*pm = *pm + 1; if(*pnum == 1)
} printf("\n %d is neither prime nor
printf("\n Sum of numbers = Xd , *psum); composite”, *pnum);
*pavg * (float)*psum / range; else if(*pnum == 2)
printf("\n Average of numbers « %.2*", printf("\n Xd is prime”, *pnum);
*pavg); else
return 0; {
} for(is2; ic*pnum/2; ire)

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

= fa = 0.5 * (*b) © (*h);


}
are[O] arr{t]arr[2]arr[3]_arr[4]
Output
Enter the base of the triangle: 10 ptr
Enter the height of the triangle: 5
Area of the triangle with base 10.0 and Figure 14.3 ptr pointing to the third element of the array
height 5.0 = 25.00
If pointer variable ptr holds the address of the first
We know that functions usually return only one value, element in the array, then the address of successive
but pointers can be used to return more than one value to the elements can be calculated by writing ptr++.
calling function, This is done by allowing the arguments to
be passed by addresses which enables the function to alter int *ptr = Sarr[0];
the values pointed to and thus helps to return more than ptres;
one value. printf("\n The value of the second element of
the array is %d", *ptr);

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

Table 14.1 summarizes pointer arithmetic

LCR OS® Pointer arithmetic

Operation Condition | Declaration Description


ao Pointers must be int *ptr!, *ptr2; Hf we write *ptrl = *ptr2. then both the pointers point tothe same
of same type location
|
Addition of an integer inti, *pt, If we write, ptr+ i,then ptr will point toith object after itsinitial
position
Subtraction of an int i, * ptr; If we write ptr— i,then ptr will point toith object before itsinitial
integer position
Comparison of Pointers should int *ptrl, *ptr2; If we write ptr! < ptr2, then it would return |if ptr] points toan
pointers point toelements clement that isnear to the beginning of the array, i.c., theelement
of the same array comes before theelement pointed by ptr2
Subtraction of Pointers should — int *ptel, *ptr: If we write ptr — ptr2, then itreturns the number of elements
pointers point toelements between ptr! and ptr2 (provided ptrl > ptr2)
‘of the same array
|Addition ofpointers isillegalinC.Therefore,
pert+ptr2ksnotvalidinC.

Enter the number: 4


Enter the number: 5
An object isa named region ofstorage; an Ivalue is an
The numbers you entered are:
expression referring to an object. 12345
The sum is: 15
17. Write a program to find mean of numbers using The mean is: 3.00
arrays.
18. Write a program to find the largest of n numbers using
#include <stdio.h>
arrays. Also display its position.
int main()
{ #include <stdio.h>
int i, n, arr[20], sum = 0; int main()
int *pn = &, *parr = arr, *psum = &sum; {
float mean = 0.0, *pmean = &mean; int i, n, arr{20], large = -32768, pos = 0;
printf("\n Enter the number of elements:"); int *pn = &n, *pare = arr, *plarge = &large,
scanf("%d", pn); *ppos = &pos;
for(i = 0; i < *pn; i++) printf("\n Enter the number of elements in
{ the array: *);
printf("\n Enter the number: "3 scanf("%d", pn);
scanf("X%d", (parr + 4)); for(i = 0; i < *pnjite)
} {
for(i=0; 4 < "pn; i++) printf("\n Enter the number: "3
*psum += *(arr + 4); scanf("Xd", parr+i);
*pmean = (float)*psum / *pn;
printf("\n The numbers you entered are: ")s oath = 0; i < *pn; ist)
for(i=0; i < *pn; i++) {
printf("Xd “, *(arr + i)); if(*(parrei) > «plarge)
printf("\n The sum is: Xd", *psum);
printf("\n The mean is: %.2f", *pmean); Signe = *(parrei);
return 0; *ppos = i;

} }
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

When we write pte2 = ptri, we are not copying the


QUENT) pirFERENCE BETWEEN ARRAY data pointed to. Rather, we are just making two pointers
NAME AND POINTER point to the same location. This is shown in Figure 14.6,

When memory is allocated to an array, its base address is pu?


fixed and it cannot be changed during program execution. . . =
In other words, an array name is an address constant. a Sl ea) (es
Therefore, its value cannot be changed. To ensure that 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
the address of the array docs not get changed even are{O} aft] aref2] arf] acr[4]
inadvertently, C does not allow array names to be used as
an lvalue, Hence, array names cannot appear on the left
side of the assignment operator
perl
However, you may declare a pointer variable of Figure 14.6 Pointers pointing to the same location
appropriate type that points to the first clement of the array
and use it as Ivalue. Figure 14.5 shows two sets of codes. Third point of difference lies with the return value of the
The first code gives an error as the array name is being address operator, The address operator returns the address
used as an Ivalue for the ++ operator. The second code of the operand. But when an address operator is applied to
shows the correct way of doing the same thing an array name, it gives the same value as the array reference
without the operator. Therefore, arr and Sarr give the same
value. However, this is not true for a pointer variable.
int) Last but not the least, the sizeof operator when applied
to an array name retums the number of bytes allocated
int arr[S], 4;
rants pie) for the array. But in case of a pointer variable, the sizeof
operator returns the number of bytes used for the pointer
*arre0; variable (machine dependent). Look at the following code
arne+; / ERROR
which illustrates this concept
Fecieo; 1 < Sjies)
printf("\n &d", *(arres)); main()
} {
rant
int arr[}={1,2,3,4,5};
int *ptr;
int arr(S], 4, *parr; ptrearr;
parr = are; printf("\n Size of array = Xd", sizeof(arr));
for(i 0; 1< S;ite)
printf("\n Size of pointer variable = Xd",
*parre0; sizeof(ptr));
; parne+; }
for(i=0; 1< Sjis+) Output (On Turbo C)
print#("\n %d", *(arrei));
} Size of array = 10
Size of pointer variable « 2
Figure 14.5 Difference between array name and pointer

Second thing to remember is that an array cannot be POINTERS AND STRINGS


assigned to another array. This is because an array name
cannot be used as the Ivalue. In C, strings are treated as arrays of characters that are
terminated with a binary zero character (written as *\0")
int arri[}={1,2,3,4,5}; Consider, for example,
int arr2[5};
arr2 = arrl; // ERROR char str[10];
str[0} = 'H';
But one pointer variable can be assigned to another str{1] = 'i
pointer variable of the same type. Therefore, the following str[2) = '!
statements are valid in C str[3] = ‘\0';
int arri[]={1,2,3,4,5}; C language provides two alternate ways of declaring
int *ptri, *ptr2; and initializing a string. First, you may write
ptrl = arri;
ptr2 = ptri; char str[10] = {'H', ' "\O"};3
Pointers 361

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

21. Write a program to copy a character array in another *peopy_str = *pstr;


character array. pcopy_str++;
#include <stdio.h> pstr++;
#include <conio.h> itt;
int main() }
{ *pcopy_str = '\0';
char str[100], copy_str[100)}; printf("\n The copied text is: “);
char *pstr, *pcopy_str; puts(copy_str);
int i = 0; return 0;
clrser( }
pstr = str;
Output
peopy_str = copy_str;
printf("\n Enter the string: “); Enter the string: How are you
gets(str); Enter the position from which to start: 2
while(*pstr I* '\0') Enter the number of characters to be
{ copied: 5
*pcopy_str = *pstr; The copied text is: w are
pstr++, pcopy_stres;
} 23. Write a program to copy the last n characters of a
*pcopy_str = '\0';
character array in another character array
printf("\n The copied text is: “); #include <stdio.h>
pcopy_str = copy str; #include <string.h>
while(*pcopy_str != *\0") int main()
{ {
printf("%c *pcopy_str); char str[100], copy_str[100];
pcopy_stre+; char *pstr, *pcopy_str;
} int i = 0, n;
getch(); pstr = str;
return 0; pcopy_str = copy str;
} printf("\n Enter the string:"
Output gets(str);
printf("\n Enter the number of characters to
Enter the string: C Programming be copied (from the end): "); scanf("%d",
The copied text is: C Programming &n);
pstr « pstr + strlen(str) - n;
22. Write a program to copy n characters of a character
while(*pstr t* *\0")
array from the m" position in another character array
{
#include <stdio.h> *pcopy_str = *pstr;
int main() pstr++; pcopy_stre+;
{ }
char str[100], copy_str{100]; *pcopy_str = ‘\0';
char *pstr, *pcopy_str; printf("\n The copied text is: ");
int m, n, i= 0; puts(copy_str);
pstr = str; return 0;
pcopy_str = copy_str; }
printf("\n Enter the string: "); Output
gets(pstr);
printf("\n Enter the position from which to Enter the string: Hi there
start: "); Enter the number of characters to be copied
scanf("kd", &m); (from the end): 5
printf("\n Enter the number of characters to The copied text is: there
be copied: ");
scanf("%d", &n); 24. Write a program to read a text, delete all the semi-
pstr = pstr + m; colons it has, and finally replace all *." with a ‘,’
i=0; #include <stdio.h>
while(*pstr != '\O’ && i <n) int main()
{ {
Pointers 363

char ste[100], copy_str[100]}; *pcopy_str = '\0';


char *pstr, *pcopy_str; printf("\n The new text is: “);
pstr = str; pcopy_str = copy str;
pcopy_str = copy str; while(*pcopy str != '\0')
printf("\n Enter the string: "); {
gets(str); printf(“Xe", *pcopy_str);
while(*pstr t= ‘\0") pcopy_stre+;

{ }
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

Here, ptr[0] is Janak, ptr[1] is Raj, and ptr[2] is


ARRAYS OF POINTERS Paul.
The memory layout of ptr can be given as shown in
An array ofpointers
can be declaredas Figure 14.7. It requires only 15 bytes to store the three
int *ptr[10]}; strings.
The above statement declares an array of 10 pointers
where each of the pointer points to an integer variable. For
example, look at the code given below.
int *ptr[10];
int p=1,q2+2,r=3,s=4,
t= 5;
ptr[O] = &p; Figure 14.7. Memory layout of ptr
ptr[1] = &q;
ptr[2] = &r; However, char str[{3][10] = {"Janak", “Raj",
pte[3] = &s; “Paul")}; will behave in the same way as an array of
ptr[4] = at characters. The only difference is the memory layout
(Figure 14.8). While the array of pointers needs only 15
Can you tell what will be the output of the following bytes of storage, str will reserve 30 bytes in memory,
statement? despite the fact that some memory locations will be
printf("\n Xd", *ptr[3]); reserved but not utilized.
The output will be 4 because ptr[3] stores the address
of integer variable s and *pte[3] will therefore print the
falafale}rof
[rials fol [efafuli fol |
value ofs that is 4, Now look at another code in which we ‘The grey locations represent the uninitialized memory cells
store the address of three individual arrays in the array of Figure 14.8 Memory layout
pointers,
Look at the following program that uses an array
main()
of character pointers to display the name of the day
{ corresponding to the number.
int arri[}={1,2,3,4,5};
int arr2[]={0,2,4,6,8)}; #include <stdio.h>
int arr3{]#{1,3,5,7,9}; char *day_of_week(int);
int *pare(3) = (arrl, arr2, arr3); main()
int 4; {
for(i = O;i<3;ie+) int day_num;
printf("%d", *parr[i}); char *day;
} printf("\n Enter the day from 1 to 7:");
scanf("%d", &day_num);
Output
day = day_of_week(day_num);
101 if(day)
printf("%s", day);
Surprised with this output? Try to understand the
else
concept. In the for loop, parr{0) stores the base address
printf("\n Invalid Day”);
ofarri (or, &are1(0}). So writing *parr[0) will print the
value stored at &arr1(0]. Same is the case with *parr[1} }
char *day_of_week(int day)
and *parr[2].
Now consider an array of character pointers that point {
char *week_day[7] = {"SUNDAY", "MONDAY",
to strings.
“TUESDAY”, “WEDNESDAY”, “THURSDAY”,
char *ptr[3]; "FRIDAY", “SATURDAY”};
if(day>=1 || day<=7)
In the ptr array, cach clement is a character pointer.
return week_day[day-1];
Therefore, we can assign character pointers to the elements
else
of the array. For example,
return NULL;
ptr[0] = str; }
Another way to initialize an array of characters with Output
three strings can be given as,
Enter the day from 1 to 7: 3
char *ptr[3] = {"Janak”,Raj”,Paul”}; TUESDAY
Pointers 365

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++)

dimensional array can be given as {


for (j=0;4<35
j++)
are(i}[j] = (*(arred))(J] = *((rarred)
ej) {
= *(arr[i}ej) printf("\n mat[Xd][Xd] = “,4,9)5
scanf("Xd", (*(mat + 4)+j);
Therefore,
}
arr(0}[0] = *(arr)[0) = *((*arr)+0) }
= *(arr[0}+0) printf("\n The elements of the matrix are
arr[1][2] = (*(arevd))[2] = *((*(aered))+2) ‘5
= *(arr[1]+2) Printf("\n eeeeecereereneeeneeerenwe™);
for(i=0;1<3;
i++)
erence If wedeclare a pointer toan {
pointer using array using, printf("\n");
for(j=0;4<3;
j++)
data_type *array_ data_type (*array_
name[SIZE); name) (SIZE);
printf("\t mat(Xd] [Kd] = %d",4,4,
*(*(mat + i)+4);
Here SIZE represents the Here SIZE represents the }
|eaianae tone aeti number ofcolumns and the return 0;
| space forcolurnas that canbe space for rows that may be
}
Léynamically wllocated,
| dynamically allocated. OR

27. Write a program to read and display a 3 = 3 matrix. #include <stdio.h>


void display(int (*){3})
#include <stdio.h> int main()
int main() {
{ int i, j, mat[3])(3);
int i, j, mat[3]}[3]; clrscr();
printf("\n Enter elements of the matrix"); printf("\n Enter elements of the matrix");
Printf("\n *#eeeeeereeeeeseneereseee™): PrINtf("\n seeeeeseeeenensnseesneene”):
for(i=0;ic3;i++) for(i=0;i<3; i++)
{ {
for(j=0;4<3;5++) for(j = 0; j < 3; j++)
{ {
printf("\n mat(Xd}(%d) = ",i,j); printf("\n mat(%d][%d] = “,i,j);
scanf("%d", &mat[{i}[j]); scanf("Xd", &mat[{i}[j]);
} }
} }
printf(“\n Elements of the matrix are”); display(mat);
Printf("\n *eeeeeeeeesereseeeereeeeen):
}
for(i=0;i¢3;i++) void display(int (*mat)[3]})
{ {
printf(“\n"); int i, 3;
for(j = 0; j < 3; j++) printf("\n Elements of the matrix are");
Pointers 367

printf("\n ** A pointer to a three-dimensional array can be declared a8


oe NP PRED ED int arr{2][2][2]={1,2,3,4,5,6,7,8};
printf("\n"); int (parr)(2]12}3
for(4=0;4<3;4++) Pare ree
printf("\t mat(Xd][(%d] = Xd",i,j, We can access an clement of a three-dimensional array
*(*(mat + i)+5)); by writing,
}
return 0; are[a}i (Jk) == *(*(0
*(*(*(arr+i)+j)+k)
} Look at the code given below which illustrates the use
of a pointer to a three-dimensional array
Output x
include <stdio.h>
Enter elements of the matrix
WEPeEESSEOOCSOOOOS
OST rery include <conio.h>
main()
123456789 {
Elements of the matrix are
int i,j,k;
int are[2}[2}[2);
int (*pare)[2)(2]= arr;
elrser();
= printf("\n Enter the elements of a 2* 2x 2
array: “);
“iad = 0; i < 2; ise)

A double pointer cannot be used as a 2D array. for(j = 0; j < 2; fre)


Therefore, it is wrong to declare: ‘int * *mat’ and then {
use ‘mat’ as a 2D array, These are two very different for(k = 0; k < 25 k++)
data types used to access different locations in memory. scanf("Xd", @are[i}[j)}[k]);
So running such a code may abort the program with a }
‘memory access violation’ error. }
A 2D array is not equivalent to a double pointer.A printf("\n The elements of the 2 x 2 « 2

‘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);

14.15.2 Calling a Function Using a Function }

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

fp[3] = div; px = &x;


printf("\n Enter the numbers: “); ppx = &px;
scanf ("Xd Xd", &numi, &num2);
do
Assume that the memory location of these variables is
as shown in Figure 14.9
{ Now if we write,
printf("\n 0: Add \n 1: Subtract \n
2: Multiply \n 3: Divide \n 4. EXIT\n"); printf(“\n Xd", **ppx);
printf("\n\n Enter the operation: “);
scanf("Xd", Bop); then it will print 10, the value of x.
result = (*fp[op]) (num1, num2);
printf(“\n Result = %0", result); x px ppx
} while(op!=4);
10 1002 2004
return 0;
} 1002 2004 4008
int sum(int a, int b)
Figure 14.9 Pointer to pointer
{
return a + b;
}
int subtract(int a, int b) MEMORY ALLOCATION IN C
{ PROGRAMS
return a - b;
} C supports three kinds of memory allocation through the
int mul(int a, int b) variables in C programs
{
return a * b; Static allocation When we declare a static or global
} variable, static allocation is done for the variable. Each
int div(int a, int b) static or global variable is allocated a fixed size of memory
{ space. The number of bytes reserved for the variable
if(b) cannot change during execution of the program. Till now
return a / b; we have been using this technique to define variables,
else arrays, and pointers.
return 0; Automatic allocation When we declare an automatic
} variable, such as a function argument or a local variable,
Output automatic memory allocation is done. The space for
an automatic variable is allocated when the compound
Enter the numbers: 2 3
statement containing the declaration is entered, and is
O: Add
freed when it exits from a compound statement
1: Subtract
2: Multiply Dynamic allocation A third important kind of memory
3: Divide allocation is known as dynamic allocation. In the following
4. EXIT sections we will read about dynamic memory allocation
Enter the operation: 0 using pointers
Result = 5
Enter the operation: 4
MEMORY USAGE
POINTERS TO POINTERS Before jumping into dynamic memory allocation, let
us first understand how memory is used. Conceptually,
In C language you are also allowed to use pointers that
memory is divided into two—program memory and data
point to pointers. The pointers in turn point to data (or memory (Figure 14.10)
even to other pointers). To declare pointers to pointers, The program memory consists of memory used for
just add an asterisk (*) for cach level of reference. main() and other called functions in the program, whereas
For example, if we have:
data memory consists of memory needed for permanent
int x = 10; definitions such as global data, local data, constants, and
int *px; //pointer to an integer dynamic memory data. The way in which C handles the
int **ppx; /* pointer to a pointer to an memory requirements is a function of the operating system
integer */ and the compiler.
Pointers (371

Memory Memory allocation/de-allocation functions

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

min) 2, Global Stack He:


" free()
realloc()
Frees previously allocated memory
Alters the size ofpreviously allocated memory _,

Figure 14.10 Memory usage


way to go, When we use malloc() for dynamic memory
When a program is being executed, its main() and all allocation, then you need to manage the memory allocated
other functions are always kept in the memory. However, for variables yourself.
the local variables of the function are available in the
memory only when they are active. When we studied
14.20.1 Memory Allocation Process
recursive functions, we have seen that the system stack
is used to store a single copy of the function and multiple Incomputer science, the free memory region is called the heap.
copies of the local variables. The size of heap is not constant as it keeps changing when
Apart from the stack, we also have a memory allocation the program is executed. In the course of program execution,
known as heap. Heap memory is unused memory allocated some new variables are created and some variables cease to
to the program and available to be assigned during its exist when the block in which they were declared is exited.
execution. When we dynamically allocate memory for For this reason it is not uncommon to encounter memory
variables, heap acts as a memory pool from which memory overflow problems during dynamic allocation process,
is allocated to those variables When an overflow condition occurs, the memory allocation
However, this is just a conceptual view of memory and functions mentioned above will return a null pointer,
implementation of the memory is entirely in the hands of
system designers. 14.20.2 Allocating a Block of Memory
Let us see how memory is allocated using malloc()
€@ET) pynamic MEMORY ALLOCATION malloc is declared in <stdlib.h>, so we include this
header file in any program that calls malloc. The malloc
The process of allocating memory to the variables during function reserves a block of memory of specified size
execution of the program or al run time is known as and returns a pointer of type void. This means that we
dynamic memory allocation. C language has four library can assign it to any type of pointer. The general syntax of
routines which allow this function. malloc() is
Till now whenever we needed an array we had declared
a static array of fixed size, say
ptr =(cast-type*)malloc(byte-size);
where ptr is a pointer of type cast-type. malloc() returns
int arr[100);
4 pointer (of cast type) to an area of memory with size
When this statement is executed, consecutive space for byte-size. For example,
100 integers is allocated, It is not uncommon that we may
be using only 10% or 20% of the allocated space, thereby
arr=(int*)malloc(10*sizeof(int));
wasting rest of the space. To overcome this problem and Tip: This statement is used to
to utilize the memory efficiently C language provides a Atedemir dynamically allocate memory
mechanism of dynamically allocating memory so that only memory allocation equivalent to 10 times the arca
the amount of memory that is actually required is reserved. f 5,YOUrmnsst of int bytes, 2 successful
We reserve space only at the run time for the variables that execution of the statement
are actually required. Dynamic memory allocation gives feadibe the space is reserved and
best performance in situations in which we do not know the address of the first byte
memory requirements in advance. of memory allocated is assigned to the pointer arr of
C provides four library routines to automatically type int
allocate memory at the run time. These routines are shown The calloc() function is another function that
in Table 14.2 reserves memory at the run time. It is normally used
When we have to dynamically allocate memory for to request multiple blocks of storage cach of the same
variables in our programs then pointers are the only size and then sets all bytes to zero. calloc() stands for
372 Computer Fundamentals and Programming in C
Contiguous memory allocation and is primarily used to printf("\n The array contains \n");
allocate memory for arrays. The syntax of calloc() can for(i = 0;4 < njit+)
be given as printf("%d", arr[i]);
// another way is to write *(arr+i)
ptr=(cast-type*) calloc(n,elem-size);
return 0;
The aforegiven statement allocates contiguous space }
for n blocks cach size of clements size bytes. The only
difference between malloc() and calloc() is that when Now let us also see how we can allocate memory using
we use calloc(), all bytes are initialized to zero. calloc() the calloc function, The calloc() function accepts two
retums a pointer to the first byte of the allocated region. parametres—num and size, where num is the number of
When
we allocate memory using malloc() orcalloc(), clements to be allocated and size is the size of elements.
a null pointer will be returned if there is not enough spac The following program demonstrates the use of calloc()
in the system to allocate, It is a not a pointer marker; to dynamically allocate space for an integer array.
therefore, it is not a pointer you can use. Thus, whenever #include <stdio.h>
you allocate memory using malloc() or calloc(), you #include <stdlib.h>
must check the returned pointer before using it. If the main ()
program receives a null pointer, it should at the very least {
print an error message and exit, or perhaps figure out some int i,n;
way of proceeding without the memory it asked for. But in int ‘arr;
any case, the program cannot go on to use the null pointer printf (“\n Enter the number of elements:
it got back from malloc()/calloc(). "3
A call to malloc, with an error check, typically looks scanf( "Xd" ,&n);
something like this: are = (int*) calloc(n,sizeof(int));
if (arr==NULL)
int *ip = malloc(100 * sizeof(int)); exit (1);
if(ip == NULL) printf("\n Enter the Xd values to be stored
{ in the array", n);
printf("\n Memory could not be allocated"); for (i = 0; i < nj i+)
return; scanf ("Xd",&arr[i});
printf ("\n You have entered: ");
for(i = 0; i <n; ise)
printf ("Xd",are[i});
29.Write a program to read and display values of an
free(arr);
integer array. Allocate space dynamically for the array return 0;
#include <stdio.h>
#include <conio.h>
#include <stdlib.h> 14.20.3 Releasing the Used Space
main()
When a variable is allocated space during the compile time,
{
int i, then the memory used by that variable is automatically
int ‘arr; released by the system in accordance with ils storage class.
clrscer();
But when we dynamically allocate memory then it is our
printf("\n Enter the number of elements "); responsibility to release the space when it is not required
scanf("Xd", &n); This is cven more important when the storage space is
arr = (int *)malloc(n * sizeof(int)); limited. Therefore, if we no longer need the data stored
if(arr == NULL) in a particular block of memory and we do not intend to
use that block for storing any other information, then as
{
printf("\n Memory Allocation Failed"); a good programming practice we must release that block
exit(0); of memory for future use, using the free function. The
general syntax of free() is,
}
for(i = O;i < njit+) free(ptr);
{
printf("\n Enter the value %d of the where ptr is a pointer that has been created by using
array: “, i); malloc() of calloc(). When memory is de-allocated
scanf("Xd", Sarr[i]); using free(), it is returned back to the free list within the
heap.
}
Pointers | (373

14.20.4 To Alter the Size of Allocated Memory strcpy(str,"Hi there");


printf("\n STR = Xs", str);
At times the memory allocated by using calloc() or /*freeing memory*/
malloc() might be insufficient or in excess. In both the free(str);
situations we can always use realloc() to change the return 0;
memory size already allocated by calloc() and malloc() }
This process is called reallocation of memory. The general
syntax for realloc() can be given as

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

printf("\n The array is as follows: “); {


for(i = 0; i < ROWS; i++) printf("\n Memory could not be
{ allocated");
for(j = 0; j < COLS; j++) exit(-1);
printf(“%d", are[i}[j}); }
} printf("\n Enter the values of the array: “);
for(i = 0; i < ROWS; i++) for(i = 0; i < ROWS; i++)
free(arr{i}); {
free(arr); for(j = 0; J < COLS; j++)
return 0; scanf("Xd", Sarr[i}[4]);
} }
Here, arr is & pointer-fo-pointer-to-int: at the first level
printf("\n The array is as follows: ");
for(i = 0; i < ROWS; i++)
it points to a block of pointers, one for cach row. We first
allocate space for rows in the array. The space allocated {
for(j = 0; j < COLS; j++)
to each row is big enough to hold a pointer-to-int, or
printf("Xd", arr[i}[4]);
int *. If we successfully allocate it, then this space will
be filled with pointers to columns (number of ints), This }
for(i = 0; i < ROWS; i++)
can be better understood from Figure 14.11
free(arr{i});
free(arr);
we: return 0;

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);

In the aforegiven declaration, func accepts a pointer~


EURT3 DRAWBACKS OF POINTERS
to-pointer-to-int and the dimensions of the arrays
Although pointers are very useful in C they are not free
as parametres, so that it will know how many rows and
from limitations. If used incorrectly, pointers can lead
columns there are
to bugs that are difficult to unearth. For example, if you
Look at the code given below which illustrates another use a pointer to read a memory location but that pointer
way of dynamically allocating space for a 2D array is pointing to an incorrect location then you may end up
#include <stdlib.h> reading a wrong value. An erroneous input always leads
#include <stdio.h> to an erroncous output, therefore however efficient your
main() program code may be, the output will always be wrong.
{ Same is the case when writing a value to a particular
int sarr, i, j, ROWS, COLS; memory location.
printf("\n Enter the number of rows and Consider a scenario in which the program code is
columns in the array: "); supposed to read the account balance of a customer, add
scanf("%d Xd", &ROWS, &COLS); new amount to it, and then re-write the modified value
arr = (int *)malloc(ROWS * COLS * to that location. If the pointer is pointing to the account
sizeof(int)); balance of some other customer then the account balance
if(arr == NULL) of the wrong customer will be updated.
Pointers (375
Let us try to find some common errors encountered Forexample, ifa function dynamically allocates memory
when using pointers. for 100 double values and forgets to free the memory and
in worst case if that function is called several times within
int x, *px;
the code then ultimately the system may crash.
x = 10;
*px = 20; Dangling pointer Dangling pointers arise when an object
is deleted or de-allocated, without modifying the value
Error un-initialized pointer. px is pointing to an unknown
of the pointer. As a result, the pointer still points to the
memory location. Hence it will overwrite that location's
memory location of the de-allocated memory.
contents and store 20 in it. Such a pointer is called a wild
Once the memory is de-allocated, the system may
pointer, A pointer which is not initialized with any address
reallocate that block of freed memory to another process.
is called a wild pointer. I may contain any garbage address
In case the program then dereferences the (now) dangling
and thus dereferencing a wild pointer can be dangerous.
pointer, unpredictable behaviour may result, as the
int x, *px; memory may now contain completely different data
x= 10 This problem can become worse when the program
px = x} writes data to memory pointed by a dangling pointer
ERROR: It should be px = &X; causing a silent corruption of unrelated data, leading to
int x = 10, y = 20, *px, *py; bugs that can be extremely difficult to find. Moreover,
px = &, py = & if the overwritten data is bookkeeping data used by the
if(px < py) // it should be *px and «py system's memory allocator, the corruption can even cause
printf("\n px is less than py"); system instabilities.
else Hence, dangling pointer problem occurs when the
printf("\n py is less than px"); pointer still points to the same location in memory even
though the reference has been deleted and may now be
Look at another code given below used for other purposes.
#include <stdio.h> Acommon mistake that we often do is to return address
main() of a stack-allocated local variable. We know that once a
{ called function returns, the space for these variables gets
char *strl, *str2; de-allocated and technically they have garbage values.
printf("\n Enter the string: “); Look at the code below which illustrates how we get a
gets(str1); dangling pointer when a called function returns.
while(*stril*’\0")
char *func(void)
{
*str2 = *stri; {
str2e+, strlee; Char che'A';
I */
} return &ch;
*str2='\0";
printf("\n Steing is: }
while(*str2!='\0") The aforegiven program returns the address of ch. So
{ the calling function may access its value. Any functions
printf("Xe", *str2); called thereafter will overwrite the stack storage allocated
str2++; for ch with other values and the pointer would no longer
} work correctly. Therefore, if a pointer to ch must be
} returned it must be declared as static.
Consider the code below which illustrates another
Error str2 will not be printed because str2 has moved
ahead of its starting location and before displaying the dangling pointer problem.
string, it has not been initialized with its starting address. #include <stdio.h>
Memory leak Memory leakage occurs when memory is include <string.h>
allocated but not released when it is no longer required void main()
This causes an application to unnecessarily consume
memory thereby reducing the memory available for other
applications, Although in small programs it is not a big char *ptr = (char *)malloc(10);
concern but when dealing with large projects, memory strcpy(ptr, "WELCOME");
leakage may result in slowing down the application or print#("%s",ptr);
free (ptr); /* ptr now becomes a dangling
crashing the application when the computer memory
resource limits are reached. pointer */
376 Computer Fundamentals and Programming in C

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

8. The malloc() function is declared in which header file Review Questions


(a) stdio.h (b) stdlib.h 1. Explain the difference between a null pointer and a void
(c) conio.h (d) jostream.h pointer,
9. Which function is used to request memory and set all Write a short note on pointers.
allocated bytes to zero? Compare pointer and array name.

(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;

Write a program to convert 3.14 into its integral ptr = arred;


equivalent for(i = 4; i >» O;i--)
printf("\n Xd", *(ptr-i));
. Write a program to find smallest of three integer values.
Write a program to input a character and categorize it as }
2 main()
3 vowel or a consonant
{
Write a program to input 10 values in an array. Categorize int arr[]={1,2,3,4,5};
each value as positive, negative, or equal to zero.
int ptr,
Write a program to input a character. If it is in uppercase ptr = arred;
print in lowercase and vice versa for(i = 0; i < 5; ie)
Write a program to display the sum and average of printf("\n %d", *(ptr-i));
numbers from 100 to 200.
}
Write a program to print all odd numbers from 100 to 200. 3 #include <stdio.h>
Write a program to input 10 values in an array. Categorize main()
each value as prime or composite, {
. Write a program to subtract two floating point numbers int val=3;
using functions. int *pval=8val;
14. Write a program to calculate the area of a circle. printf("Xd Xd", +eval, *ptr);
15, Write a program to add two integers using functions
Use call by address technique of passing parameters
380 ‘Computer Fundamentals and ProgramminginC

4 #include <stdio.h> 12 #include <stdio.h>


main() main()
\
int arr[}={1,2,3,4,5
int *pvale&val; int i=1,j=2;
printf("Xd Xd", val, *ptr++); printf("\n 2d", *(arrelei));
} printf("\n Xd", *(arre*(arr+l)));
#include <stdio.h> printf("\n Xd", *(arrei)e*(arre+j));
main() printf("\n 4d", *(arr+j));
{ }
int vale=3; main()
int *pvale&val; {
printf("%d Xd", val, ++*pte); char str[]="ABCDEFGH", *pstrestr;
} pstr++;
. Hinclude <stdio.h> while(*pstri="H")
main() printf("%c", *pstr++);
{ }
int arr[)*{1,2,3,4,5); main()
printf("%d", ++*arr); {
} char str[]="ABCDEFGH";
#include <stdio.h> printf("Xd", (&str[3]-&str[0}));
main() }
{ main()
int arr[{}={1,2,3,4,5); {
int *parr = arr+2; char *stre"ABCDEFGH";
printf("Xd Xd", ++*parr-1, 1+*-parr); (*stre+);
} printf("Xs", str);
#include <stdio.h> }
main() main()
{ {
int num = 5, *ptreéa, xe*pte; char *stre"ABCDEFGH";
printf("X%d %d Xd", ++num, x2, *ptr--); stre+;
} printf("X%s", str);
#include <stdio.h> }
main() main()
{ {
int numeS, *ptre&num; char *stre"AbcDefGh";
printf("\n %d", *&num); int iO;
printf("\n %d", *&*&num); while(*str)
printf("\n Xd", *&ptr); {
printf("\n Xd", **&ptr); if(isupper(*str++))
printf("\n Xd", &**&ptr); ite;
} }
10. main() printf("%d", i);
{ }
int nums5, *ptr=&num; 18. main()
printf("%d Xd", num, x#2, (*ptr)--); {
} printf("Hello World"+3);
ll #include <stdio.h> }
main() 19. main()
A {
int arr[]={1,2,3,4,5}, i, k = 3; int arr{}[2]={1,2,3,4,5,6,7,8,9}5
for(ix0; icl0;i++) printf("Xd", sizeof(arr));
*(arrei)=i;
printf("%d", *(are[+k-1]));
}
Pointers 3st

20. main() 24, main()


{ {
int arr[{2](3]={1,2,3,4,5,6,7,8,9}; register int num = 3, *ptr = &num';
printf("%d", sizeof(arr[1])); printf("%d", *ptr);
} }
21 main() 25. #include <stdio.h>
{ void func(int (*parr)[3]);
int arr[S], *parrsarr; main()
while(parr < 6arr[5}) {
{ int arr[2}[3] = {1,2,3,4,5,6};
*parr = parr-arr; func(arr);
printf("Xd", *pare); func(arr + 1);
parts; }
} void func(int (*parr)[3])
} {
22 main() int 4;
{ for(i = 0; i < 2; ite)
char *str = “Hello World"; printf("xd", (*parr)[1]);
str[S}='!";
printf("%s", str);
} Find errors if any in the following statements.
23 main() 1. int ptr, *ptr;
{ 2. int num, *ptrenum;
char *str1 = "Hello World"; 3. int *ptr=10;
char str2[20) = “Hello World"; 4, int num, **ptr=&num;
char str3[{] = “Hello World"; S. int *ptri, *ptr2, *ptr3=*ptrie*ptr2;
printf(" %d Xd Xd", sizeof(stri), 6. int *ptr; scanf("Xd", &ptr);
sizeof(str2), sizeof(str3));
382 Computer Fundamentals and Programming in C

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.

ptr is array of pointer to


Some Illegal Declarations in C
Step 4: Continue moving left. Here, you find int. So say,
It is quite possible that you end up with some illegal
ptr is array of pointer to int. declarations using this rule. So, you must be very clear about
Pointers 383

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

CASE STUDY 3: Chapters 13 and 14


In C language, a string is a null-terminated character array and read_str(str1);
4 pointer is a variable that contains the memory location of break;
another variable. Therefore. a pointer is a variable that represents case 2:
the location of a data item such as a variable or an array element. display _str(str1);
Pointers provide an altemate way to access individual elements break;
of the array and they are used to pass arrays and strings as function case 3:
arguments, We will utilize all these concepts to write a program read_str(str2);
that performs various operations on a string (using pointers), merge_str(stri, str2, merged str);
1, Write
amenu-driven program to read the following operations: break;
1. Read a string, 2. Display the string, 3. Merge two strings, case
printf("\n Enter the position from which
4, Copy n characters from the m" position, 5. Calculate the
length of the string, 6. Count the number of upper case, lower to copy the text: ");
case, numbers and special characters, 7. Count the number of
scanf("Xd", &m);
words, lines, und characters, 8. Replace, with; 9. Exit
printf("\n Enter the number of characters
to be copied: “);
#include <stdio.h> scanf("Xd", &n);
#include <string.h> copy(str1, m, n);
include <conio.h> break;
void read_str(char *my_str); case 5:
void display str(char *my str); length = cal_len(stri);
void merge str(char *my_stri, char *my_str2, printf("\n The length of the string is:
char *my_str3); Xd", length);
void copy(char my_stri{], int m, int n); break;
int cal_len(char my_ste[]); case 6:
void count(char my_str[]); count(str1);
void count_wic(char my_str{}); break;
void replace str(char *my_str); case 7:
int main() count_wie(str1);
{ break;
char str1{100], str2[100], merged_str[200), case 8:
copy_str[100}; replace_str(stri);
int option, m, n, length#0; break;
cleser(); }
do Jwhile (option != 9);
return 0;
{
printf("\n 1. Enter the string”); }
printf("\n 2. Display the string”
printf("\n 3. Merge two strings”);
void read_str( char *my_str)
printf("\n 4. Copy n characters from m‘” {
position");
printf("\n Enter the string: *);
gets(my_str);
printf("\n 5. Calculate length of the
string"); }
printf("\n 6. Count the number of upper
void display str(char *my_str)
case, lower case, numbers, and special
characters"); {
printf("\n 7. Count the number of words, printf("\n The string is: ");
lines, and characters”); while(*my_
str != ‘\0")
printf("\n 8. Replace, with ;");
{
printf("\n 9. EXIT"); printf("Xc", *my_str);
my_str++;
printf("\n\n Enter your option: ");
}
scanf("Xd", &option);
}
switch(option)
{ void merge_str(char *my_stri, char *my_str2,
case 1: char *my_str3)
Pointers 385

strcpy(my_str3,my_str1); char *pstr = my_str;


strcat(my_str3, my_str2); int words =0, lines =0, characters = 0;
display_str(my_str3); while(*pstr I= ‘\0')
} {
if (*pstr == "\n")
void copy(char my_stri{], int m, int n) Lines++;
if (*pstr == ' * && *(my_strel) I=‘ ‘)
int i = 0; words++;
char *pstr; characters++;
printf("\n The copied string is: “); pstree;
while(i <n || my_stri[m]!="\o")
}
{ print#("\n Number of words = Xd", words+l
*pstr = my_stri[m]; print€("\n Number of lines = Xd", lines+1
metjiee; printf("\n Number of characters = %d",
printf("%c", *pstr); characters);

void replace_str(char my_str[{})


int cal_len(char my_str[])
{
{ char *pstremy_str;
char ‘str = my_str; while (*pstr != '\0")
int len = 0;
{
while(*str != *\0") if(*pstr == *)
{ *pstr = °
street; pstre+;
len++; }
} display_str(my_str);
return len; }
Output
1. Enter the string
void count(char my_str[]}) Display the string
{ Merge two strings
char *pstr « my_str; Copy n characters from m'" position
int upper_case = 0, lower_case = 0, numbers Calculate length of the string
= 0, spcl_char « 0; anawn
Count the number of upper case, lower case,
while (*pstr I= "\O") numbers, and special characters
{ 7. Count the number of words, lines, and
if (*pstr >= 'A' B& *pstr <= '2Z") characters
upper_case++; 8. Replace, with;
else if (*pste >= ‘a’ && *pstr <= 2") 9. EXIT
lower_case++; Enter your option: 1
else if (*pstr >= ‘0’ && *pstr <= "9") Enter the string: Hi
numbers++;
else . Enter the string
spcl_char+s; . Display the string
pstre+; Merge two strings
} Copy n characters from m‘" position
printf("\n Upper case characters = %d", « Calculate length of the string
upper_case); - Count the number of upper case, lower case,
avewne
printf("\n Lower case characters = %d", numbers and special characters
lower_case) ; 7. Count the number of words, lines and characters
printf("\n Numbers = Xd", numbers); 8. Replace, with;
printf("\n Special characters = %d", spcl_char); 9. EXIT
} Enter your option: 3
Enter the string: there
void count_wle(char my_str[]) The string is: Hi there
15.
Structure, Union, and
~~ “Enumerated Data Type
TAKEAWAYS
* Structure declaration, © Structures and functions © Arrays of structures * Enumerated
Initialization, and access © Self-referential structures * Unions within structures data type
* Nested structures * Unions * Structure within unions
* Arrays of unions

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

Declare a structure to create an inventory record


Solution
struct inventory
{
Figure 15.1 Memory allocation for structure variables char prod_name[20]};
float price;
Let us sce some more structure declarations int stock;
}s
Example 15.1

Declare a structure to store information about a point in the


coordinate system
Solution Structure type and variable declaration of a structure can
struct point be either local or global depending on their placement in
{ the code.
int x,y3
fi
Last but not the least, structure member names and names
Example 15.2 of the structure follow the same rules as laid down for the
names of ordinary variables. However, care should be taken
Declare a structure to store customer information. to ensure that the name of structure and the name of a structure
Solution member should not be the same. Moreover, structure name
struct customer and its variable name should also be different.
{
int cust_id; 15.1.2 Typedef Declarations
char name[20);
char address[{20}; The typedef (derived from type
Programming Tip: definition) keyword enables the
long int phone_num;
int DOB;
C does notallow programmer to create a new
hi declaration of data type name from an existing
variables atthe data type. By using typedef,
Example 15.3 time ofcreating a no new data is created, rather
typedef definition. an alternate name is given to a
Declare a structure to store information of a particular date. So variables must known data type.
Solution bedeclared in The general syntax of using
struct date an independent the typedef keyword is given
statement. as
{
int day; typedef existing data_type new data_type
int month;
int year; Note that typedef statement does not occupy any memory,
it simply defines a new type. For example, if we write
hi
typedef int INTEGER;
Example 15.
then INTEGER is the new nameof data type int. To declare
Declare a structure to store information of a particular book. variables using the new data type name, precede the
388 Computer Fundamentals and Programming in C

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

The dot operator is used to select a particular member


struct student stud1
of the structure. For example, to assign value to the = {01, "Rahul", "BCA", 45000);
individual data members of the structure variable stud,
we may write [ o ] [Ratu] [Bca} [45000|
ro name course fees
studi.r_no = 01;
studi.name = “Rahul”; struct student stud2 « studl;
studl.course = "BCA";
studl.fees = 45000;
{or} [Rahat] [aca] [45000 |
To input values for data members of the structure r_no name course fees
variable stud1, we may write
Figure 15.3 Copying values of structure variables
scanf("Xd", &studi.r_no);
scanf("Xs", stud1.name);
C does not permit comparison of one structure
Similarly, to print the values of structure variable
variable with another, However, individual members of
studl, we may write
one structure can be compared with individual members
print#("%s", studl.course); of another structure. When we compare one structure
printf("X#", studl.fees); member with another structure's member, the comparison
will behave like any other ordinary variable comparison.
Memory is allocated only when we declare variables
For example, to compare the fees of two students, we
of the structure. In other words, memory is allocated only
will write
when we instantiate the structure. In the absence of any
variable, structure definition is just a template that will be if(studl.fees > stud2.fees)
used fo reserve memory when a variable of type struct is // Fees of studi is greater than stud2
declared.
Once the variables of a structure are defined, we can 15.1.6 Finding the Size of a Structure
perform a few operations on them. For example, we can
use the assignment operator '=' to assign the values of one In this section, we will read about three different ways
variable to another, through which we can find the number of bytes a structure
will occupy in the memory

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

Using sizeof Operator /* address of the first element of second


employee */
As discussed earlicr, sizeof operator is used to calculate end = &e[1].emp_ID;
the size of a data type, variable, or an expression. To use
this operator simply write, sizeof (struct_name); len = end - start;
For example, the code given below prints the size of printf("\n Size of the structure = Xd",
structure Employee. len);
#include <stdio.h> }
#include <conio.h> Output
typedef struct Employee Size of the structure = 54
{ int emp_1D;
char name[ 20); 1, Write a program using structures to read and display the
double salary; information about a student
char designation([
20];
#include <stdio.h>
float experience;
include <conio.h>
hi
int main()
void main() {
{ struct student
struct Employee e;
{
printf("\n Xd", sizeof(e)); int roll_no;
} char name[80};
Output float fees;
char 00B[80);
54
b
struct student stud1;
cleser();
Syntax of sizeof operator is similar tothat of a function printf("\n Enter the roll number: “);
but sizeof isnot a library function. It isan operator in C. scanf("%d", &studi.roll_no);
printf("\n Enter the name: ");
scanf("Xs", stud1.name) ;
Subtracting the Addresses printf("\n Enter the fees: ");
In this technique, we use an array of structure variables. scanf("X#", Bstudl. fees);
Then we subtract the address of first clement of next printf("\n Enter the DOB: ");
consecutive variable from the address of the first clement scanf("Xs", stud1.008);
of preceding structure variable. For example, the code printf("\n *******STUDENT'S DETAILS
below finds the size of structure Employee. ones
printf("\n ROLL No. = Xd", stud1.roll_no);
#include <stdio.h>
printf("\n NAME = Xs", stud1.name);
#include <conio.h>
printf("\n FEES = Xf", studl.fees);
typedef struct Employee printf("\n 008 = Xs", stud1.008);
{ int emp_I0;
getch();
char name(20]; return 0;
double salary;
}
char designation[ 20];
float experience; Output
i Enter the roll number: 01
void main() Enter the name: Rahul
Enter the fees: 45000
{
struct Employee e[5]; Enter the 008: 25-09-1991
int start, end, len; **STUDENT'S DETAILS **
ROLL No. = O1
/* address of the first element of first NAME Rahul
employee */ FEES = 45000.00
start = &e[0].emp_ID; DOB = 25-09-1991
Structure, Union, and Enumerated Data Type 391

2. Write a program, using structures to find the largest of case 1:


three numbers. printf("\n Enter the real and imaginary
parts of the first complex number: “);
#include <stdio.h> scanf("%d Xd", &cl.real, &c1.imag);
#include <conio.h> printf("\n Enter the real and imaginary
int main() parts of the second complex number: ");
{ scanf("Xd Xd", &c2.real, &c2.imag);
struct numbers break;
{ case 2:
int a, b, ¢; printf("\n The first complex number is:
int largest; Xd + Xdi", cl.real, cl. imag);
i printf("\n The second complex number is:
struct numbers num; Md + Xdi", c2.real, c2.imag);
clrser(); break;
printf("\n Enter the three numbers: case 3:
scanf("Xd Xd Xd", &num.a, &num.b, &num. sum_c.real = cl.real + c2.real;
if (num.a > num.b && num.a > num.c) sum_c.imag = cl.imag + c2.imag;
num. largest = num.a; printf("\n The sum of two complex numbers
if (num.b > num.a && num.b > num.c) is: %d + Xdi", sumc.real, sum_c.imag);
num. largest = num.b; break;
case 4:
if (num.c > num.a && num.c > num.b)
sub_c.real * cl.real - c2.real;
num. largest = num.c;
printf("\n The largest number is: Xd", num.
sub_c.imag » cl.imag - c2.imag;
printf("\n The difference between two
largest);
complex numbers is: %d + %di",
getch(); sub_c.real, sub_c.imag);
return 0;
break;
} }
Output }while(option t= 5);
getch();
Enter the three numbers: 7 9 1 return 0;
The largest number is: 9 }
3. Write a program to read, display, add, and subtract two Output
complex numbers,
** MAIN MENU *
#include <stdio.h> 1. Read the complex nos
#include <conio.h> 2. Display the complex nos.
int main() 3. Add the complex nos.
{ 4. Subtract the complex nos.
typedef struct complex 5. EXIT
{ Enter your option: 1
int real; Enter the real and imaginary parts of the first
int imag; complex number: 2 3
}COMPLEX; Enter the real and imaginary parts of the
COMPLEX cl, c2, sum_c, sub_c; second complex number: 4 5
int option; ** MAIN MENU *
clrser(); 1. Read the complex nos.
do 2. Display the complex nos.
{ 3. Add the complex nos.
printf("\n ***** MAIN MENU *****"); 4 . Subtract the complex nos.
printf("\n 1. Read the complex nos."); 5 . &xIT
printf("\n 2. Display the complex nos."); Enter your option: 3
printf("\n 3. Add the complex nos."); The sum of two complex numbers is: 6 + 8i
printf("\n 4, Subtract the complex nos.”);
printf("\n 5S. EXIT"); 4. Write a program to enter two points and then calculate
printf("\n Enter your option: “); the distance between them.
scanf("Xd", Soption) ;
switch(option) #include <stdio.h>
include <conio.h>
{
392 Computer Fundamentals and Programming in C

#include <math.h> typedef struct


int main() {
{ int dd;
typedef struct point int mm;
{ int yy;
int x, y; JDATE;
}POINT;
POINT pil, p2; typedef struct student
float distance; {
clrscr(); int r_no;
printf("\n Enter the coordinates of the first NAME name;
point: "); char course([20);
scanf("Xd %d", Bpl.x, &pl.y); DATE DOB;
printf("\n Enter the coordinates of the float fees;
second point: "); hi
scanf("Xd Xd", &p2.x, &p2.y);
In this example, we see that the structure student
distance = sqrt(pow((pl.x - p2.x), 2) +
contains two other structures—NAME and DATE. Both these
pow((pl.y = p2.y), 2)); structures have their own fields. The structure NAME has
printf("\n The coordinates of the first point
three ficlds: first_name, mid_name, and last_name, The
are: Xdx Xdy", pl.x, pl.y);
structure DATE also has three fields: dd, mm, and yy, which
printf("\n The coordinates of the second
specify the day, month, and year of the date, To assign
point are: Xdx Xdy", p2.x, p2.y);
values to the structure fields, we will write
printf("\n Distance between pi and p2 = Xf",
distance); student studi;
getch(); stud1.name.first_name = “Janak";
return 0; stud1.name.mid_name = "Raj";
} stud1.name.last_name = “Thareja";
Studl.course = "BCA";
Output
stud1.D08.dd = 15;
Enter the coordinates of the first point: 2 3 stud1.008.mm = 09;
Enter the coordinates of the second point: 9 9 stud1.00B.yy = 1990;
The coordinates of the first point are: 2x 3y studl.fees = 45000;
The coordinates of the second point are: 9x 9y
In case of nested structures, we use the dot operator
Distance between pl and p2 = 9.219544
in conjunction with the structure variables to access
the members of the innermost as well as the outermost
G83 Nestep stRUCTURES structures. The use of nested structures is illustrated in the
following program
A structure can be placed within another structure, i.c., a
5. Write a program to read and display information ofa
structure may contain another structure as its member. A
student using a structure within a structure,
structure that contains another structure as its member is
called a nested structure. #include <stdio.h>
Let us now see how we declare nested structures or include <conio.h>
structures that contain structures, Although it is possible int main()
to declare a nested structure with one declaration, it is not {
recommended. The casier and clearer way is to declare struct DOB
the structures separately and then group them in a high- {
level structure. When you do this, take care to check that int day;
nesting is done from inside out (from lowest level to the int month;
most inclusive level), Le., to say, declare the innermost int year;
structure, then the next level structure, working towards }
the outer (most inclusive) structure. struct student
typedef struct {
{ int roll_no;
char first_name[20]; char name[{100);
char mid_name[20]; float fees;
char last_name[20]; struct DOB date;
}NAME ;
Structure, Union, and Enumerated Data Type 393

struct student studl; struct struct_name


clrscr(); {
printf("\n Enter the roll number: 3 data_type member_name1;
scanf("Kd", &stud1.roll_no); data_type member_name2;
printf("\n Enter the name: “); data_type member_name3;
scanf("Ks", studi.name);
printf("\n Enter the fees: ");
scanf("Xf", &studl.fees); struct struct_name struct_var[index];
printf("\n Enter the DOB: "); Consider the given structure definition
scanf("%d Xd Xd", &studi.date.day,
&stud1.date.month, &studi.date.year); struct student
printf("\n ***** STUDENT'S DETAILS **** {
printf("\n ROLL No. = Xd", studl.roll_no); int r_no;
printf("\n NAME = Zs", studl.name) ; char name[20];
printf("\n FEES = %f", studi.fees); char course[20)};
printf("\n DOB = Xd - Xd - Xd", studl.date. float fees;
day, stud1.date.month, stud1.date.year); hs
getch(); A student array can be declared simply by writing
return 0;
} student stud[30];

Output Now, to assign values to the i”th student of the class, we


will write,
Enter the roll number: 01
Enter the name: Rahul stud[i].r_no = 09;
Enter the fees: 45000 stud[i].name = "RASHI";
Enter the DOB: 25 09 1991 stud[i].course = "MCA";
**e** STUDENT'S DETAILS ***** stud[i].fees = 60000;
ROLL No, = O01
In order to initialize the array of structure variables at
NAME = Rahul
the time of declaration, you should write as follows:
FEES = 45000.00
DOB * 25-09-1991 student stud[3] = {{01, “Aman”, "BCA",
45000},{02, “Aryan", "MCA", 60000}, {03,
John", "BCA", 45000}};

ARRAYS OF STRUCTURES 6. Write a program to read and display the information of


all the students in the class
In the aforegiven examples, we have seen how to declare a
include <stdio.h>
structure and assign values to its data members. Now we will
include <conio.h>
how to declare an array of a structure. For this purpose,
lyse, where we would need array of structures. int main()
lass, we do not have just one student, But there {
may be at least 30 students. So the same definition of the struct student
structure can be used for all {
i depmaeh the 30 students, This would int roll_no;
array subscripts when P€ Possible when we create char name(80];
int fees;
ferring to individual an array of the structure, An
char DOB[80];
tructures ofanarray array of a structure is declared
in the same way as we declare i
of structures. struct student stud[S0];
an array of a built-in data type.
int n, i;
Another example where an array of structures is desirable
clrscr();
is in case of an organization. An organization has a number
of employees. So, defining a separate structure for every printf("\n Enter the number of students: ”);
employee is not a viable solution, So here we can have a scanf("Xd", &n);
common structure definition for all the employees, This can for(i = 0;4 < njit+)
again be done by declaring an array of the structure employee. {
The general syntax for declaring an array of a structure printf("\n Enter the roll number: ");
can be given as scanf("Xd", &stud[i}.roll_no);
printf("\n Enter the name: ");
394 Computer Fundamentals and Programming in C

gets(stud{i].name); int n, i, rolno, new_rolno;


printf("\n Enter the fees: “); int new_fees;
scanf("%d", &stud[i].fees) char new_008[80], new_name[80];
printf("\n Enter the DOB: *); clrser();
gets(stud(i].D0B); printf("\n Enter the number of students: ");
} scanf("Xd", &n);
for(i = O;4 < njite) for(i = O;i < njie+)
{ {
printf("\n ********DETAILS OF STUDENT Xd printf("\n Enter the roll number: ");
» #1); scanf("Xd", &stud[i}.roll_no);
printf("\n ROLL No. = %d", stud{i]}. printf("\n Enter the name: “);
roll_no); gets(stud[i].name);
printf("\n NAME « Xs", stud[i].name) printf("\n Enter the fees: “);
printf("\n FEES = Xd", stud[i].fees) scanf("Xd", stud[i].fees);
printf("\n DOB = Xs", stud{i].008); printf("\n Enter the DOB: ");
} gets(stud[i].008);
getch(); }
return 0; for(i = O;1 < njite)
} {
printf("\n * *****DETAILS OF STUDENT
Output
» ied);
Enter the number of students: 2 printf("\n ROLL No. = Xd", stud[i}.
Enter the roll number: 1 roll_no);
Enter the name: kirti printf("\n NAME = Xs", stud[i].name)
Enter the fees: 5678 printf("\n FEES = Xd", stud[{i].fees)
Enter the DOB: 9 9 91 printf("\n DATE OF BIRTH = Xs",
Enter the roll number: 2 stud[i]. 008);
Enter the name: kangana }
Enter the fees: 5678 printf("\n Enter the roll no. of the
Enter the DOB: 27 8 91 student whose record has to be edited: ");
s#e*¥ee*DETAILS OF STUDENT Iseeeeees scanf("%d", &rolno);
ROLL No, = 1 printf("\n Enter the new roll number: ");
NAME = kirtd scanf("%d", &new_rolno);
FEES = 5678 printf("\n Enter the new name: ");
DOB = 99 91 scanf("Xs", new_name);
*DETAILS OF STUDENT 2** printf("\n Enter the new fees: ");
ROLL No. = 2 scanf("Kd", &new_fees);
NAME = kangana printf("\n Enter the new date of birth: ");
FEES = 5678 scanf("%s", new_D08);
008 = 27 8 91 stud[{rolno-1].roll_no = new_rolno;
strcpy(stud[rolno-1].name, new_name);
7. Write a program to read and display the information of stud[rolno-1].fees = new_fees;
all the students in the class. Then edit the details of the strcpy(stud[rolno-1] .D08,new_DOB) ;
i® student and redisplay the entire information. for(i=O;icn; i++)
#include <stdio.h> {
#include <string.h> printf("\n ********DETAILS OF STUDENT
Kdereee » itt);
#include <conio.h>
int main() printf("\n ROLL No, = Xd", stud[i}.
roll_no);
{
struct student printf("\n NAME = Xs", stud[i].name);
{ printf("\n FEES = Xd", stud[i].fees);
int roll_no; printf("\n DATE OF BIRTH = %s",
char name[80); stud[i].D0B);
int fees; }
char DOB[80)};
getch();
i return 0;
struct student stud[50];
}
Structure, Union, and Enumerated Data Type 39: 5

Output 15.4.1 Passing Individual Members


Enter number of students: 2 To pass any individual member of the structure to a
Enter roll number: 1 function we must use the direct selection operator to
Enter name: kirti refer to the individual members for the actual parameters.
Enter fees: 5678 The called program does not know if the two variables
Enter DOB: 9 9 91 are ordinary variables or structure members. Look at the
Enter roll number: 2 following code that illustrates this concept
Enter name: kangana
Enter fees: 5678 #include <stdio.h>
Enter DOB: 27 8 91 typedef struct
seeeeee*DETAILS OF STUDENT it*eeeeee {
ROLL No. * 1 int x;
NAME = kirtd int y;
FEES = S678 }POINT;
bop = 9 9 91 void display(int, int);

weeeeee*DETAILS OF STUDENT 2**eeee0%


int main()
ROLL No. = 2 {
NAME = kangana POINT pl = {2, 3};
FEES = 5678 display(pl.x, pl.y);
DOB = 27 8 91 return 0;
Enter the roll no. of the student whose record }
has to be edited: 2 void display(int a, int b)
Enter the new roll number: 2 {
Enter the new name: kangana khullar printf("The coordinates of the point are: wd
Enter the new fees: 7000 xd", a, b);
Enter the new date of birth: 27 8 92 }
s#******DETAILS OF STUDENT Iseeeeee® Output
ROLL No, = 4
NAME = kirtd The coordinates of the point are: 2 3

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.

Passing structures Passing the #include <stdio.h>


to functions entire structure typedef struct
{
int x;
Passingthe address
of the structure int y;
}POINT;
Figure 15.4 Passing structures to functions void display(POINT);
396 Computer Fundamentals and Programming in C

main() printf("\n The sum of two distances


{ is: Xd kms Xd metres", d3.kms, d3.metres);
POINT pl = (2, 3}; break;
display(p1); case 4:
return 0; d4 = subtract_distance(d1, d2);
} printf("\n The difference between two
void display(POINT p) distances is: Xd kms Xd metres”, d4.kms,
{ G4.metres);
printf("%d Xd", p.x, p.y); break;
} }
}while(option I= 5);
8. Write a program to read, display, add, and subtract two getch();
distances. Distance must be defined using kms and return 0;
metres,
}
#include <stdio.h> DISTANCE add_distance(DISTANCE d1, DISTANCE d2)
#include <conio.h> {
typedef struct distance DISTANCE sum;

{ sum.metres = di.metres + d2. metres;


int kms; sum.kms = dl.kms + d2.kms;
int metres; if(sum.metres >= 1000)
}DISTANCE; {
DISTANCE add_distance(DISTANCE, DISTANCE); Sum.metres = sum.metres%1000;
DISTANCE subtract_distance(DISTANCE, sum. kms += 1;
DISTANCE); }
DISTANCE di, d2, d3, d4; return sum;
int main() }
{ DISTANCE subtract_distance(OISTANCE di,
int option; DISTANCE d2)
clrser(); {
do DISTANCE sub;
{ if(dl.kms > d2.kms)
printf("\n ***** MAIN MENU +****" {
printf("\n 1. Read the distances “); sub.metres = di.metres - d2. metres;
printf("\n 2, Display the distances"); sub.kms = di.kms - d2.kms;
printf("\n 3. Add the distances”); }
printf("\n 4. Subtract the distances"); else
printf("\n 5. EXIT"); {
printf("\n Enter your option: “); sub.metres = d2.metres - dl. metres;
scanf("%d", &option) ; sub.kms = d2.kms - di.kms;
switch(option) }
{ if(sub.metres < 0)
case 1: {
printf("\n Enter the first distance in sub. kms = sub.kms - 1;
kms and metres: “); sub.metres = sub.metres + 1000;
scanf("Xd Xd", &d1.kms, &d1.metres); )
printf(“\n Enter the second distance in return sub;
kms and metres: “); }
scanf("Xd Xd", &d2.kms, &d2.metres); Output
break;
case 2:
seee* MAIN MENU #e008
printf("\n The first distance is: %d 1. Read the distances
kms %d metres”, di.kms, dl.metres); 2. Display the distances
printf("\n The second distance is: %d 3. Add the distances
kms 2d metres”, d2.kms, d2.metres); 4. Subtract the distances

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;

printf("\n 1, Read time “); }


printf("\n 2. Display time"); TIME subtract_time(TIME ti, TIME t2)
printf("\n 3. Add"); {
printf("\n 4. Subtract"); TIME sub;
printf("\n 5. EXIT"); if(ti.he > t2.hr)
printf("\n Enter your option: “); {
scanf("%d", &option); if(ti.sec < t2.sec)
switch(option) {
{ tl.sec += 60;
ti.min--;
case 1:
printf("\n Enter the first time in }
hrs, mins, and secs: “); sub.sec = tl.sec - t2.sec;
if(tl.min < t2.min)
scanf("%d Xd Xa", &ti.nr, &ti.min, &ti.sec);
printf("\n Enter the second time in {
hes, secs: ");
mins, and tl.min += 60;
scanf("%d Xd Xd", &t2.hr, &t2.min, &t2.sec); ti.hr--;
break; }
case 2: sub.min = tl.min - t2.min;
printf("\n The first time is: Xd hr Xd min sub.hr = ti.hr - t2.hr;
Md sec”, tl.hr, tl.min, ti.sec); }
printf("\n The second time is: %d hr Xd else
min Xd sec”, t2.hr, t2.min, t2.sec); {
break; if(t2.sec < tl.sec)
case 3: {
t3 = add_time(ti, t2); t2.sec += 60;
398 Computer Fundamentals and Programming in C

t2.min--; through pointers. It is possible to create a pointer to almost


} any type in C, including user-defined types. It is extremely
sub.sec = t2.sec - tl.sec; common to create pointers to structures. As in other cases,
if(t2.min < t1.min) 4 pointer to a structure is never itself a structure, but merely
{ a variable that holds the address of astructure. The syntax
t2.min += 60 to declare a pointer to a structure can be given as follows:
t2.hr--;
struct struct_name
}
sub.min = t2.min - ti in; {
sub. hr = t2.hr = ti.hr;
data_type member_name1;
data_type member_name2;
} data_type member_name3;
return sub;
}
Output
OR
*ee* MAIN MENU # +88
struct struct_name *ptr;
» Read time
. Display time For our student structure, we can declare a pointer
Add variable by writing
awne
» Subtract
struct student *ptr_stud, stud;
5. EXIT
Enter your option: 1 The next thing to do is to assign the address of stud to
Enter the first time in hrs, mins, and secs: the pointer using the address operator (&) as we would do
2 30 20 in case of any other pointer. So to assign the address, we
Enter the second time in hrs, mins, and secs: will write
3 20 30
ptr_stud = &stud;
**** MAIN MENU ##**
1. Read time To access the members of the structure, one way is to
2. Display time write
3. Add
/* get the structure, then select a member */
4. Subtract
5S. EXIT
(*pte_stud) .roll_no;
Enter your option: 3 Programming Tip: Since parentheses have
The sum of the two time values is: 5 hr 50 min The sel a higher precedence than *,
50 sec writing this statement would
operator (->) is
ee work well. But this statement
Let us summarize some points that must be considered
Zs any wh is not easy for a beginner to
while passing a structure to a function.
t a work with. So C introduces a
* If the called function is retuming a copy of the entire new operator to do the same
structure then its return type must be declared as struct task. This operator is known as the pointing-to operator
followed by the structure name. (->). Here it is being used
* The structure variable used as parameter in the function
declaration must be the same as that of the actual /* the roll_no in the structure ptr_stud
argument in the called function (and that should be the points to */
ptr_stud -> roll_no = 01;
name of the struct type)
+ When a function returns a structure then in the calling This statement is far easier than its alternative,
function the returned structure must be assigned to a
structure variable of the same type 10. Write a program, using @ pointer to a structure to
initialize the members of the structure.
Programming Tip: 15.4.3 Passing
2 Structures
#include <stdio.h>
Using pointers to Through Pointers ®@include <conio.h>
ppb Passing large structures to struct student
pisos functions using the call- {
Read oe by-value method is very int r_no;
ait ” inefficient. Therefore, it is char name[20);
preferred to pass structures char course[20);
Structure, Union, and Enumerated Data Type 399

int fees; DETAILS OF SECOND STUDENT


ey ROLL NUMBER = 02
NAME = Aditya
int main() COURSE = MCA
{ FEES = 60000
struct student studi, stud2, *ptr_studi,
*ptr_stud2; 11. Write a program, using a pointer to a structure, to
clrser(); initialize the members of the structure using an
ptr_studi = &stud1; alternative technique.
ptr_stud2 = &stud2; #include <stdio.h>
ptr_stud1 -> r_no = 01; #include <conio.h>
strcpy(ptr_stud1 -> name, “Rahul”); struct student
strepy(ptr_studi -> course, "BCA"); {
ptr_studl -> fees = 45000; int r_no;
char name[20];
printf("\n Enter the details of the second char course[20};
student:"); float fees;
printf("\n Enter the Roll Number ="); i
scanf("Xd", &ptr_stud2 -> r_no);
printf("\n Enter the Name = “); int main()
gets(ptr_stud2 -> name); {
printf("\n Enter the Course = “); struct student *ptr_stud1;
gets(ptr_stud2 -> course); struct student studl = {01, “Rahul”, “BCA”
printf("\n Enter the Fees = “); 45000};
scanf("%d", &ptr_stud2 -> fees); clrser();
ptr_studl = &stud1;
printf("\n DETAILS OF FIRST STUDENT"); printf("\n DETAILS OF STUDENT");
printf("\n ROLL NUMBER = Xd", ptr_studi -> printf("\n ROLL NUMBER = %d", ptr_studl ->
r_no); r_no);
printf("\n NAME = Xs", ptr_studl -> name); printf("\n NAME = Xs ", ptr_stud1 -> name);
printf("\n COURSE « %s", ptr_studl -> printf("\n COURSE = Xs", ptr_studl
course); -> course);
printf("\n FEES = %d", ptr_studl -> fees); printf("\n FEES = %.2*", ptr_studl -> fees);
printf("\n\n\n\n DETAILS OF SECOND return 0;
STUDENT"); }
printf("\n ROLL NUMBER «= Xd", ptr_stud2 ->
rno); Outpu
printf("\n NAME = Xs", ptr_stud2 -> name); DETAILS OF STUDENT
printf("\n COURSE = Xs", ptr_stud2 -> ROLL NUMBER = O1
course); NAME = Rahul
printf("\n FEES = Xd", ptr_stud2 -> fees); COURSE = BCA
FEES = 45000.00
return 0;
} 12. Write a program, using an array of pointers to a
structure, to read and display the data of a student.
Output
include <stdio.h>
Enter the details of the second student:
#include <conio.h>
Enter the Roll Number = 02
#include <alloc.h>
Enter the Name = Aditya
typedef struct student
Enter the Course = MCA
Enter the Fees = 60000
{
int r_no;
char name[20);
DETAILS OF FIRST STUDENT
ROLL NUMBER = 01
char course[20];
int fees;
NAME = Rahul
COURSE = BCA
bs
struct student *ptr[10];
FEES = 45000
400 Computer Fundamentals and Programming in C

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

ROLL NUMBER = O1 ft Sd inch", h3.ft, h3.inch);


break;
NAME = Rahul case 4:
COURSE = BCA h3 = subtract_height(&h1, &n2);
FEES = 45000 printf("\n The difference of two heights
is: %d ft %d inch", h3.ft, h3.inch);
ROLL NUMBER = 02 break; }
NAME = Priya }
COURSE = BCA }while(option != 5);
FEES = 25000 getch();
Structure, Union, and Enumerated Data Type aor

return 0; 14. Write a program that passes a pointer fo a structure 16


} a function.
HEIGHT add_height(HEIGHT *hi, HEIGHT *h2)
include <stdio.h>
{
HEIGHT sum; include <conio.h>
sum.inch = hl -> inch + h2 -> inch; #include <alloc.h>
while(sum.inch > 12) typedef struct student
{ {
sum.inch -= 12; int r_no;
sum. ft++; char name{20];
) char course[{20};
sum.ft = hl ~> ft # h2 -> ft; int fees;
return sum; i
}
HEIGHT subtract_height (HEIGHT *hi, HEIGHT *h2) void display(struct student *);
{ int main()
HEIGHT sub; {
if(hl -> ft > h2 -> ft) struct student *ptr;
{ ptr = (struct student *)malloc(sizeof
if(hl -> inch < h2 ~> inch) (struct student));
{ printf("\n Enter the data for the student ");
hl -> inch += 12; printf("\n ROLL NO.: ");
hl -> ft--; scanf("Xd", &ptr -> e_no);
} printf("\n NAME: ");
sub.inch = hl -> inch ~ h2 -> inch;
gets(ptr -> name);
sub.ft = hi -> ft ~ h2 -> ft; );
printf("\n COURSE:
}
gets(ptr -> course);
else
printf("\n FEES: ");
{
if(h2 -> inch < hl -> inch) scanf("Xd", &ptr -> fees);
display(ptr);
{
h2 -> inch += 12; getch();
h2 -> ft--5 return 0;
} }
sub.inch = h2 => inch - hi -> inch;
sub.ft © h2 -> ft - hl -> ft; void display(struct student *ptr)
} {
return sub; printf("\n DETAILS OF STUDENT");
} printf("\n ROLL NUMBER « Xd", ptr -> r_no);
Outpu printf("\n NAME = Xs", ptr -> name);
printf("\n COURSE = Xs", ptr -> course);
#0" MAIN MENU *#* printf("\n FEES = Xd", ptr -> fees);
1. Read height }
2. Display height
3. Add Output
4. Subtract Enter the data for the student
5. EXIT ROLL NO.: O1
Enter your option: 1 NAME: Rahul
Enter the first height in feet and inches: 2 3
COURSE: BCA
Enter the second height in feet and inches: 4 5
FEES: 45000
*e* MAIN MENU ***
1, Read height DETAILS OF STUDENT
2. Display height
ROLL NUMBER = 01
3. Add
NAME = Rahul
4, Subtract
5. EXIT COURSE = BCA

Enter your option: 3 FEES = 45000.00


The sum of two heights is: 6 ft 8 inch
402 Computer Fundamentals and Programming in C

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

ARRAYS OF UNION VARIABLES struct student stud;


char choice;
Like structures we can also have an array of union printf("\n You can enter the name or roll
variables. However, because of the problem of new data number of the student");
overwriting existing data in the other fields, the program printf("\n Do you want to enter the name? (Y
may not display the accurate results or N): ");
#include <stdio.h> gets (choice);
union POINT if(choice=="y’ || choice=='Y")
{ {
int x, y; printf("\n Enter the name: “);
gets(stud.name);
ft
}
int main() else
{ {
int 4; printf("\n Enter the roll number: “);
union POINT points[3); scanf("Xd", &stud.roll_no);
points[O].x = 2; }
points[0].y = 3; printf("\n Enter the marks: ");
points[1].x = 4;
scanf("Xd", &stud.marks);
points[1].y = 5; if(choices='y' || choices='Y')
points[2}.x = 6; printf("\n Name: Xs “, stud.name);
points[2].y = 7; else
printf("\n Roll Number: %d ", stud.roll_no);
for(ie0;ic3;i++) printf("\n Marks: Xd", stud.marks);
printf("\n Co-ordinates of Point(%d} return 0;

are %d and Xd", 4, points[i]}.x, }


points[(i).y); Now in this code, we have a union embedded within
return 0; a structure. We know, the fields of a union will share
} memory, so in the main program we ask the user which
Output data he/she would like to store and depending on his/her
choice the appropriate field is used.
Co-ordinates of Point[0] are 3 and 3
Co-ordinates of Point{1] are 5 and 5
Co-ordinates of Point[(2] are 7 and 7
Pointing to unions, passing unions to functions, and
passing pointers to unions to functions are all done in the
GED UNIONS INSIDE STRUCTURES same way as that of structures.

You must be wondering, why do we need unions? In


general, unions can be very useful when declared inside a
structure, Consider an example in which you want a field GGED structures INSIDE UNIONS
of a structure to contain a string or an integer, depending
on what the user specifies. The following code illustrates C also allows users to have a structure within a union. The
such a scenario. program given below illustrates the use of structures within
a union. There are two structure variables in the union. The
#include <stdio.h> size of the union will be the size of the structure variable
struct student
which is larger of the two. During run-time, programmer
{ will choose to enter name or roll number of the student and
union
the corresponding action will thus be taken.
{
char name[ 20}; #include <stdio.h>
int roll_no; typedef struct a
I { int marks;
int marks; char name [20];
hi iF
int main() typedef struct b
Structure, Union, and Enumerated Data Type Gos

{ int marks; of a set of named integer constants. In other words)


int roll_no; in an enumerated type. each integer value is assigned
a an identifier. This identifier (which is also known as an
enumeration constant) can be used as a symbolic name to
typedef union Student make the program more readable.
{ struct a A; To define enumerated data types, we use the keyword
struct b B; enum, which is the abbreviation for ENUMERATE.
hb Enumerations create new data types to contain values that
main() are not limited to the values that fundamental data types
{ may take, The syntax of creating an enumerated data type
union Student s; can be given as follows:
char ch;
printf("\n Do you want to enter name or roll enum enumeration_name {identifier,,
number of the student : (N/R)- “); identifier,, ., identifier, };
scanf("Xce", &ch); The enum keyword is basically used to declare and initialize
if(ch == 'R') a sequence of integer constants. Here, enumeration_name
t is optional. Consider the following example, which creates
printf#("\n Enter the roll number : “); a new type of variable called COLORS to store colour
scanf("X%d", &s.B.roll_no); constants.
printf#("\n Enter the marks : “);
scanf("Xd", &s.8.marks); enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW,
} PURPLE, WHITE};
else
{ Note that no fundamental data type is used in the
printf("\n Enter the name : “); declaration of COLORS. After this statement, COLORS has
gets(s.A.name); become a new data type. Here, COLORS is the name given
printf("\n Enter the marks : “); to the set of constants, In case you do not assign any
scanf("Xd", &s.A.marks); value to a constant, the default value for the first one in
the list—RE0 (in our case) has the value of 0. The rest
printf("\n ****** STUDENT'S DETAILS of the undefined constants have a value | more than
seeeenhys its previous one. That is, if you do not initialize the
if(ch == 'N') constants, then each one would have a unique value. The
first would be zero and the rest would count upwards, So,
printf("\n NAME : "); in our example,
puts(s.A.name);
printf("\n MARKS : Xd", s.A.marks); RED = 0, BLUE = 1, BLACK = 2, GREEN = 3,
} YELLOW = 4, PURPLE = 5, WHITE = 6
else
If you want to explicitly assign values to these integer
printf("\n ROLL NO : Xd", s.B.roll_ no);
constants then you should specifically mention those
printf("\n MARKS : Xd", s.B.marks); values shown as follows:
} enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN
} = 7, YELLOW, PURPLE, WHITE = 15};
Output
As a result of this statement, now RED = 2, BLUE =
Do you want to enter name or roll number of 3, BLACK = 5, GREEN = 7, YELLOW = 8, PURPLE = 9,
the student : (N/R)- R WHITE = 15.
Enter the roll number : 12 Look at the code which illustrates the declaration and
Enter the marks : 99 access of enumerated data types.
****** STUDENT'S DETAILS ******

ROLL NO : 12 #include <stdio.h>


MARKS : 99 int main()
{ enum {RED=2, BLUE, BLACK=5, GREEN=7, YELLOW,
PURPLE, WHITE=15};
ENUMERATED DATA TYPE printf(“\n RED = %d", RED);
printf("\n BLUE = Xd", BLUE);
The enumerated data type is a user-defined type based printf("\n BLACK = %d", BLACK);
on the standard integer type. An cnumeration consists printf("\n GREEN = Xd", GREEN);
406 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

15.10.2 Using the Typedef Keyword


C also permits to use the typedef keyword for enumerated
data types. For example, if we write
The value of an enumerator constant is always of the
type int. Therefore, the storage associated with an typedef enum COLORS color;
enumeration variable isthe storage required for a single Then, we can straightaway declare variables by writing
int value,The enumeration constant or avalue ofthe
enumerated type can be used anywhere in the program color forecolor = RED;
where the C language permits aninteger expression.
15.10.3 Assigning Values to Enumerated
The following rules apply to the members of an Variables
enumeration list Once the enumerated variable has been declared, values
* An enumeration list may contain duplicate constant can be stored in it, However, an enumerated variable can
values, Therefore, two different identifiers may be hold only declared values for the type. For example, to
assigned the same value, say 3 assign the colour black to the background colour, we will
The identifiers in the enumeration list must be different write,
from other identifiers in the same scope with the
same visibility including ordinary variable names and
bg_color = BLACK;
identifiers in other enumeration lists. An important thing to note here is that once an
Enumeration names follow the normal scoping rules. So enumerated variable has been assigned a value, we can
every enumeration name must be different from other store its value in another variable of the same type. The
enumeration, structure, and union names with the same following statements illustrate this concept
visibility.
enum COLORS bg color, border_color;
bg_color = BLACK;
border_color = bg color;
If we create an enumerated type without enumeration_
name, it is known as an anonymous enumerated type.
For example, enum (OFF, ON); declares an enumerated 15.10.4 Enumeration Type Conversion
type that has two constants OFF with a value 0 and ON Enumerated types can be implicitly or explicitly cast, For
with a value 1. example, the compiler can implicitly cast an enumerated
type to an integer when required, However, when we
implicitly cast an integer to an enumerated type, the
15.10.1 enum Variables compiler will either generate an error or a warning
message
We have seen that enumerated constants are basically
To understand this, answer one question. If we write
integers, so programs with statements such as int fore_
color = RED; is considered to be a legal statement in C. enum COLORS{RED, BLUE, BLACK, GREEN, YELLOW,
In extension to this, C also permits the user to declare PURPLE, WHITE);
variables of an enumerated data type in the same way as enum COLORS c;
we create variables of other basic data types. The syntax ¢ = BLACK + WHITE;
Structure, Union, and Enumerated Data Type 407

Here, c is an enumerated data type variable. If we write


enumerated type, we read/write it as an integer. The
c = BLACK + WHITE, then logically. it should be 2 + 6 =
compiler would implicitly do the type conversion as
8, which is basically a value of type int. However, the
discussed earlier. The following statements illustrate this
left-hand side of the assignment operator is of the type
concept
enum COLORS. So the statement would report an error. To
remove the error, you can do cither of two things. First, enum COLORS(RED, BLUE, BLACK, GREEN, YELLOW,
declare c to be an int, Second, cast the right-hand side in PURPLE, WHITE};
the following manner enum COLORS c;
scanf("Xd", &c);
c¢ = enum COLORS(BLACK + WHITE);
printf("\n Color = %d", c);
To summarize,
16. Write a program to display the name of the colours
enum COLORS(RED, BLUE, BLACK, GREEN, YELLOW,
using an enumerated type.
PURPLE, WHITE};
enum COLORS c; #include <stdio.h>
€ = BLACK; //valid in C enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW,
€¢ #2; // illegal in ¢ PURPLE, WHITE};
¢ = (enum COLORS)2; // Right way int main()
{
15.10.5 Comparing Enumerated Types
enum COLORS c;
char *color_name[] = {"RED", "BLUE",
C also allows using comparison operators on enumerated "BLACK", "GREEN", “YELLOW", “PURPLE”,
data type. Look at the following statements, which WHITE");
illustrate this concept for(c = RED; ¢ <= WHITE; c++)
bg_color = (enum COLORS)6; printf("\n Xs", color_name[c]);
if(bg_color == WHITE) return 0;
fore_color = BLUE;
fore_color = BLACK;
if(bg_color == fore_color) OR
printf("\n NOT VISIBLE"); include <stdio.h>
include <stdlib.h>
Since enumerated types are derived from integer type,
they can be used in a switch case statement. The following #@include <conio.h>
code demonstrates the use of the enumerated type in a enum COLORS {red, blue, black, green, yellow,
switch case statement, purple, white};
int main()
enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, {
WHITE}bg_ color; enum COLORS c;
switch(bg_ color) © = rand()%7;
{ switch(c)
case RED: {
case BLUE: case red: printf("\n RED"); break;
case GREEN; case blue: printf("\n BLUE"); break;
printf("\n It is a primary color"); case black: printf("\n BLACK"); break;
break; case green: printf("\n GREEN"); break;
case default: case yellow: printf("\n YELLOW");
printf("\n It is not a primary color"); break;
break; case purple: printf("\n PURPLE");
break;
case white: printf("\n WHITE"); break;
15.10.6 Input/Output Operations on }
return 0;
Enumerated Types
Output
Since enumerated types are derived types, they cannot
be read or written using formatted inpuVoutput functions GREEN
available in the C language. When we read or write an
408 Computer Fundamentals and Programming in C

| 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

(d) Age main()


(e) Salary {
(f) Designation i-*2;
26, Declare a structure(s) that represents the following f = 2.3;
hierarchical information printf("\n Xd Xf", i, £);
(a) Student }
(b) Roll Number struct values
{c) Name
{
int i;
(i) First name float £;
(ii) Middle Name
Wi
(iii) Last Name main()
(d) Sex {
(e} Date ofBirth static values v = {5, 2.3);
(i) Day printf("\n Xd %f", v.i, v.#);
(ii) Month }
(ill) Year struct first
(1) Marks {
(i) English int 4;
{ii) Mathematics float #;
(ili) Computer Science }
27. Define a structure to store the name, an array marks{}
struct second
which stores marks of five different subjects and a
{
character grade. Write a program to display the details of
int i;
the student whose name is entered by the user, Use the
float f;
}
structure definition of question 26 to make an array of
main()
student, Display the name of the students who have
secured less than 40% of aggregate. {
struct first f = {7,4.5};
28. Modify question 27 to print each student's average struct second s = {4,3.4};
marks, class average (that includes average of all the
int diff;
students’ marks).
diff = f.i - 5.4;
29. Make an array of students as illustrated in question 26 peintf("\n Xd", diff);
and write a program to display the details of the student }
with the given DOB.
struct values
30, Make an array of students as illustrated in question 26
{
and write a program to delete the record of the student int i;
with the given last name. int val{10];
jv = {1,2,3,4,5,6,7,8,9}, *ptr = By;
Find the output of the following codes. main()
1, main() {
{ printf("\n Xd Xd", v.d, ptr -> 4);
struct values printf("\n Xd Xd Xd", v.val[3],
{ ptr -> val(3), *(v.val+3));
int i; }
float f; struct values
W; {
ved = 2; int i;
vif = 2.35 float f;
printf("\n Xd Xf", v.i, v.f); if
} void change(values *v, int a, float b)
2, struct values {
{ visa;
int i; vf =d;
float f; }
3 main()
412 ‘Computer Fundamentals and Programming in C

{ 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

Key Points About Bit Fields


* C does not permit arrays of bit fields, pointers to bit fields, In all implementations, the default integer type for a
and functions returning bit fields. bit field is unsigned.
+ C permits ordinary member variables along with bit fields
as structure members. Drawbacks
* The declarator is optional and is used to name the bit Bit fields are basically used to represent single bit flags, with
field. each flag stored in a separate bit. However, bit members in
* Bit fields can only be declared as part ofastructure. structs have prictical drawbacks,
* The address-of operator (&) cannot be applied to bit- + First, the ordering of bits in memory is architecture-
field components, This means that you cannot use scanf dependent and memory padding rules vary from compiler
to read values into a bit field. To read a value, you may use to compiler. Moreover, many C compilers that are used
a temporary variable and then assign its value to the bit today generate inefficient code for reading and writing bit
field. members.
Bit fields that are not named cannot be referenced, and * Second, bit fields can require a surprising amount of
their contents at run time are unpredictable. However, they run-time code to manipulate the values and therefore, the
can be used as dummy fields, for alignment purposes. programs may end up using more space than they save.
* Bit fields must be long enough to contain the bit pattern.
Therefore, the following statement is invalid in C tan- SLACK BYTE
guage. In order to store any type of data in a structure, there is a
minimum fixed byte which must be reserved by the memory.
short num: 15
This minimum byte, which is usually machine-dependent,
+ When a value that is out of range is assigned to a bit field, is known as that word boundary. For example, TURBO C
the lower-order bit pattern is preserved and the appropriate is based on the 8086 microprocessor and has two-byte word
bits are assigned, boWundary. So any data type reserves at least two bytes of
* Although the maximum bit field length is 64 bits, for por- memory space. To understand it clearly, consider the following
tability reasons, do not use bit fields that are greater than structure.
32 bits in size,
struct employee
* Bit fields with a length of 0 must be unnamed.
414 Computer Fundamentals and Programming in C

{ only in the first byte. Now char promotion_due will search


char grade; for one byte and since one byte is available it will store the data
int id; in that byte. Now int id will reserve two bytes and stores the
int emp_code; data in the two bytes allocated to it. Similarly, int emp_code
float salary; will reserve two bytes to store the data and float salary will
char promotion_due; reserve four bytes todo the same. Note that by re-arrangement of
hs the fields, there is no slack byte, and we have saved the wastage
of memory and structure employee_m is a balanced structure.
Cl | | | | | | | | ww To understand the concept with clarity, execute the
following code
grade slack id emp_code salary slack main()
byte promotion_due byte {

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

Converting an unbalanced structure into a balanced char grade;


structure char promotion_due;
Now consider the same structure in which the sequence of ant: 403
fields hax been altered. At CaP
float
sal;
coaes
struct employeem 5
{ clescr();
char grade; printf(“\n Size of employee =
char promotion_due; Xd", sizeof(struct employee));
int id; printf("\n Size of employee_m =
int emp_code; Xd", sizeof(struct employee_m));
float sal; getch();
bb }

ha FED ON se
Output

pata a eens eg Size of employee_m = 10


promotion_due Hence, slack byte is useful for speed optimization as it
aligns bytes so that they can be read from the structure faster.
First char grade will reserve two bytes and stores the data
TAKEAWAYS
* Streams inc © Error handling * Renaming files
© Reading data from files * Command line arguments * Creating temporary files
* Writing data to files © Random access of data

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

In a text file, an integer value 123 will be stored as a File Name


sequence of three characters—1, 2, and 3. So cach character Every file on the disk has a name associated with it. The
will take | byte and, therefore, to store the integer value naming convention of a file varies from one operating
123 we need 3 bytes. However, in a binary file, the int system to another. For example, in DOS the file name
value 123 will be stored in 2 bytes in the binary form. This can have one to eight characters optionally followed by
clearly indicates that binary files take less space to store a period and an extension that has one to three characters.
the same picce of data and eliminate conversion between However, Windows and UNIX permit filenames having
internal and external representations and are thus more maximum of 256 characters. Windows also lays some
efficient than the text files. restrictions on usage of certain characters in the filenames,
ie., characters such as /,\,:,*,?,",<,>, and ! cannot be
part of a file name.
In C, fopen() may contain the path information instead
€TED UsING FiLes INC of specifying the filename. The path gives information
about the location of the file on the disk. If a filename
To use files in C, we must follow the steps given below is specified without a path, it is assumed that the file is
* declare a file pointer variable located in the current working directory. For example, if a
* open the file file named Student .DAT is located on O drive in directory
* process the file BCA, then the path of the file can be specified by writing
+ close the file D: \BCA\Student ,DAT
In this section, we will go through all these steps in detail In C, a backslash character has a special meaning with
fespect to escape sequences when placed in a string. So in
16.2.1 Declaring a File Pointer Variable order to represent a backslash character in a C program,
you must precede it with another backslash. Hence, the
The n be anumber of files on the disk. In onder to access
above path will be specified as given below in the C
aparticular file, you must specify the name of the file that has program.
to be used, This is accomplished
Programming Tip: by using a file pointer variable D:\\BCA\\Student .DAT
An error willbe that points to a structure FILE
generated if you (defined in stdio.h). The file File Mode
use the filenameto pointer will then be used in all
access afile rather subsequent operations in the The second argument in fopen() is the mode. Mode
than the file pointer. file. The syntax for declaring a conveys toC the type of processing that will be done with
file pointer is the file. The different modes in which a file can be opened
FILE *file_pointer_name; for processing are given in Table 16,1
For example, if we write Look at the code given below which opens a file using
FILE *fp; fopen().

Then, fp is declared as a file pointer. FILE *fp;


fp = fopen("Student.DAT", “r");
if(fp==NULL)
16.2.2 Opening a File
{
A file must first be opened before data can be read from it printf("\n The file could not be opened");
or written to it, In order to open a file and associate it with exit(1);
4 stream, the fopen() function is used. The prototype of
}
fopen() can be given as
OR
FILE *fopen(const char *file_name, const char
*mode); char filename[ 30];
Using the above declaration, the file whose pathname
FILE *fp;
gets(filename);
is the string pointed to by
Programming Tip: file_name is opened in the fp = fopen(filename, rt
Afile mustbeopened mode specified using the if(fp==NULL)
before any operation mode, If successful, fopen() {
can be performed returns a pointer-to- printf("\n The file could not be opened");
on it. structure and if it fails, it exit(1);
returns NULL.
418 Computer Fundamentals and Programming in C

odes Programming Tip:


opened simultancously, the
5
programmer must close a file
ied ? r when it has been used. The
t Open a text file for reading. Ifthe stream (file) does recommended
‘not exist, then an error will bereported. a prototype of the fclose()
files when tk function can be given as
w Open a text file for writing. Ifthestream does not
int fclose(FILE *fp);
exist, then itixcreated. Ifthefile already exists, then
its contents
would be deleted. L ioimareinn Here, fp is a file pottiter
further in the program. ve .
which points to the file that
a Append toa textfile. Ifthe tile does not exist, itis
created,
has to be closed. The function
returns an integer value which indicates whether fclose()
th Open a binary fileforreading. "b’indicates binary. was successful or not. A zero is returned if the function
| Bydefault thiswillbea sequential fileinMedia 4 was successful, and a non-zero value is returned if an error
format.
occurred
wb Open a binary fileforwriting.
ab Append
toa binary file.
‘Open a text file for both reading and writing. The
stream willbepositioned atthebeginning ofthetile When fclose() is executed, any unwritten buffered data
‘When you specify ‘r+’,you indicate thatyou want for the stream will bewritten tothefile and any unread
to read the file before you write toit.Thus, the file buffered
data will bediscarded,
smiust already exint
wt Open a text file for both reading and writing. The
In addition to fclose(), there is a function fcloseall()
stream will becreated ifitdoes not exist, and will be
which closes all the streams that are currently opened
truncatedifHtexists.
except the standard streams (such as stdin, stdout, and
ae Open a textfileforbothreading and writing. The stderr). The prototype of fcloseall() can be given as
stream will bepositioned attheend ofthe filecontent,
rebirb+ = Open a binary fileforread/write, int fcloseall(void);
web/wbt Create a binary file for read/write, fcloseal1() also flushes any stream buffers and returns
(aetvab+ Append
abinary tile forread/write. the number of streams closed.
Ifa file's buffer has to be flushed without closing it then
use fflush() or flushall() to flush the buffers of all open
We have already dise' ssed that fopen() returns a pointer streams.
fo FILE structure if suces sful and a NULL otherwise. So it is
recommended to check whether
Programming Tip: the file was successfully opened EGED READING DATA FROM FILES
An error will be before actually using the file
generated if you try The fopen() function can fail C provides the following set of functions to read data from
to open afile that to open the specified file under a file
does not exist. certain conditions that are listed * fscanf()
as follows: * fgets()
* Opening a file that is not ready for use * fgetc()
* Opening a file that is specified to be on a non-existent * fread()
directory/drive In this section, we will read about these functions.
* Opening a non-existent file for reading
* Opening a file to which access is not permitted
16.3.1 fscanf()
The fscanf() function is used to read formatted data from
16.2.3 Closing a File Using fclose()
the stream.The syntax of fscanf() can be given as
To close an open file, the fclose() function is used which
int fscanf(FILE *stream, const char *format,..);
disconnects a file pointer from a file. After fclose() has
disconnected the file pointer from the file, the pointer can be The fscan#() function is used to read data from the stream
used to access a different file or the same file but in a different and store them according to the parameter format into the
mode. The fclose() function not only closes the file, but also locations pointed by the additional arguments. However,
flushes all the buffers that are maintained for that file. these additional arguments must point to the objects that
If you do not close a file after using it, the system have already occupied memory. These objects are of type
Closes it automatically when the program exits. However, as specified by their corresponding format tag within the
since there is a limit on the number of files which can be format string.
Files 419

Similar to the format specifiers used in scanf(), #include <stdio.h>


in fscanf() also the format specifiers is a C string that int main()
begins with a percentage sign (%). The format specifier is {
used to specify the type and format of the data that has FILE *fp;
to be obtained from the stream and stored in the memory char name[80);
locations pointed by the additional arguments. The int roll_no;
prototype ofa format specifier can be given as fp = fopen("Student.DAT", "r");
if(fp==NULL)
%[*](width] [modifiers }type, where
{
* is an optional argument that suppresses assignment printf("\n The file could not be
of the input field. It indicates that data should be read opened");
from the stream and ignored (not stored in the memory exit(1);
location). }
printf("\n Enter the name and roll number
width specifies the maximum number of characters to be
read. However, fewer characters will be read if the fscanf of the student: ");
// READ FROM KEYBOARD
function encounters a while space or an unconvertible
fscanf(stdin, “Xs Xd", name, &roll_no);
character,
/* read from keyboard */
modifiers can be h, 1, or L for the data pointed by the printf("\n NAME: Xs \t ROLL NUMBER = Xd",
corresponding additional arguments. Modifier h is used name, roll_no);
for short int or unsigned short int, 1 is used for long // READ FROM FILE Student .DAT
int, unsigned long int, or double values. Finally, t is fscanf(fp, "Xs Xd", name, &roll_no);
used for long double data values. printf("\n NAME: Xs \t ROLL NUMBER = Xd",
fype specifies the type of data that has to be read. It also name, roll_no);
indicates how this data is expected to be read from the fclose(fp);
user, return 0;
The type specifiers for fscanf function are given in }
Table 16.2, Output
Table 16.2 Type specifiers Enter the name and roll number of the student:
01 Zubin
Type | Qualifying input
NAME: Zubin ROLL NUMBER = 01
le for single characters. NAME: Goransh ROLL NUMBER = 03
i) for decimal values
e.E.f.g.G forfloating point numbers
0 foroctalnumbers
Ss for a sequence of (string of) characters if you want to use fprintf () to write on the screen,
u for unsigned decimal values then specify stdout instead of specifyingany other file
x.X for hexadecimal values pointer.

The fscanf function has some additional arguments. 16.3.2 fgets()


Each of the additional arguments must point to an object
of the type specified by its corresponding % tag within the The fgets() function stands for file get string. The fgets()
format string, in the same order function is used to get a string from a stream, The syntax of
fgets() can be given as

char *fgets(char *str, int size, FILE


The fscanf function Is similar to the scant function, *stream);
except that the first argument of fscanf specifiesa The fgets() function reads at most one less than the
stream from whichto read, whereas scanf can only read number of characters specified by size (gets size ~ 1
from standard input, characters) from the given stream and stores them in the
string str. The fgets() fuction terminates as soon as it
Let us look at an example which illustrates the use of encounters cither a newline character, EOF, or any other
#scanf(). Here, we will not give the complete program error. However, if a newline character is encountered it
but just a partial program to demonstrate the use of is retained. When all the characters are read without any
fscanf() error, a ‘\0' character is appended to the end of the string
420 Computer Fundamentals and Programming in C

The gets() and fgets() functions are almost same {


except that gets() has an infinite size and a stream of FILE *fp;
stdin. Another difference is that when gets() encounters char str[80];
a newline character, it does not retain it, Le., the newline int i, ch;
character(if any) is not stored in the string fp = fopen("Program.c”, "r");
On successful completion, fgets() will retum str if (fp==NULL)
However, if the stream is at EOF, the EOF indicator for the {
stream will be sct and fgets() will returm a NULL pointer. printf("\n The file could not be
In case, fgets() encounters any error while reading. the opened") ;
error indicator for the stream will be set and NULL pointer exit(1);
will be returned, Look at the program code given below }
which demonstrates the use of fgets() - // Read 79 characters and store them in str
ch = fgetc(fp);
#include <stdio.h>
for(is0; (i < 79) && (feof(fp) == 0); i+)
int main()
{ {
str[i] = (char)ch;
FILE *fp;
ch = fgetc(stream);
char str[80];
// reads character by character
fp = fopen("ABC.DAT", “r");
if(fpe=NULL) }
ste[i] = '\0';
{ // append the string with a null character
printf("\n The file could not be opened”);
printf("\n Xs", str);
exit(1);
felose(fp);
}
/* the file will read 79 characters during }
each iteration and will print them on the The above program displays cither first 79 characters
screen */ or less characters if the file contains less than 79
while (fgets(str, 80, fp) f= NULL) characters,
printf("\n Xs", str); The feof() function is used to detect the end of file. We
printf("\n\n File Read. Now closing the file"); will read more on this function later in this chapter.
fclose(fp);
return 0; 16.3.4 fread()
}
The fread() function is used to read data from a file, Its
Output syntax can be given as
Abdceweeferrttet gfejjherroiew tjketjer int fread(void «str, size_t size, size_t num,
fddfgdtgfd FILE *stream);
File Read, Now closing the file
The fread() function reads num number of objects
(where cach object is size bytes) and places them into the
16.3.3 fgets()
array pointed to by str. The data is read from the given
The fgetc() function returns the next character from input stream.
stream, EOF if the end of file is reached, or if there is an Upon successful completion, fread() returns the
error, The syntax of fgete() can be given as number of bytes successfully read. The number of
int fgetc(FILE *stream);
objects will be less than num if a read error or end-of-file
is encountered. If size or num is 0, fread() will return 0
#getc() returns the character read as an int or returns EOF and the contents of str and the state of the stream remain
to indicate an error or end of file unchanged. In case of error, the error indicator for the
fgetc() reads a single character from the current stream will be set
position of a file (file associated with stream). After The fread() function advances the file position
reading the character, the function increments the indicator for the stream by the number of bytes read.
associated file pointer (if defined) to point to the next
character, However, if the stream has already reached the
end of file, the EOF indicator for the stream is set. Look at
the following program code which demonstrates the use of
The fread() function does not distinguish between end-
fgets() function.
of-file and error. The programmer must use feof and
#include <stdio.h> ferror to determine which ofthe two has occurred,
main()
Files 421

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

{ When an output streai


printf("\n The file could not be opened”); he pcre is
unbuffered. information
exit(1); acne Gea ec appears on the destination
} aaa tar also device as soon as it is
printf("\n Provide feedback on this book: “); written. When it is buffered,
gets( feedback); characters are saved internally
fflush( stdin); and then written out as a group. In order to force buffered
// feedback stored characters to be output before the buffer is full, use
fputs(feedback, fp); fflush()
fclose(fp);
} 16.4.4 fwrite()
Output The fwrite() function is used to write data to a file. The
Provide feedback on this book: good syntax of fwrite can be given as
int fwrite(const void «str, size_t size,
16.4.3 fputc() size_t count, FILE *stream);
The fpute() function is just the opposite of fgetc() and The fwrite() function will write objects (number
is used to write a character to the stream of objects will be specified by count) of size specified
by size, from the array pointed to by str to the stream
int fputc(int c, FILE *stream);
pointed to by stream.
The fputc() function will write the byte specified by The file-position indicator for the stream (if defined)
C (converted to an unsigned char) to the output stream will be advanced by the number of bytes successfully
pointed to by stream On successful completion, fpute() written. If an error occurs, the resulting value of the file-
will return the value it has written. Otherwise, in case of position indicator for the stream is unspecified.
error, the function will return EOF and the error indicator On successful completion, the fwrite() function
for the stream will be set returns the number of objects successfully written, The
#include <stdio.h> number of objects will be less than count if an error is
main() encountered, If size or count is 0, fwrite() will return
{ 0 and the contents of the stream remains unchanged
FILE *fp; In case of error, the error indicator for the stream will
char feedback[100}; be set
int 4;
fp = fopen("Comments.TXT™, w")5 include <stdio.h>
if (fpe*NULL) Minclude <string.h>
{ include <stdlib.h>
printf("\n The file could not be int main(void)
opened”); {
exit(1); FILE *fp;
} size_t count;
printf("\n Provide feedback on this book: vu char str[] = "GOOD MORNING";
gets(feedback) ; fp = fopen("Welcome.txt", “wb");
for(i = 0;4 < feedback[(i);i++) if (fp==NULL)
fputc(feedback[i}, fp);
{
fclose(fp);
printf("\n The file could not be opened");
} exit(1);
Output }
Provide feedback on this book: good count = fwrite(str, 1, strlen(str), fp);
printf("\n %d bytes were
written to the file", count);
fclose(fp);
The standard file stdout is buffered in case the output
return 0;
unit Is not the terminal. On the contrary, the standard
}
file stderr is usually unbuffered. However, the
settings of stdout and stderr can be changed using Output
setbuf. 13 bytes were written to the file
424 Computer Fundamentals and Programming in C
printf("\n The file could not be opened”);
exit(1);
fwrite() can be used to write characters, integers, or
structures toafile.However, fwrite() can be used only }
/* The loop continues until fp reaches
with files that are opened in binary mode.
the end-of-file */
while(!
feof(fp))
{
QTD DETECTING THE END-OF-FILE fgets(str, 79, fp);
// Reads 79 bytes at a time
When reading or writing data to files, we often do not know printf("\n Xs", str);
exactly how long the file is. For example, while reading }
the file, we usually start reading from the beginning and printf("\n\n File Read. Now closing the
proceed towards the end of the file. In C, there are two file");
ways to detect EOF fclose(fp);
* While reading the file in text mode, character by return 0;

character, the programmer can compare the character }


that has been read with EOF, which is a symbolic constant Output
defined in stdio.h with a value -2, The following
statement does that 1 Aditya 2 Chaitanya3 Goransh
while(1)
{
c = fgetc(fp); @TRD ERROR HANDLING DURING FILE
// here
if (c#*EOF)
¢ is an int variable
OPERATIONS
break;
print#("%ce", ¢); It is quite common that an error may occur while reading
data from or writing data to a file. For example, an error
may anse
ay is to use the standard library function
ch is defined in stdio.h. The feof()
* when trying to read a file beyond EOF indicator
* when trying to read a file that does not exist
function is used to distinguish between two cases:
* when trying to use a file that has not been opened
* When a stream operation has reached the end of a file * when trying to use a file in an inappropriate mode, i.c,,
* When the EOF error code has retumed an error
writing data to afile that has been opened for reading
* when writing to a file that is write-protected (i,c., trying
indicator even when the end of the file has not been
to write to a read-only file)
reached
If we fail to check for errors, then the program may
The prototype of feof() can be given as behave abnormally. Therefore,
int feof(FILE *fp); Programming Tip: an unchecked error may result
An error will be in premature termination of the
The function takes a pointer to the FILE structure of generated ifyou try program or incorrect output,
the stream to check as an argument and returns zero to read a file that is In C, the library function
(false) when the end of file has not been reached and a opened inw mode ferror() ix used to check
one (truc) if the end of file has been reached. Look at the and vice versa. for errors in the stream. Its
following: prototype can be given as
The output assumes that a file Student.0aT already
exists and conatins the following data: 1 Aditya 2 int ferror (FILE *stream);
Chaitanya 3 Goransh The ferror() function checks for any errors in the
#include <stdio.h> stream. It returns value zero if no errors have occurred and
main() a non-zero value if there is an error, The error indication
{ will last until the file is closed or it is cleared by the
FILE *fp; clearerr() function. Look at the code given below which
char str[80); uses the ferror().
fp = fopen("Student.DAT", “r"); #include <stdio.h>
if (fp==NULL) main()
{ {
Files 425

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

printf("\n Files are identical"); Output


else
printf("\n Files are not identical");
Enter the name of the first filename: Comments.
TXT
Enter the name of the second filename:
fclose(fp1);
fclose(fp2); User_Comments
.TXT
FILE COPIED
getch();
return 0; 6. Write a program to copy one file into another. Copy
} multiple characters simultaneously
Output include <stdio.h>
Enter the name of the first filename: #include <conio.h>
Comments
.TXT int main()
Enter the name of the second filename: {
Letter.
TXT FILE *fpl, *fp2;
Files are not identical char filename1(20], filename2(20}, str[30);
clrser();
§. Write a program to copy one file into another. Copy print€("\n Enter the name of the first
one character at a time filename: “);
gets(filename1);
#include <stdio.h>
fflush(stdin);
#include <conio.h>
printf("\n Enter the name of the second
int main()
filename: “);
{ gets(filename2) ;
FILE *fpl, *fp2; fflush(stdin);
int ch;
char filename1{20}, filename2{20); if((fplfopen(filenamel, “r"))==0)
clrser(); {
printf("\n Enter the name of the first file: “); printf("\n Error opening the first file");
exit(1);
gets(filename1) ;
fflush(stdin); }
printf("\n Enter the name of the second if ((fp2=fopen(filename2, “w"))==0)
file: "); {
printf("\n Error opening the second file");
gets(filename2) ;
exit(1);
fflush(stdin);
if((fplefopen(filenamel, “r"))#*0) }
while((fgets(str, sizeof(str),
i
fp) )leNULL)
printf("\n Error opening the first file");
fputs(str, fp2);
exit(1);
fclose(fp1);
} fclose(fp2);
if((fp2=fopen(filename2, “w"))==0)
getch();
{ return 0;
printé("\n Error opening the second file");
exit(1); }
Output
// Copy from fpl to fp2
Enter the name of the first filename:
ch = fgetc(fpl);
Comments
.TXT
while(ch!=EOF)
Enter the name of the second filename:
putc(ch, fp2); User_Comments.TXT
FILE COPIED
ch = fgetc(fp1);
} 7. Write a program to read a file that contains characters.
printf("\n FILE COPIED"); Encrypt the data in this file while writing it into another
fclose(fp1); file. (e.g., while writing the data in another file you can
fclose(fp2); use the formula ch = ch —2, i.c., if the data contains
getch(); character ‘red’ the encrypted data becomes ‘peb').
return 0;
include <stdio.h>
#include <conio.h>
Files 429

int main(int argc, char *argv[)) return 0;


{ }
FILE *fpi, *fp2; fpl = fopen(argv[1], “r");
char ch, if(fpl == NULL)
clrser(); {
if(arge != 3) printf("\n File Opening Error”);
{ return 0;
printf("\n Full information is not }
provided"); fp2 = fopen(argv[2], “w");
return 0; if(fp2 == NULL)
} {
fpl = fopen(argv(1), “r*); printf("\n File Opening Error");
if(fpl == NULL) return 0;
{ }
printf("\n File Opening Error"); while (feof(fp1) =« 0)
return 0; {
} fscanf(fpl, "Zc", &ch);
fp2 = fopen(argv(2], "w"); fprintf(fp2, "Xe", ch - 32);
if(#p2 == NULL) }
{ fcloseall();
printf("\n File Opening Error"); printf("\n File copied with upper case
return 0; characters");
} getch();
while (feof(fp1) == 0) return 0;

{ }
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

return 0; #include <conio.h>


} int main()
#p3 = fopen(argv(3], "w"); {
if(fp3 == NULL) FILE *fp;
{ typedef struct student
printf("\n File Opening Error"); {
return 0; int roll_no;
} char name[80];
while (feof(fp1) != 0) float fees;
{ char 008[80);
fscanf(fp1, “Xe”, &ch); }STUDENT;
fprintf(fp3, "Xe", ch); STUDENT studi;
} cleser();
while (feof(fp2) != 0)
{ fp = fopen(“student_details.dat", “w");
fscanf(fp2, "Xe", &ch);
if(fp == NULL)
fprintf(fp3, "“%c", ch);
{
} printf("\n File Opening Error”);
fcloseall(); return 0;
printf("\n File merged");
}
getch();
printf("\n Enter the roll number: ");
return 0; scanf("Xd", &stud1.rol2_no);
} printf("\n Enter the name: “);
Output scanf("Xs", stud1.name);
printf("\n Enter the fees: ");
File merged
scanf("Xf", &studl.fees
10. Write a program to read some text from the keyboard printf("\n Enter the Dot
and store it in a file scanf("Xs", stud1.00B);

#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

Enter the filename: Greet. TXT Enter the fees: 45000


Enter the text: Good Morning Enter the 008: 20-9-91

*** STUDENT'S DETAILS ***


ROLL No. = O01
11. Write @ program to read the details of a student and NAME = Aman
then print it on the screen as well as write it into afile FEES = 45000
#include <stdio.h> DOB = 20-9-91
Files 431

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

file *fp; if (ch >= ‘a’ && ch <= ‘z')


char ch; lower_case++;
clrscr(); if (ch >= ‘0' && ch <= '9')
fp = fopen("characters.dat", “w"); numbers++;
if(fp == NULL) else
{ special_chars++;
printf("\n File Opening Error”); }
return 0; fclose(fp);
} printf("\n Number of upper case
printf("\n Enter the characters: characters = %d", upper_case);
scanf("%e", &ch); printf("\n Number of lower case
while(ch I= ***) characters = Xd", lower_case);
{ printf("\n Number of digits = Xd",
fprintf(fp, “Kc”, ch); numbers);
scanf("Xe", &ch); printf("\n Number of special characters
} = %d", special_chars);
printf("\n Written to the file"); getch();
fclose(fp); return 0;
getch(); }
return 0;
Output
}
Number of upper case characters = 2
Output
Number of lower case characters = 12
Enter the characters: abcdef* Number of digits = 1
Written to the file Number of special characters = 3
15. Write a program to count the number of lower case, 16. Write a program to write record of students to a file
upper case, numbers, and special characters present using array of structures,
in the contents of a file, (Assume that the file contains
#include <stdio.h>
the following data; 1, Hello, How are you?) include <conio.h>
#include <stdio.h> int main()
#include <conio.h> {
int main(int arg c, char *argv{}) FILE *fp;
{ typedef struct student
FILE *fp; {
int ch, upper_case « 0, lower_case « 0, int roll_no;
numbers = 0, special_chars = 0: char name[80);
clrser(); int marks;
if(arge |= 2) }STUDENT;
{ STUDENT studi[5];
printf("\n Full information is not int i;
provided"); clesce();
return 0; fp = fopen(“student_details.txt", “w");
} if(fp == NULL)
fp = fopen(argv[1], “r"); {
if(fp == NULL) printf("\n File Opening Error");
{ return 0;
printf("\n File Opening Error”); }
return 0; for(i = 0; i < 3;i++)
} {
i=0; printf("\n Enter the roll number: ");
while(feof(fp) == 0) scanf("Xd", &stud1[i].roll_no);
{ printf("\n Enter the name:
fscanf(fp, "Xe", &ch); scanf("Xs", studi{i].name
if (ch >= ‘A’ && ch <= ‘Z') printf("\n Enter the marks:
upper_case++; scanf("Xd", &stud1{i}.marks);
Files 433

// PRINT ON SCREEN printf("\n Enter the Name = ");


for(i = O;i < 3;i++) scanf("X%s", stud1.name) ;
{ printf("\n Enter the Marks = “);
printf("\n *** STUDENT'S DETAILS ***"); scanf("Xd", &studl.marks);
printf("\n ROLL No. = %d", studI{i].roll_no); fprintf("fp, “\n Xd %s %d", studi.roll_no,
printf("\n NAME = %s", studi[i].name); studl.name, studl.marks) ;
printf("\n MARKS = Xd", studi[{i].marks); /* After entering the record add a -1 to the
// WRITE TO FILE file to denote the end of records */
fprint#(fp,"Xd Xs Xd", studi[i].roll_no, fprintf("fp, Xd", -1);
studi(i}.name, studi{i}.marks) printf("\n Data Appended™);
} fclose(fp);
printf("\n Data Written to the file"); getch();
fclose(fp); return 0;
getch(); }
return 0;
Output
}
Enter the Roll Number = 04
Output
Enter the Name = Sanchita
***STUDENT'S DETAILS *** Enter the Marks = 50
ROLL No. » 01 Data Appended
NAME = Aditya
MARKS = 78 18. Write a program to read the record of a particular
student
***STUDENT’S DETAILS ***
ROLL No, = 02 ®include <stdio.h>
NAME = Goransh include <conio.h>
MARKS » 100 int main()
{
***STUDENT’S DETAILS *** FILE *fpl;
ROLL No. = 03 typedef struct student
NAME = Sarthak
{
MARKS «= 81 int roll_no;
Data Written to the file char name[80};
int marks;
17. Write a program to append a record to the student's
}STUDENT;
file
STUDENT studi;
#include <stdio.h> int found «0, rno;
#include <conio.h> clrser();
int main() fpl = fopen("student_details.txt", "r");
{ if(fp1 == NULL)
FILE *fp; {
typedef struct student printf("\n File Opening Error");
{ return 0;
int roll_no; }
char name[80); printf("\n Enter the roll number of the
int marks; student whose record has to be read: ");
}STUDENT; scanf("Xd", &rno);
STUDENT stud1; while(1)
clrser(); {
fp = fopen("student_details.txt”, a"); fscanf(fpl, “Xd %s %d", &stud1.roll_no,
if(fp == NULL) studl.name, &stud1.marks);
{ if(stud1.roll_no == -1)
printf("\n File Opening Error”); break;
return 0; if(stud1.roll_no == rno)
} {
printf("\n Enter the Roll Number = “); found = 1;
scanf("Xd", &studi.roll_no); printf("\n The details of student are");
434 Computer Fundamentals and Programming in C
printf(" %d Xs Xd", studi.roll_no, record are ");
studi.name, studl.marks); printf(* Xd %s Xd", stud1.roll_no,
break; studl.name, stud1.marks);
} printf("\n Enter the modified name of
} the student: *);
if (found==0) scanf("Xs", studl.name);
printf("\n Record not found in the file"); printf("\n Enter the modified marks of
fclose(fp1); the student: ");
return 0; scanf("Xd", &studl.marks);
} /* Write the modified record to the
Output temporary file */
fprint#(fp2, "Xd Xs Xd", stud1.roll_no
Enter the roll number of the student whose studl.name, studl.marks);
record has to be read: 02 }
The details of student are - 02 Goransh 100 else
19. Write a program to edit the record of a particular student {
/* Copy the non-matching records to
#include <stdio.h> the temporary file */
#include <conio.h> fscanf(fpl, “%s %d", studl.name,
int main() &studl.marks);
{ fprintf(fp2, “Xd Xs %d", studl.roll_no,
FILE *fpl, *fp2; stud1.name, stud1.marks);
typedef struct student
{ }
int roll_no; fprintf(fp2,"%d", -1);
char name[80}; fclose(fp1);
int marks; fclose(fp2);
STUDENT; if(found==0)
STUDENT studi; printf("\n The record with roll number %d
int found = 0, no; was not found in the file", rno);
clrscr(); else
fp1 = fopen("student_details.txt", "r"); {
if(fpl == NULL) fpl = fopen("student_details.txt", "w");
{ if(fpl =» NULL)
printf("\n File Opening Error"); {
return 0; printf("\n File Opening Error");
} return 0;
fp2 = fopen(“temp.txt", Ww") }
if(fp2 == NULL) fp2 = fopen("temp.txt”, “r");
{ if(fp2 == NULL)
printf("\n File Opening Error”); {
return 0; printf("\n File Opening Error");
} return 0;
printf("\n Enter the roll number of the }
student whose record has to be /* Copy the contents of temporary file
modified: “); into actual file */
scanf("Xd", &rno); while(1)
while(1) {
{ fscanf(fp2,"%d",&stud1.roll_no);
fscanf(fp1, "Xd", &studi.roll_no); if(studi.roll_noe=-1)
if(studi.roll_no *= ~1) break;
break; fscanf(fp2, “Ss %d",studi.name,
if(studi.roll_no == rno) &studi.marks);
{ fprintf(fpl, "Xd Xs Xd", stud1.roll1_
found = 1; no, studl.name, studl.marks);
fscanf(fpl, “Xs Xd", stud1.name
&stud1.marks) ; }
printf("\n The details of existing fclose(fp1);
Files 435

fclose(fp2); /* The matching record is not copied


printf("\n Record Updated"); to temp file */
getch(); else
return 0; {
} /* Copy the non-matching records to
Output
the temporary file */
fscanf(fpl, "Xs Xd", studi.name
Enter the roll number of the student whose &studl.marks);
record has to be modified: 03 fprintf(fp2, “Sd Xs Xd “, studi.roll
The details of exisitng record are - 03 no, studl.name, studl.marks);
Sarthak 81
Enter the modified name of the student: Sarthak }
Enter the modified marks of the student: 85 fprintf(fp2," Xd", “1);
Record Updated fclose(fp1);
fclose(fp2);
20. Write a program to delete the record of a particular
if(found==0)
student
printf("\n The record with roll number %d
Hinclude <stdio.h> was not found in the file", rno);
#include <conio.h> else
int main() {
{ fpl = fopen("student_details.txt", "w");
FILE *fpl, *fp2; if(fp1 == NULL)
typedef struct student {
{ printf("\n File Opening Error");
int roll_no; return 0;
char name[80}; }
int marks; fp2 = fopen("temp.txt", "r");
}STUDENT; if(fp2 == NULL)
STUDENT studi; {
int found =0, rno; printf(“\n File Opening Error");
clrser(); return 0;
fp1 = fopen("student_details.txt", e")5 }
if(fpl == NULL) /* Copy the contents of temporary file
{ into actual file */
printf("\n File Opening Error”); while(1)
return 0; {
} fscanf(fp2,"%d" ,&stud1.roll_ no);
fp2 = fopen("temp.txt", Ww") if(stud1.roll_no==-1)
if(fp2 == NULL) break;
{ fscanf(fp2, “Zs %d",studl.name,
printf("\n File Opening Error”); &studl.marks);
return 0; fprintf(fpl, “Xd Xs Xd “, studi.roll_
} no, studl.name, stud1.marks);
printf("\n Enter the roll number of the }
student whose record has to be }
deleted: “); fprintf(fpl, “Xd ",-1);
scanf("Xd", &rno); fclose(fp1);
while(1) fclose(fp2);
{ printf("\n Record Deleted”);
fscanf(fpl, "Xd", &studi.roll_no); /* The programmer may delete the temp
if(studi.roll_no *= -1) file which will no longer be required */
break; getch();
if(stud1.roll_no == rno) return 0;
{ }
found = 1; Output
fscanf(fpl, “Xs Xd", stud1.name
&stud1.marks); Enter the roll number of the student whose
record has to be deleted: 01
436 Computer Fundamentals and Programming in C

Record Deleted int main()


{
21. Write a program to store records of an employee in typedef struct employee
employee file. The data must be stored using binary {
file int emp_code;
#include <stdio.h> char name[20];
#include <conio.h> int hra;
int main() int da;
int ta;
{
typedef struct employee iF
{ FILE *fp;
int emp_code; struct employee e;
char name[(20); int i;
int hra; clrser();
int da; fp = fopen(“employee.txt", "rb");
int ta; if(fp==NULL)
is {
FILE *fp; printf("\n Error opening file");
struct employee e[5); exit(1);
int i; }
fp = fopen("employee.txt™, “wb"); printf("\n THE DETAILS OF THE EMPLOYEES ARE ");
if (fp==NULL) while(1)
{ {
printf("\n Error opening file"); fread(&e, sizeof(e), 1, fp);
exit(1); if(feof(fp))

} 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);

{ printf("\n\n HRA, DA, and TA: Xd %d


printf("\n\n Enter the employee code: xd", e.hra, e.da, e.ta);
scanf("%d", &e[i}.emp_code); }
printf("\n\n Enter the name of the fclose(fp);
employee: "); getch();
scanf(*X%s", e[i].name); return 0;
printf("\n\n Enter the HRA, DA, and TA: “); Output
scanf("X%d Xd Xd", &e[i].hra, &e[i].da,
&e[i].ta); THE DETAILS OF THE EMPLOYEES ARE
fwrite(&e(i], sizeof(e{i}), 1, fp); Employee Code: 01
} Name: Gargi
fclose(fp); HRA, DA and TA: 10000 S000 2000
getch(); Employee Code: 02
return 0; Name: Nikita

} HRA, DA and TA: 10000 5000 2000


Output 23. Write a program to append a record to the employee
file (binary file).
Enter the details
Enter the employee code: 01 ®include <stdio.h>
Enter the name of the employee: Gargi Binclude <conio.h>
Enter the HRA, DA and TA: 10000 2000 5000 int main()
Enter the employee code: 02 af
Enter the name of the employee: Nikita typedef struct employee
Enter the HRA, DA and TA: 10000 2000 5000 {
int emp_code;
22. Write a to read the records stored in “employee.txt’ file char name[20);
in binary mode. int hra;
#include <stdio.h> int da;

#include <conio.h> int ta;


Files 437

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, {

WinewangasO Co) Si fun


Programming s P printf("\n Error opening file");
exit(1);
thethid parameter) non-zero value. For example, }
Spacifigd asSEEK_END, if you try to perform a ak printf("\n\n Enter the rec_no you want to
then you must provide 3
operation * on apes
a fileoe
that is read: ");
a negative offset, not opened in binary mode scanf("Xd", &rec_no);
Othense RWEYIO
access beyond EOF.
| en a non-zero value will be if(rec_no >= 0)
retumed. {
Files 439

/* from the file pointed by fp read a e.hra, e.ta, e.da);


record of the specifed record }
starting from the beginning of the fclose(fp);
file*/ getch();
fseek(fp, (rec_no-1)*sizeof(e), SEEK_SET); return 0;
result = fread(&e, sizeof(e), 1, fp); }
if(result == 1)
Output
{
print#("\n EMPLOYEE CODE: Xd", e.emp_code); EMPLOYEE CODE: 06
printf("\n Name: Xs", e.name); Name: Tanya
printf("\n HRA, TA and DA: Xd Xd Xd", HRA, DA and TA: 20000 10000 3000
e.hra, e.ta, e.da); EMPLOYEE CODE: 05
} Name: Ruchi
else HRA, DA and TA: 10000 6000 3000
printf("\n Record Not Found");
27. Write a program to edit a record in binary mode using
}
fclose(fp); fseek()
getch(); #include <stdio.h>
return 0; #include <conio.h>
} int main()
Output {
typedef struct employee
Enter the rec_no you want to read: 06 {
EMPLOYEE CODE: 06 int emp_code;
Name: Tanya char name[20];
HRA, DA and TA: 20000 10000 3000 int hra;
int da;
26. Write a program to print the records in reverse order int ta;
The file must be opened in binary mode. Use fseek()
hi
#include <stdio.h> FILE *fp;
#include <conio.h> struct employee e;
int main() int rec_no;
{ fp = fopen(“employee.txt", “r+");
typedef struct employee if(fpe*NULL)
x {
int emp_code; printf("\n Error opening file");
char name[20); exit(1);
int hra; }
printf("\n Enter record no. to be modified: ");
scanf("Xd", &rec_no);
i fseek(fp, (rec_no-1)*sizeof(e), SEEK_SET);
FILE *fp; fread(&e, sizeof(e), 1, fp);
struct employee e; printf("\n Enter modified name of the employee: ");
int result, i; scanf("Xs", e.name);
fp = fopen(“employee.txt", “rb"); printf("\n Enter the modified HRA, TA,
if (fp==NULL) and DA of the employee: *);
{ scanf("Xd %d Xd", &e.hra, Be.ta, &e.da);
printf("\n Error opening file”); fwrite(&e, sizeof(e), 1, fp);
exit(1); fclose(fp);
} printf("\n Record Edited");
for(i=1;i>=0;4--) getch();
{ return 0;
fseek(fp, i*sizeof(e), SEEK_SET); }
fread(&e, sizeof(e), 1, fp); Output
printf("\n EMPLOYEE CODE: Xd", e.emp_code);
printf("\n Name: Xs“, e.name); Enter record no. to be modified: 04
printf(“\n HRA, TA, and DA: %d Xd Xd", Enter modified name of the employee: Ananya
0 Computer Fundamentals and Programming in C

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

Output char text[20];


fp = fopen("practise.c", "rb");
Provide comments on this book: Good
if(fp == NULL)
Contents of the file are: Good
{
However, you must prefer to use fseek() equivalent printf("\n Error opening file");
code rather calling rewind() because it is impossible to exit(1);
determine if rewind() was successful or not }
/* Read some data and then check the
16.8.4 fgetpos() position. */
fread(text, sizeof(char), 20, fp);
The fgetpos() function is used to determine the current
if(fgetpos(fp, &pos) I= 0)
position of the stream. The prototype of the fgetpos() {
function as given in stdio.h is printf("\n Error in fgetpos()");
int fgetpos(FILE *stream, fpos_t *pos) exit(1);
}
Here, stream is the file whose current file pointer position fread(text, sizeof(char), 20, fp);
has to be determined. pos is used to point to the location printf("\n 20 bytes at byte %ld: %s",
where fgetpos() can store the position information. In pos, text);
simple words, fgetpos() stores the file position indicator
of the given file stream in the pos variable. The pos /* Set a new random position and read
variable is of type fpos_t which is defined in stdio.h and more data */
is basically an object that can hold every possible position pos = 90;
in a FILE. if(fsetpos(fp, &pos) != 0)
On success, fgetpos() returns zero and in case of
{
an error a non-zero value is returned. The value of pos printf("\n Error in fsetpos()");
obtained through fgetpos() can be used by the fsetpos() exit(1);
function to return to this same position }
fread(text, sizeof(char), 20, fp);
16.8.5 fsetpos() printf("\n 20 bytes at byte %ld: Xs", pos,
text);
The fsetpos() function is used to move the file position
fclose(fp);
indicator of a stream to the location indicated by the
information obtained in ‘pos’ by making a call to }
fgetpos(). Like fgetpos(), fsetpos() is defined in Output
stdio.h and its prototype can be given as
20 bytes at byte 20: #include <conio.h>
int fsetpos(FILE *stream, const fpos_t pos); m3
20 bytes at byte 90: getch();
Here, stream points to the file whose file pointer
return 0;
indicator has to be re-positioned. pos points to positioning
} Programming Tip:
information as returned by fgetpos .
On success, fsetpos() returns a zero and clears the EOF
Only use values
for
fsetpos() that are
indicator, In case of failure it returns a non-zero value.
returned from fgetpos().
Afier the successful call to
Programming Tip: fsetpos(), the next operation
An error will be on @ stream in update mode
generated ifyou try to may be input or output. Look
OGED DELETING A FILE
place the file position at the program code given
The remove() function as the name suggests, is used to
indicator before the below which illustrates the use
erasea file. The prototype of remove() as given in stdio.h
first byte ofthe file. of fgetpos() and fsetpos()
functions
can be given as
Look at the program given below which opens a file and int remove(const char *filename);
reads bytes at several different locations.
The remove() function will erase the file specified by
#include <stdio.h> filename. On success, the function will return zero and in
main() case of error, it will return a non-zero value.
{ If filename specifies a directory, then remove (filename)
FILE *fp; is the equivalent of rmdir (filename). Otherwise, iffilename
fpost_pos; specifies the name of a file then remove(filename) is the
442 Computer Fundamentals and Programming in C

€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”);

EGR RENAMING A FILE


EUREB CREATING A TEMPORARY FILE
The rename() function, as the name suggests, is used to
rename a file, The prototype of the function is The tmpfile() function is used to create a temporary file.
int rename(const char *oldname, const char The tmpfile() function opens the corresponding stream
*newname) with access parameters set as "we". The file created
with tmpfile() will be automatically deleted when all
Here, oldname specifies the pathname of the file to be references to the file are closed, i.c., the file created will
renamed and newname gives the new pathname of the file be automatically closed and erased when the program has
On success, rename () returns zero. In case of error, been completely executed. The prototype of tmpfile() as
it will return a non-zero value and will set the errno to given in stdio.h header file is
indicate the error. When an error occurs neither the file
named by oldname nor the file named by newname shall be
FILE * tmpfile(void);
changed or created On success, tmpfile() will return a pointer to the stream
of the file that is created. In case of an error, the function
Points to remember about rename() will return a NULL pointer and set errno to indicate the error.
* If the oldname specifies the pathname of a file that is The function can be used in the following manner
not a directory, the newname shall also not point to the
FILE *tp = tmpfile();
pathname of a directory
If the oldname specifics the pathname of a directory then Now the file created can be used in the same way as any
the newname shall not point to the pathname of a file that other text or binary file.

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

Multiple-choice Questions Review Questions


1, Which function gives the current position of the file? 1. What isa file?
(a) fseek() (b) fsetpos() 2. Why do we need to store data in files?
(c) ftell() (d) rewind() 3. Define the term stream.
2. Which function is used to perform block output in binary 4. Differentiate between a text file and a binary file.
files? 5. Explain the different modes in which a file can be opened
(a) fwrite() (b) #print#() in aC program
6. Under which circumstances does the fopen() fail?
(c) fpute() (d) fputs()
7. Why should you close a file after it is used?
3. Select the standard stream in C
8. Whatis the impact of fclose() on buffered data?
(a) stdin (b) stdout
9. Differentiate between gets() and fgets()
(c) stderr (d) all of these
10. What is the difference between a buffered output
4, From which standard stream does a C program read stream and an unbuffered output stream?
data? 11. Under what circumstances does the ftel1() fail?
(a) stdin (b) stdout 12. Where can ftell() be used?
(c) stderr (d) all of these 13. Write a short note on fgetpos() and fsetpos()
5. What acts as an interface between stream and 14, What will happen if the argument to remove() specifies
hardware? a directory? Also state its behaviour when the argument
(a) file pointer (b) buffer is a filename.
(c) stdout (d) stdin 15. Give the importance of associating a buffer with the
6. Which function is used to associate a file with a stream? stream,
16. Write a short note on functions that are used to: (a) read
(a) fread() (b) fopen()
data from a file (b) write data to a file.
{c) floes() (d) #flush()
17. Write a short note on the following functions. For each
7, Which function returns the next character from stream, function, give a program code that demonstrates its usage.
EOF if the end of file is reached, or if there is an error?
(a) fopen() (b) fclose()
(a) fgete() (b) fgets()
(c) ferror() (d) clearerr()
{c) fpute() (d) fwrite()
18. What do you understand by EOF?
19. How will you check for EOF when reading a file?
State True or False
20. Why is it not possible to read from a file and write to the
1, You can use a file without opening it
same file without resetting the file pointer?
2. It is mandatory to close all the files before exiting the
21. Write a short note on error handling while performing
program,
operations.
3. stderr is a standard stream in C
22. Give the importance of rewind()
4, An error will be generated if you try to position the file 23. Differentiate between rewind() and fseek(). Can
marker beyond EOF.
fseek() work as an alternative to rewind()? If yes, how?
5. Afile can be read if and only If it is opened in “r” mode.
24. Why do we need fflush()?
6. Binary files are slower than text files.
25. Differentiate between fscanf()and fread()
7. In text files, the data is stored in internal format of the
computer. Programming Exercises
8. Text files can store only character data 1. Write a program that uses a temporary file created using
9. Standard output is an output stream used by programs tmpfile()
to report error messages or diagnostics. 2. Write a program to write employees details in a file
10, Each line in a text file can have a maximum of 80 called employee.dat. Then read the record of the n'
characters. employee and calculate his salary.
11. Binary files store data in a human readable format 3. Write a program to read the n" record and display it on
12. fread()returns the number of elements successfully screen. Repeat the procedure until ~1 is entered,
read. Write a program to copy a file using feof ().
13, fseek() is used to reposition a binary stream. 5. Create a file and store some names in it. Write a program
14, The tmpfile() function opens the corresponding stream to read the names in the file in the reverse order without
with access parameters set as “w+”. re-opening the file
15. The value obtained by using fgetpos() can be used 6. Write a program to read the contents of a binary file.
only with fsetpos(). 7. Write a program to read the contents of a text file,
Files 445

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

for(c = 'A';c <= » cee) fread(&i,sizeof(int),1,fp);


fwrite(&c, 1, 1, fp); printf("%d", i);
pos = ftell(fp); fclose(fp);
pos = -3; }
fseek(fp, pos, SEEK_END); 7. main()
fread(&,1,1,fp); {
print#("Xc", c); int i;
fclose(fp); FILE *fp;
} long int pos;
6. main() fp = fopen("temp”,"w+b");
{ for(i = 1;4 <= 10;ie+)
int 4; fwrite(&i, sizeof(int), 1, fp);
FILE *fp; fseek(fp, -sizeof(int)*2, SEEK_CUR);
long int pos; fread(Si,sizeof(int),1,fp);
fp = fopen("temp”, “web"); printf("Xd", i);
for(i = 1,4 <= 10;i++) fclose(fp);
fwrite(&i, sizeof(int), 1, fp);
fseek(fp, sizeof(int)*2, SEEK_SET);
” ae

oma Preprocessor Directives

TAKEAWAYS
* Preprocessor directives * Pragma directives * Conditional directives
© #error directive * Predefined macro names

anywhere in the program code, However, if written in


INTRODUCTION between, the directive will be applied only in the remainder
of the source file. The advantages of using preprocessor
The preprocessor is a program that processes the source directives in a C program include:
code before it passes through the compiler. It operates
under the control of preprocessor directive which is placed * Program becomes readable and easy to understand.
in the source program before main(). Before the source * Program can be easily modified or updated.
code is passed through the compiler, it is examined by * Program becomes portable as preprocessor directive:
the preprocessor for any preprocessor directives. In case make it easy to compile the program in different
the program has some preprocessor directives, appropriate execution environments.
actions are taken (depending on the directive) and the * Duc to the aforesaid n ‘ons, the program also becomes
source program is handed over to the compiler more efficient to use,
Preprocessor directives are lines included in ¢ programs
that are not program statements but directives for the TYPES OF PREPROCESSOR
preprocessor. The preprocessor directives are always
preceded by a hash sign (#) directive. The preprocessor DIRECTIVES
directive i executed before the actual compilation of
programs code begins. Therefore, the preprocessor expands We can broadly categorize the preprocessor directives into
all the directives and takes the corresponding action before two groups—conditional and unconditional preprocessor
any code is generated by the program statements. directives. Figure 17.1 shows the categorization of
The preprocessor directives preprocessor directives.
Programming Tip: are only one line long because The conditional directives are used to instruct the
Preprocessor direc- as soon as a newline character preprocessor to select whether or not to include a block of
tives must startwith is found, the preprocessor code in the final token stream passed to the compiler, Such
a hash () sign. directive is considered to directives are #if, #else, #elif, ifdef, #ifndef,
end, No semicolon (;) can be and #endif.
placed at the end of apreprocessor directive. However, the The unconditional directives such as #define,#line,
preprocessor directives may contain a comment (which #undef,#include,#error,and #pragma perform well-
will be simply ignored) defined tasks. In this chapter we will learn about all these
directives in detail

In order to extend a preprocessor directive to multiple itdefine


lines, place a backslash character (\) as the last character
of the line. Thismeans that the line is continued
in the To define preprocessor macros we use #define. The #define
line following it. statement is also known as macro definition or simply a
macro. There are two types of macros:
Although the preprocessor directive is usually placed * object-like macro and
before main(), practically speaking, il can appear * function-like macro,
448 Computer Fundamentals and Programming in C

17.3.1 Object-like Macro #define INPUT printf("\n Enter a number: ");


scanf("Xd", &num);
An object-like macro is a simple identifier which will be @define EQUALS ==
replaced by a code fragment. They are usually used to give define PRINT1 printf("\n GREAT")
symbolic names to numeric constants. Object-like macros define PRINT2 printf("\n TRY AGAIN")
do not take any argument. It is the same what we have Sdefine START main() {
been using to declare constants using #define directive. Sdefine ENO getch();\
The general syntax of defining a macro can be given as return 0; }
tdefine identifier string START Programming Tip:
The preprocessor replaces every occurrence of the en In order toextend a
identifier in the source code by a string. The macro must . preprocessor directive
start with the keyword #define and should be followed INPUT to multiple lines,
if (num EQUALS 100) places backslash
by an identifier and a string with at least one blank space PRINT1; ¢(\) as the
between them. The string may be any text, a statement, or
anything. However, the identifier must be a valid C name. “— last character
ofthe
PRINT2; line.
The line END
tdefine PI 3.14 By convention, macro names are written in uppercase
defines a macro named PI as an abbreviation for the This makes the program casy to read as anyone can tell at
token 3.14, If somewhere after this #define directive there a glance which names are macros
comes a C statement of the form
area = PI « radius « radius;
An identifier is never replaced ifitappears in a comment,
Then the C preprocessor will recognize and expand the within a string, oraspart ofa longer identifier.
macro PI. The C compiler will see the same tokens as it
would if you had written 17.3.2 Function-like Macros
area « 3.14 xradius « radius; Function-like macros are more complex than object-like
macros. They are known as function-like macros because
A macro definition can also include an expression.
they are used to stimulate functions. When a function is
However, when using expressions for replacement,
stimulated using a macro, the macro definition replaces
make sure that the order of
the function definition. The name of the macro serves
sect ny far evaluation is correct. As a
as the header and the macro body serves as the function
not he dat the good programming habit, use
body. The name of the macro will then be used to replace
end
pas
of a preprocessor P
arenthesis in the expression
the function call
For example, consider the
directive. following macro definitions: The function-like macro includes a list of parameters.
References to such macros look like function calls. We
tdefine ROWS 3 have studied that when a function is called, control passes
#define COLS 3 from the calling function to the called function at run time.
#idefine SIZE (ROWS = COLS) However, when a macro is referenced, source code is
inserted into the program at compile time. The parameters
Look at the following program which illustrates the use are replaced by the corresponding arguments, and the text
of #define for literal text substitution:
is inserted into the program stream. Therefore, macros are
#include <stdio.h> considered to be much more efficient than functions as
#include <conio.h> they avoid the overhead involved in calling a function.

Preprocessor directive

Conditional

define line cor


= pragma if else elif ifdef ifndef endif

Figure 17.1 Preprocessor directives


Preprocessor Directives 449

A function-like — macro parentheses to ensure correct evaluation of replacement


Snag sitet definition declares the names text. For example, if amacro SQUARE is defined as
betas aes of formal parameters within
define SQUARE(x) (xxx)
parentheses, scpa-rated by
Sega aie commas. In case the function- Then invoking the macro by writing
sili if iK like macro does not accept
int a= 2, b = 3,c¢;
upy A me any argument, then an empty c = SQUARE(a); // cm 2x25
formal parameter list can be
provided. The above statement is fine and would return the value 4
The syntax of defining a function-like macro can be However, had you written the statements given below, you
given as would have got incorrect results. For example, if had you
written
# define identifier(argi, arg2,...argn) string
An identifier is followed by a parameter list in
int a = 2, b = 3,¢;
parentheses and the replacement string. Note that white
© = SQUARE(a+b
space cannot separate the identifier (which is the name of
[, = 243x243; SoC #24643 = 11
the macro) and the left parenthesis of the parameter list. It is, therefore, very important that you put parentheses
Acomma must separate cach parameter. around cach parameter in the definition to correctly
evaluate an expression. So let us redefine our SQUARE
Invoking a Function-like Macro macro by writing

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

+ Spaces, tabs, and comments Rules of using the # operator in a function-like


Programming Tip: are allowed to be used freely macro definition
Although the within a #define directive.
shearer nics All the spaces, tabs, and The # operator must be used in a function-like macro by
rare dans jeees comments are replaced by a following the rules mentioned below
vs single space.
* A parameter following # operator in a function-like
appearanywherein White space between macro is converted into a string literal containing the
the program code. the identifier and the left
argument passed to the macro.
Hepes bd parenthesis that introduces
* Leading and trailing white-space characters (those that
Mcrae the parameter list is not appear before or after) in the argument passed to the
Lasvibr rapa allowed macro are deleted.
appiled only
inthe + When referencing a macro,
* Ifthe argument passed to the macro has multiple white-
petcorned alas you may use comments
space characters, then they are replaced by a single-
and white-space characters
space character.
freely Comments are
If the argument passed to the macro contains a string
replaced with a single space. However, white-space
literal and if a \(backslash) character appears within
characters (except leading and trailing white spaces)
the literal, then on expansion of the macro, a second \
are preserved during the substitution.
character is inserted before the original \
* The number of arguments in the reference must match
* Ifthe argument passed to the macro containsa " (double
the number of parameters in the macro definition.
quotation mark) character, then on expansion of the
macro, a \ character is inserted before the *
17.3.5 Operators Related to Macros * The conversion of an argument into a string literal
occurs before macro expansion on that argument.
In this section, we will read about some operators that are * If there is more than one # operator in the replacement
direetly or indirectly related to macros in C language list of a macro definition, the order of evaluation of the
operators is not defined
# Operator to Convert to String Literals + If the result of the macro expansion is not a valid
character string literal, the behaviour is undefined.
The # preprocessor operator which can be used only in
a function-like macro definition is used to convert the Merge Operator (##)
argument that follows it to a string literal. For example:
At times you need macros to generate new tokens, Using
#include <stdio.h> the merge operator you can concatenate two tokens into a
fdefine PRINT(num) printf(#num “ = Xd", num) third valid token. For example,
main()
{ #include <stdio.h>
PRINT(20); Sdefine JOIN(A,B) AvaB
main()
}
{
The macro call expands to int i;
printf("num" “= %d", num) for(i = 1;i <= Site)
printf("\n HI JOIN(USER, i): ");
Finally, the preprocessor will automatically concatenate }
two string literals into one The above program would print
Programming Tip: string. So the above statement HI USERI
Ensure that there is will become HI USER2
pate ble printf("num = Xd", num) HI USER3
HI USERS
replacement listof Hence, the unary # operator HI USERS
a macro definition produces a string from its
because in such a
case the orderof
operand. Consider another
macro MAC which is defined as
#include
evaluation
operators ofnot
is the fi MAC(x)
#define #x An extemal file containing functions, variables or macro
definitions can be included as a part of our program. This
defined. MAC("10") gives a string avoids the effort to re-write the code that is already written,
literal equal to "10" .Similarly,
The include directive is used to inform the preprocessor
MAC("HI") would give a string literal “HI”. to treat the contents of a specified file as if those contents
Preprocessor Directives 451

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 #pragma COPYRIGHT_DATE “string”


Here, the string is a date which will be used by the
The #pragma directive is used to control the actions of
COPYRIGHT pragma.
the compiler in a particular portion of a program without
affecting the program as a whole. You can include the pragma
For example, consider the pragma given below
directive in your C program from the point where you want pragma COPYRIGHT DATE “1999-2011”
them to take effect. The effect of pragma will be applied from pragma COPYRIGHT “JRT Software Ltd.”
the point where it is included to the end of the compilation
The above pragma will place the following string in the
unit or until another pragma changes ils status. object code:
A #pragma directive is an instruction to the compiler © Copyright JRT Software Lid, 1999-2011. All rights
and is usually ignored during preprocessing. The syntax
reserved. No part of this program may be photocopied,
of using a pragma directive can be given as
reproduced, or transmitted without prior written consent
#pragma string of JRT Software Ltd.
Preprocessor Directives 453

Pragma optimize Pragma HP_sHLI8_VERSION


The syntax of using the pragma OPTIMIZE can be given as The syntax for HP_SHLIB_VERSION pragma which is used
#pragma OPTIMIZE ON to create different versions of a shared library routine can
#pragma OPTIMIZE OFF
be given as
The pragma OPTIMIZE is basically used to tum on/off pragma HP_SHLIB_VERSION ["]date["]
Optimization in sections of a source program. However, Here, the date argument is of the form month/year,
when using this pragma you must specify one of the optionally enclosed in quotes. The month must be specified
optimization options on the aC command (while giving using any number from | to 12. The year can be specified
the command to compile the program), otherwise this as cither the last two digits of the year (99 for 1999) or
pragma is ignored. Also remember that the pragma a full year specification (1999), Here the two-digit year
OPTIMIZE cannot be used within a function. codes from 00 to 40 are used to represent the years from
For example, 2000 to 2040, respectively.
acC +02 Prog.C /* Set optimization to level 2
for Prog.c */
#pragma OPTIMIZE OFF The version number applies to all global symbols defined
void Funci() in the module's
source file,
{ /* Turn off optimization for this
function */ This pragma should be used only if incompatible
changes are made to a source file.

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

This block is called a conditional group, The controlled


A conditional directive is used to instruct the preprocessor text will be included in the output of the preprocessor
to select whether or not to include a block of code in the if and only if MACRO is defined. The #ifdef is said to be
final token stream passed to the compiler. The preprocessor successful if the MACRO is defined. The controlled text will
conditional directives can test arithmetic expressions, or be executed only if the #ifdef succeeds
whether a name is defined as a macro, ete Even if the #ifdef directive fails, the controlled text
Although the conditional preprocessor directive inside it is still run through initial transformations and
resembles an if statement, it is important to understand tokenization. So, the programmer must ensure that
the difference between them. The condition in an if the controlled text is lexically valid. For example, all
statement is tested when the program is executed. So the comments and string literals inside a failing conditional
same C program may behave differently from run to run, group must still end properly
depending on the data it is operating on. However, the
condition in a preprocessing conditional directive is tested
when the program is being compiled. This facilitates the The kind of optimization done by the operating
system
programmer to allow different code to be included in the
at each level isbeyond the scope of this book. Asthe
program depending on the situation at compile time.
statements under the controlled text of the #ifdef
However, in today’s scenario the distinction is
directive are not enclosed in braces, the #endif directive
becoming less clear. Modern compilers usually test if
statements during program compilation in order to check must be used to mark the end of the #ifdef block,
if their conditions are known not to vary at nan time, and
climinate code which can never be executed. If you have The following example defines an array STACK if MAX is
such a modem compiler then the use of an if statement is defined for the preprocessor.
recommended as the program becomes more readable if sifdef MAX
you use if statements with constant conditions. int STACK[MAX];
Conditional preprocessor directives can be used in the fendif
following situations:
In the above exampl STACK will not be created if MAX had
* A program may need to use different code depending not been initially de! ned
on the machine or operating system it is to run on.
This may be because in certain situations, the code for
one operating system becomes erroneous on another
17.8.2 #ifndef
operating system. For example, the program might refer The #ifndef directive is the opposite of #ifdef directive
to data types or constants that do not exist on the other It checks whether the MACRO has not been defined or if
system, When this happens, it is not enough to avoid its definition has been removed with #undef. #ifndef
executing the invalid code; as even the presence of is successful and returns a non-zero value if the MACRO
such data types and constants will make the compiler has not been defined. Otherwise in case of failure, that is
reject the program, Therefore, in such situations the when the MACRO has already been defined, #ifndef returns
conditional preprocessing is effective. false (0)
The conditional preprocessor directive is very useful Therefore, #ifndef directive is used to define code that
When you want to compile the same source file into two is to be executed when a particular macro name is not
different programs. While one program might make defined. The gencral format to use #ifndef is the same as
frequent time-consuming consistency checks on its for sifdef:
intermediate data, or print the values of those data for
ifndef MACRO
debugging, the other program, on the other hand can
controlled text
avoid such checks.
endif
The conditional preprocessor directives can be used
to exclude code from the program whose condition is Here, MACRO and controlled text have the same
always false but is needed to keep it as a sort of comment meaning as they have in case of #ifdef .Again, the #endif
for future reference, directive is needed to mark the end of the ifndef block.
Preprocessor Directives 455

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

defined OPERATOR #ifndef VERSION


error Version number is not specified.
We have scen that we can check the existence of a macro sendif
by using #ifdef directive. However, there is another way
to do the same The alternative to #ifdef directive is to #ifdef WINDOWS
Preprocessor Directives 457

++. /* Windows specific code */ Table 17.2 Predefined macros


felse Macro Value
#error "This code works only on WINDOWS A decimal integer constant which specifies the
operating system" current line number inthesource file being
#endif compiled, Wehave already studied thattheline
The #error directive causes the preprocessor to report a ‘fsumber can bealtered with a #line directive,
fatal error. A string literal which specifies the name of
Here the string need not be enclosed within double the source filebeingcompiled.
quotes, It is a good programming practice to enclose the _DATE__ Specities thedate ofcompilation
ofthe
string in double quotes. The #error directive is a very current source file.It isa string literal ofthe
important directive mainly because of two reasons: form mm dd yyyy.

+ 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

9, ss épreprocessor operator is used to convert the compilation process terminates.


argument that follows it to a string literal, 19.___ causes the preprocessor to issue a warning
10, The __ operator is used to concatenate two and continue preprocessing
tokens into a third valid token. 20. specifies full conformance with ANSI
11. When we include a file using _ , a search is made standard
for the file in a standard list of system directories.
Preprocessor Directives 459

Multiple-choice Questions While undefining a macro, you have to specify the


1, The preprocessor directives must be preceded by which parameters, if any.
symbol? #ifdef checks whether the MACRO has not been defined
(a) * (c) @ or if its definition has been removed with #undef
We can use enumerated data types in the expressions of
(b) & (d) #
conditional directives.
2, In order to extend a preprocessor directive to multiple
lines, which character is placed as the last character of 4 The #endif directive is used to end the conditional
the line?
compilation directive
15. _TIMESTAMP_ is used to specify the time at which the
(a) \ (c) * compilation process began.
{b) / (d) !
3. Which directive is used to control the line numbers Review Questions
within the code files as well as the file name that appears 1 What do you understand by the term preprocessor
when an error takes place? directive?
(a) #pragma (c) tine Can we have a C program that does not use any
(b) #define (d) #filename preprocessor directive?
4, Which directive is used to check for the existence of Why should we incorporate preprocessor directives in
macro definitions? our programs? Give atleast one example to support your
(a) #if (c) #ifdef answer.
(b) #define (d) #undef Explain the importance of the #define preprocessor
5. Choose the operator which can be used in the conditional
directive.
expression of #if directive. How are trailing arguments, if any, handled by the
preprocessor?
(a) defined (c) typecast
What happens when the argument passed to the macro
(b) sizeof (d) address has multiple white-space characters?
6. Which predefined macro is used to specify the date and Why should we not use more than one # operator in the
time of the last modification of the current source file? replacement list of amacro definition?
(a) TIME (c) _TIMESTAMP. How can #include directive be used in your C program?
(b) _DATE_ (d) _STOC_ Wustrate with respect to both the forms available for
usage.
State True or False File inclusion can be nested. Justify this statement with
1, Preprocessor directives are executable statements in a the help of a suitable example
C program. Can the #undef directive be applied to a macro name
2. The preprocessor is executed before the actual that has not been previously defined? If yes, why?
compilation of program code begins. Explain in detail the #pragma directive.
3. Preprocessor directives can only be one line long. Write a short note on conditional directives.
4. Preprocessor directives can appear anywhere in the Compare an if statement with the #if directive.
program. in which situations will you recommend to use
Object-like macros takes one argument conditional directives in a program?
A macro definition can include an expression Comment on the restrictions imposed on the conditional
It is compulsory to write macro names in uppercase. expression of #if directive.
. The # preprocessor operator can be used only in a
e2xnaw Give the importance of ¢error and #warning directives.
function-like macro definition. Give the rules for using macros
9, The conversion of an argument into a string literal occurs Enumerate the rules for using the # operator in a
before macro expansion on that argument function-like macro definition
10, File inclusion cannot be nested.
oduction to Data Structures

TAKEAWAYS
* Data structures Linked lists Trees
* Primitive and non-primitive
data structures Stacks Graphs
* Linear and non-linear
data structures Queues

solution. A solution is said to be efficient if it solves the


INTRODUCTION problem within the required resource constraints such
as the total space available to store the data and the time
A data structure is a group of data elements that are put allowed to perform cach subtask; and the best solution
together under one name, to define a particular way of is the one that requires fewer resources than known
storing and organizing data in a computer so that it can be alternatives.
used efficiently.
Data structures are used in almost every program
or software system. Some common examples of data CLASSIFICATION OF DATA
structures are arrays, linked lists, queues, stacks, binary
trees, and graphs. Data structures are widely applied in
STRUCTURES
areas such as: Data structures are generally categorized into two classes:
Compiler design primitive and non-primitive data structures.
Operating system
Statistical analysis package 18.2.1 Primitive and Non-primitive Data
Database management system (DBMS) Structures
Numerical analysis
Simulation Primitive data structures are the fundamental data types
Artificial intelligence (Al) which are supported by a programming language. Some
Graphics basic data types are integer, real, character, and boolean.
The terms “data type’, ‘basic data type’, and ‘primitive
When you study DBMS as a subject, you will realize that
data type’ are often used interchangeably.
the major data structure used in the network data model is
Non-primitive data structures are those data structures
graphs, in hicrarchical data models is trees, and in relational
which are created using primitive data structures, Examples
database management systems (RDBMS) is arrays.
of such data structures include linked lists, stacks, trees,
Specific data structures are essential ingredients of
and graphs.
many efficient algorithms as they enable the programmers
Non-primitive data structures can further be classified
to manage huge amounts of data casily and efficiently.
into two categories: /inear and non-linear data structures.
Some formal design methods and programming languages
emphasize data structures and algorithms as the key
18.2.2 Linear and Non-linear Structures
organizing factors in software design. This is because
representing information is fundamental to computer If the elements of a data structure are stored in a linearor
science. The primary goal of a program or software is sequential order, then it is a linear data structure. Examples
not to perform calculations or operations but to store and include arrays, linked lists, stacks, and queues. Linear data
retrieve information as fast as possible. structures can be represented in memory in two different
Be it any problem at hand, the application of an ways. One way is to have to a linear relationship between
appropriate data structure provides the most efficient elements by means of sequential memory locations, The
Introduction to Data Structures Gor

other way is to have a linear relationship between elements


by means of links.
However, if the elements of a data structure are not 0D 2D GD GO-GO GD Gx
stored in a sequential order, then it is a non-linear data Figure 18.2 A simple linked list
structure, The relationship of adjacency is not maintained
between clements of a non-linear data structure. Examples next node. In Figure 18.2, we see a linked list in which
include trees and graphs. every node contains two parts—one integer and the other
C supports a varicty of data structures. We will now a pointer to the next node.
introduce all these data structures. The left part of the node that contains data may include
a simple data type, an array, or a structure. The right part
of the node contains a pointer to the next node (or address
ARRAYS of the next node in the sequence). The last node will have
no next node connected to it, so it will store a special
An array is a collection of similar data clements. These value called NULL. In Figure 18.2, NULL is represented by
data clements have the same data type. The elements of x. However, when we do programming, we usually define
the array are stored in consecutive memory locations and NULL as -1. Hence, a NULL pointer denotes the end of the
are referenced by an index (also known as the subscript). list. Since in a linked list every node contains a pointer to
Arrays are declared using the following syntax: another node which is of the same type, it is also called a
type name[size]; self-referential data type.
A linked list contains a pointer variable, START, which
Por example stores the address of the first node in the list, We can
int marks[10); traverse the entire list using a single pointer variable
START. The START node will contain the address of the first
This statement declares an array marks that contains 10 node; the next part of the first node will in turn store the
elements. In C, the array index starts from zero. This means address of its succeeding node, Using this technique, the
that the array marks will contain 10 elements in all. The individual nodes of the list will form a chain of nodes, If
first clement will be stored in marks[0), second clement in START = NULL, this means that the linked list is empty and
marks[1}, and so on, Therefore, the last clement, i.c., the contains no nodes,
10th element will be stored in marks[9]. In memory, the In. C, we will implement a linked list using the following
array will be stored as shown in Figure 18.1. code:
The limitations of arrays are as follows:
struct node
+ Arrays are of fixed size,
* Data clements are stored in contiguous memory {
int data;
locations which may not be always available.
struct node *next;
+ Adding and removing clements is difficult because of
shifting the clements from their positions. i
However, these limitations can be solved by using a Let us see how a linked list is maintained in memory, In
linked list, We have already read about arrays in Chapter 12. order to form a linked list, we need a structure called node
that has two ficlds—OATA and NEXT, The DATA ficld will
store the information part, and NEXT will store the address
LINKED LISTS of the next node in the sequence. Consider Figure 18.3,
From Figure 18.3, we can see that the variable START
A linked list, in simple terms, is a linear collection of is used to store the address ofthe first node. Here, in this
data elements. These data elements are called nodes. example, START = 1, so the first data is stored at address
Linked lists are data structures that in tum can be used 1, which is 'H’. The corresponding variable NEXT stores
to implement other data structures. Thus, they act as the address ofthe next node, which is 4. So, we will look
building blocks to implement other data structures such at address 4 to fetch the next data item. The second data
as stacks, queues, and their variations. A linked list can be element obtained from address 4 is “€’. Again, we see
perceived as a train or a sequence of nodes in which cach the corresponding NEXT, to go to the next node. From the
node contains one or more data fields and a pointer to the entry in NEXT, we get the next address, that is 7 and fetch

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

Figure 18.4 Algorithm to traverse a linked list

In step | of this algorithm, we first initialize PTR with


the address of START. So now, PTR points to the first node
of the linked list. Then, in step 2, a while loop is executed,
which is repeated until PTR processes the last node, that i:
until it encounters NULL. In step 3,we apply the proc
Figure 18.3 START pointing to the first (c.g., print) to the current node, which is the node pointed
element of a linked list in memory by PTR. In step 4, we move to the next node by making the
PTR variable point to the node whose address is stored in
Note that this figure shows a chunk of memory locations, the NEXT field
whose address ranges from | to 10. The shaded portion Let us now write an algorithm to count the number of
contains data for other applications. Remember that the nodes in the linked list. To do this, we will traverse each
nodes of a linked list need not be in consecutive memory and every node of the list, and while traversing every
locations. In our example, the nodes for the linked list are individual node, we will increment the counter by |, Once
stored at addresses—1, 4, 7, 8, and 10. we reach NULL, that is, when all the nodes of the linked
list have been traversed, the final value of the counter will
Linked Lists Versus Arrays be displayed. Figure 18.5 shows the algorithm to print the
Both linked lists and arrays are a linear collection of data number of nodes in the linked list
elements. However, unlike an array, a linked list docs not
store ils nodes in consecutive memory locations. Another Step 1: [INITIALIZE] SET COUNT = 0
point of difference between an array and a linked list is Step 2: [INITIALIZE] SET PTR = START
that a linked list does not allow random access of data. Step 3: Repeat Steps 4 and 5 while PTR |» NULL
Nodes in a linked list can be accessed only in a sequential Step 4: SET COUNT
» COUNT + 1
manner. However, like an array, insertions and deletions Step S: SET PTR » PTR->NEXT
can be done at any point in the list in constant ime [END OF LOOP]
Another advantage of linked lists over arrays is that Step 6: Write COUNT
we can add any number of clements in the list. This is not Step 7: EXIT
possible in case of an array, For example, if we declare an
array as int marks[10), then the array can store a maximum Figure 18.5 Algorithm to print the number of nodes ina
of 10 data elements and not even a single clement more than linked list
that, There is no such restriction in case of a linked list.
Thus, linked lists provide an efficient way of storing 18.4.2 Searching for a Value in a Linked List
related data and performing basic operations such as
insertion, deletion, and updating of information at the cost Searching a linked list means finding a particular clement
of the extra space required for storing the address of the in the linked list. As already discussed, a linked list
next node, consists of a node which is divided into two parts—the
information part, which stores the relevant data, and the
NEXT part, which stores the address of the next node in
18.4.1 Traversing a Linked List sequence. Hence, obviously, searching means finding
Traversing a linked list means accessing the nodes of whether a given value is present in the information part
the list in order to perform some processing on them. of the node or not. If it is present, the search algorithm
Remember, a linked list always contains a pointer variable returns the address of the node which contains that value.
START, which stores the address of the first node of the list. Figure 18.6 shows the algorithm to search a linked list.
Introduction to Data Structures 463

Step 1: [INITIALIZE] SET PTR = START GO GD -2D 60 Gh


PTR
Step 2: Repeat Step 3 while PTR I» NULL
Here, PTR-> DATA = 1. Since PTR-> DATA t= 4,
Step 3: IF VAL = PTR->DATA
we move to the next node
SET POS = PTR
Go To Step $ GD GD G0 GD GD GO Gy
ELSE
Here, PTR-> DATA = 7. Since PTR-> DATA | = 4, we
SET PTR = PTR- NEXT
move to the next node
[ENO OF IF}
[END OF Loop)
Step 4: SET POS » NULL R
Here, PTR-> DATA = 3. Since PTR-> DATA ! = 4. we
Step 5: €xIT
move to the next node

Figure 18.6 Algorithm to search a linked list oD cd 2D 6D Ga


Here, PTR-> DATA = 4. Since PTR-> DATA = 4, POS
In step 1, we initialize a pointer variable PTR with = PTR. POS now stores the address of the node that
START, which contains the address of the first node. In step contains VAL
2, a while loop is executed that will compare every node's Figure 18.7 Searching a linked list
DATA with the VAL for which the search is being made. If
the search is successful, that is, VAL has been found, then
the address of that node is stored in POS, and the control Before we start with the algorithms to perform insertions
jumps to the last statement of the algorithm. However, in these four cases, let us first discuss an important term,
if the search is unsuccessful, POS is set to NULL, which OVERFLOW. OVERFLOW is a condition that occurs when AVAIL
indicates that the VAL is not present in the linked list = NULL, or no free memory cell is present in the system.
Consider the linked list shown in Figure 18.7. If we have In other words, we want to add data to the data structure,
VAL « 4, then the flow of the algorithm can be explained as but there is no memory space available to do so. When
shown in this figure. this condition prevails, the programmer must give an
appropriate message.
18.4.3 Inserting a New Node in a Linked List Case 1: The new node is inserted at the beginning of
In this section, we will see how a new node is added to an the linked list Consider the linked list shown in Figure
already existing linked list. We will take four cases and 18.8. Suppose we want to add a new node with data 9
then see how insertion is done in each case. and add it as the first node of the list. Then, the following
changes will be done in the linked list
Case 1 The new node is inserted at the beginning of the Figure 18.9 shows the algorithm to insert a new node
linked list at the beginning of a linked list. In step 1, we first check
Case 2 The new node is inserted at the end of the linked whether memory is available for the new node. If the
list. free memory has exhausted, then an OVERFLOW message
is printed. Otherwise, if a free memory cell is available,
Case 3 The new node is inserted after a given node.
then we allocate space for the new node. Set its DATA part
Case 4 The new node is inserted before a given node. with VAL, and its NEXT part is initialized with the address

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

Step 1: IF AVAIL « NULL, then Step 1 IF AVAIL = NULL, then


Write OVERFLOW Write OVERFLOW
Go to Step 7 Go to Step 10
[END OF IF} {END OF IF]
Step 2: SET New Node « AVAIL Step 2: SET New_Node = AVAIL
Step 3: SET AVAIL = AVAIL~>NEXT Step 3: SET AVAIL = AVAIL~>NEXT
Step 4: SET New_Node->DATA « VAL Step 4: SET New_Node->DATA = VAL
Step 5: SET New_Node->Next = START Step S: SET New_Node->Next = NULL
Step 6: SET START = New_Node Step 6: SET PTR = START
Step 7: EXIT Step Repeat Step 8 while PTR->NEXT I= NULL
Step SET PTR = PTR ->NEXT
Figure 18.9 Algorithm to insert a new node at the [END OF LOOP]
beginning of a linked list Step 9: SET PTR->NEXT = New Node
Step 10: EXIT
of the first node of the list, which is stored in START. Since
the new node is added as the first node of the list, it will Figure 18.11 Algorithm to insert a new node at the end of
now be known as the START node, that is, the START pointer a linked list
variable will now hold the address of New_Node
Note the two steps: memory has exhausted, then an OVERFLOW message is
printed. Otherwise, if a free memory cell is available, then
Step 2: SET New Node = AVAIL
we allocate space for the new node. Set its DATA part with
Step 3: SET AVAIL = AVAIL->NEXT
VAL, and its NEXT part is initialized with NULL, because this
These steps allocate memory for the new node. In C, is going to be the last node of the linked list.
there are functions like malloc(), alloc(), and calloc(), In step 6, we take a PTR and initialize it with START.
which does all this automatically on behalfofthe user. We That is, PTR now points to the first node of the linked list
have already discussed these functions in Chapter 14 In the while loop, we traverse through the linked list to
Case 2: The new node is inserted at the end of the reach the last node. Once we reach the last node, in step
linked list Consider the linked list shown in Figure 18.10. 9, we change the NEXT pointer of the last node to store the
address of the new node, Remember that the NEXT fleld of
Suppose we want to add a new node with data 9 and add
it as the last node of the list, Then, the following changes
the new node contains NULL, which signifies the end of the
will be done in the linked list linked list.
ure 18.11 shows the algorithm to insert a new Case 3: The new node is inserted after a given node
node at the end of the linked list. In step 1, we first check Consider the linked list shown in Figure 18,12. Suppose
whether memory is available for the new node. If the free we want to add a new node with value 9 and add it after

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

Figure 18.14 Inserting an element before a give node in a linked list

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 1; IF START = NULL, then Step 1: IF START « NULL, then


Write UNDERFLOW Write UNDERFLOW
hattenlni dt sl Go to Step 10
[END OF IF}
Step 2: SET PTR = START [END OF IF)
Step 3: Repeat Steps 4 and S$ while PTR Step 2: SET PTR « START

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

#include <conio.h> case 3: start = insert_beg(start);


#include <malloc.h> break;
struct node case 4: start = insert_end(start);
{ break;
int data; case 5: start = insert_before(start);
struct node *next; break;
i case 6: start = insert_after(start);
struct node *start = NULL; break;
struct node *create_11(struct node *); case 7: start = delete _beg(start);
struct node *display(struct node *); break;
struct node *insert_beg(struct node * case 8: start = delete_end(start);
struct node *insert_end(struct node *); break;
struct node *insert_before(struct node * case 9: start = delete_node(start);
struct node *insert_after(struct node *); break;
struct node *delete_beg(struct node *); case 10: start = delete_after(start);
struct node *delete_end(struct node *); break;
struct node *delete_node(struct node *); case 11: start = delete list(start);
struct node *delete_after(struct node *); printf(“\n LINKED LIST DELETED”);
struct node *delete list(struct node *); break;
struct node *sort_list(struct node *); case 12: start « sort_list(start);
break;
}
}while(option !=13);
int main() { getch();
int option; return 0;
do }
{ struct node *create_11(struct node *start)
printf("\n\n ** MAIN MENU {
printé("\n 1: Create a list”); struct node *new_node, *ptr;
printf("\n Display the list”); int num;
printf("\n Add a node at the printf("\n Enter -1 to end”
beginning’ printf("\n Enter the data :
printf("\n Add a node at the end”);
printf("\n 5: Add a node before a given
node”);
printf("\n 6: Add a node after a given new_node = (struct node*)
node”); malloc(sizeof(struct node));
printf("\n 7: Delete a node from the new_node -> datasnum;
beginning”); if (start==NULL)
printf("\n 8: Delete a node from the {
end”); new_node -> next = NULL;
printf("\n Delete a given node”); start = new_node;
printf("\n 10: Delete a node after a given }
node”); else
printf("\n 11: Delete the entire list”); {
printf("\n 12: Sort the list”); ptrestart;
printf("\n 13: EXIT”); while(ptr->next!=NULL)
printf("\n\n Enter your option : "); ptr=ptr-onext;
scanf("Xd", &option); ptr-onext = new_node;
switch(option) new_node~>next=NULL;
{ }
case 1: start = create_11(start); printf("\n Enter the data : ");
printf("\n LINKED LIST CREATED”); scanf("%d", &num);
break; }
case 2: start = display(start); return start;
break;
Computer Fundamentals and Programming in C

struct node *display(struct node *start) ptr = ptr -> next;


{ }
struct node *ptr; preptr -> next = new_node;
ptr = start; new_node -> next = ptr;
while(ptr != NULL) return start;
{ }
printf("\t %d”, ptr -> data); struct node *insert_after(struct node *start)
ptr = ptr -> next; {
} struct node *new_node, *ptr, *preptr;
return start; int num, val;
} printf("\n Enter the data : ");
struct node *insert_beg(struct node *start) scanf("%d", &num);
{ printf("\n Enter the value after which the
struct node *new_node; data has to be inserted : ");
int num; scanf("%d", &val);
printf("\n Enter the data : new_node = (struct node *)
scanf("Xd", &num); malloc(sizeof(struct node));
new_node = (struct node *) new_node -> data = num;
malloc(sizeof(struct node)); ptr = start;
new_node -> data = num; preptr = ptr;
new_node -> next = start; while(preptr -> data != val)
start = new_node; {
return start; preptr = ptr;
} ptr = ptr -> next;
struct node *insert_end(struct node *start) }
{ preptr -> nextenew_node;
struct node *ptr, *new_node; new_node -> next = ptr;
int num; return start;
printf("\n Enter the data : }
scanf("xd", &num) ; struct node *delete_beg(struct node *start)
new_node = (struct node *) {
malloc(sizeof(struct node)); struct node *ptr;
new_node -> data » num; ptr «= start;
new_node -> next * NULL; start = start -> next;
ptr = start; free(ptr);
while(ptr -> next I= NULL) return start;
ptr = ptr => next; }
ptr -> next = new_node; struct node *delete_end(struct node *start)
return start; {
} struct node “ptr, *preptr;
struct node *insert_before(struct node *start) ptr = start;
{ while(ptr -> next != NULL)
struct node *new_node, ‘ptr, *preptr; {
int num, val; preptr = ptr;
printf("\n Enter the data : “); ptr = ptr -> next;
scanf("Xd", &num); }
printf("\n Enter the value before which the preptr -> next = NULL;
data has to be inserted : “); free(ptr);
scanf("¥d", &val); return start;
new_node = (struct node *) }
malloc(sizeof (struct node)); struct node *delete_node(struct node *start)
new_node -> data = num; {
ptr = start; struct node *ptr, *preptr;
while(ptr -> data I= val) int val;
{ printf("\n Enter the value of the node which
preptr = ptr; has to be deleted : ");
Introduction to Data Structures: 471

scanf("%d", &val); int temp;


ptr = start; ptr = start;
if(ptr -> data == val) while(ptri -> next != NULL)
{ {
start = delete_beg(start); ptr2 = ptri -> next;
return start; while(ptr2 t= NULL)
} {
else if(ptri -> data > ptr2 -> data)
{ {
while(ptr -> data t= val) temp = ptri -> data;
{ ptr -> data « ptr2 -> data;
preptr = ptr; ptr2 -> data = temp;
ptr = ptr => next; }
} ptr2 = ptr2 -> next;
preptr => next = ptr -> next; }
free(ptr); ptrl = ptrl -> next;
return start; }
} return start;
} }
struct node *delete_after(struct node *start)
Output
{
struct node *ptr, *preptr; ++ e+ eMAIN MENU # #68
int val; 1: Create a list
printf("\n Enter the value after which the 2: Display the list
node has to deleted : "); 3: Add a node at the beginning
scanf("xd", &val); 4: Add the node at the end
ptr = start; 5S: Add the node before a given node
preptr = ptr; 6: Add the node after a given node
while(preptr -> data l= val) 7: Delete a node from the beginning
{ 8: Delete a node from the end
preptr © ptr; 9: Delete a given node
ptr « ptr -> next; 10: Delete a node after a given node
} 11: Delete the entire list
preptr -> nexteptr -> next; 12: Sort the list
free(ptr); 13: Exit
return start; Enter your option : 3
} Enter your option : 73
struct node *delete_list(struct node *start)
{
struct node *ptr; STACKS
if(start!eNULL){
ptrestart; Stack is an important data structure which stores its
while(pte t= NULL) clements in an ordered manner. We will explain the
{ concept of stacks using an analogy. You must have seen a
printf("\n Xd is to be deleted next”, pile of plates where one plate is placed on top of the other,
ptr -> data); as shown in Figure 18.22. Now, whenever you want to
start = delete_beg(ptr);
ptr = start;
Another plate The top most
} will be plate will be
added on top removed first
of this plate
return start;
}
struct node *sort_list(struct node *start)
{
struct node *ptri, *ptr2; Figure 18.22 Stack of plates
472 Computer Fundamentals and Programming in C

== When A calls B. A is pushed on When B calls C. B is pushed on top of the


—— top of the system stack When the system stack. When the execution ofCis
—— execution of B is complete, the complete, the system control will remove B
=a system control will remove A from the stack and continue with its execution.
from the stack and continue with
FunctionA) its execution.
— When C calls D_ C is pushed on When D calls E, D is pushed on top of the system
[_____] __‘0p of the system stack. When the stack. When the execution of E is complete,
‘une! execution of D is complete. the the system control will remove D from the
Function BB} _*¥Stem control will remove C
Function B) stack and continue with its execution.
FunctionA} ftom the stack and continue with
its execution.

remove a plate, you will remove the topmost plate first.


Hence, you can add and remove an clement (plate) only at When E has executed,
from one position, that is, the topmost position D will be removed for
A stack is a lincar data structure which uses the same execution,
principle, that is, the elements in a stack are added and
removed only from one end, which is called sop, Hence,
a stack is called a last in, first out (LIFO) data structure
as the clement that is inserted last is the first one to be
taken out ‘When D has executed,
Now the question is, where do we need stacks in C will be removed for
computer science? The answer to this question is, in execution.
function calls. Consider an example, where we are
executing function A. In the course of its execution,
function A calls another function B. Now, function B calls
another function C, which in turn calls function D. Finally, ‘When C has executed,
function D calls another function E B will be removed
In order to keep track of the returning point of cach for execution,
active function, a special stack called system stack or call
stack is used. Whenever a function calls another function,
the calling function is pushed on to the topofthe stack. This When B has executed,
is because after the called function gets executed, control A will be removed
will be passed back to the calling function. Figure 18.23 for execution.
depicts this concept Figure 18.24 System stack when a called function returns
Now, when function E is executed, function D will to the calling function
be removed from the top of the stack and executed.
Once function D gets completely executed, function
TOP is used to store the address of the topmost clement of
C will be removed from the stack for execution. The the stack. It is this position from where the clement will
whole procedure will be repeated until all the functions
be added or deleted. There is another variable, MAX, which
get executed completely. Let us see the stack after each
will be used to store the maximum number of elements
function is executed. This is shown in Figure 18.24
that the stack can hold.
Thus, system stacks ensure a proper execution order
If TOP = NULL, then it indicates that the stack is empty,
of functions. Therefore, stacks are frequently used in
and if TOP = MAX - 1, then the stack is full. (You must be
situations where the order of processing of data is very
wondering why we have written MAX - 1. Do not forget
important, especially when the processing needs to be
that array indices start from 0.) Refer to Figure 18.25.
postponed until other conditions are fulfilled
The stack in Figure 18.25 shows that TOP = 4, so
Stacks can be implemented using both arrays and linked
insertions and deletions will be done at this position. In
lists. In this chapter, we will discuss array implementation
this stack, five more elements can still be stored
of stacks,

Array Representation of Stacks


In computer memory, stacks can be represented as a linear
(a [a senevend [TT |
3 TOP=4 5 6

array. Every stack has a variable TOP associated with it Figure 18.25 An example of a stack
Introduction to Data Structures 473

18.5.1 Operations on Stacks


A stack supports three basic operations: push, pop, and
et 2 3TOP=4 5
A 6 7 8 .
peek. The push operation adds an clement to the top of the Figure 18.29 An example of a stack
stack, and the pop operation removes an clement from the
top of the stack. The peek operation retums the value of To delete the topmost element, we will first check
the topmost element of the stack if TOP = NULL. If the condition is false, then we will
Push operation The push operation is used to insert an decrement the value of Top, Thus, the updated stack
element into the stack. The new clement is added at the becomes as shown in Figure 18.30.
topmost position of the stack. However, before inserting
the value, we must first check if TOP = MAX - 1, as it would
mean that the stack is full and no further insertions can be
ss 2 TOP=3 4 5 6 él 8 9
done, If an attempt is made to insert a value in a stack that Figure 18.30 Stack after deletion
is already full, an OVERFLOW message is printed. Consider
the stack shown in Figure 18,26. Figure 18.31 shows the algorithm to delete an clement
from the stack. In step |, we first check for the UNDERFLOW

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

3 4 TOP=5 6 7 5s 9 Figure 18.31 Algorithm to pop an element from the stack


Figure 18.27 Stack after insertion Peek operation Peck is an operation that returns the value
of the topmost clement of the stack without deleting it
Figure 18.28 shows the algorithm to insert an clement
from the stack. The algorithm for the peck operation is
in the stack. In step 1, we first check for the OVERFLOW
given in Figure 18.32
condition, In step 2, TOP is incremented, so that it points
to the next free location in the array. In step 3, the value is
Step 1: IF TOP = NULL, then
stored in the stack at the location pointed by Top.
WRITE “STACK IS EMPTY”
Go TO Step 3
Step 1: IF TOP = MAX -1, then
{ENO OF IF}
WRITE “OVERFLOW” Step 2: RETURN STACK{TOP]
Go to Step 4 Step 3: EXIT
[ENO OF IF}
Figure 18.32 Algorithm for peek operation
Step 2: SET TOP = TOP + 1
Step 3: SET STACK[TOP] = VALUE The peck operation first checks if the stack is empty
Step 4: EXIT or if it contains some elements. For this, a condition is
checked. If TOP = NULL, then an appropriate message is
Figure 18.28 Algorithm to push an element in a stack printed; else, the value is returned. Consider the stack
Pop operation The pop operation is used to delete given in Figure 18.33
the topmost clement from the stack. However, before
deleting the valuc, we must first check if TOP = NULL,
as it would mean that the stack is empty and therefore
aS 2 3 TOP=4 5 6 7 8 9
no further deletions can be done. If an attempt is made Figure 18.33 An example of a stack
to delete a value from a stack that is already empty, an
UNDERFLOW message is printed. Consider the stack given in Here, the peck operation will return 5, as it is the value
Figure 18,29 of the topmost clement of the stack.
474 Computer Fundamentals and Programming in C

2. Write a program to perform Push, Pop, and Peek if(top == MAX-1)


operations on a stack. {
printf("\n STACK OVERFLOW");
Solution }
#include <stdio.h> else
#include <stdlib.h> {
#include <conio.h> tope+;
#define MAX 3 st[top] = val;
}
int st[{MAX], top=-1; }
void push(int st[], int val); int pop(int st[])
int pop(int st{]); {
int peek(int st[}); int val;
void display(int st(]); if(top == -1)
{
int main() { printf("\n STACK UNDERFLOW");
int val, option; return -1;
do }
{ else
printf("\n ***MAIN MENU** {
printf("\n 1. PUSH"); val = st[top];
printf("\n 2. POP"); top--;
printf("\n 3. PEEK"); return val;
4. DISPLAY");
printf("\n 4. }
printf("\n s. EXIT"); }
printf("\n Enter your option: "); void display(int st[]})
scanf("Xd", &option); {
switch(option) int i;
{
if(top «= -1)
case 1:
printf("\n STACK IS EMPTY");
else
printf("\n Enter the number to be pushed
on stack: "); {
scanf("%d", &val);
for(istop;i>=0;1--)
push(st, val);
printf("\n Xd",st[{i});
printf(*\n");
break;
case 2: }
val = pop(st); }
int peek(int st{])
if(val != -1)
printf("\n The value deleted from stack {
if(top == -1)
is: %d", val);
break; {
printf("\n STACK IS EMPTY");
case 3:
return ~1;
val = peek(st);
}
if(val != -1) else
printf("\n The value stored at top of return (st{top]);
stack is; %d", val);
}
break;
case 4: Output
display(st); #****MAIN MENU*# eee
break; 1. PUSH
} 2. POP
}while(option != 5); 3. PEEK
return 0; 4. DISPLAY
} S. EXIT
void push(int st[], int val) Enter your option : 1
{ Enter the number to be pushed on stack : 500
Introduction to Data Structures 475

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

#define MAX 10 reart+;


int queue[MAX]; queve[rear] = num;
int front = -1, rear = -1; }
void insert(void); int delete_element()
int delete_element(void); {
int peek(void); int val;
void display(void); if(front == -1 || frontorear)
int main() {
{ printf("\n UNDERFLOW’) ;
int option, val; return -1;
do }
{ else
printf("\n\n ***** MAIN MENU ***ee {
printf("\n 1. Insert an element”) val = queve[front};
printf("\n 2. Delete an element”); front++;
printf("\n 3. Peek”); if(front > rear)
print#("\n 4. Display the queue”); front = rear = -1;
printf("\n 5. EXIT”); return val;
print#("\n Enter your option : “);
scanf("Xd", &option); }
switch(option) int peek()
{ {
case if(front==-1 || frontorear)
insert(); {
break; peintf("\n QUEUE IS EMPTY”);
case return -1;
val = delete_element(); }
if (val I= -1) else
printf("\n The number deleted is : Xd", {
val); return queve[front];
break; }
case 3: }
val » peek(); void display()
if (val Ie -1) {
print#("\n The first value in queue is : int i;
Xd”, val); printf("\n");
break; if(front == -1 || front > rear)
case 4: printf("\n QUEUE IS EMPTY”);
display(); else
break; {
} for(i = front;i <= rear;it+)
}while(option != 5); printf("\t Xd”, queve[i});
getch(); }
return 0; }
} Output
void insert()
{ sees MAIN MENU #406
int num; + Insert an element
printf("\n Enter the number to be inserted - Delete an element
in the queue : “); . Peek
scanf("Xd", &num); . Display the queue
if(rear == MAX-1) . iT
vawne
printf("\n OVERFLOW”); Enter your option : 1
else if(front == -1 — rear == -1) Enter the number to be inserted in the queue
front = rear = 0; : 50
else
Introduction to Data Structures 477

TREES Key Terms


* Parent; 1€N is any node in T that has left successor S, and
A tree is recursively defined as a set of one or more nodes right successor S», then N is called the parent of 5; and
where one node is designated as the root of the tree and S». Correspondingly, S; and S, are called the left child
all the remaining nodes can be partitioned into non-empty and the right child of N.Every node other than the root
sets each of which is a subtree of the root. In this chapter, node has a parent,
we will discuss binary trees in which each note has 0, 1, or * Level number: Every node in the binary tree is assigned
at the most 2 children. a level number (refer Fig. 18.40). The root node is
In a binary tree every node contains a ‘left’ pointer defined to be at level 0, The left and the right child of
which points to the left child, a ‘right’ pointer which the root node have a level number 1. Similarly, every
points to the right child, and a data element. The root node is at one level higher than its parents. So all child
element is the topmost node in the tree which is pointed nodes are defined to have level number as parent's level
by the root pointer. If root = NULL, it means that the tree number + 1
is empty.
Figure 18.39 shows a binary tree. In the figure, & is the
root node and the two trees T, and T, are called the left and
Level @) feetnods

“ @@
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

* Degree of a node: \t is equal to the number of children

©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

ELE EGS) GerFigure 18.41


x] u Ex] EK] 2 [x
Linked representation of a binary tree

¢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

Stina PREORDER(TREE->LEFT) Figure 18.46 Algorithm for post-order traversal


Step 4: PREORDER(
TREE ->RIGHT)
[END OF LOOP] Level-order traversal In level-order traversal, all the
Step 5: EXIT nodes at a level are accessed before going to the next
level. This algorithm is also called breadth-first traversal
Figure 18.44 Algorithm for pre-order traversal algorithm. Considering the tree given in Figure 18.43, the
level order of the tree can be given as: A, 8, and C.
In-order algorithm To traverse 4 non-empty binary
tree in in-order, the following operations are performed GRAPHS
recursively at cach node. The algorithm works by
* Traversing the left sub-tree A graph is a data structure that is used to implement the
* Visiting the root node mathematical concept of graphs, It is basically a collection
* Traversing the right sub-tree of vertices (also called nodes) and edges that connect these
Consider the tree given in Figure 18.43. The in-order vertices. A graph is often viewed as a generalization of the
traversal of the tree is given as 8, A, C; first the left sub- tree structure, where instead of ahaving a purely parent-to-
tree, second the root node, and then the right sub-tree child relationship between tree nodes, any kind of complex
In-order traversal is also called symmetric traversal. In relationships between the nodes can be represented.
this algorithm, the left sub-tree is always traversed before Graphs are widely used to model any situation where
the root node and the right sub-tree. The word ‘in’ in *in- entities or things are related to each other in pairs; for
order’ specifies that the root node is accessed in between example, the following information can be represented by
the left and right sub-trees. The in-order algorithm is also graphs:
known as LNR (Left-Node-Right) traversal algorithm. * Family trees in which the member nodes have an edge
The algorithm for in-order travel is shown in Figure 18.45. from parent to each of their children.
480 Computer Fundamentals and Programming in C

* 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

Figure 18.49 Adjacency matrix entry

Therefore, a change in the order of nodes will result in a


different adjacency matrix, Figure 18.50 shows a graph
and its corresponding adjacency matrix

ABCDE
o1010

|® Ol sreis D

Figure 18.51 Graph G and its adjacency list

lo CO) r}o ooo: struct node


m {
oo100
char vertex;
struct node *next;
Figure 18.50 Directed graph with adjacency matrix
i
struct node *gnode;
Adjacency list The adjacency list is another way in which void displayGraph(struct node *adj[], int no_
graphs can be represented in computer memory. This of _nodes);
structure consists of a list of all nodes in G. Furthermore, void deleteGraph(struct node *adj[], int no_
every node is in turn linked to its own list, which contains of_nodes);
the names of all other nodes that are adjacent to itself void createGraph(struct node *adj[]}, int no_
The key advantages of using an adjacency list include: of _nodes);
* Itis casy to follow, and clearly shows the adjacent nodes int main()
of a particular node {
* Itis often used for storing graphs that have a small to struct node *Adj[10);
moderate number of edges, That is, an adjacency list int i, no_of_nodes;
is preferred for representing sparse graphs in computer clrscr();
memory. Otherwise, an adjacency matrix is a good printf("\n Enter the number of nodes in G:

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

{ ptr = ptr -> next;


last = NULL; }
printf("\n Enter the number of neighbours
of Xd: ", i); }
scanf("Xd", &n); void deleteGraph (struct node *Adj[], int
for(j = 1; j <= nj j++) no_of_nodes)
{ {
printf("\n Enter the neighbour %d of %d: int i;
", J, i)5 struct node *temp, *ptr;
scanf("%d", &val); for(i = 0; i <= no_of_nodes; i++)
new_node = (struct node *) |
malloc(sizeof(struct node)); ptr = Adj(i];
new_node -> vertex « val; while(ptr | = NULL)
new_node -> next = NULL; {
if (Adj[i] == NULL) temp = ptr;
Adj[i] = new_node; ptr = ptr -> next;
else free(temp);
last -> next = new_node; }
last = new_node Adj[i] = NULL;
} }
} }
} Output
void displayGraph (struct node *Adj[], int
no_of_nodes) Enter the number of nodes in G; 3
Enter the number of neighbours of 0: 1
struct node *ptr; Enter the neighbour 1 of 0: 2
int 4; Enter the number of neighbours of 1: 2
for(i = 0; i < no_of_nodes; i++) Enter the neighbour 1 of 1: 0
{ Enter the neighbour 2 of 1: 2
ptr = Adj[i); Enter the number of neighbours of 2: 1
printf("\n The neighbours of node Xd Enter the neighbour 1 of 2: 1
are:", i); The neighbours of node 0 are: 1
while(ptr t* NULL) The neighbours of node 1 are: 0 2
{ The neighbours of node 2 are: 0
printf("\tkd", ptr -> vertex);

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

State True or False


* Delete two letters
1. Alinked list is a linear collection of data elements.
* AddG
2. Alinked list can grow and shrink during run-time.
* Addi
3. A node in a linked list can point to only one node at a
time. © Delete four letters
4, Anode ina singly linked list can reference the previous ° Add I
node 8. Consider the following queue which has FRONT = 1 and
5, Alinked list can store only integer values. REAR = 5S
6. A linked list is a random access structure.
7. Every node in a linked list contains an integer part and a
pointer. Now perform the following operations on the queue
8, START stores the address of the first node in the list * AddF
9, Underflow is a condition that occurs when we try to * Delete two letters
delete a node from a linked list that is empty.
*° AddG
10, A queue stores elements in manner such that the first
element is at the beginning of the list and the last * Add H
element is at the end of the list * Delete four letters
11, Pop() is used to add an element on the top of the stack. * AddI
12. Nodes that branch into child nodes are called parent 9. Explain the concept of trees. Give its applications.
nodes. 10. How many binary trees are possible with four nodes?
13, The size of the tree is the number of nodes in the tree. 11. Is it possible to implement binary trees using linear
14. Aleaf node does not branch out further. arrays? If yes, explain how?
15, Anode that has no successors is called the root node. 12. What are the two ways of representing binary trees in
16, A binary tree of n nodes has exactly n - 1 edges. memory? Which one do you prefer, and why?
17. Every node has a parent 13. Consider the following tree.Now perform the following
18, Graph is a linear data structure. actions:
19. In-degree of a node is the number of edges leaving that

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.

23. Consider the graph given in the previous question and


show the changes in the graph as well as its adjacency
list when node E and edges (A, E) and (C, E) are added to
it. Also, delete edge (B, D) from the graph
24. Given five cities, (a) New Delhi, (b) Mumbai, (c) Chennai,
(d) Bangalore, and (e) Kolkata, a list of flights that
connect these cities is given below. Use the given
information to construct a graph
Flight Number | __ ORIG DEST
101 | b ¢
@) (>) (0) Gr) (2)
y —/ y Vy 102 € b
Introduction to Data Structures 487

[ 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

l ow | « | « values in a linked list that stores integer values.


17. Write a program to interchange the value of the first
10 d e element with the last element, second element with
second last element, and so on, of a doubly linked list
Programming Exercises 18. Write a program to make the first element of singly
1 Write a program to calculate the number of items in a linked list, the last element of the list
queue. 19. Write a program to count the number of occurrences of
Write a program that removes all nodes that have a given value in alinked list
duplicate information. 20. Write a program to form a linked list of integer values,
Write a program to print the total number of occurrences Calculate the sum of integers and then display the
of agiven item in a linked list average of the numbers in the list
. Write a program to multiply every element of a linked 21 Write a program to delete the k™ node from a linked list
list with 10. 22 Write a program to multiply a polynomial with a given
Write a program to print the number of non-zero number,
elements in a linked list. 23. Write a program that creates a singly linked list. Use a
Write a program that prints whether a given linked list is function isSorted() that returns 1 if the list is sorted
sorted (in ascending order) or not. and 0 otherwise.
. Write a program to merge two linked lists 24, Write a program to implement a stack using a linked list.
Form a linked list to store students’ details. Then insert How is a linked stack better than a linear stack? Do we
the record of a new student in the list. Also delete the have underflow and overflow situations in a linked
record of a student with a specified roll number. stack?
Write a program to merge two sorted linked lists. The 25. Write a program to implement a simple queue.
resultant list must also be sorted 26. Write a program to implement a stack that stores names
10 Write a program to create a linked list from an already of students in the class
given list. The new linked list must contain every 27, Write a program to create a queue from a stack.
alternate element of the existing linked list. 28. Write a program to create a stack from a queue.
il You are given a linked list that contains letters from English 29. Write a program to reverse the elements of a queue.
alphabet. The letters may be in upper case or lower case. 30. Write a program to input two queues and compare their
Create two linked lists—one which stores upper case contents.
letters and the other that stores lower case letters.
31 Write a program to input two stacks and compare their
12. Write a program to contents.
a. Delete the first occurrence of a given character in a 32 Write a function that accepts two stacks. Copy the
linked list. contents of the first stack into the second stack, Note
b. Delete the last occurrence of a given character. that the order of elements must be preserved. (Hint
c. Delete all the occurrences of a given character. Use a temporary stack.)
B Write a program to reverse a linked list using recursion. 33. Write a program to create and print a graph.
twise Operations

1010 * 0011 = 1001


BIT LEVEL PROGRAMMING * A bitwise AND (&) takes two bit patterns of equal
A C programmer usually does not need to care about length and performs the logical AND operation on each
operationsatthe bitlevel. He has to think only intermsof pair of corresponding bits. In each pair, the resultant bit
int and double, or even higher level data types composed is set to 1 if the first bit is 1 and the second bit is 1.
Otherwise, it is set to 0. For example:
of a combination of these. However, at times it becomes
necessary to go to the level of an individual bit. For 1010 & 0011 = 0010
example, in case of exclusive OR (XOR) encryption or The bitwise AND is commonly used to perform bit
when dealing with data compression, a programmer needs masking. This is done to isolate part of a string of bits,
to operate on individual bits of the data and thus needs to or to determine whether a particular bit is 1 or 0. For
do programming at the bit level. Moreover, bit operations example, to determine if the second bit is 1, you can
can be used to speed up your program. straightaway do a bitwise AND to it and another bit
pattern containing | in the second bit. For example,
Thinking About Bits 1010 & 0010 = 0010

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

_ The general form of an arithmetic right shift can be


given as op >> n. Have you wondered what will happen if you shift a
Here, op is an integer expression that has to be shifted number like 128 and store it in a single byte: 10000000?
and n is the number of bit positions to be shifted. For Since, 128 = 2 = 256, and a register is incapable ofstoring
example, if we write a number that is bigger than a single byte, so it should not
unsigned int x = 11000101; be surprising that the result is 00000000.

nal dit
ANSI C Library Functions

<ctype.h> ERANGE // code used for range


int isalnum(int // to check if c is an Kasei A
©)3 alphabet or a digit <limits .h>
int isalpha(int // to check if ¢ is an CHAR_BIT // Specifies the number of
©)5 alphabet bits in a char
int isentrl(int // to check if c isa CHAR _MAX // Specifies the maximum
c); control character value of type char
int isdigit(int // to check if cis a CHAR_MIN // Specifies the minimum
©) decimal digit value of type char
int isgraph(int // to check if c is a SCHAR_MAX // Specifies the maximum
©); printing character other value of type signed char
hi
RB SCHAR_MIN // Specifies the minimum
int islower(int // to check if c is a value of type signed char
c); lower-case character
UCHAR_MAX // Specifies the maximum
int isprint(int // to check if c is value of type unsigned char
©)5 a printing character r |
including space
SHRT_MAX // Specifies the maximum
value of type short
int ispunct(int // to check if c is a
ate printing character other SHRT_MIN // Specifies the minimum
than space, letter, or value of type short
| digit USHRT_MAX // Specifies the maximum
int isspace(int // to check is c if a value of type unsigned
©)3 space, formfeed, newline, —— short -
carriage return, tab, or INT_MAX // Specifies the maximum
vertical tab value of type int

int isupper(int // to check if ¢ is an INT_MIN // Specifies the minimum


©)3 upper-case character value of type int
int isxdigit(int // to check if c isa UINT MAX // Specifies the maximum
3 |
hexadecimal digit | value of type unsigned int
int tolower(int // to convert ¢ into its LONG_MAX // Specifies the maximum
OH lower-case equivalent value of type long
int toupper(int // to convert c into its LONG_MIN // Specifies the minimum
©)5 _| upper-case equivalent value of type long
serreoshy ULONG_MAX // Specifies the maximum
errno // object to which certain value of type unsigned
library functions assign long
specific positive values
when an error occurs cath,b>
EDOM // code used for domain double exp(double | // Calculates the
errors x)5 exponential value of x
ANSI C Library Functions 491

double 1og(double 7 Calculates the natural size_t // Specifies the type for
x); logarithm of x objects declared to store

double logi0(double | // Calculates the base-10 the result of the sizeof


x)3 logarithm of x operator
double pow(double // Calculates the value of <stdio.h>
x, double
y); x raised to power y BUFSIZ // Specifies the size of
double sqrt(double // Calculates the square the buffer used by setbuf |
x); root of x EOF // Indicates the end-of- |
double ceil(double // Calculates the smallest stream or an error
x)5 | integer_not_less FILENAME_MAX // Specifies the maximum
than x | length of characters to
hold a filename
double floor(double | // Calculates the largest —
x)5 [integer not greater than x FOPEN_MAX // Specifies the maximum
no. of files you can open
double fabs(double // Calculates the absolute
simultaneously |
x); value of x
L_tmpnam // Specifies the no. of
double ldexp(double |// Calculates the x times characters required for a
x, int n); 2 to the power n
temporary filename |
double fmod(double // If y is non-zero, | NULL // Specifies the null |
x, double y); floating-point remainder of pointer constant |
x/y, with the same sign as
‘SEEK_CUR // Used in fseek() for
x is returned, else the
result is implementation- specifying the current file
defined position |

double sin(double // Calculates the sine of


SEEK_END // Used in fseek() for |
specifying the end of file |
x)3 x
double cos(double = // Calculates the cosine
SEEK_SET // Used in fseek() for
x); of x
specifying the beginning
of a file |
double tan(double // Calculates the tangent ~ ee |
TMP _MAX // Specifies the minimum
x); of x
no. of unique filenames
double asin(double // Calculates the arc-sine | generated |
x)3 of x
// Used in setvbuf() for
double acos(double // Calculates the arc- | specifying full buffering
*)5 cosine of x // Used in setvbuf() for
double atan(double | // Calculates the arc- | specifying line buffering |
x) tangent of x
_TONBF // Used in setvbuf() for
double atan2(double |// Calculates the arc- | specifying no buffering |
Y, double x); tangent of y/x stdin // Specifies the file
double sinh(double // Calculates the pointer for standard input
x)3 hyperbolic sine of x stream. Automatically
double cosh(double // Calculates the opened when program
x)i hyperbolic cosine of x [execution begins. |
double tanh(double // Calculates the stdout // Specifies the file

x)3 hyperbolic tangent of x pointer for standard


output stream,
<stddef.h>
Automatically opened when
NULL // Specifies the null | program execution begins. |
pointer constant stderr // Specifies the file
offsetof(stype, m) // gives the offset (in pointer for standard error
bytes) of member m from stream. Automatically
start of structure type opened when program
| stype. execution begins.
492 Computer Fundamentals and Programming in C

FILE // Specifies the type of ‘FILE* tmpfile(); |/ To create a temporary file |


object holding information (mode “wb+") which will be
necessary to control a removed when closed or on
| stream normal program termination.
fpos_t // Specifies the type The function returns stream
for objects declared or NULL on failure. |
to store file position int setvbuf(FILE* // To control buffering
information stream, char* buf, for stream. mode can be
int mode, size_t _IOFBF, _IOLBF or _IONBF.
size_t // Specifies the type for
size); The function returns
objects declared to store
non-zero value on error.
result of sizeof operator
However, the function must
FILE* fopen(const // To open a file filename. be called before any other
char* filename, It returns a stream, or operation on the stream. |
const char* mode); NULL on failure. mode may void setbuf(FILE* // To control buffering
be one of the following stream, chare for stream. For null buf,
for text files~ r: reading, buf); turns off buffering,
w: writing, a: append, otherwise it is equivalent
re: update (reading and to (void)setvbuf(stream,
writing), we: update, [buf, OFF, BUFSIZ).
discarding previous int fprintf(FILE* // To convert (according
content (if any), a+: stream, const to format) and writes
append, reading, and char* format, output to stream, Returns
writing at end or one ooeds either the no. of
of those strings with b characters written, or
included (after the first negative value on error.
character), for binary int printf(const // peintf(f, ...)
files. char* format, is equivalent to
FILE* freopen(const | // To close a file seedy fprintf(stdout, f, )
char* filename, associated with stream,
int sprintf(char* | // The function is same as |
const char* mode, then opens file filename s, const char* fprintf, but the output is
FILE* stream); with specified mode and format, ...); written into string s, which
associates it with must be large enough to hold
stream, It either returns
the output. It terminates
stream or NULL in case of
the string with ‘\0’ and |
failure.
returns length of s
int fflush(FILE* // To flush the stream. It
Tint vfprintf(FILE* // Same as fprinté but with
stream); returns zero on success or stream, const variable argument list
EOF on error. Note that char* format, va_ replaced by arg, which must
fflush(NULL) flushes all list arg); have been initialised by |
i 7 - output streams.
int fclose(FILE* // To close the stream
the va_start macro
int vprintf(const // Same as printf but
stream); (also flushes it if it is an
char* format, va_ with variable argument
0/P stream). Returns EOF on list arg); list replaced by arg,
error, zero otherwise. which must have been
int remove(const // To remove the specified initialised by the va_
chare filename) ; file. Returns non-zero on start macro |
failure. int vsprintf(char* // Same as sprintf but with
int rename (const // To change name of file S, const char* variable argument list
chare oldname, oldname to newname. Returns format, va_list replaced by arg, which must
const char* zero on success and a non- arg); have been initialised by
newname
); zero value on failure. the va_start macro |
ANSI C Library Functions 493

int fscanf(FILE* // To perform formatted int putchar(int // Same as pute(c, stdout)


stream, const input conversion, reading ©)5
char* format, from stream according int puts(const // To write s (excluding
wwe)y to the specified format. char* s); terminating NUL) and a
The function returns no. newline to stdout. Returns
of items converted and a non-negative value on
assigned, or EOF if end- success or EOF on error.
of-file or error occurs a |
int ungetc(int c, // To push c (which must
before any conversion. FILE* stream); not be EOF), onto the
int scanf(const // scanf(f, ...) is same input stream such that it
char* format, as fscanf(stdin, f, ...) will be returned by the
usa)s next read. Returns ¢ or
int sscanf(char* // Same as fscanf but EOF on error.
Ss, const char* input is read from string size_t fread(void* // To read (at most) nobj
format, ...)5 s. ptr, size_t size, objects of size size from
int fgetc(FILE* // Used to return next size_t nobj, FILE* stream stream into ptr and |
stream); character from (input) stream! returns number of objects
stream or an EOF on end- read. |
T 1
of-file or error. size_t fwrite(const // To write to stream

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

char* getenv(const | // Returns string char* strcat(char* |// Concatenates ct to s


char* name); associated with name name s, const chare | and returns s
from implementation’s ct); |
environment, or NULL if no char* | // To concatenate at most
_ _ __|such string exists strncat(char* s, n characters of ct to s.
void* bsearch(const | // To search a sorted array const char* ct, Appends a ‘\O’ character
void* key, const base (of n objects each size_t n); |to sand returns it.
voids base, size_t | of size size) for item
int stremp(const | // To compare cs with
n, size_t size, int matching key according to
char* cs, const ct, returning negative
(*cmp) (const void comparison function cmp. char* ct); | value if cs < ct, zero if
keyval, const cmp must return negative
cs==ct, positive value if
void* datum)); value if first argument
is less than second, zero
if equal and positive if int strnemp(const |// To compare the first
greater. The function char* cs, const n characters of cs and
either returns a pointer chare ct, size_t ct, returning negative
to an item matching key if 9)5 value if cs < ct, zero if
successful or returns NULL |csmact, positive value if
| if a match is not found. jes > ct.

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

size_t n); than n then appends a jis found


‘0° character to s and size_t strlen(const | // To return the length of
_| returns Ss. char* cs); les
496 Computer Fundamentals and Programming in C

char* strerror(int // To return a pointer _<time.h>


;
n)5 to implementation- CLOCKS_PER_SEC // Specifies the number of
defined message string clock_t units per second
corresponding with clock_t | // Specifies an arithmetic
error n.
type elapsed processor
char *strtok(char // The strtok function representing time
*stri, const char is used to isolate
time_t // Specifies an arithmetic
*delimiter); sequential tokens in a
type representing calendar
null-terminated string, | time
str. These tokens are +
separated in the string struct te | // Specifies the components
using delimiters. The [of calendar time: —
first time that strtok int tm_sec; // Gives seconds after the
is called, str should +
minute
be specified; subsequent int tm_min; | // Gives minutes after the
calls, wishing to obtain [hour |
further tokens from the <time.h>
same string, should pass
int tm_hour; 1/7 Gives hours since
a null pointer instead.
However, the delimiter
‘int tm_mday; // Gives the day of the
must be supplied each
month
time, though it may change
between calls.
int tm_mon; | // Gives months since
| January
size_t // To store in s no
int tm year; |// Gives years since 1900
strxfrm(char* s, more than n characters
const char* ct, (including ‘\0’) of a int tm wday;_ _|// Gives days since Sunday
size_t n); string produced from ct int tm_yday; // Gives days since
according to a locale-
[January 1
specific transformation. int tm_isdst // Specifies the Daylight
Returns length of entire |Saving Time flag. It is
transformed string. positive if DST is in

[voids memcpy(void+ /1 To copy n characters


jeffect, zero
effect, negative if
if not in

S, const void« ct, from ct to s and returns


| information is not known.
size_t n); s. In case of object
overlap, s may be
clock_t // Returns elapsed
corrupted. clock(void); processor time used by
program or -1 if not
void* // To copy n characters | available
memmove(void* s, from ct to s and returns
time_t | // Returns current
const void* ct, s. Inc case of object
time(time_t* tp); | calendar time or -1 if
size_t n); overlap, s will not be
not available. If tp +
corrupted.
NULL, return value is also
int mememp(const // To compare at most the | assigned to *tp.
void* cs, const first n characters of cs
double | // Returns the difference
void* ct, size_t and ct, returning negative difftime(time_t in seconds between time2
")3 value if cs < ct, zero if
time2, time_t and timel
cs == ct, positive value
time1);
—— +
if cs > ct.
char* asctime(const | // Returns the given
void* memchr(const // To return a pointer to struct tme tp); time as a string of the
void* cs, int c, first occurrence of c in form: Sun Jan 3 13:08:42
size_t n); first n characters of cs, 1988\n\0
or NULL if not found.
char* ctime(const | // Returns string
void* memset(void+ // To replace each of the time_t* tp); equivalent to calendar
s, int c, size_t first n characters of s by time tp converted to local
n)3 c and return s | time
ANSI C Library Functions 497

struct tm // Returns calendar size_t // Formats *tp into


emtime(const time *tp converted to strftime(char* s, Ss according to fmt.
time_t* tp); Coordinated Universal size_t smax, const Places no more than
Time, or NULL if not char* fmt, const smax characters into s,
| available struct tm tp); and returns either no.
struct tm+ // Returns calendar time of characters produced
localtime(const *tp converted into local (excluding ‘\0"), or 0 if
time_t* tp); | time greater than smax. |
. — 4

rw Advanced Type Qualifiers


~— >.“and Inline Functions in C
Now, the compiler will not optimize the loop and the
VOLATILE AND RESTRICT TYPE system will detect the change when it occurs. The volatile
QUALIFIERS keyword is basically used to allow access to memory-
mapped devices and makes use of variables in signal
handlers,
Type Qualifier: Volatile
In C, a variable or object declared with the volatile Points to remember
keyword will not be optimized by the compiler because * C permits declaration and definition of a volatile or
the compiler must assume that their values can change at const function only if it is anon-static member function
any time. C permits declaration and definition of a function that
For example, consider the code given below. Here, the retums a pointer to a volatile or const function,
value stored in WAIT is 0, It then starts to poll that value * An object can be both const and volatile. Such
repeatedly until it changes to 255. an object cannot be legitimately modified by its own
static int WAIT; program but can be modified by some asynchronous
void func (void) process.
{ If you put more than one qualificr on a declaration, then
WAIT = 0; the compiler will ignore duplicate type qualifiers
while (WAIT f= 255); * The volatile keyword indicates to the compiler that
} a variable may be modified outside the scope of the
program. A volatile variable is normally used in
An optimizing compiler will observe that no other code multitasking (threading) systems, when writing drivers
is changing the value stored in WAIT, and therefore assumes with interrupt service routines, or in embedded systems,
that it will remain equal to 0 at all times, The compiler will where the peripheral registers may also be modified by
then replace the function body with an infinite loop similar hardware alone.
to the one that follows: + When you use the volatile keyword, your program
void func_optimized(void) will run slower, because of the extra read operations
{ Also the program will be larger since the compiler is not
foo « 0; allowed to optimize as thoroughly
while (true);
} When to use the volatile keyword?
However, func might represent 4 location that can be A variable must be declared using the volatile type
changed by other clements of the computer system at qualifier when.
any time (for example, a hardware register of a device * a variable is used in more than one context
connected to the CPU), The above code would never * a common variable is used in more than one task or
detect such a change. So when the volatile keyword is thread
used, the compiler assumes that the current program is the * avariable is used both in a task and one or more interrupt
only part of the system that could change the value. The service routines
declaration of WAIT must therefore be modified as + a variable corresponds to processor-internal registers
static volatile int WAIT; configured as input
void bar (void)
{ Type Qualifier: Restrict
WAIT = 0; The restrict type qualifier may only be applied to a
while (WAIT |= 255); pointer. A pointer declaration with the restrict keyword
establishes a special association between the pointer and
Advanced Type Qualifiers and Inline Functions in C 99

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.

The restrict qualifier and aliasing pr


The restrict qualifier addresses the issue that potential Look at the following inline function which returns the
aliasing can inhibit optimizations. Specifically, if a greatest of two integer values.
compiler is unable to determine that two different pointers inline int large(int x, int y)
are referencing different objects, then it cannot apply {
optimizations such as maintaining the values of the objects return ((x > y) ? x : y)5
in registers other than in memory, or reordering loads and }
stores of these values,
The restrict qualifier usually extends two types of The function may be called in the same way as an ordinary
aliasing information already specified in the language. function is called. The statement given below demonstrates
how an inline function can be called.
+ First, ifa single pointer isdirectly assigned the retum value
from an invocation of malloc, then that pointer is the only inta=7, b= 9;
way of accessing the allocated object (i.¢., another pointer int big = large(a, b);
can access that object only by being assigned a value that Look at another inline function which is used to add two
is based on the value of the first pointer). integer values.
* Second you must have observed that there are two
versions of an object copying function. This is because inline int ADD(int a, int b) {return a + b;}
on many systems a faster copy is possible if it is known Remember that the inline specifier does not change the
that the source and target arrays do not overlap. The meaning of the function.
restrict qualifier can be used to express the restriction
on overlap in a new prototype that is compatible with
the original version: Motivation
void *«memcpy(void ‘restrict si, const void When a function is called, the control is transferred from
*restrict s2, size_t n); the calling program to the function. After the called
S00 Computer Fundamentals and Programming in C

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);

printf("Xd %d Xd Xd", arr(O], arr[2], arr[4], }


arr[S), arr[8)});5 Ans: Kamesh 0 0.0
}
When an automatic structure is partially initialized, the
Ans:13560 remaining clements of the structure are automatically
When an automatic structure is partially initialized, the initialized to 0
remaining elements of the structure are automatically
initialized to 0 PP
5. #include <stdio.h>
TONE EE EERE OREO NORTE RR Een ee main()
3. #include <stdio.h> {
void display(struct stud); int option = 5;
struct student switch(option)
{ {
int roll_no; default: printf("Please check your option");
char name[100); case 1: printf({"\n SUM");
‘ break;
main() case 2: printf("\n SUBTRACT”);
{ break;
struct student s; case 3: printf("\n MULTIPLY");
s.roll_no = 10; break;
S.name = "ABC"; }
display(s); }
} Ans: Please check your option
display( struct student si)
{
printf("\n %d Zs", s.roll_no, s.name); SORE ERE EERE REET RETR TERETE EEE
} 6. #include <stdio.h>
Ans: ERROR. main()
502 Computer Fundamentals and Programming in C

{ 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>

while( num {= 100) void main()

{ {
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

Ans: ERROR. Unary operator can be applied to printf("4d %d",*p,*q);


variables and not to constants. Since 2 is a constant, }
therefore the program generates error. Ans: Garbage Value 1

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;

Because *pstr « H, &(*pstr) « pstr. Finally, Ans: =1


*(&(*pstr) eH

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

Ortr rrr terse 37. main( )


33, main() {
{ void *pv;
int num = scanf("Xd", Snum); char ch = *, *pstr = “music”, print_char;
printf("%d", num); int num =10;
}
pv = &ch;
print_char = *(char *)pv;
Ans: 1
506 Computer Fundamentals and Programming in C

printf("%c", print_char); Ans: ERROR


py = &num;
You can create a variable of void * but not of void.
print_char = *(int *)pv
printf("Xd", print_char);
pv = pstr;
printf("%s",(char *)py + 2); 41. main()
} {
Ans: r10sic char *str="BIRO";
char stri[]="BIRD";
Aeenenseeernenereaserene printf("Xd Xd", sizeof(str), sizeof(str1));
38, main()
{
int i, n;
char *str = “bird";
n = strlen(str); 42. main()
*str = str[n]; {
for(i = 0; i < nj ++i) int *pnum;
{ {
printf("%s\n",ste);
int num = 1;
stres; pnum = &num;
} }
} print#("Xd", *pnum) ;
Ans:
(blank space) Ans: 1

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 = &num;
}
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

char *p; char *str="\0";


p="Xd\n"; if(printf("%s", str))
p = pe2; print("GO0D");
printf("%c", *(p-2)); else
} print€("BAD");
}
Ans: ®
Ans: GooD
rrr eer ete eter ett
53. IsEqual(int x, int y)
{ 57. main()
if(x == y) {
return 1; int a = a+;
else static int p= p++:
return 0; printf("Xd Xd", a, p);
} }
main()
ns: Garbage valuc | because a is an int which has not
{
been initialized whereas p is a static int which is initialized
int fun(), Is Equal();
printf("Ad", fun(Istqual, 2, 3));
to zero by default.
}
int fun((*pf)(), int a, int b)
{ 58. main()
return((*pf) (a, b)); {
} unsigned int i = 5;
Ans: 0 i i-1;
while(i)
printf("Xu ",1);
Prrerttrter
rrriititet rrr
}
54, main()
{ Ans: Infinite loop because 'i* is an unsigned integer, so
static int nume4; its value can never be less than 0. As soon as the value
num * num = 1; gets decremented after reaching 0, 'i' will be assigned
if(num >= 0){ positive value like 65535
main();
printf
("Xd" ,num);
} 59. main()
} {
Ans:0 000 int arr[] = {1,2,3,4,5};
printf(°%d", *arr+l-*arr+3);
num is a static variable, so its value persists in between
}
function calls. After main() has been called for 4 times,
the value of num becomes 0 and the same value is printed. Ans: 4 because *arr and *arr cancel out and only 1
+ 3is left

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

S427 7-5 printf("HELLO”);


}
” Ans: HELLO
61, main() Internal representation of 0 is same as that of unsigned —1
{
unsigned int num * 125;
while(num-=>0) 66. main()
print#("%d", num); {
} char *str = “plmno";
Ans: -1 print€("Xc",++*(stre+);
}
As soon as num becomes zero, the loop terminates, The
post decrement operator subtracts 1 from num which had
Ans: aq
become 0), hence the result

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().

SOHAEN ARNE E RENE ERROR Ree een eee


69. main()
64, main() {
{ int num = 3;
unsigned char ch = 0; int *pnumi = Snum, *pnum2 = &num;
while(ch> = 0) {che+;}
num += 2;
printf("X%d\n", ch); *pnuml += 3;
} *pnum2 += 4;
Ans: Infinite loop because the value of ch will never be printf("%d %d Xd", num, *pnuml, *pnum2);
negative as it is declared as unsigned. }
Ans: 12 12 12
ePrret rece r
All the three variables are different names for the same
65. main() memory location. So any increment to their value results
{ in the same value being updated.
unsigned int num = -2;
if(~0 == num)
510 Computer Fundamentals and Programming in C

70, main() int dd, mm, yy;


{ a
char *str="BAD"; scanf("XsXs Xd Xd Xd", stud.name, student.
printf("\n sizeof(str) = Xd, sizeof(*str) = add.a, S&stud.DOB.dd, &stud.D0B.mm, &stud.
Xd, strlen(str) = Xd", sizeof(str), DOB. yy) 5
sizeof(*str), strlen(str)); printf("Xs%s Xd Xd Xd", stud.name, student.
} add.a, stud.DOB.dd, stud.DOB.mm, stud.DOB.
Ans:
yy)i
}
sizeof(str) = 2, sizeof(*str) = 1, strlen(str)
Ams: ERROR
=3
struct Address should be defined before being used in
TORRONE EOE E ERE R TERRE ER On enon struct student. Forward declaration is not permissible in
C. Same is the case with struct 008.
71, main()
{
char ste[]="BAD";
printf("\n sizeof(str) = Xd, strlen(str) = 74, main()
Xd", sizeof(str), strlen(str)); {
} char str[4]="Go00";
print€("%s", str);
Ans: sizeof(str) = 5
}
(length of the string + | for null character)
Ans: GOoo
strlen(str) = 3 The string does not have space for storing the null
character, therefore ste does not end properly and it
Seed eneeneeernereerererenerares continues to print garbage values till it accidentally comes
72, main() across a NULL character.
{
char * str = "GOO";
char * pstr = str;
75. char *f1()
char ch «= 127;
{
while (*pstre+)
char *temp = "GOOD";
ch = (*ptr < ch) ? *ptr : ch; return temp;
printf("%d",ch);
}
} char *#2()
Ans: 0 {
char temp[] = “BAD";
The ASCII value of null character is ‘0° which is less than return temp;
127,
}
main()
Perrerrrrti
reir tirir trrrr {
73. main() puts(f1()
{ printf("%s", £2());
struct Date; }
struct student Ans: GOOD
{
char name[30); Garbage value
struct Address add; The answer is OK for the first function £1() but in case
struct Date DOB; of £2(), temp is a character array for which memory is
}stud;
allocated in heap and is initialized with "BAD". Temp is
struct Address created dynamically when the function gets called, and
{ is deleted dynamically when the control passes out of the
char a[100); function. Therefore, temp is not visible in main(). Hence,
hi gurbage value is printed.
struct Date
{
be ” 7
oven

P wtp Linux: A Short Guide


Linux is avery powerful multitasking. multi-user operating Hardware
system based on UNIX. It was originally created by Linus
Torvalds, a Finnish-American software engincer, with the The hardware consists of hard disk, CPU, and RAM and
assistance of developers from around the globe the peripheral devices connected to the computer such as
It is an open source operating system since its source V/Odevices, and storage devices.
code is freely available on the Intemet and is free to use. Linux operating system works in either kemel mode or
user mode. Kermel component code executes in a special
privileged mode called kerne! mode with full access to all
CW components OF LINUX SYSTEM resources of the computer. In this mode, the kernel provides
system services to processes and allows a protected access
Linux Operating System has three main components to hardware.
System library contains all the support code which is
not required to run in kernel mode. User programs and
Kernel
other system programs that do not require access to system
Kernel is said to be the core part of Linux. It interacts hardware and kernel code works in user mode, User
directly with the hardware and is responsible for all major programs or utilities (programs that gives users most of the
activities. Kernel consists of various modules to provide functionalities of an operating systems) use System libraries
abstraction to hide low level hardware details from system to access Kernel functions to get system’s low level tasks.
or application programs. The Shell is an interface to kernel
that hides complexity of kernel’s functions from users.
Users type their commands in the shell G2EBB WORKING WITH SHELL IN LINUX
System Library The shell (ex, BASH, Tch, ksh, etc) is the component of
Linux that ts commonly referred to as “the command
System libraries contain special functions or programs that line”. It is actually a piece of software that provides an
when included in user's programs allow them to access interface to the services of a kernel
Kernel's features. These libraries implement most of the
functionalities of the operating system.
Most modern Linux systems use BASH (Bourne
Again Shell) as the default shell.

The command line allows users to execute a wide range


of commands. At the command line, users can navigate
to perform different tasks like backing up some files to
disabling a dying piece of hardware
For every Linux distribution, the command line prompt
looks little different. For example, on one system it may
appear as username, the ‘@" symbol, the machine name,
current directory, and some kind of symbol to indicate the
end of the prompt (like a dollar sign) as given below
user@linux ~/$

In other systems, the prompt may appear as username, a


space, the fully qualified domain name of the computer,
the complete path of the present working directory
512 Computer Fundamentals and Programming in C

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

(BGR rocess orienTED COMMANDS


NETWORKING COMMANDS
The ps command is one of the most basic commands that
is used to view the details of processes (like user id, CPU The following Linux commands help to diagnose any
usage, memory usage, command name, etc.) running on networking problem.
the system, To execute the ps command simply type,
ps. You would be shown the following details about the
Current process.
Command |Description | Example
hostname =— To find host or hostname displays the
* Process ID (PID) domain name and —machine's host
* TTY, terminal on which the process is being run IP address of a hostname -{ displays the
* TIME to tell how much time is used by CPU to execute host machine's IP address
this process hostname -d displays the
domain name of the machine
To see information about all the processes currently being
executed, write ping To test network = ping www.google.com
connection
ps -ax
ifconfg Togetnetwork — ifconfig
Where a means all and x means even those processes that configuration
are not being run on the terminal
S14 Computer Fundamentals and Programming in C

‘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

traceroute To find the route traceroute google.com grep Checks


each line ofinput received
from the standard
traversed to reach input and outputs lines that contain a specified
. the network host pattern
ofcharacters.
fat Reads text from standard input, formats it and then
displays it onstandard output.
pr Accepts input from the standard input and splits
23 1/0 REDIRECTION the data into pages with page breaks, headers, and
footers in preparation for printing.
Most command-line programs display the results by head Displays only thefirstfewlinesofitsinput.
sending them to the standard output (the screen). To send
tail Displays
only the Last few lines of
its input.
the standard output to a file, the “>” character is used.
tr ‘Stands for translate. It translates characters, for
Is> file.txt example, from upper to lower case
Here, the 1s command is executed and the results are awk A programming language for constructing filters
written in file. txt, Since the output has been redirected to
4 file, no results are displayed on the screen. For example,
Whenever the above command is repeated, the contents
cat file. txt|fmt|pr|
lpr
of file.txt are overwritten by the new output generated by
the execution of the command 1s. If you want the new results Here, the contents of the file file. txt is read and passed
to be appended to the existing contents of the file, use ">>" to a filter fmt which formats the text of the file and then
passes it to a filter pr, which splits the text into pages and
ls>> file.txt
finally gives the results to lpr, lpr takes input from the
Many commands accept input from the standard input standard input and sends it to the printer for printing,
which is the keyboard. But, like standard output, input can Now can you guess, what is the result of cat file. txt
also be redirected so that it is taken from a file instead | sort | uniq|pr | lpr?
of the keyboard. For example, to sort a file you need to It takes as an input an unsorted file, sorts it, removes
supply the contents of the file to the sort command. This duplicate entries, splits into pages and then prints it,
means that the sort command is not taking input from the
standard input but from the file. In such situations, use the
“<" character #3 vieviror
sort < file.txt vi stands for visual editor and is the default editor that comes
If you want to redirect the sorted contents of file. txt to with Linux. It is a full screen editor that works in two modes,
another file named sorted_file.txt, then write
1. Command mode which gives commands to perform
sort < file.txt > sorted_file.txt some actions on the file. In this mode, every character
Linux: A Short Guide 5

typed is treated as a command to perform some Command Description


action
I Inserts text at the beginning of the current
2. Insert mode to enter text into the file. Pressing the Ese line
key turns off the insert mode.
Appends text after cursor
There are a number of vi commands, which are discussed Appends text to the end of current line
in the table.
Replaces single character under cursor
Replaces characters starting with current
Linux and vi are case sensitive. cursor position
Deletes single character under cursor
Deletes n characters starting with the
To start vi editor, type vi filename. If the filename exists,
character under cursor
then its contents are displayed, otherwise an empty file is
opened in which text can be entered. Deletes a single word beginning with
character under cursor

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

Fill in the Blanks


1. set of instructions executed by the computer; 2. data, instructions; 3. millions; 4. nano or pico seconds; 5. data;
6, RAM; 7. UNIVAC and ENIAC; 8. atomic energy; 9. Spreadsheet; 10. super computers; 11. Modem; 12. VGA
connector; 13, Stored program; 14 smartphones, tablets; 15, BIOS

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

Fill in the Blanks


1, Input device;2. Print Screen; 3. laser; 4. Stylus; 5. serial; 6. OMR:; 7. Sound card; 8. Web cameras; 9. Headset; 10.
the sharpness of text and images on paper

Multiple-choice Questions
1, Function keys; 2. All of these; 3. Daisy wheel and band printer; 4. None of these; 5. LCD

State True or False


1, False 2. True 3. False 4 5. True 6. False
7. True True 9 10

CHAPTER 3

Fill in the Blanks


1.primary; 2. Primary; 3.Secondary;4.Processor registers; 5. 4 or 6 bytes; 6. D flip flop; 7. PROM; 8,EEPROM;
9, flash memory; 10, tracks on a single platter of the disk; 11. burni 12. Nero Burning ROM; 13, EBCDIC; 14
Tracks and sectors; 15. transfer rate; 16. Control; 17. processor registers; 18. Memory address register; 19. opcode,
operands; 20. the power is tumed off, 21. data, address, control information; 22. opcode; 23. tick; 24. MHz, GHz;
25, 10°, 10'*;26,Multi-core
Answers to Objective Questions 517

Multiple-choice Questions
1, Cache memory;2.Auxiliary memory; 3.Disk latency;4.Allofthese;5. Flash memory; 6.CU; 7. MBR; 8.GFLOPS

State True or False


1. True 2. False 3. Truc 4. False 5. True 6. False
7. False 8. True 9. Truc 10. Truc Il. False 12. True
13. Truc 14, False 15. False 16. False 17. False 18. True
19. True 20. False 21. False 22. False

CHAPTER 4

Fill in the Blanks


1. binary; 2. 16; 3. 1, and borrow | from the next more significant bit; 4, sign-and-magnitude; 5. unpacked BCD; 6.
128; 7. 8 bit; 8, 0-9 and alphabets from af, 9. carly mainframe computer systems; 10. 16s column, a 256s column,
a 4096s column, a 65,5368 column, and so forth

Multiple-choice Questions
1, EBCDIC; 2, Gray code; 3. EBCDIC; 4. 5349; 5. 181CD

State True or False


1, True 2. False 3. False 4. True 5. False 6
7. True 8. True 9. False 10. True
y

r
CHAPTER 5S

Fill in the Blanks


1, binary; 2, Bolean; 3, Venn diagrams; 4. Truth table;5.identity;6.literal; 7, maxterm, 8, 0; 9. Boolean expression;
10, NAND, NOR

Multiple-choice Questions
1. NAND; 2, 2"; 3. Distributive; 4. 6; 5. Intersection

State True or False


1, False 2. False 3. False 4. False 5. True 6. True
7, False

CHAPTER 6

Fill in the Blanks


1. Software; 2.software; 3. programming; 4.Programming language; 5. Compiler; 6.Driver software; 7. Operating
system;8.System software; 9.Cryptographic utility; 10. Word processor, 11. CAD software; 12, Desktop publishing;
13, DBMS; 14. query; 15. graphics; 16. user, operating system; 17, FORTRAN; 18. label, opcode, operands; 19.
Assembler; 20, Compilers, interpreters
S18 Computer Fundamentals and Programming in C

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

State True or False


1. Truc 2. True 3. Truc (program specifically) 4. False 5. False
6. True 7. False 8. Truc 9. False 10. Truc 1h. True
12, False 13. True 14. False 15. True 16. Palse

CHAPTER 7

Fill in the Blanks


1. coaxial;2.cladding; 3. 35,400;4.half-duplex;5.parallel;6.asynchronous; 7. clock; 8. network topology; 9. star;
10. n= (n? 1)/2; 11. ethernet; 12. piconet; 13. routing table; 14, Intemet; 15, Tim Berners-Lee; 16. ethernet; 17. WAP;
18. 2.4 Hz, 1 MBPS; 19. Web browser; 20. Presentation

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

State True or False


1, True 2. False 3. False 4. True 5. True 6. False
7, True 8. False 9. Truc 10. False I. False 12. False
13, True 14. False 15, False 16. True 17. Truc 18. False
Answers to Objective Questions 519
at
CHAPTER 9
Fill in the Blanks
1, Dennis Ritchie; 2. function; 3. main();4.ASCII codes; 5. operating system;6.modulus operator; 7, Logical NOT;
8. unary; 9. type casting; 10, number of values that are successfully read 11. printf{); 12. abs()in math.h; 13, single
quotes; 14. closing bracket ; 15. math.h; 16. \n; 17, double; 18. const; 19. the sign of the first operand is positive;
20, the direction in which the operator having the same precedence acts on the operands; 21, parenthesis; 22. sizeof;
23. Yohd; 24. x; 25.

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

State True or False


1, False 2. False 3. True 4, False 5. False 6. False
7. Truc 8. False 9. True 10. False Il. True 12. True
13. False 14. False 15. False 16. True 17. True 18. True
19. True 20. True 21. False 22. False 23. Truc
_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

State True or False


1. False 2. False 3. Truc 4. Truc 5. Truc 6. True
7, True 8. False 9. True 10. Truc 11. True 12. False
13. False 14. True 15. False 16. True 17. False 18. True
19, True 20, True 21. True 22. True 23. False 24. False

CHAPTER 11

Fill in the Blanks


1. function name; 2. calling function; 3. calling function; 4. arguments/parameters; 5. operating system; 6. function
header and function body; 7. call-by-reference; 8. goto label; 9. recursive; 10. system stack; 11. recursive; 12. zero
or no; 13, global; 14. main(); 15. int; 16. local variable

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

State True or False


1, False 2. True 3. True 4. True 5. True 6
7, True 8. False 9. True 10. True Il. True 12
13, True 14. False 15. False 16. True 17, True

CHAPTER12

Fill in the Blanks


1, collection of similar data elements; 2. subscripVindex; 3. integral; 4. consecutive; 5. n; 6, pointer; 7. data type,
name and size; 8, the clement being referenced; 9. array name; 10. the number of elements stored in it; 11, traversing;
12. sorted array; 13. array of arrays; 14. fourth; 15, linear

Multiple-choice Questions
2; 2.7; 3. 200;4. $0;5.25;6.best case; 7. allofthese

State True or False


1, True 2. False 3. Truc 4. True 5. True 6. False
7, True 8. False 9. True 10. False I. False 12. False
13, True 14, True 15. False 16. False 17. True 18. True
19, True 20. True 21. False 22. False 23. True 24. True

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()

State True or False


1, False 2. False 3. False 4. True 5. False 6. False
7. True 8. False 9. False 10. False 1. True 12. True
13.False 14. True 15. False 16. False 17. False
Answers to Objective Questions $21
~
CHAPTER 14
Fill in the Blanks
; 2.dynamic memory allocation; 3. address, pointer; 4. null; 5. data type; 6. 2; 7. rvalue; 8. memory
9. pointers; 10, *; 11. main memory; 12. stacks; 13. system stack; 14, executable image of shared libraries
that are being used by the program; 15. a pointer (of cast type) to an area of memory with size byte-size; 16. free
list, heap; 17, void pointer, null pointer; 18, change the memory size already allocated by calloc() and malloc(); 19.
pointer-to-pointer-to-int; 20, garbage value; 21. 0; 22. pointer-to-pointer-to-int; 23. pointers; 24. free(); 25, arrays
of varying sizes
Multiple-choice Questions
1, Dereferencing operator, 2. num; 3. all of these; 4. indirection; 5. &; 6, stack; 7. heap; 8. stdlib.h; 9, calloe()

State True or False


1, True 2. True 3. True 4. True 5. True 6. False
7. True 8. False 9. True 10. False 11. False 12. False
13. True 14. True 15. False 16. True 17. True 18. False
19. True 20. True 21. False 22. False 23. False 24. False
25. True 26. True
Le y

CHAPTER 15

Fill in the Blanks


1. user defined; 2. records; 3. array;4.structure; 5. structure variable declaration; 6. structure declaration; 7. structure;
8. structure name; 9. typedef, 10. 0; 11. \0; 12. dot operator, 13. nested structure; 14. self referential; 15. create a new
data type name for an existing data type; 16. union; 17. refer to the individual members for the actual parameters;
18. union

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

State True or False


1. False 2. False 3. False 4. Truc 5. True 6. False
7. False 8. Truc 9. Truc 10. True 11. False 12. False
13. True 14. False 15. False 16. Truc 17. True 18. True
19. False 20. True 21. Truc
di

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()

State True or False


1, False 2. False 3. Truc 4. True 5. False 6. False
7. False 8. False 9. False 10. False ll. False 12. True
13. Truc 14. True 15. True
y

rc
CHAPTER 17

Fill in the Blanks


|. pre-processor; 2. pre-processor; 3,preprocessor directives;4.preprocessor directives;5,#define statement;6,give
symbolic names to numeric constants; 7, #define directive; 8. arguments in the invocation that exceed the number of
parametersin the definition;9,#; 10, merge; 11. angular brackets; 12, 10; 13. #define; 14. #pragma; 15. conditional
directive; 16. a closing #endif; 17. #if; 18. error; 19. #waring directive; 20._ STDC
Multiple-choice Questions
1. #; 2.\; 3.#line;4,#ifdef; 5. defined; 6. TIMESTAMP.

State True or False


2. Truc 3. False 4. True 5. False 6. True
8. Truc 9. Truc 10. False 11. False 12. True
14, True 15. False

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

State True or False


1, True 2. Truc 3. False 4. False 5. False 6. False
7, False 8. Truc 9. Truc 10. True 11. False 12. True
13, True 14, True 15. False 16, True 17. False 18. False
19, False False 21. False
In ex
Sdetine 447 Compiling and executing 169 Data structures 460 1
C tokens 171 Linear and non-linear 460 Identifiers 172
Uses 166 Primitive and non-primitive Input devices 16, 22, 28
Hendif Directive 456 Character manipulation func- 460 Audiovisual 28
#ildef 454 tions 331 Data transmission 133 Handheld 25
Hif Directive 455 clearert()
425 Asynchronous 135 Keyboard 22
#itndel 454 Comments 170 allel 134 Optical 26
H#include 450 Computer, 3,4,$, 9, 11 Serial 134 Pointing 23
451 15, 16 Simplex, half-duplex, and Input/Output statements 176
#pragma 482 Application 11 full-duplex 133 Formatting input/output 176
#undef 451 Bioinformatics 12 Synchronous 135 printi{) 176
Characteristics 3 Debugging 158 seanf() 179
A Classification 9 Dec won control Internet 12, 139
Adjacency list 481 Decision support statements 205 Chatting 142
Adjacency matrix 480 systems 15 Electronic mail 141
Algorithms 153 Expert systems 15 E Electronic newspaper 143
Array of function pointers 369 Genenation 6 Efficient programs 152 File transfer protocol 142
Arrays 275, 337, 364, 461 Geographic information Enumerated data type 405 Internet conferencing 143
Applications 308 system 13 Errors 157 Internet protocol 139
Calculating the address 277 Mainframe computers 9 World Wide Web 143
Declaration 275 Microcomputers 10 F Iteration 267
Elements 276 Minicomputers 9 File 415 Iterative statements 216
Operations 279 Robotics 15 wC4i7 do-while loop 218
Supercomputers 9 F ¢ mode 417 for loop 221
B Computer networks 124 F ing point constant 175 while loop 216
BCD code 70 Connecting media 127 Character constant 175
ASCII code 71 Local area network 125 String constant 175 K
EBCDIC 7! Metropolitan area network Flowchart 154 Karnaugh map 87
Excess-3 code 71 12s fprinti{) 421 Keywords 171
Gray code 73 Networking devices 128 fputs () 422
Unicode 73 Network topologies 130 fscanfl) 418 L
Boolean algebra 76 Search engine 144 fsetposi) 441 Linked list 461, 463, 466
Absorption law 80 Wide area network 125 fell) 440 Logic gates 82
Associative law 79 Wireless 132 Function-like macros 448 and gate 83
Basic laws 78 Computer software 92 Function pointers 368 NOR gate 83
Commutative law 78 Application software 96 Functions 248, 249, NOT gate 83
Complement law 78 Customized 96 250, 251
Consensus law 80 Pre-written 96 Call 251 M
De Morgan's laws 80 Public domain 97 Declaration 249 Macros 450
Distributive law 79 System software 93 Definition 250 Operators 450
Idempotency law 78 Conditional branching Prototype 249 Mass storage devices 50
Identity law 78 statements 205 Automated tape library 50
Involution law 78 if-else af statement 209 G CD-Rom jukebox 50
Boolean expressions 84 if-else statement 207 goto statement 2 Disk array 50
Boolean functions 81 if statement 205 Graph 479 Memory 39
Maxterm &2 switch case Graphics software 109 Cache 40
Minterm 81 Conditional directives 454 Graph terminology 480 Hierarchy 39
Break statement 232 Constants 174 Adjacent or Primary memory 40
Continue statement 232 neighbours 480 Memory allocation 370
c Deg ee of a node 480 Dynamic 371
C 166, 167, 168 D Motherboard 17
Characteristics 166 Database management Multidimensional 305
Character set 171 software 109 Hard disk 17 Multimedia software 109
524 Computer Fundamentals and Programming in C

N Null 384 Return statement 252 strtod 336


Nested loops 224 Pointer arithmetic 350 Rewind() 440 strtok 335
Nested structure 392 Pointer expressions 350 strtol 335
Number systems 59 Pointers to pointers 370 s Strings 318, 319, 322, 337
Binary $9 Preprocessor directives 447 Searching 289 Operations 322
Hexadecimal 66 Processor 40 Binary search 290 Reading 318
Octal 63 Random access memory 41 Lincar search 289 Writing 319
Read-only memory 41 Secondary storage String taxonomy 322
0 Registers 40 devices 42 Delimited 322
Object-like macro 448 Processor architecture $1 Blu-ray disks 48 Fixed-length 322
Operating systems 110 Execution unit $1 CD-R 47 Length-controlled 322
Batch processing 110 Instruction cycle $2 CD-ROM 47 Variable-length 322
Linux 116 Instruction set 52 CD-RW 47 Structure 386
Microsoft DOS 112 Pipelining and parallel DVD-ROM 47 and functions 395
Mobile 116 processing $4 Floppy disks 43 Arrays of 393
Multiprocessing 111 Processor speed 53 Hard disks 44 Inside unions 404
Multi-user multitasking 111 Registers $1 Magnetic tapes 43 Self-referential 402
Real-time 111 System clock $3 Memory cards 49 Suppressing input 321
Single-user multitasking 110 Processors $4 Optical drives 46
UNIX 11S Complex instruction set USB flash drives 4% T
Virtual machine 111 computer $4 Signed number representation TCP/IP model 138
Windows 113 Reduced instruction set in binary form 69 Temporary 442
Operator 182 computer $5 One's complement 70 Testing 15%
Arithmetic 183 Productivity software97 Sign-and-magnitude 70 Tower of Hanoi 266
Assignment 189 Microsoft office 97 Two's complement 70 Trees 477
Bitwise 187 Programming languages 117 Sparse matrix 306 Binary trees 478
Comma 189 Generations 118 Array representation 307 Traversing 478
Conditional 187 Progr mening Stacks 471 Truth tables 7
Equality 185 paradigms 149 Operations on 473 Two-dimension, arrays 295,
Logical 185 Monolithic 149 Storage class 259 296, 300, 302
Precedence chart 191 Object-oriented 151 Auto 259 Accessing the elements 297
Relational 15 Procedural 149 Extem 260 Declaring 295
sizeof 191 Structured 150 Register 260 Initializing 296
Unary 186 Pseudocode 156 Static 261 Operations 300
OSI model 136 Stream 176, 415 Typecasting 195, 196
Output devices 16, 29 Q String manipulation functions 332 Type conversion 195
Hard copy 33 Quewes 475 atofl) 336
Soft copy 29 Operations on 475 alow) 336 t
ato) 336 Unions 402
Pr R streat 332 Inside structures 404
Passing arrays 292 Recursion 265, 266, 267 strehr 332 Universal gates 85
Passing parameters 253 Direct 265 stremp 333 NAND 85
Call by reference 254 Indirect 265 stropy 333 NOR #6
Call by value 253 Linear 266 strespn 335
perror() 425 Tail 265 strlen 3M V
Pointers 348 Tree strncat 332 Variables 173, 257
and 2D arrays 365 Recursive function 262 strcmp 333 Block scope 257
and 3D arrays 367 Base case 262, 263 strncpy 334 File scope 259
and arrays 356 Exponent 264 strpbrk 335 Function scope 258
ind strings 360 Fibonacci series 264 strrchr 333 Program seope 258
Drawbacks 375 GCD 263 strspa 334 Scope 2
Generic 354 Recursive case strstr 334 Venn diagrams 77
About the Author
Reema Thareja is Assistant Professor, Department of Computer Science, Shyama Prasad Mukherji
College for Women, University of Delhi, She holds a Master of Computer Application (MCA)
degree in Software Engineering and M Phil in Computer Science and is currently pursuing research
in improving data warchouse quality. She has about 10 years of teaching experience and specializes
in programming languages, operating systems, microprocessors, database management systems
(DBMS), multimedia, and web technologies.
Prof. Thareja has published several research papers in national and international journals of
repute, She has undertaken projects on quality monitoring of automated teller machine (ATM)
networks and steganography in Centre for Development of Telematics (CDoT) and Defence
Research and Development Organization (DRDO), respectively. She is a member of the Computer Society of India (CSI).
She has authored several books, including Data Warehousing (2009), Data Structures using C, 2e(2014), Fundamentals
of Computers
(2014), Introduction to C Programming, 2¢ (2015), Information Technology and Its Applications in Business
(2015), Object Oriented Programming with C++ (2015), and Programming in C, 2e (2015), all published by Oxford
University Press India.
Related Titles
|| DATA STRUCTURES USING C++ © Contains a chapter on Developing Efficient Programs,
(9780198066231) which details steps for developing correct, efficient, and
Data maintainable programs
Noe Structures
Varsha H. Patil, Matoshri College
Using of Engineering & Research Center, rs We SCOBJECT ORIENTED
+4. Nashik t PROGRAMMING WITH C++
Oriented 9780199459636
The book begins with a discussion on Programming
the fundamentals of data structures S+* | Reema Thareja, University of Delhi
and algorithms, and moves on to the
This textbook intends to develop
concepts of linear data structures,
recursion, searching, and sorting.
efficient programming skills by
providing a sound knowledge of C++
Key Features programming concepts as well as their
© Provides a thorough overview of the fundamental concepts applications,
© Includes numerous algorithms and program codes in C++ Key Features
to illustrate the topics discussed
© Provides plenty of compiled and tested programs along
© Provides several illustrations and flowcharts to help
with their outputs to help readers hone their programming
understand the subject effectively
skills
PROGRAMMING IN © Includes notes and programming tips to help readers keep
JAVA (SECOND EDITION) in mind the critical concepts and do's and don'ts while
9780198094852 developing a program
© Provides case studies including programs interspersed
chin Malhotra, IMS Ghaziabad and
within the text to demonstrate the implementation of the
Saurabh Choudhary, [T Consultant
concepts learnt
and Corporate Trainer
DATA STRUCTURES USING C
Thoroughly updated for Java Standard Date (SECOND EDITION)
Edition 7 Java SE 7), this textbook
ata 9780198099307
provides greater topical coverage and
more programming examples in every chapter Reema Thareja, University of Delhi
Key Features The book provides a comprehensive
© Provides a quick recap of object-oriented programming coverage of the concepts of data
concepts before getting started with Java structures and their implementation
© Includes plenty of user-friendly programs with line-by- using C language.
line explanations and comments in them to encourage
Key Features
self-study
© Provides a brief recapitulation of C programming basics
© Contains a lab manual with useful program codes and a set
before delving into the analysis of data structures
of interview questions with answers as appendices
© Makes use of numerous algorithms, programs, and
RELATED TITLES BY THE SAME AUTHOR illustrations to explain the concepts
© Provides analysis of all major algorithms in terms of their
a AE) PROGRAMMING INC running times
| 7 (SECOND EDITION)
9780199456147 OTHER RELATED TITLES
Reema Thareja, University of Delhi 9780198097402 Harsh Bhasin: Programming in C#
Thistextbook provides comprehensive 9780199455508 Uttam K. Roy: Advanced Java Programming
coverage of the fundamental concepts 9780198093695 S. Sridhar: Design and Analysis of
Programming in C
of C programming Algorithms
9780198082873 Naresh Chauhan: Principles of Operating
Key Features Systems
© Provides more than 200 programming examples with 9780198070887 Srimanta Pal: Systems Programming
outputs to illustrate the concepts 9780198071068 Chander Kumar Nagpal: Formal
© Includes case studies after sclect chapters to help Languages and Automata Theory
readers develop a practical understanding of the 9780198066644 K.Muneeswaran: Compiler Design
concepts learnt 9780198066774 Bhushan Trivedi: Computer Networks
Visit us at https://indis oup.com/section/high-edw
Computer Fundamentals and Programming in€ =seconp eprtion
This second edition of Computer Fundamentals and
Programming in C is designed as a textbook for the = New chapter: Introduces a chapter on Boolean
undergraduate students of engineering, computer science, Algebra and Logic Gates, which discusses the basic
and computer applications. The book provides a thorough concepts underlying digital computing systems
coverage of all the fundamental concepts reiated to
computer science and C programming. = New topics: Presents new sections on processor
The book is divided in two parts. Part |, Computer
Fundamentals, starts with an introduction to computers and
offers a detailed account of various topics ranging from input
and output devices, primary and secondary memory devices,
processor architecture, number systems, description
of
various systemand application software, and computer
networks and the Internet. Part Il, Programming in C, detves
into the basics of C programming and introduces important
data structures.
Written in a lucid language, the book provides several
pedagogical features including case studies, plenty of well-
labelled illustrations, Key terms, and chapter-end exercises.
The text is interspersed with notes that provide additional
information and programming tips that will help students ® New appendix Discusses the basics of Linux kernel
avoid common programming errors. and shell and describes the most commonly used
Unux commands
Key Features
Praise for the First Edition
= Provides exhaustive coverage of computer fundamentals,
focusing on both the hardware as well as software Objective questions are very useful for GATE/NET and
components
other competitive exams.
© Offers a detailed coverage of different types of number
systems and computer codes Naresh
E, MSRIT, Bangalore
© Covers user-defined data types (arrays, strings, structures, The fact that | found this book in the library of Stanford
Unions) in detail, with each of the operations on these data
University in itself is a big compliment. | am teaching
types implemented using numerous example codes
from this book and my students find it an excellent book
= Includes case studies after select chapters
to follow.

Arijit Das, Naval Postgraduate School, California, USA

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

For product details and price, 9 "780199"4637,


please visit www.india.oup.com

You might also like