0% found this document useful (0 votes)
195 views404 pages

Introduction To C Programming - Thareja, Reema, Author

Uploaded by

memestoneage
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)
195 views404 pages

Introduction To C Programming - Thareja, Reema, Author

Uploaded by

memestoneage
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

OXFORD

HIGHER EDUCATION
Digitized by the Internet Archive
in 2023 with funding from
Kahle/Austin Foundation

[Link]
INTRODUCTION TO

PROGRAMMING
SECOND EDITION

Reema Thareja
Assistant Professor
Department of Computer Science
Shyama Prasad Mukherji College for Women
University of Delhi

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

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

First Edition published in 2012


Second Edition published in 2015

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


a retrieval system, or transmitted, in any form or by any means, without the
prior permission in writing of Oxford University Press, or as expressly permitted
by law, or under terms agreed with the appropriate reprographics
rights organization. Enquiries concerning reproduction outside the scope of the
above should be sent to the Rights Department, Oxford University Press, 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-945205-7
ISBN-10: 0-19-945205-7

Typeset in Times New Roman


by Pee-Gee Graphics, New Delhi
Printed in India by Magic International (P) Ltd., Greater Noida
To my family
and
my uncle Mr B. L. Theraja
who is a well-known author
Features of the Book
Programming Tips
Programming Tip: ee ee) AREA

If you do not place Educates the reader about common


a parenthesis after programming errors and how to avoid
‘main’, a compiler them ‘
error will be
generated,
RR

ce

oe a a
Cis a case-sensitive language.
These elements highlight important Therefore rno, Rno, RNo, RNO are
AG
terms and concepts for a quick recap
considered
as different identifiers.

SO eee eee eeeee Se eee Ce

The book is visually rich with a number of


illustrations to support the explanations,
which help clarify
theconcepts in a clear
inary Contents | .
manner —.
of ch

aiavigcveres) Implicit conversion example

Solved Examples
A ee ee ee Example 8.3 Declare a structure to store information of a
Every chapter contains plenty of solved particular date.
examples to demonstrate the applicability
struct date
of concepts discussed
int day;
int month;
int year;
}i
Case Studies
Case studies at the end of select , Case Study
chapters contain detailed programs
that reinforce the concepts learntin c for Cha oters 6 and 7
hae

In C language, a string is nothing but a null-terminated int option, m,n, length=0;


character array and a pointer is a variable that contains the clrscr();
memory location of another variable. Therefore, a pointer do
is a variable that represents the location of a data item such {
; as a variable or an array element. printf ("\n 1 1. Enter the string") ;
Pointers provide an alternate way to access individual printf ("\n 2 2. Display the string") ;
printf ("\n 3. Merge two strings") ;
elements of the array and they are used to pass arrays
printf ("\n 4. Copy n characters from
and strings as function arguments. Now utilize all these
4 position") ;
concepts to write a program that performs various
printf ("\n 5. Calculate length of the
operations on a string (using pointers).
string") ;

_ Break statement Statem 0 terminate the ex- _ function and can appear only before one stat
_ ecution of the nearest enclosing ks p in which it appears. thesame function, —se Contains:a list of important ter!ms
| Conditional branching Cond onal branching state- _r¢ statement Simplest form of decision control state- and their definitions at the end of
_ ments is used to jump from one part of the program to —_ ment that is frequently usedindecision making.
another depending on whether aparticular condition re.
e1se-i¢ statement Decision control statement ~ each chapter for recapitulation of the
GLOSSARY
EN that works in the same way as anormal if statement. — important concepts learnt
atement Statement that can sar iN {tis also [Link] nested if construct.
the bod! of loop. When the compiler encounters a
_If-else statement Decision control statement in
continue statement then the rest of the statements
which first the test expression is evaluated. If the ex-
in the loop are skipped and the control is uncondition-
pression is true, statement block 1 is executed and
ally transferred to the loop-continuation portion of the
statement block 2 is skipped. Otherwise, if the ex-
nearest enclosing loop.
false, statement block 2 is executed and
) Dangling else problem Problem encountered wh
statement block 1 is ignored.
nesting of if-else statements whic is created when
: there iis no matching else for es if statement.

Fill in the Blanks


Comprehensive exercises at the end 1. Structure isa data type. State True or False
of each chapter to facilitate revision 2. Astructure is similar to ,
4. Computer hardware does all the physical work.
Ss contains related information of the same

EXERCISESdata type. 2. The computer hardware cannot think and make


decisions on its own.
Multiple Choice Questions
1. A data structure that can store related information Review Questions
together is
(a) array (b) string 1. Declare a structure(s) that represents the following
-(c) structure (d) all of these hierarchical information:

| 2. A data structure that can store related information of (a) Student


different data types together is (b) Roll Number
(a) array (b) string (c) Name
(c) structure (d) all of these (i) First name
Preface to the Second Edition
C still continues to be the most popular and widely used e Solved examples within the chapters to demonstrate
programming language, even after four decades of its the applicability of concepts discussed
inception and conceptualization. Its versatility can be e Glossary of important terms at the end of each
drawn from the fact that many advanced languages as chapter for recapitulation of the important concepts
well as operating systems like Windows and Unix have learnt
inherited the control structures and other basic features e Comprehensive exercises at the end of each chapter
of C. Programmers all over the world embrace the C to facilitate revision
language as it provides them maximum control and e Case studies containing programs that reinforce the
incredible efficiency. C programs can produce codes concepts learnt in chapters
that are compiled directly to a machine’s native code. In e Programming tips educating readers about common
optimized conditions, a C code can run as fast as a code programming errors and how to avoid them
written in assembly language! C codes are versatile, e Notes highlighting important terms and concepts for
extensible, portable, and at the same time, extremely easy a quick recap
to learn and practice. Hence, for most of the students, C
unquestionably remains the first step towards learning the
art of professional programming. NEW TO THIS EDITION
This second edition presents the following new features:
e How to write and execute C programs in platforms
such as Unix, Linux, and Ubuntu
Introduction to C Programming 2e is designed to serve
e Asection on how to test and build robust C programs
as a textbook for undergraduate-level courses in computer
e Detailed discussion on algorithms and how they act
science and engineering and postgraduate-level courses of
as a blueprint for writing effective C programs
computer applications. The book explains the fundamental
e An introductory section on categorization of high-
concepts of the C programming language and illustrates
level languages
the application of these concepts for solving real-world
e New and updated example program codes
problems with a step-by-step approach.
Unlike existing textbooks on C which concentrate more
on the theory of programming in C, this book focuses on ONLINE RESOURCES
its applicability by providing numerous programming
The online resource centre provides resources for faculty
examples and a rich set of programming exercises at
and students. The following resources are available at
the end of each chapter. The book will also be useful
[Link] for faculty and students using
as a reference and resource to computer professionals
this text
operating in the domain of C and other C-like languages.
Every chapter in this book contains multiple For Faculty
programming examples to impart practical knowledge of e Solutions Manual
the concepts. To reinforce the concepts, there are numerous
e PowerPoint Slides
objective, subjective, and programming exercises at the
end of each chapter. The salient features of the book For Students
include: e Multiple Choice Questions
e Lucid style of presentation that makes the concepts e Program Codes
easy to understand
Much of the content from the CD that accompanied the
e Plenty of illustrations to support the explanations, first edition has been uploaded to the companion site from
which help clarify the concepts in a clear manner where they can be accessed easily.
Preface to the Second Edition | Vii |

CONTENT AND STRUCTURE Chapter 7 presents a detailed overview of pointers,


pointer variables, pointer arithmetic, so and so forth. The
The text is organized into 11 chapters. chapter also relates the use of pointers with arrays, strings,
Chapter I provides an introduction to computer software. and functions. This helps the reader to understand how
It also provides an insight into different programming pointers can be used to write efficient programs.
languages and the generations through which these Annexure 5 explains the process of deciphering pointer
languages have evolved. declarations.

Chapter 2 discusses the building blocks of the C Chapter 8 introduces two user-defined data types. The
programming language. The chapter talks about first is a structure and the second is a union. The chapter
identifiers, constants, variables, and operators supported includes the use of structures and unions with pointers,
by the language. arrays, and functions so that the inter-connectivity between
the programming techniques can be well understood.
Annexure I shows the steps to write, compile, and execute
Annexure 6 talks about bit fields and slack bytes.
a C program in Unix, Linux and Ubuntu and also discusses
some of the bitwise operations. Chapter 9 discusses how data can be stored in files. The
chapter deals with opening, processing, and closing of files
Chapter 3 deals with special types of statements such
through a C program. These files are handled in text mode
as decision control statement, iterative statement, break
as well as binary mode for a better clarity of the concepts.
statement, control statement, and jump statement.
Chapter 10 explains the concept of pre-processor
Annexure 2 discusses about algorithms. directives. The chapter includes small program codes that
Chapter 4 deals with declaring, defining, and calling illustrate the use of different directives in a C program.
functions. The chapter also discusses the storage classes Annexure 7 provides an introduction to data structures.
as well as variable scope in C. The chapter ends with the
Chapter 11 introduces linked list which is a preferred data
important concept of recursive functions and a discussion structure when memory needs to be dynamically allocated
on the Tower of Hanoi problem. for the data. The chapter discusses different types of linked
Annexure 3 explains the usage of user-defined header lists and the techniques to insert and delete data from a
files. linked list.

Chapter 5 provides a detailed explanation of arrays


including one-dimensional, two-dimensional, and multi- ACKNOWLEDGEMENTS
dimensional arrays. Finally, the operations that can be
I would like to gratefully acknowledge the feedback and
performed on such arrays are also explained.
suggestions given by various faculty members for the
Annexure 4 presents some of the widely used sorting improvement of the book.
techniques. I am obliged to the editorial team at Oxford University
Press India for all their support towards revising this book.
Chapter 6 unleashes the concept of strings which are better
Suggestions for improving the presentation and contents
known as character arrays. The chapter not only focuses
can be sent to the publisher through its website [Link].
on reading and writing strings but also explains various
com or to the author at reemathareja@[Link].
operations that can be used to manipulate the character
arrays. Reema Thareja
=

tiv i erpianted onosad ov aMaontoyt


ee

Palette resale *baltnisb & eos S a)


off iinet 02 bos a pera he ae: ea
Zune “yvenn dew i ir 0 Sas Se oly “iat
Spit benersbiw ot ben cod vyledl ehtT copied, bed
s J 2fntgorg insights sthiw ot bean adi ersten
“alan gatvustgiosh To vastenp-aityasiaiqu> t stank
: Peeermning lncways, expe oe boy eid

aio WheYee FW Matias


acta olese ee WT tat
Sayre ORO he Re Se Sh Sahiltl
7 Hessian FH AN AO: atiracuentveya
» eacgrge
=a per:HOS > Belles? yateniter-gotr sr!
a De

ne aeuciioeniy stab ieee:uty sterubauul|)


spun abn mt ma

.¥ Pulte Alone
wit» Ort)

wd awe eye S eltnatnit -» agra be ge «


le ay are aoe . , as

« i nrerneers
7 ss ens of sali! bine 1 ——
_ A erdinee
wldsel
y enon id milly enebooquise
= anths Ge my < Seay op Shabrl ail bo desir copqem rire leh
wo ebliewadstapti
bryan transAabegs
iby nieanhbop)dleniet.
Maoh
AN sina voialeuennge Zorpia (Cit thieyoikgilanih wen vatedsamdau om a trae {aad
PP igce Wnraiinipemeneto
tonympice?amit panel his eCoTs WA ny
. oi ary ahaa allHypccnti wrinldag sale oo), tie web ati er as eqnive ane bas ab
ph altten RRR Nbr ve Th Aintate Stl ad a dure reboot 2 slug (ioe at bose 2d paca: Meldae en
hua cial an
yew

= Ov x. :

ha or
, 7 /
= & = } r . w~
Preface to the First Edition
C is the most popular and widely used language for i.e., It uses procedures such as functions, methods, or
developing computer programs. Programmers all over routines to call itself or other procedures. However, many
the world embrace the C language as it provides them applications are still better suited to the procedural style of
maximum control and efficiency. One of the major benefits design, which often goes untaught to many programmers,
of learning C is its user-friendliness-that allows the user who focus exclusively on object-oriented design. Learning
to read and write codes for a wide range of platforms, C provides a strong procedural background, which is a
ranging from embedded microcontrollers to advanced worthy skill-set.
scientific systems. The versatility of C is apparent from Some other features of C that give it the tag of the most
the fact that many modern operating systems have used C widely used professional language include its portability,
to develop their core. that is, a C program written on one computer can be made to
Developed by Dennis Ritchie in 1972, C has derived run on any other computer with little or few modifications
numerous features from its precursors such as ALGOL, and its extensibility, that is, any number of functions can
BCPL, and B. Its tremendous growth resulted in the be added to the C library and called any number of times
development of different versions of the language that in the program, thus making the code easier to write and
were similar but incompatible with each other, for example, understand. Therefore, it is not only desirable but also
the traditional C and K&R C. Therefore, the American necessary to have a strong fundamental knowledge of the
National Standards Institute (ANSI) in December 1989 C language.
defined a standard for the language and renamed it as ANSI
C. In 1990, the International Standards Organization (ISO)
adopted the ANSI standard. This version of C was known
as C89. In 1995, some minor changes were made to C89 I am grateful to my family, friends, and fellow members
and the new modified version was known as C95. During of the teaching staff at the Institute of Information
1990s, C++ and Java became popular among the users Technology and Management.
and hence the standardization committee felt the need to My special thanks would always go to my parents,
integrate a few features of C++/Java in C to enhance its brother Pallav, sisters Kimi and Rashi, and son Goransh.
usefulness. Some significant changes were made in 1999 My sincere thanks go to my uncle Mr B. L. Thareja for his
and the modified version became C99. inspiration and guidance in writing this book.
Since C is such a widely accepted and used language, Finally, I would like to acknowledge the technical
jumping to other modern-day programming languages assistance provided to me by Er Udit Chopra. I would
such as C++ and Java becomes much easier for a person like to thank him for sparing his precious time to help me
who is well acquainted with C. The programming design and test the programs.
constructs in C, such as ‘if’ statements, ‘for’ and ‘while’ Last but not the least, my acknowledgements will
loops and the types of variables used can be found in many remain incomplete if I do not thank the editorial staff at
modern languages, therefore the ideas expressed in C are Oxford University Press, India, who have supported my
well understood by program developers. Moreover, unlike
creative writing activities over the past few years.
most of the modern-day languages that apply object-
oriented design, C applies a procedural style of design, Reema Thareja
Brief Contents
Features of the Book iv

Preface to the Second Edition vi


Preface to the First Edition ix

Detailed Contents xi

ih. Introduction to Programming

. Introduction to C

. Decision Control and Looping Statements

. Functions

. Arrays 145

. Strings 19]

. Pointers pe

. Structure, Union, and Enumerated Data Types ei

. Files 301

. Preprocessor Directives 336

is Linked Lists 354

Answers to Objective Questions 378

Index 383
Detailed Contents
Features of the Book iv Preface to First Edition ix
Preface to Second Edition vi Brief Contents x

‘Introduction to Programming =. 1 2.10 Variables 24


2.10.1 Numeric Variables 24
Lol Introduction to Computer Software / 2.10.2 Character Variables 24
2.10.3 Declaring Variables 24
HZ Classification of Computer Software 2
2.10.4 Initializing Variables 25
1.2.1 System Software 2
1.2.2 Application Software 5 2.11 Constants 25
2.11.1 Integer Constant 25
3 Programming Languages 5
2.11.2 Floating Point Constant 26
1.4 Generation of Programming Languages 6 2.11.3 Character Constant 26
1.4.1 First Generation: Machine Language 6 2.11.4 String Constant 26
1.4.2 Second Generation: Assembly Language 7 2.11.5 Declaring Constants 26
1.4.3 Third Generation Programming Language 7
2.12 Input/output Statement in C 27
1.4.4 Fourth Generation: Very High-Level Languages 8
2.12.1 Streams 27
1.4.5 Fifth Generation Programming Language 8
2.12.2 Formatting Input/output 27
5 Categorization of High Level Languages 9 212.3 prince (25
1.5.1 Unstructured Programming 9 2.12.4 scanf() 30
1.5.2 Structured Programming Language 9 2.12.5 Examples printf/scanf 32
1.5.3 Logic-oriented Programming Language // 2.12.6 Detecting Errors During Data Input 34
1.5.4 Object-Oriented Programming //
2.13 Operators inC 35
2.13.1 Arithmetic Operators 35

Introductiontoc. 45 2.13.2 Relational Operators 36


2.13.3 Equality Operators 37
2.13.4 Logical Operators 38
Dal Introduction /5 2.13.5 Unary Operators 39
2.1.1 Background /5 2.13.6 Conditional Operator 40
2.1.2 Characteristics of C 16 2.13.7 Bitwise Operators 41
Mes IONE OME. ILH
2.13.8 Assignment Operators 42
2.2 Structure of C Program /7 2.13.9 Comma Operator 44
2.13.10 Sizeof Operator 44
Ye, Writing the First C Program 18
2.13.11 Operator Precedence Chart 44
2.4 Files Used in C Program 19
2.4.1 Source Code File 19 2.14 Programming Examples 45
2.4.2 Header Files 19 2.15 Type Conversion and Typecasting 48
2.4.3 Object Files 20 2.15.1 Type Conversion 49
2.4.4 Binary Executable File 20 2.15.2 Typecasting 50
2S Compiling and Executing C Programs 20 Annexure 1 59

2.6 Using Comments 2/


Zed, Keywords 22 3. Decision Control and Looping
2.8 Identifiers 22 tatements |
2.8.1 Rules for Forming Identifier Names 22
3.1 Introduction to Decision Control Statements 62
Des) Basic Data Types in C 23
2.9.1 How are Float and Double Stored? 24
| xii | Detailed Contents

3.2 Conditional Branching Statements 62 4.10.3 Fibonacci Series /33


3.2.1 I£ Statement 62 4.11 Types of Recursion /34
3.2.2. If-Else Statement 64 4.11.1 Direct Recursion 1/34
3.2.3 If-Else-If Statement 66 4.11.2 Indirect Recursion /34
3.2.4 Switch Case 7/ 4.11.3 Tail Recursion /34
3.3 Iterative Statements 75 4.11.4 Linear and Tree Recursion /35
3.3.1 While Loop 75 4.12 Tower of Hanoi 136
3.3.2. Do-while Loop 78
4.13 Recursion versus Iteration /37
3.3.3 for Loop 80
Annexure 3 144 ‘
3.4 Nested Loops 83
3.5 break and continue Statements 93
3.5.1 break Statement 93
3.5.2. continue Statement 93
5.1 Introduction /45
3.6 goto Statement 95
3.7 Building a Robust C Program 97 5.2 Declaration of Arrays 146
s

Annexure 2 107 5.3 Accessing Array Elements 1/47


5.3.1 Calculating the Address of Array Elements /47
Case Study for Chapters 2 and 3 I11
5.4 Storing Values in Arrays 148
5.4.1 Initialization of Arrays 148
5.4.2 Inputting Values 148
5.4.3 Assigning Values 149
4.1 Introduction 1/5
5.5 Length of an Array 149
4.1.1 Why are Functions Needed? 1/5
5.6 Array Operations 150
4.2 Using Functions //6
5.6.1 Traversal 150
4.3 Function Declaration/Function Prototype //7 5.6.2 Insertion 155
4.4 Function Definition 1/8 5.6.3 Deletion 158
5.6.4 Merging 160
4.5 Function Call 1/8
5.6.5 Searching /62
4.5.1 Points to Remember While Calling a
Function 119 5.7 One-Dimensional Arrays for Inter-Function
Communication /65
4.6 Return Statement /20
4.6.2 Using Variable Number of Arguments /2/ 5.8 Two-Dimensional Arrays 168
5.8.1 Declaration of Two-dimensional Arrays 169
4.7 Passing Parameters to the Function /2/
5.8.2 Initialization of Two-dimensional Arrays /70
4.7.1 Call by Value 12/
5.8.3 Accessing the Elements /7/]
4.7.2 Call by Reference /22
5.9 Operations on Two-dimensional(2D) Arrays 173
4.8 Scope of Variables 125
4.8.1 Block Scope 125 5.10 Two-Dimensional Arrays for Inter-Function
4.8.2 Function Scope 126 Communication 1/76
4.8.3 Program Scope 126 5.10.1 Passing a Row 176
4.8.4 File Scope /27 5.10.2 Passing an Entire 2D Array 176

4.9 Storage Classes 127 5.11 Multidimensional Arrays 178


4.9.1 auto Storage Class 128 5.12 Sparse Matrices 180
4.9.2 register Storage Class 128
Annexure 4 186
4.9.3 extern Storage Class 129
494 static Storage Class 130
4.9.5 Comparison of Storage Classes 130
4.10 Recursive Functions /3/
4.10.1 Greatest Common Divisor /32 6.1 Introduction /9/
4.10.2 Finding Exponents /32 6.1.1 Reading Strings /93
Detailed Contents | Xili |

6.1.2 Writing Strings 193 7.15 Function Pointers 249


6.1.3. Summary of Functions Used to Read and Write 7.15.1 Initializing a Function Pointer 249
Characters 194 7.15.2 Calling a Function Using a Function Pointer 249
6.2 Suppressing Input 196 7.15.3 Comparing Function Pointers 250
6.2.1 Using a Scanset 196 7.15.4 Passing a Function Pointer as an Argument to a
Function 250
6.3 String Taxonomy /97
7.16 Array of Function Pointers 250
6.4 String Operations 198
6.4.1 Length 198 7.17 Pointers to Pointers 25/
6.4.2 Converting Characters of a String into Upper 7.18 Memory Allocation in C Programs 252
Case 199 gs
7.19 Memory Usage 252
6.4.3 Converting Characters of a String into Lower
Case 199 7.20 Dynamic Memory Allocation 252
6.4.4 Concatenating Two Strings to form a New 7.20.1 Memory Allocations Process 253
String 200 7.20.2 Allocating a Block of Memory 253
6.4.5 Appending 20] . 7.20.3 Releasing the used Space 254
6.4.6 Comparing Two Strings 20/ 7.20.4 To alter the Size of Allocated Memory 254
6.4.7 Reversing a String 202 7.21 Drawbacks of Pointers 256
6.4.8 Extracting a Substring from Left 203 Annexure 5 265
6.4.9 Extracting a Substring from Right of the
String 203 Case Study for Chapters 6 and 7 268
6.4.10 Extracting a Substring from the Middle of a
String 204
6.4.11 Insertion 205 _ Struc and Enumerated _
6.4.12 Indexing 205 - Data ees
an
6.4.13 Deletion 206
6.4.14 Replacement 207 8.1 Introduction 27]
6.5 Miscellaneous String and Character Functions 207 8.1.1 Structure Declaration 27/
6.5.1 Character Manipulation Functions 208 8.1.2 Typedef Declarations 273
6.5.2 String Manipulation Functions 208 8.1.3 Initialization of Structures 273
8.1.4 Accessing the Members of a Structure 274
6.6 Array of Strings 2/3
8.1.5 Copying and Comparing Structures 274
8.2 Nested Structures 277
7 Powters = 8.3. Arrays of Structures 278
8.4 Structures and Functions 280
7.1 Understanding the Computer’s Memory 225
8.4.1 Passing Individual Members 280
7.2 Introduction to Pointers 226 8.4.2 Passing the Entire Structure 28/
7.3 Declaring Pointer Variables 227 8.4.3 Passing Structures Through Pointers 284
7.4 Pointer Expressions and Pointer Arithmetic 229 8.5 Self-referential Structures 288
7.5 Null Pointers 233 8.6 Union 289
7.6 Generic Pointers 233 8.6.1 Declaring a Union 289
8.6.2 Accessing a Member of a Union 289
7.7 Passing Arguments to Function Using Pointers 234
8.6.3 Initializing Unions 289
7.8 Pointers and Arrays 235
8.7 Arrays of Union Variables 290
7.9 Passing an Array to a Function 239
8.8 Unions Inside Structures 290
7.10 Difference between Array Name and Pointer 240
8.9 Enumerated Data Types 29/
7.11 Pointers and Strings 24/ 8.9.1 Enum Variables 292
7.12 Array of Pointers 244 8.9.2 Using the Typedef Keyword 292
8.9.3 Assigning Values to Enumerated Variables 292
7.13 Pointers and 2-D Arrays 246
8.9.4 Enumeration Type Conversion 292
7.14 Pointers and 3-D Array 248 8.9.5 Comparing Enumerated Types 293
xiv | Detailed Contents

8.9.6 Input/Output Operations on Enumerated 10.3 #define 337


Types 293 10.3.1 Object-like Macro 337
Annexure 6 299 10.3.2 Function-like Macros 338
10.3.3 Nesting of Macros 339
10.3.4 Rules for Using Macros 339
Goo files = 308 10.3.5 Operators Related to Macros 339
10.4 #include 340
9.1 Introduction to Files 30/
9.1.1 Streams inC 30/
10.5 #undef 34/
9.1.2 Buffer Associated with File Stream 302 10.6 #line 341
9.1.3 Types of Files 302 10.7 Pragma Directives 342
9.2 Using Files in C 303 10.8 Conditional Directives 343
9.2.1 Declaring a File Pointer Variable 303 10.8.1 #ifdef 344
9.2.2 Opening a File 303 10.8.2 #ifndef 344
9.2.3 Closing a file using fclose () 305 10.8.3 The #if Directive 345
9.3 Read Data from Files 305 10.8.4 The #else Directive 345
9.3.1 fscanf() 305 10.8.5 The #elif Directive 345
9.3.2 fgets() 306 10.8.6 The #endif Directive 346
03.3 ifgeto() 307, 10.9 The Defined Operator 346
9.3.4 fread () 307 10.10 #error Directive 347
9.4 Writing Data to Files 308 10.11 Predefined Macro Names 347
9.4.1 fprintf() 308 Annexure 7 351
9.4.2 fputs() 310
9.4.3 fpute () 3/0
9.4.4 fwrite() 31/ ais linkediists
9.5 Detecting the End-of-File 3//
11.1 Introduction 354
9.6 Error Handling During File Operations 3/2
Soul clearerr@) 372 11.2 Linked Lists versus Arrays 355
9.6.2 perror() 3/3 11.3 Memory Allocation and Deallocation for a Linked
9.7 Accepting Command Line Arguments 3/3 List355
9.8 Functions for Selecting a Record Randomly 327 11.4 Different Types of Linked Lists 357
98:1 tseek ()"327 11.5 Singly Linked List 357
9.8.2 ftell() 329 11.5.1 Traversing a Singly Linked List 357
9.8.3 rewind () 329 11.5.2 Inserting a New Node’in a Linked List 358
9.8.4 fgetpos () 330
11.6 Circular Linked List 366
9.8.5 fsetpos () 330
11.7 Doubly Linked List 367
9.9 remove () 33/
11.8 Circular Doubly Linked List 368
9.10 Renaming the File 33/
11.9 Header Linked List 368
9.11 Creating a Temporary File 33/
Case Study for Chapters 8, 9, and 11 374

10. Preprocessor Directives —- 336 Answers to Objective Questions 378

Index 383
10.1 Introduction 336
10.2 Types of Preprocessor Directives 336
. oe

tae

or

CHAPTER

Introduction to Programming
S

Takeaways
© System Software © Application Software © Compiler, Interpreter, Linker, Loader
*® Generation of Programming Languages © Structured and Unstructured Programming @ Logic-oriented Programming
© Object-oriented Programming

the software would be the intelligence which helps in


1.1 INTRODUCTION TO COMPUTER
interpreting the images that are seen by the eyes, instructing
SOFTWARE the arms how to lift objects, and understandable to the
When we talk about a computer, we actually mean two filling the lungs with air.
things (Fig. 1.1): Since the computer hardware is part of a machine, it
can only understand two basic concepts: on and off. The
e First is the computer hardware that does all the
on and off concept is called binary. Computer software
physical work computers are known for.
was developed to make efficient use of binary to instruct
e Second is the computer software that commands the the hardware to perform meaningful tasks.
hardware what to do and how to do it. The computer hardware cannot think and make
decisions on its own. So, it cannot be used to analyse
a given set of data and find a solution on its own. The
hardware needs a software (a set of programs) to instruct
what has to be done. A program is a set of instructions
that is arranged in a sequence to guide a computer to find
a solution for the given problem. The process of writing a
program is called programming.
Computer software is written by computer programmers
using a programming language. The programmer writes a
“System softw:are Application software
set of instructions (program) using a specific programming
language. Such instructions are known as the source code.
aratigesial Parts of a computer system
Another computer program called a compiler is then used
on the source code, to transform the instructions into a
If we think of computer as a living being, then the language that the computer can understand. The result is an
hardware would be the body that does things like seeing executable computer program, which is another name for
with eyes, lifting objects, and filling the lungs with air; software.
| 2 | Introduction to C Programming

Examples of computer software include: we think of when we say the word computer
e Computer games are widely used as a form of enter- programs. Examples of application software include
tainment software that has many genres. spreadsheets, database systems, desktop publishing
systems, program development software, games,
e Driver software which allows a computer to interact
web browser, among others. Simply put, application
with additional hardware devices such as printers,
software represents programs that allow users to do
scanners, and video cards.
something besides simply run the hardware.
e Educational software includes programs and
games that help in teaching and providing drills to
help memorize facts. Educational software can be User 1 User 2 :
diversely used—from teaching computer-related
activities like typing to higher education subjects like
Chemistry. Application programs (f ames, spreadsheets,
word processor, database, web browsers)
e Media players and media development software that
are specifically designed to play and/or edit digital
media files such as music and videos.
Software (operating
e Productivity software is an older term used to
denote any program that allows the user to be
more productive in a business sense. Examples of
such software include word processors, database eyboatd, CPU, disk)’
management utilities, and presentation software.
e Operating system software which helps in oo 1. 2 Relationship between hardware, system
coordinating system resources and allows execution _ software, and application software
of other programs. Some operating systems include
Windows Vista, Mac OS X, and Linux.
1.2.1 System Software

12 CLASSIFICATION OF COMPUTER © System software is software designed to operate the


computer hardware and to provide and maintain a platform
SOFTWARE
for running application software.
Computer software can be broadly classified into two The most widely used system software are discussed in
groups: system software and application software. the following sections:
e System software [according to Nutt (1997)] provides
a general programming environment in which Computer BIOS and Device Drivers
programmers can create specific applications to suit The computer BIOS and device drivers provide basic
their needs. This environment provides new functions functionality to operate and control the hardware connected
that are not available at the hardware level and to or built into the computer.
performs tasks related to executing the application BIOS or the basic input/output system is a de facto
program. standard defining a firmware interface. The BIOS is built
System software represents programs that allow into the computer and is the first code run by the computer
the hardware to run properly. System software when it is switched on. The key role of the BIOS is to load
is transparent to the user and acts as an interface and start the operating system.
between the hardware of the computer and the When the computer starts, the first function that BIOS
application software that users need to run on the performs is to initialize and identify system devices such
computer. Figure 1.2 illustrates the relationship as the video display card, keyboard and mouse, hard disk,
between application software, system software, and CD/DVD drive, and other hardware. In other words, the
hardware. code in the BIOS chip runs a series of tests called POST
e Application software is designed to solve a (Power On Self Test) to ensure that the system devices are
particular problem for users. It is generally what working correctly.
Introduction to Programming | 3 |

The BIOS then locates software held on a peripheral Operating System


device such as a hard disk or a CD, and loads and executes
The primary goal of an operating system is to make
that software, giving it control of the computer. This
the computer system (or any other device in which it is
process is known as booting.
installed like the cell phone) convenient and efficient
BIOS is stored on a ROM chip built into the system. A
to use. The operating system offers generic services to
BIOS will also have a user interface like that of a menu
support user applications.
(Fig. 1.3) that can be accessed by pressing a certain key
From the user’s point of view the primary consideration
on the keyboard when the PC starts. The BIOS menu
is always the convenience. Users should find it easy to
can enable the user to configure hardware, set the system
launch an application and work on it. For example, we
clock, enable or disable system components, and most
use icons which give us a clue about the application. We
importantly, select which devices are eligible to be a
have a different icon for launching a web browser, e-mail
potential boot device and set various password prompts.
application, or even a document preparation application.
To summarize, BIOS performs the following functions:
In other words, it is the human—computer interface which
e Initializes the system hardware helps to identify and launch an application. The interface
e Initializes system registers hides a lot of details of the instructions that perform all
e Initializes power management system these tasks.
Similarly, if we examine the programs that help us in using
e Tests RAM
input devices like keyboard/mouse, all the complex details
e Test all the serial and parallel ports of the character reading program are hidden from the user.
e Initializes floppy disk drive and hard disk controllers We as users simply press buttons to perform the input op-
e Displays system summary information eration regardless of the complexity of the details involved.

Figure 1.3 BIOS menu oe


4 | Introduction to C Programming

An operating system ensures that the system resources e File managers can be used to provide a convenient
(e.g., CPU, memory, I/O devices, etc.) are utilized efficiently. method of performing routine data management
For example, there may be many service requests on a web tasks such as deleting, renaming, cataloguing,
server and each user request need to be serviced. Moreover, moving, copying, merging, generating, and
there may be many programs residing in the main memory. modifying data sets.
Therefore, the system needs to determine which programs e System profilers can be used to provide detailed
are currently being executed and which programs need to information about the software installed and
wait for some I/O operation. This information is necessary hardware attached to the computer.
because the programs that need to wait can be suspended
e Anti-virus utilities are used to scan for computer
temporarily from engaging the processor. Hence, it is
viruses.
important for an operating system to have a control policy
e Data compression utilities can be used to output a
and algorithm to allocate the system resources.
file with reduced file size.
Utility Software e Cryptographic utilities can be used to encrypt and
decrypt files.
Utility software is used to analyse, configure, optimize, and
e Launcher applications can be used as a convenient
maintain the computer system. Utility programs may be
access point for application software.
requested by application programs during their execution
for multiple purposes. Some of them are as follows: e Registry cleaners can be used to clean and optimize
the Windows registry by deleting the old registry
e Disk defragmenters can be used to detect computer
keys that are no longer in use.
files whose contents are broken across several
e Network utilities can be used to analyse the
locations on the hard disk, and move the fragments
computer’s network connectivity, configure network
to one location in order to increase efficiency.
settings, check data transfer, or log events.
e Disk checkers can be used to scan the contents
e Command line interface (CLI) and Graphical user
of a hard disk to find files or areas that are either
interface (GUI) can be used to make changes to the
corrupted in some way, or were not correctly saved,
operating system.
and eliminate them in order to make the hard drive
operate more efficiently.
Compiler, Interpreter, Linker, and Loader
e Disk cleaners can be used to locate files that are
either not required for computer operation, or take Compiler It is a special type of program that transforms
up considerable amounts of space. Disk cleaners source code written in a programming language (the source
help the user to decide what to delete when their language) into machine language comprising just two
hard disk is full. digits, 1s and Os (the target language). The resultant code
e Disk space analysers are used for visualizing the in 1s and Os is known as the object code. The object code is
disk space usage by getting the size for each folder the one which will be used to create an executable program.
(including sub folders) and files in a folder or drive. Therefore, a compiler is used to translate source code
e Disk partitions are used to divide an individual drive from a high-level programming language to a lower level
into multiple logical drives, each with its own file language (e.g., assembly language or machine code).
system. Each partition is then treated as an individual If the source code contains errors then the compiler will
drive. not be able to perform its intended task. Errors that limit
e Backup utilities can be used to make a copy of all the compiler in understanding a program are called syntax
information stored on a disk. In case a disk failure errors. Syntax errors may be spelling mistakes, typing
occurs, backup utilities can be used to restore the mistakes, etc. Another type of error is logical error which
entire disk. Even if a file gets deleted accidentally, occurs when the program does not function accurately.
the backup utility can be used to restore the deleted Logical errors are much harder to locate and correct.
file. The work of a compiler is simply to translate human
e Disk compression can be used to enhance the readable source code into computer executable machine
capacity of the disk by compressing/decompressing code. It can locate syntax errors in the program (if any)
the contents of a disk. but cannot fix it. Until and unless the syntactical error
Introduction to Programming — |
5 |

is rectified the source code cannot be converted into the a user-defined task. This is in contrast with system
object code. software which is involved in integrating a computer’s
capabilities, but typically does not directly apply them in
Interpreter Like the compiler, the interpreter also executes
the performance of tasks that benefit the user.
instructions written in a high-level language. Basically, a
To better understand application software consider an
program written in a high-level language can be executed
analogy where hardware would depict the relationship of
in any of the two ways. First by compiling the program
an electric light bulb (an application) to an electric power
and second, to pass the program through an interpreter.
generation plant (a system) that depicts the software.
While the compiler translates instructions written in
The power plant merely generates electricity which is
high level programming language directly into the machine
not by itself of any real use until harnessed to an application
language; the interpreter on the other hand, translates
like the electric light that performs a service which actually
the instructions into an intermediate form, which it then
benefits the user.
executes. This clearly means that the interpreter interprets
Typical examples of software applications are word
the source code line by line. This is in striking contrast with
processors, spreadsheets, media players, education software,
the compiler which compiles the entire code in one go. CAD, CAM, data communication software, statistical and
Usually, a compiled program executes faster than operational research software, etc. Multiple applications
an interpreted program. However, the big advantage of bundled together as a package are sometimes referred to as
an interpreter is that it does not need to go through the an application suite.
compilation stage during which machine instructions are
generated. This process can be time consuming if the
program is long. Moreover, the interpreter can immediately 1.3 PROGRAMMING LANGUAGES |
execute high-level programs.
A programming language is a language specifically
All in all, compilers and interpreters both achieve
designed to express computations that can be performed
similar purposes, but inherently different as to how they
by the computer. Programming languages are used to
achieve that purpose.
create programs that control the behaviour of a system,
Linker (link editor binder), It is a program that combines to express algorithms, or as a mode of human-computer
object modules to form an executable program. Generally, communication.
in case of a large program, the programmers prefer to Usually, programming languages have a vocabulary of
break a code into smaller modules as this simplifies the syntax and semantics for instructing a computer to perform
programming task. Eventually, when the source code of all specific tasks. The term programming language usually
the modules has been converted into object code, you need refers to high-level languages, such as BASIC, C, C++,
to put all the modules together. This is the job of the linker. COBOL, FORTRAN, Ada, and Pascal to name a few. Each
Usually, the compiler automatically invokes the linker as of these languages has a unique set of keywords (words
the last step in compiling a program. that it understands) and a special syntax for organizing
program instructions.
Loader It isa special type of program that copies programs While high-level programming languages are easy
from a storage device to main memory, where they can be for the humans to read and understand, the computer
executed. However, in this book we will not go into the actually understands the machine language that consists
details of how a loader actually works. This is because of numbers only. Each different type of CPU has its own
the functionality of a loader is generally hidden from unique machine language.
the programmer. As a programmer, it suffices to learn In between the machine languages and high-level
that the task of a loader is to bring the program and all its languages, there is another type of language known as
related files into the main memory from where it can be assembly language. Assembly languages are similar to
executed by the CPU. machine languages, but they are much easier to program
because they allow a programmer to substitute names for
numbers.
1.2.2 Application Software
However, irrespective of what language the programmer
Application software is a type of computer software that uses, the program written using any programming
employs the capabilities of a computer directly to perform language has to be converted into machine language so
| 6 | Introduction to C Programming

that the computer can understand it. There are two ways to In the 1950s each computer had its own native
do this: compile the program or interpret the program. language, and programmers had primitive systems for
The question of which language is the best depends on combining numbers to represent instructions such as add
the following factors: and subtract. Although there were similarities between
e The type of computer on which the program has to each of the machine languages a computer could not
be executed understand programs written in another machine language
(Fig. 1.4).
e The type of program
e The expertise of the programmer
For example, FORTRAN is a particularly good <_ MACHINE LANGUAGE
is [Link] example of a
language for processing numerical data, but it does not
am
two pnp ers:ee findt
lend itself very well to organizing large programs. Pascal
can be used for writing well-structured and readable
programs, but it is not as flexible as the C programming
language. C++ goes one step ahead of C by incorporating
powerful object-oriented features, but it is complex and
difficult to learn.

1.4 GENERATION | Pokaan

We now know that programming languages are the


primary tools for creating software. As of now, hundreds
of programming languages exist in the market, some
more used than others, and each claiming to be the best.
However, back in 1940s when computers were being
developed there was just one language—the machine
language.
The concept of generations of programming languages aratigaseces A machine langu
(also known as levels), is closely connected to the advances
in technology that brought about computer generations.
In machine language, all instructions, memory locations,
The four generations of programming languages include:
numbers, and characters are represented in strings of Is
e machine language and 0s. Although machine-language programs are typically
e assembly language displayed with the binary numbers represented in octal
e high-level language (also known as third generation (base 8) or hexadecimal (base 16), these programs are not
language or 3GL) easy for humans to read, write, or debug.
e very high-level language (also known as fourth The main advantage of machine language is that the
generation language or 4GL). code can run very fast and efficiently, since it is directly
executed by the CPU.
However, on the down side, the machine language is
1.4.1 First Generation: Machine Language
difficult to learn and is far more difficult to edit if errors
Machine language was used to program the first stored occur. Moreover, if you want to add some instructions
program on computer systems. This is the lowest level into memory at some location, then all the instructions
of programming language. The machine language is the after the insertion point would have to be moved down
only language that the computer understands. All the to make room in sey to accommodate the new
commands and data values are expressed using Is and Os, instructions.
corresponding to the ‘on’ and ‘off? electrical states in a Last but not the least, the code written in machine
computer. language is not portable across systems and to transfer
Introductionto Programming | 7 |

the code to a different computer it needs to be completely understand only the language of Is and Os and will not
rewritten since the machine language for one computer understand mnemonics like ADD and SUB.
could be significantly different from another computer. The following instructions are a part of assembly
Architectural considerations made portability a tough language code to illustrate addition of two numbers:
issue to resolve.
MOV AX,4 Stores the value 4 in the AX
register of CPU
1.4.2 Second Generation: Assembly Language MOV BX,6 Stores the value 6 in the BX
register of CPU
The second generation of programming language includes
ADD AX,BX Add the contents of AX and BX
the assembly language. Assembly languages are symbolic
register. Store the result in
programming languages that use symbolic notation to
AX register
represent machine-language instructions. These languages
are closely connected to machine language and the internal Although assembly languages are much better to work
architecture of the computer system on which they are as compared to the machine language, they still require the
used. Since they are close ,to the machine, assembly programmer to think on the machine’s level. Even today,
language is also called low-level language. Nearly all some programmers still use assembly language to write
computer systems have an assembly language available parts of applications where speed of execution is critical,
for use. such as video games but most programmers today have
Assembly language developed in the mid 1950s switched to 3GL or 4GLs to do the same.
was a great leap forward. It used symbolic codes also
known as mnemonic codes that are easy-to-remember 1.4.3 Third Generation Programming Language
abbreviations, rather than numbers. Examples of these
A third generation programming language (3GL) is
codes include ADD for add, CMP for compare, MUL for
a refinement of the second-generation programming
multiply, etc.
Assembly language programs consist of a series of language. The 2GL languages brought logical structure to
individual statements or instructions that instruct the com- software. The third generation was introduced to make the
puter what to do. Basically, an assembly language state- languages more programmer friendly.
ment consists of a /abel, an operation code, and one or 3GLs spurred the great increase in data processing that
more operands. occurred in the 1960s and 1970s. In these languages, the
Labels are used to identify and reference instructions in program statements are not closely related to the internal
the program. The operation code (opcode) is a mnemonic characteristics of the computer and is therefore often
that specifies the operation that has to be performed such referred to as high-level language.
as move, add, subtract, or compare. The operand specifies Generally, a statement written in a high-level program-
the register or the location in main memory from where ming language will expand into several machine language
the data to be processed is located. instructions. This is in contrast to assembly languages,
However, like the machine language, the statement where one statement would generate one machine lan-
or instruction in the assembly language will vary from guage instruction. 3GLs made programming easier, effi-
one machine to another because the language is directly cient, and less prone to errors.
related to the internal architecture of the computer and is High-level languages fall somewhere between natural
not designed to be machine independent. This makes the languages and machine languages. 3GL includes languag-
code written in assembly language less portable as the es like FORTRAN (FORmula TRANslator) and COBOL
code written for one machine will not run on machines (COmmon Business Oriented Language) that made it pos-
from a different or sometimes even the same manufacturer. sible for scientists and business people to write programs
No doubt, the code written in assembly language will be using familiar terms instead of obscure machine instruc-
very efficient in terms of execution time and main memory tions.
usage as the language is also close to the computer. The first widespread use of high-level languages in the
Programs written in assembly language need a early 1960s changed programming into something quite
translator often known as the assembler to convert them different from what it had been. Programs were written
into machine language. This is because the computer will in an English-like manner, making them more convenient
| 8 | Introduction to C Programming

to use and giving the programmer more time to address a There is no standard rule that defines what a fourth-
client’s problems. generation language is but certain characteristics of such
Although 3GLs relieve the programmer of demanding language include:
details they do not provide the flexibility available in low- e the code comprising instructions are written in
level languages. However, a few high-level languages English-like sentences;
like C and FORTRAN combine some of the flexibility
e they are non-procedural, so users concentrate on
of assembly language with the power of high-level
‘what’ instead of the ‘how’ aspect of the task;
languages, but these languages are not well suited to the
e the code is easier to maintain;
amateur programmer.
While some high level-languages were designed to serve e 4GL code enhances the productivity of the
a specific purpose (such as controlling industrial robots programmers as they have to type fewer lines of code
or creating graphics), other languages were flexible and to get something done. It is said that a programmer
considered to be general-purpose languages. Most of the becomes 10 times more productive when he writes
programmers preferred to use general purpose high-level the code using a 4GL than using a 3GL.
languages like BASIC (Beginners’ All-purpose Symbolic A typical example of a 4GL is the query language that
Instruction Code), FORTRAN, PASCAL, COBOL, C++, or allows a user to request information from a database with
Java to write the code for their applications. precisely worded English-like sentences. A query language
Again, a translator is needed to translate the instructions is used as a database user interface and hides the specific
written in high-level language into computer-executable details of the database from the user. For example, when
machine language. Such translators are commonly known working with Structured Query Language (SQL), the
as interpreters and compilers. Each high level language programmer just needs to remember a few rules of syntax
has many compilers. and logic, but it is easier to learn than COBOL or C.
For example, the machine language generated by one Let us take an example in which a report has to be
computer’s C compiler is not the same as the machine generated that displays the total number of students
language of some other computer. Therefore, it is necessary enrolled in each class and in each semester. Using a 4GL,
to have a C compiler for each type of computer on which the request would look similar to this:
the C program has to be executed.
TABLE FILE ENROLLMENT
3GLs make it easier to write and debug a program and
SUM STUDENTS BY SEMESTER BY CLASS
gives the programmer more time to think about its overall
logic. The programs written in such languages are portable So we see that a 4GL is much simpler to learn and work
between machines. For example, a program written in with. The same code if written in C language or any other
standard C can be compiled and executed on any computer 3GL would require multiple lines of code to do the same
that has a standard C compiler. task. ,
4GLs are still evolving, which makes it difficult to
1.4.4 Fourth Generation: Very High-Level define or standardize them. The only down side of a 4GL
Languages is that it does not make efficient use of the machine’s
resources. However, the benefit of executing a program
With each generation, programming languages started fast and easily, far outweighs the extra costs of running it.
becoming easier to use and more like natural languages.
However, 4GLs 1s a little different from its prior generation
1.4.5 Fifth Generation Programming Language
because they are basically non-procedural. When writing
code using a procedural language, the programmer has to 5GLs are centred on solving problems using constraints
tell the computer how a task is done—add this, compare given to the program, rather than using an algorithm
that, do this if the condition is true, and so on, in a very written by a programmer. Most constraint-based and logic
specific step-by-step manner. In striking contrast, while programming languages and some declarative languages
using a non-procedural language the programmers define form a part of the fifth-generation languages. 5GLs are
only what they want the computer to do, without supplying widely used in artificial intelligence research. Typical
all the details of how it has to be done. examples of a 5GL include Prolog, OPSS, and Mercury.
Introduction to Programming | 9 |

Another aspect of a 5GL is that it contains visual tools 1.5.1 Unstructured Programming
to help develop a program. A good example of a fifth
In unstructured programming, programmers write small
generation language is Visual Basic.
and simple programs consisting only of one main program.
So taking a forward leap than the 4GLs, 5GLs are
Here the main() con-
designed to make the computer solve a given problem
sisted of statements that
without the programmer. While working with a 4GL, the
modifies the data which
programmer had to write specific code to do a work but
is global throughout the
with 5GL, the programmer only needs to worry about
whole program. Refer Fig.
what problems need to be solved and what conditions need
1.6. Though this technique
to be met, without worrying about how to implement a
is simple, but is not good
routine or algorithm to solve them.
for writing large programs. Figure a3) |Unstructured
Generally, 5GLs were built upon Lisp, many originating
For example, if we need to ‘programming
on the Lisp machine, such as ICAD. Then, there are many
perform a particular task
frame languages such as KL-ONE.
multiple times in the program, then we need to copy the
In the 1990s, 5GLs wereconsidered to be the wave of
same sequence of statements at different locations within
the future, and some predicted that they would replace all
the program. This has lead to the idea to write functions or
other languages for system development (except the low-
procedures. The new technique of using procedures came
level languages). In 1982 to 1993 Japan had put much
to be known as procedural programming.
research and money into their fifth generation computer
systems project, hoping to design a massive computer
network of machines using these tools. But when larger 1.5.2 Structured Programming Language
programs were built, the flaws of the approach became Structured programming also referred as modular
more apparent. Researchers began to observe that starting programming was first suggested by two mathematicians—
from a set of constraints for defining a particular problem, Corrado Bohm and Guiseppe Jacopini. It is basically a
then deriving an efficient algorithm to solve the problem subset of procedural programming that enforces a logical
is a very difficult task. All these things could not be structure on the program to make it more efficient and
automated and still requires the insight of a programmer. easier to understand and modify.
However, today the fifth-generation languages are back Structured programming employs a top-down approach
as a possible level of computer language. Software vendors in which the overall program structure is broken down
across the globe currently claim that their software meets into separate modules. This allows the code to be loaded
the visual ‘programming’ requirements of the SGL concept. into memory more efficiently and also be reused in other
programs. Modules are coded separately and once a module
EL is written and tested individually, it is then integrated with
15 _CATEGOR ZATION OFHIGH LEV other modules to form the overall program structure.
bon
-LANGUA 5ES_ Structured programming is therefore based on
High level languages can be easily categorized into four modularization which groups related statements together
groups based on programming paradigm supported by (modules). Modularization makes it easier to write,
them (refer Fig. 1.5). Programming paradigm refers to the debug, and understand the program.
approach the programming language has employed for Ideally, modules should not be longer than a page. It
solving different types of problems. is always easy to understand a series of 10 single-page
modules than it is a single ten-page program.
For some large and complex programs, the overall
High level language program structure may further require the need to break
the modules into subsidiary pieces. This process continues
until an individual piece of code can be written easily.
Almost any language can use structured programming
techniques to avoid common pitfalls of unstructured
languages. Unstructured programs depend on _ the
een Categorizatition
o of high level languages
programmer’s skills to avoid structural problems and
| 10 | Introduction to C Programming

are therefore poorly organized. Most modern procedural instructions that are not grouped for specific tasks.
languages support the concepts of structured programming. Their logic is cluttered with details and therefore
Even the object-oriented programming can be thought difficult to follow.
of as a type of structured programming, as its uses the e Individual procedures are easy to change as well
techniques of structured programming for program flow, as understand. In a structured program every
and adds more structure for data to the model. procedure has meaningful names and has clear
In structured programming, the program flow documentation to identify the task performed by it.
follows a simple sequence and usually avoids the use Moreover, a correctly written structured program is
of GoTo statements. Besides sequential flow, structured self-documenting and can be easily understood by
programming also supports selection and repetition. another programmer. }
Selection allows for choosing any one of a number of
statements to execute, based on the current status of the Example Imagine that your institute wants to create a
program. Selection statements contain keywords like “if,” program to manage a name and address list of students.
“then,” “endif,” or “switch” that help to identify the order For this, you would break down the program into the
as a logical executable. following modules:
In repetition, a selected statement remains active until
1. Enter new names and address. .
the program reaches a point where there is a need for
2. Modify existing entries.
some other action to take place. It includes keywords like
3. Sort entries
“repeat,” “for,” or “do...until.” Essentially, the repetition
4. Printing the list
instructs the program how long to continue the function
before requesting further instructions. Now each of the above modules can be further broken
down into smaller modules. For example, Enter new entries
Advantages modules can be subdivided into modules like

e The goal of structured programming is to write cor- e Prompt the user to enter new data
rect programs that are easy to understand and change. e Read the existing list from the disk
e Modules enhance programmer’s productivity by e Add the name and address to the existing list
allowing them to look at the big picture first and then e Save the updated list to the disk
focus on details later. Similarly, modify existing entries can further be divided into
e With modules, many programmers can work on a modules like:
single, large program, each working on a different
e Read the existing list from disk.
module.
e Modify one or more entries.
e A structured program takes less time to be written
e Save the updated list to disk.
than other programs. Modules or procedures written
for one program can be reused in other programs also. Observe that two sub-modules: Read the existing list from
disk and save the updated list to disk are common to both
e A structured program is easy to debug because in
the modules. So once these sub-modules are written they
it each procedure is specialized to perform just one can be used by both the modules which require the same
task so every procedure can be checked individually task to be performed. Structured programming method
for the presence of any error. In striking contrast, results in a hierarchical or layered program structure, which
unstructured programs consist of a sequence of is depicted in Fig. 1.7.

iM: inprogram to maintain the name and address listofthe students |

Addthe ~ : Save the Read | Modify Save the —


new entry | updated list list ligt, updated list

Figure 1.7 [yas program structure


Introductionto Programming | 11 |

1.5.3 Logic-oriented Programming Language


Logic-oriented programming languages employs a pro-
gramming paradigm that is based on formal predicate
logic. The logic paradigm is remarkably different from
the other programming paradigms. The predicate logic de-
scribes the nature of a problem by defining relationships
between rules and facts. These rules together with an in-
ference algorithm form a program. Prolog, Lisp, and Dat-
Object | )
alog are few examples of logic-oriented programming 3
languages. Z
The logical sentence in logic program is given in the form
of
OW, Wy SE EO) etal alg)
For example, the sister relation can be defined using other
‘Objects ofthe progra n inte
simpler relations and properties father, mother, female as
sending messages to each
shown in Fig. 1.8. According to the figure, A can be a sister
of B if both A and B have the same father and mother and
A is a female. Figure sl) Object-oriented paradigm _

Sister(A, B):- de Aiis the sister of B) if there are two | the actions the software should accomplish. However, the
people F and M for which */ object-oriented paradigm is task-based and data-based.
Father(F, A | /* F is the father of A+)
In the object-oriented paradigm, all the relevant data and
/* Fisthe father ofB 7
* Mis the mother of A 7) tasks are grouped together in entities known as objects.
Mother(M, AA * Mis the mother of B */ | For example, consider a list of numbers stored in
: ey * Aisa female */ — an array. The procedural or modular programming
paradigm considers this list as merely a collection of
Figure 1.8 Predicate logic that defines a sister data. Any program that accesses this list must have some
| relationship procedures/functions to process this list. For example, to
find the largest number or to sort the numbers in the list,
We have already seen that mathematical (or Boolean) we needed specific procedures/functions to do the task.
logic has played a vital role in design of logic circuits Thus, the list is passive entity as it is maintained by a
which forms the basis of any computer system. Therefore, controlling program rather than having the responsibility
in logic-oriented programming languages, a more
of maintaining itself.
advanced construct called predicate logic is used. In these
However, in the object-oriented paradigm, the list and
languages, different logical assertions about a situation
are made, establishing all known facts. Then queries are the associated operations are treated as one entity known
made and any deducible solution to the query is returned as an object. So, in the object-oriented approach, the list is
as output. The role of the computer in this paradigm is thus considered an object consisting of the list together with a
to maintain data and make logical deductions. collection of routines for manipulating the list. In the list
There are two main advantages of using logic-oriented object, there may be routines for adding a number to the
programming. First, the computer solves the problem so list, deleting a number from the list, sorting the list, etc.
the programs are of minimum statements and complexity. The striking difference with traditional approaches
Second, the validity of the solution can easily proved.
is that the program accessing this list does not need to
contain procedures for performing tasks rather it uses
1.5.4 Object-Oriented Programming the routines provided in the object. So in other words,
We have seen that unstructured and structured program- instead of sorting the list as in the procedural paradigm,
ming paradigms are basically task-based as they focus on the program asks the list to sort itself.
| 12 | Introduction to C Programming

Therefore, we can conclude that the object-oriented descending. Hence, an interface specifies how messages
paradigm is task-based (as it considers operations) as well can be sent to the object.
as data-based (as these operations are grouped with the
relevant data).
Figure 1.10 represents a generic object in the object-
oriented paradigm. Every object contains some data and
Private data
the operations/methods/functions that operate on that data.
While some objects may contain only basic data types such Interface

as characters, integers, floating types, the other object, the Me ae ene Ons
other objects on the other hand may incorporate complex
data types such as trees or graphs.
Programs that need the object will access the object’s
methods through a specific interface. The interface
specifies how to send a message to the object, that is, a
request for a certain operation to be performed.
For example, the interface for the list object may Figure 1.10 _ Generic Object _.
require that any message for adding a new number to the
list should include the number to be added. Similarly,
OOP is used for simulating real world
the interface might also require that any message for problems on computers because real
sorting specify whether the sort should be ascending or world is made ofobjects. _

e A computer has two parts—computer hardware operating system. The code in the BIOS chip runs
we
Oo which does all the physical work and the computer a series of tests called POST (Power On Self Test)
software which tells the hardware woe todo and — to ensure that the system devices are working
how to do it. correctly. BIOS is stored on a ROM chip built into
a e Aprogram is a set of instructions tat is arranged in the system.
= a sequence to guide a computer to find a solution e Utility software is used to analyse, configure,

<I for the given problem. The process of wenng = - optimize, and maintain the computer system.—

Og
2 | program is called programming.
e Computer software is written by computer
eA compiler is a special type of program that
transforms source code written in a programming
programmers using a programming language. language (the source language) into machine
-e Application software is designed to solve a language comprising of just two digits—1s and Os
particular problem for users. (the target language). The resultant code in 1s and
e System software represents programs that allow Os is known as the object code.
the hardware to run properly. System software e Linker is a program that combines object modules
acts as an interface between the hardware of the to form an executable program. —
computer and the application software that users e A loader is a special type of program that copi
need to run on the computer. programs from a storage device to main memo
The key role of the BIOS is to load and start the where they can be executed.

_ Fill in the Blanks


4 tells the hardware what to do and how 3. The process of writing a program is called
to do it.
2. The hardware needs a to instruct what is used to write computer software.
has to be done. S. transforms the source code into bina
language.
Introductionto Programming | 13 |

EXERCISES

Multiple Choice Questions


BlOSisstoredin

m _ (b) Assembler ——7,: Explain the role of


_ (d) Linker = 8. Give some exampl
m itor, keyboard, and mouse areexamples .. Differentiate betw
DF _ | =Objectcode,
10. Why are compi
1. Isthere any difference b
interpreter?
| 14 | Introduction to C Programming

7)
LJ
=
VU
c
Lil
x<
Lid
CHAPTER

Introduction to C
x

Takeaways
e Writing a C Program © Compiling and Executing C Programs Basic Data Types
e Keywords e Identifiers -e Variables and Constants
e |/O Statements e Operators e Type Conversion and Typecasting

INTRODUCTION Before C, several other programming languages were


developed. For example, in 1967 Martin Richards developed
The programming language C was developed in the early a language called BCPL (Basic Combined Programming
1970s by Dennis Ritchie at Bell Laboratories to be used Language). BCPL was basically a type-less (had no concept
by the UNIX operating system. It was named ‘C’ because of data types) language which facilitated the user with
many of its features were derived from an earlier language direct access of memory. This made it useful for system
called ‘B’. Although C was designed for implementing programmers. Then in 1970, Ken Thompson developed a
system software, it was later on widely used for developing language called B. B was used to develop the first version
portable application software. of UNIX. C was developed by Dennis Ritchie in 1972 that
C is one of the most popular programming languages. It took concepts from ALGOL, BCPL, and B. In addition to
is being used on several different software platforms. In a the concepts of these languages, C also supports the concept
nutshell, there are a few computer architectures for which
of data types. Since UNIX operating system was also
a C compiler does not exist.
developed at Bell Laboratories along with C language, C
It is a good idea to learn C because it has been around
and UNIX are strongly associated with each other.
for a long time which means there is a lot of information
For many years, C was mainly used in academic
available on it. Quite a few other programming languages
institutions, but with the release of different C compilers
such as C++ and Java are also based on C which means
for commercial use and popularity of UNIX, C was widely
you will be able to learn them more easily in the future.
accepted by computer professionals.
C (also known as Traditional C) was documented and
2.1.1 Background popularized in the book The C Programming Language
Like many other modern languages, Cis derived from by Brian W. Kernighan and Dennis Ritchie in 1978. This
ALGOL (the first language to use a block structure). book was so popular that the language came to be known
Although ALGOL was not accepted widely in the United as ‘K&R C’. The tremendous growth of C language
States but it was widely used in Europe. ALGOL’s resulted in the development of different versions of the
introduction in the 1960s led the way for the development language that were similar but incompatible with each
of structured programming concepts. other. Therefore, in the year 1983, the American National
Standards Institute (ANSI) started working on defining the C compiler combines the features of assembly language
standard for C. This standard was approved in December and high-level language which makes it best suited for
1989 and came to be known as ANSI C. In 1990, the writing system software as well as business packages.
International Standards Organization (ISO) adopted the Some basic characteristics of C language that define the
ANSI standard. This version of C came to be known as language and have led to its popularity as a programming
C89. In 1995, some minor changes were made to C89, language are listed below. In this book we will learn all
the new modified version was known as C95. Figure 2.1 these aspects.
shows the taxonomy of C language. During 1990s C++ e A high-level programming language enables the
and Java programming languages became popular among programmer to concentrate on the problem at hand
the users so the standardization committee of C felt that and not worry about the machine code on which the
a few features of C++/Java if added to C would enhance program would be run.
its usefulness. So, in 1999 when some significant changes e Small size—C has only 32 keywords. This makes
were made to C95, the modified version came to be known it relatively easy to learn as compared to other
as C99. Some of the changes made in the C99 version are languages.
as follows:
e Makes extensive use of function calls.
e Extension to the character types, so that they can e Cis well suited for structured programming. In this
support even non-English characters
programming approach, C enables the users to think
e Boolean data type of problem in terms of functions/modules where the
e Extension to the integer data type collection of all the modules makes up a complete
e Including type definitions in the for statement program. This feature facilitates easiness in program
e Inclusion of imaginary and complex types debugging, testing, and maintenance.
e Addition of //, better known as C++ style line comment @ Unlike PASCAL it supports loose typing (as a charac-
ter can be treated as an integer and vice versa).

pecolny e Structured language as the code can be organized as


a collection of one or more functions.
e Stable language. ANSI C was created in 1983 and
since then it has not been revised.
e Quick language: as a well written C program is likely
to be as quick as or quicker than a program written in
any other language. Since C programs make use of
operators and data types, they are fast and efficient.
For example, a program written to increment a value
from 0—15000 using BASIC would take 50 seconds
whereas a C program would do the same in just 1
second.
e Facilitates low level (bitwise) programming.
e Supports pointers to refer computer memory, array,
structures, and functions.
e Core language. C is a core language as many other
programming languages (such as C++, Java, Perl,
etc.) are based on C. If you know C, learning other
Figure 24 |Taxonomy of Clanguage computer languages becomes much easier.
e C isa portable language, i.e.,a C program written
for one computer can be run on another computer
2.1.2 Characteristics of C with little or no modification.

C is arobust language whose rich set of built-in functions e C isan extensible language as it enables the user to
and operators can be used to write complex programs. The add his own functions to the C library.
Introduction to C | 17 |

e Cis often treated as the second best language for any executed together. The statements in a C program are
given programming task. While the best language written in a logical sequence to perform a specific task.
depends on the particular task to be performed, the The main() function is the most important function and is
second best language, on the other hand, will always a part of every C program. The execution of a C program
be C. begins at this function.

2.1.3 Uses of C

Cis a very simple language that is widely used by software


professionals around the globe. The uses of C language
can be summarized as follows. ¥
e C language is primarily used for system program-
ming. The portability, efficiency, the ability to
access specific hardware addresses and low runtime L
demand on system resources makes it a good choice
Statements . :
for implementing operating systems and embedded
system applications.
e C has been so widely accepted by professionals
that compilers, libraries, and interpreters of other
programming languages are often implemented in C.
e For portability and convenience reasons, C is
sometimes used as an intermediate language for
implementations of other languages. Examples of
compilers who use C this way are BitC, Gambit, the
Glasgow Haskell Compiler, Squeak, and Vala.
Basically, C was designed as a programming
language and was not meant to be used as a compiler
target language. Therefore, although C can be used
as an intermediate language it is not an ideal option.
This led to the development of C-based intermediate
languages such as C.
e Cis widely used to implement end-user applications.
Geter Structure ofaCprogram
All functions (including main()) are divided into two
parts—the declaration section and the statement section.
C program is composed of preprocessor commands, a The declaration section precedes the statements section
global declaration section, and one or more functions and is used to describe the data that will be used in the
(Fig. ZZ). function. Note that data declared within a function are
The preprocessor directives contain special instructions known as local declaration as that data will be visible only
that indicate how to prepare the program for compilation. within that function. Stated in other terms, the life-time of
One of the most important and commonly used preproces- the data will be only till the function ends. The statement
sor commands is include which tells the compiler that to section in a function contains the code that manipulates
execute the program, some information is needed from the the data to perform a specified task.
specified header file. From the structure given above we can conclude that a
In this section we will omit the global declaration part C program can have any number of functions depending
and will revisit it in Chapter 7. on the tasks that have to be performed and each function
A C program contains one or more functions, where can have any number of statements arranged according to
a function is defined as a group of C statements that are specific meaningful sequence.
18 | Introduction to C Programming

the braces form the function body. The function body


Note yz Programmers can choose any name for
contains a set of instructions to perform the given task.
the functions. It is not mandatory to write
Functionl, Function2, etc., but with printf ("\n Welcome to the world of C ");
an exception that every program must The printf function is defined in the stdio.h file and is
contain one function that has its name as used to print text on the screen. The message that has to be
main(). displayed on the screen is enclosed within double quotes
and put inside brackets.
The message is quoted because in
Programming Tip:
2.3 WRITING THE FIRST C PROGRAM C a text (also known as a string
Placing a semi-
or a sequence of characters) is
To write a C program, we first need to write the code. For colon after the
always put between inverted
this, open a text editor. If you are a Windows user you may parenthesis of main
commas. The ‘\n’ is an escape
use Notepad and if you prefer working on UNIX/Linux you will generate a
_ sequence and_= represents a
can use emacs or vi. Once the text editor is opened on your compiler error. | | newline character. It is used to
screen, type the following statements: print the message on a new line
#include <stdio.h> on the screen. Like the newline character, the other escape
int main () sequences supported by C language are shown in Table 2.1.
{
printf ("\n Welcome to the world of C ");
Table 21 Escape sequences
HeCUTI OF
} Escape Escape
Purpose Purpose —
Output me a
Welcome to the world of C Audible Sana | Question mark
mark |
After writing the code, select the directory of your choice Sue Back slash
and save the file as first.c. Single quote
Newline i Double quote
#include <stdio.h>
This is a preprocessor command that [Link] the first Vertical tab Octal constant
statement in our code. All preprocessor commands start New page\ Hexadecimal
with symbol hash (#). The #include statement tells the Clear screen constant
compiler to include the standard input/output library or
header file (stdio.h) in the program. This file has some
agin Carciacerrettn,|
1)erintien |msecies wgBG
in-built functions. So simply by including this file in our Netey Note Escape sequences are actually non-
code we can use these functions directly. The standard printing control characters that begin
input/output header file contains functions for input and with a backslash (\).
output of data like reading values from the keyboard and
printing the results on the screen. return 0;

int main () This is a return command that is used to return the value
Every program contains a main() function which is the 0 to the operating system to give an indication that there
starting point of the program. int is the return value of the were no errors during the execution of the program.
main function. After all the statements in the program have
been written, the last statement of Every statement inthe main function
Programming Tip: ends with a semi-colon (;).
the program will return an integer
Ifyou do not place
value to the operating system.
a parenthesis after
The concepts will be clear to Now that you have written all the statements using
‘main’, a compiler
us when we read the chapter on the text editor, save the text file as first.c. If you are a
error will be
_ Functions. So even if you do not Windows user then open the command prompt by clicking
generated.
: ll understand certain things, do not Start ->Run and typing ‘command’ and clicking Ok.
sims sypumsus
WOIty. Using the command prompt, change to the directory in
{ } The two curly brackets are used to group all the related which you had saved your file and then type:
statements of the function main. All the statements between C2\St ea lasitae
Introduction to C | 19

In case you are working on UNIX/Linux operating 2.4.2 Header Files


system, then exit the text editor and type
When working with large projects, it is often desirable
SCG EI rst. ca—-Onlrst
to separate out certain sub routines from the main() of
The -o is for the output file name. If you leave out the the program. There also may be a case that the same
-o then the file name [Link] is used. subroutine has to be used in different programs. In the
This command is used to compile your C program. If latter case, one option is to copy the code of the desired
there are any mistakes in the program then the compiler sub-routine from one program to another. But copying
will tell you the mistake you have made and on which line the code is often tedious as well as error prone and makes
you made it. In case of errors you need to re-open your. maintainability more difficult.
c file and correct those mistakes. However, if everything So, another option is to make subroutines and store them
is right then no error(s) will be reported and the compiler in a different file known as header file. The advantage of
will create an exe file for your program. This .exe file can header files can be realized in the following cases:
be directly run by typing
e The programmer wants to use the same subroutines
‘[Link]’ for Windows and ‘./hello’ for
UNIX/Linux operating system.
in different programs. For this, he simply has to
compile the source code of the subroutines once, and
When you run the exe file, the output of the program
then link to the resulting object file in any other
will be displayed on screen. That is,
program in which the functionalities of these sub-
Welcome to the world of C routines are required.

_ The printf and return statements have e The programmer wants to change or add subroutines,
been indented or moved away fromthe and have those changes reflected in all the other
left side. This is done to make the code programs. In this case, he just
more readable. _ Programming Tip: needs to change the source file
Missing the inclusion for the subroutines, recompile its
_ofappropriate header
M
_ FILESUSEDINCPROGRA
source code, and then recompile
file in theC program
and re-link programs that use
will generate an error. —
Every C program has four kinds of files associated with it Such a program may them. This way enormous time
(Fig. 2.3). These include: compile but the linker can be saved as compared to
will give an error editing the subroutines in every
message as itwill not _ individual program that uses
be able to find the — them.
functions used in the
program. | Thus, we see that using a header
caieees | file produces the same results as
"Executable copying the header file into each source file that needs it.
fle
Also when a header file is included, the related declarations
appear in only one place. If in future we need to modify
Figure 2.3 | Files in of
the subroutines, we just need to make the changes in
one place, and programs that include the header file will
2.4.1 Source Code File automatically use the new version when recompiled later.
There is no need to find and change all the copies of the
The source code file contains the source code of the
subroutine that has to be changed.
program. The file extension of any C source code file is
Conventionally, header files names ends with a ‘dot
‘.c’. This file contains C source code that defines the
h’ (.h) extension and its name can use only letters, digits,
main function and maybe other functions. The main ()
dashes, and underscores. Although some standard header
is the starting point of execution when you successfully
files are automatically available to C programmers but in
compile and run the program. A C program in general
addition to those header files, the programmer may have
may include even other source code files (with the file
his own user defined header files.
extension.c).
| 20 | Introduction to C Programming

Standard Header Files In all our programs that we had The programming process starts with creating a source
been writing till now, we were using many functions that file that consists of the statements of the program written in C
were not written by us. For example, strcmp () function language. This source file usually contains ASCII characters
which compares two strings. We just pass string arguments and can be produced with a text editor, such as Windows
and retrieve the result. We do not know the details of how notepad, or in an Integrated Design Environment.
these functions work. Such functions that are provided The source file is then processed by a special program
by all C compilers are included in standard header files. called a compiler.
Examples of these standard header files include:
Every programming language has its own
e string.h: for string handling functions . compiler. — :
® stdlib.h : for some miscellaneous functions
e stdio.h : for standardized input and output The compiler translates the source code into an object code.
functions The object code contains the machine instructions for the
e math.h — : for mathematical functions CPU, and calls to the operating system API (Application
e alloc.h : for dynamic memory allocation Programming Interface).
e conio.h : for clearing the screen However, even the object file is not an executable file.
All the header files are referenced at the start of the Therefore, in the next step, the object file is processed with
source code file that uses one or more functions from that another special program called a linker. While there is a
file. different compiler for every individual language, the same
linker is used for object files regardless of the original
2.4.3 Object Files language in which the new program was written. The
output of the linker is an executable or runnable file. The
Object files are generated by the compiler as a result
process is shown in Fig. 2.4.
of processing the source code file. Object files contain
compact binary code of function definitions. Linker uses
this object file to produce an executable file (.exe file)
by combining the object files together. Object files have
Executable
files
a ‘.o’ extension, although some operating systems
including Windows and MS-DOS havea *‘.obj’ extension
for the object file.

2.4.4 Binary Executable File Figure 2.4 MeV aa7(Vie)j compilation and execution process

The binary executable file is generated by the linker. The


linker links the various object files to produce a binary In c language programs, there are two kinds of source
file that can be directly executed. On Windows operating files. In addition to the main (.c) source file, which
system, the executable files have ‘.exe’ extension. contains executable statements there are also header (.h)
source files. Since all input and output in C programs

2.5 COMPILING AND EXECUTING C


is done through library functions, every C program
therefore uses standard header files. These header files
PROGRAMS should be written as part of the source code for modular
C programs.
C is a compiled language. So once the C program is
The compilation process shown in Fig. 2.5 is done in
written, you must run it through a C compiler that can
two steps. In the first step, the preprocessor program reads
create an executable file to be run by the computer. While
the source file as text, and produces another text file as
the C program is human-readable, the executable file on
output. Source code lines which begin with the # symbol
the other hand, is a machine-readable file available in an
are actually not written in C but in the preprocessor
executable form.
language. The output of the preprocessor is a text file
The mechanical part of running a C program begins
which does not contain any preprocessor statements. This
with one or more program source files, and ends with an
file is ready to be processed by the compiler. The linker
executable file, which can be run on a computer.
Introduction toC | 21 |

Figure 2.5 compilation before execution


ao

combines the object file with library routines (supplied known as a /ine comment. A line comment can be
with the compiler) to produce the final executable file. placed anywhere on the line and it does not require
In modular programming the source code is divided to be specifically ended as the end of the line auto-
into two or more source files. All these source files are matically ends the line.
compiled separately thereby. producing multiple object
e /* is used to comment multiple statements. A /* is
files. These object files are combined by the linker to
ended with */ and all statements that lie within these
produce an executable file (Fig. 2.6).
characters are commented. This type of comment is
known as block comment.
Note that commented statements are not executed by
Many a time the meaning or the purpose of the program the compiler. Rather, they are
code is not clear to the reader. Therefore, it is a good ignored by the compiler as they
programming practice to place some comments in the code are simply added in the program
to help the reader understand the code clearly. Comments _ to make the code understandable
are just a way of explaining what a program does. It is _ by the programmer as well as
merely an internal program documentation. The compiler other people who read it. It
ignores the comments when forming the object file. This is a good habit to always put a comment at the top of a
means that the comments are non-executable statements. program that tells you what the program does. This will
C supports two types of commenting. help in defining the usage of the program the moment you
e // is used to comment a single statement. This is open it.

Figure 2.6 ar programming—the complete compilation


and execution process
| 22 | Introduction to C Programming

Commented statements can be used anywhere in the the names given to program elements such as variables,
program. You can also use comments in between your arrays, and functions. Identifier may consist of an alphabet,
code to explain a piece of code that is a bit complicated. digit, or an underscore.
The code given below shows the way in which we can
make use of comments in our first program. 2.8.1 Rules for Forming Identifier Names
/* Author: Reema Thareja
Description: To print ‘Welcome to the
Some rules have to be followed while forming identifier
world of C’ on the screen */ names. They are as follows:
#include <stdio.h> e It cannot include any special
characters or
int main ()
punctuation marks (like #, $, *, ?/ a cicajrexcept
{
printf ("\n Welcome to the world of C "); the underscore *_’.
// prints message e There cannot be two successive underscores.
return 0; // returns a value 0 to the
operating system e Keywords cannot be used as identifiers.
} e The case of alphabetic characters that form the
Output identifier name is significant. For example, "FIRST"
is different from ‘first’ and ‘First’.
Welcome to the world of C
e The identifier name must begin with an alphabet or
Since comments are not executed by the compiler, they do an underscore. However, use of underscore as the
not affect the execution speed and the size of the compiled first character must be avoided
program. Therefore, use comments liberally in your Programming Tip:
programs so that other users can understand the operations
Cisacase sensitive _ because several compiler-defined
of the program and will serve as an aid to debugging and
language. Ifyou type identifiers in the standard C li-
testing. printf function as brary have underscore as their
Printf, then an error _ first character. Hence, inadver-
will be generated. tently duplicated names may
2.7. KEYWORDS cause definition conflicts.

Like every computer language, C has a set of reserved e Identifiers can be of any reasonable length. They
words often known as keywords that cannot be used as should not contain more than 31 characters. It can
an identifier. All keywords are basically a sequence of actually be longer than 31, but the compiler looks at
characters that have a fixed meaning. By convention all only the first 31 characters of the name.
keywords must be written in lowercase (small) letters. Although it is a good practice to use meaningful identifier
Table 2.2 contains a list of keywords in C. names, it is not compulsory. Good identifiers are
descriptive but short. To cut short the identifier, you may
GRRE Keywords in C language
use abbreviations. C allows identifiers (names) to be up to
break |case char continue |default 63 characters long. If a name is longer than 63 characters,
then only the first 31 characters are used.

retum short signed | sizeof


As a general practice, if the identifier is a little long,
then you may use an underscore to separate the parts of the
struct union |unsigned |void
name or you may use capital letters for each part.
ldo fit static [whe ||| Examples of valid identifiers include:

When you read this book, the meaning and utility of each roll_ number, marks, name, emp_number, basic_
keyword will become automatically clear to you. pay, HRA, DA, dept _code, DeptCode, Roll1No,
EMP_NO

Examples of invalid identifiers include:


2.8 IDENTIFIERS
23 student, smarks, @name, #emp number,
Identifiers, as the name suggests helps us to identify data
[Link], -HRA, (DA), &dept_code, auto
and other objects in the program. Identifiers are basically
Introduction to C | 23 |

always try to use int unless there is a special need to use


any other data type.

;
by tes vie >
Data types determine the set of values that a data item char al
can take and the operations that can be performed on the unsigned char {eatingies|
al i MOwowrals
item. C language provides very few basic data types. Table
2.3 lists the data type, their size, range, and usage for a
signed char igs‘Aluon —128 to 127
int | 22 | -32768 to 32767
C programmer on a 16-bit computer. Table 2.3 shows the
basic data types. In addition to this, we also have variants
unsigned int Pena
2 0 to 65535

of int and float data types.


signed short int ues
2 —32768 to 32767

The char data type is one byte and is used to store single signed int ven.
2 GS —32768 to 32767
characters. Note that C does not provide any data type for short int 2, —32768 to 32767
storing text. This is because text is made up of individual unsigned short int Peheeaas
2 0 to 65535
characters.
You will be surprised to see that the range of char
is given as -128 to 127. The char is supposed to store
long int

unsigned long int


pt |tease
4 —2147483648 to

0 to 4294967295

Ye
characters not numbers, so why this range? The answer is signed long int —2147483648 to
that, in memory characters are stored in their ASCII codes. 2147483647
For example, the character ‘A’ has the ASCII code 65. In
memory we will not store ‘A’ but 65 (in binary number
acetal
4 3.4E—38 to 3.4E+38
8 1.7E—308 to 1.7E+308
format).
long double 3.4E—-4932 to
10
1.1E+4932

Character
characters
Integer int 2 —32768to |Tostore
S276) integer Last but not the least the void type holds no value. It is
numbers primarily used in three cases:
Floating float 4 3.4E-38 to | To store e To specify the return type of a function (when the
Point 3.4E+38 floating point function returns no value)
numbers e To specify the parameters of the function (when the
passef 1.7E-—308 to | To store big function accepts no arguments from the caller)
1.7E+308 floating point
e To create generic pointers. We will read about
numbers
generic pointers in the chapter on Pointers.
valueless | void | 0 [Valueless _| We will discuss the void data type in detail in the
Table 2.4 shows the variants of basic data types in detail. coming chapters.
In Table 2.4, we have unsigned char and signed
char. Do we have negative characters?—no, then why do
we have such data types? The answer is that we use signed
and unsigned char to ensure portability of programs that
store non-character data as char.
While the smaller data types take less memory, the larger
types incur a performance penalty. Although the data type
we use for our variables does not have a big impact on the
speed or memory usage of the application, but we should
| 24 | Introduction to C Programming

2.9.1 How are Float and Double Stored? form, the exponent is biased by half its possible value. For
type float, the bias is 127; for type double, it is 1023. You can
In computer memory, float and double values are stored compute the actual exponent value by subtracting the bias
in mantissa and exponent forms where the exponent value from the exponent value. Finally, the normalized
represents power of 2 (not 10). The number of bytes used binary equivalent is stored in such a way that lower byte is
to represent a floating point number generally depends on stored at higher memory address. For example, ABCD is
the precision of the value. While float is used to declare actually stored as DCBA.
single-precision values, double is used to represent double-

2.10 VARIABLES.
precision values.
Floating-point numbers use the JEEE (Institute of
Electrical and Electronics Engineers) format to represent A variable is defined as a meaningful name given to the
mantissa and exponents. According to the IEEE format, data storage location in computer memory. When using a
a floating point value in its binary form is known as a variable, we actually refer to address of the memory where
normalized form. In the normalized form, the exponent is the data is stored. C language supports two basic kinds of
adjusted in such a way that the binary point in the mantissa variables—numeric and character.
always lies to the right of the most significant non-zero
digit. 2.10.1 Numeric Variables

Example Convert the floating point number 5.32 into an Numeric variables can be used to store either integer
IEEE normalized form. values or floating point values. While an integer value is
a whole number without a fraction part or decimal point a
Oh e20K 2S Osey! Write the floating point value can have a decimal point.
ey
remainders inthe
0.64x2=1.28| 1Jfie Numeric variables may also be associated with
reverse order of 0.28 x 2 = 0.56 the same
modifiers like short, long, signed, and unsigned. The diffe-
0.56 x 2= 1.12
generation order of
generation
rence between signed and unsigned numeric variables is
Thus, the binary equivalent of 5.32 = 101.010: that signed variables can be either negative or positive
The normalized form of this binary number is obtained by but unsigned variables can only be positive. Therefore, by
adjusting the exponent until the decimal oo is tothe using an unsigned variable we can increase the maximum
right of the most significant 1. _ positive range. When we do not specify the signed/unsigned
Therefore, the normalized binary equivalent = 1.010101 x 22
modifier, C language automatically takes it as a signed
variable. To declare an unsigned variable, the unsigned
Moreover, the IEEE format for storing floating point modifier must be explicitly added during the declaration of
numbers uses a sign bit, mantissa, and the exponent the variable.
(Fig. 2.7). The sign bit denotes the sign ofthe value. If the
value is positive, the sign bit contains 0 and in case the 2.10.2 Character Variables
value is negative it stores 1.
Character variables are just single characters enclosed
within single quotes. These characters could be any
Constants ina C program character from the ASCII character sef—letters (‘a’, ‘A’),
numerals (‘2’), or special characters (‘&’). In C, a number
that is given in single quotes is not the same as a number
Integer Floating — Character String without them. This is because 2 is treated as an integral
type point type - type type value but *2’ is a considered character not an integer.

Figure 2.7 IEEE format for storing floating point numbers 2.10.3 Declaring Variables

Generally, exponent is an integer value stored in Each variable to be used in the program must be declared.
unsigned binary format after adding a positive bias. In To declare a variable, specify the data type of the variable
other words, because exponents are stored in an unsigned followed by its name. The data type indicates the kind of
Introduction to C | 25 |

data that the variable will store. Variable names should initializes the variable flag and not count. If you want
always be meaningful and must reflect the purpose of both the variables to be declared in a single statement then
their usage in the program. The memory location of the write,
variable is of importance to the compiler only and not to inte Cowinc = O, iellecey S ily
the programmer. Programmers must only be concerned When variables are declared but not initialized they
with accessing data through their symbolic names. In C, usually contain garbage values (there are exceptions to
variable declaration always ends with a semicolon, for this that we will study later).
example:

int emp num;

float salary;

char grade;
Constants are identifiers whose value does not change.
Variables can change their value at any time but constants
double balance amount;
can never change their value. Constants are used to define
unsigned short int acc_no;
fixed values like Pi or the charge on an electron so that
In C variables can be declared at any place in the their value does not get changed in the program even by
program but two things must be kept in mind. First, mistake.
variables should be declared before using them. Second, A constant is an explicit data value specified by the
variables should be declared closest to their first point of programmer. The value of the constant is known to the
use to make the source code easier to maintain.
compiler at the compile time. C allows the programmer
C allows multiple variables of the same type to be
to specify constants of integer type, floating point type,
declared in one statement. So the following statement is
character type, and string type (Fig. 2.8).
absolutely legal in C.
flloaey temphan celsius, temp in’ farenheit;

In C variables are declared at three basic places as


follows:
e When a variable is declared inside a function it is
known as a local variable.
e When a variable is declared in the definition of
function parameters it is known as formal parameter
(we will study this in the chapter on Functions). Figure 2.8. .
e When the variable is declared outside all functions,
it is known as a global variable.
2.11.1 Integer Constant
A constant of integer type consists of a sequence of digits.
For example, 1, 34, 567, 8907 are valid integer constants.
A literal integer like 1234 is of type int by default. For a
long integer constant the literal is succeeded with either ‘L’
2.10.4 Initializing Variables or ‘l’ (like 1234567L). Similarly, an unsigned int literal is
While declaring the variables, we can also initialize them written with a ‘U’ or ‘wv’ suffix (ex, 12U). Therefore, 1234L,
with some value. For example, 12341, 1234U, 1234u, 1234LU, 1234ul are all valid

int emp num = 7;


integer constants.
ElOdtmSo lain sO OO IIs, Integer literals can be expressed in decimal, octal or
Chat Guade = Avs; hexadecimal notation. By default an integer is expressed
double balance amount = 100000000; in decimal notation. Decimal integers consist of a set of
The initializer applies only to the variable defined digits, 0 through 9, preceded by an optional - or + sign.
immediately before it. Therefore, the statement Examples of decimal integer constants include: 123, —-123,
ine, Cowinic, sllkecy = uly +123, and 0.
| 26 | Introduction to C Programming

While writing integer constants, embedded spaces, integer with an optional plus or minus sign. Therefore, the
commas, and non-digit characters are not allowed. There- numbers given below are valid floating point numbers
fore, integer constants given below are totally invalid in c.
0.5e2 14E2 1.2e+3° 2.1E-3 —5.6e2
hs 456 12, 34,567 $123
Thus, we see that scientific notation is used to express
An integer constant preceded by a zero (0) is an octal numbers that are either very small or very large. For
number. Octal integers consist of a set of digits, 0 through example,
7. Examples of octal integers include
120000000 = 1.2E8 and -—0.000000025 =—2.5E-8
012 0 01234
t

Similarly, an integer constant is expressed in hexadecimal


2.11.3 Character Constant
notation if it is preceded with Ox or 0X. Hexadecimal
numbers contains digits from 0-9 and alphabets A through A character constant consists of a single character
F. The alphabets A through F represent numbers 10 through enclosed in single quotes. For example, ‘a’, ‘@’ are
15. For example, decimal 72 is equivalent to 0110 in octal character constants. In computers, characters are stored
notation and 0x48 in hexadecimal notation. Examples of using machine’s character set using ASCII codes. All
hexadecimal integers are 0X12 Ox7F OxXABCD 0X1A3B. escape sequences mentioned in Table 2.1 are also character
constants.
Notey | In C, a decimal integer constant
is treated as
rag _ an unsigned long if itsmagnitude exceeds
2.11.4 String Constant
_ that of signed long. An octal or hexadecimal
integer that exceeds the limit of intis A string constant is a sequence of characters enclosed in
taken to be unsigned. Ifeven this limit is double quotes. So "a" is not the same as ‘a’ . The characters
_ exceeded, it is taken as long; and in case this comprising the string constant are stored in successive
limit is exceeded, it is treated asunsigned
memory locations. When a string constant is encountered
long. _ .
in a C program, the compiler records the address of the
first character and appends a null character (‘\0’) to the
2.11.2 Floating Point Constant string to mark the end of the string. Thus, length of a string
constant is equal to number of characters in the string plus 1
Integer numbers are inadequate to express numbers that
(for the null character). Therefore, the length of string literal
have a fractional part. A floating point constant therefore
"hello"
Is 6.
consists of an integer part, a decimal point, a fractional
part, and an exponent field containing an e or E (e means
exponent) followed by an integer where the fraction part 2.11.5 Declaring Constants
and integer part are a sequence of digits. However, it is not
To declare a constant, precede the normal variable
necessary that every floating point constant must contain
declaration with const keyword and assign it a value. For
all these parts. Some floating point numbers may have
example,
certain parts missing. Some valid examples of floating
point numbers are: 0.02, -0.23, 123.456, +0.34 123, 0.9, Comsie Wil@eie jon, Ges) iets

—0.7, +0.8, etc. The const keyword specifies that the value of pi
A literal like 0.07 is treated as of type double by cannot change.
default. To make it a float type literal, you must specify However, another way to designate a constant is to
it using suffix ‘F’ or ‘f’. Consider some valid floating use the pre-processor command define. Like other
point literals given below (Note that suffix L is for long preprocessor commands, define is preceded with a #
double). symbol. Although #define statements can be placed
0.02F 0.34f 3.141592654L 0.002146 2.146E-3 anywhere in a C program, it is always recommended that
these statements be placed at the beginning of the program
A floating point number may also be expressed in
to make them easy to find and modify at a later stage. Look
scientific notation. In this notation, the mantissa is either
at the example given below which defines the value of PI
a floating point number or an integer and exponent is an
using define.
Introduction to C | 27 |

#define PI 3.14159
#define servicestax 0.12
"Streams ina
In these examples, the value of Pr will never change _ Cprogram —
but service tax may change. Whenever the value of the
service tax is altered, it can needs to be corrected only in
the define statement. Text stream
When the preprocessor reformats the program to be
compiled by the compiler, it replaces each defined name Figure a) StreamsinC a
(such as PI, service_tax) in the source program with its
corresponding value. Hence, it just*works like the Find
We can do input/output from the keyboard/monitor or
and Replace command available in a text editor.
from any file but in this chapter we will assume that the
Let us take a look at some rules that needs to be applied
source of data is the keyboard and destination of the data
to a #define statement which defines a constant.
is the monitor (Fig. 2.10). File handling, 1.e., handling
Rule I Constant names are usually written in capital input and output via C programs will be discussed later as
letters to visually distinguish them from other variable a separate chapter.
names which are normally written in lower case characters.
Note that this is just a convention and not a rule.

Rule 2. No blank spaces are permitted in between the #


symbol and define keyword.
“Keyboard
Rule 3 Blank space must be used between #define and
constant name and between constant name and constant
value.

Rule 4 #define is a pre-processor compiler directive Figure 2.10 ‘Input and output streams in C_ 7
and not a statement. Therefore, it does not end with a
semi-colon.
2.12.2 Formatting Input/Output

2.12 INPUT/OUTPUT STATEMENT IN C_ C language supports two formatting functions printf


and scanf. printf is used to convert data stored in the
Before going straightaway into performing input and program into a text stream for output to the monitor, and
output in C programs let us first understand the concept scanf is used to convert the text stream coming from
from scratch. This section deals with the basic understand- the keyboard to data values and stores them in program
ing of the phenomena involved in accepting input and variables. In this section, we will discuss these functions.
printing output in C programs.
Background
2.12.1 Streams The most fundamental operation ina C program is to accept
input values to the program from standard input device
A stream acts in two ways. It is the source of data as well
(keyboard) and output the data produced by the program
as the destination of data. C programs input data and output
to a standard output device (monitor). So far we had
data from a stream. Streams are associated with a physical
been assigning values to variables using the assignment
device such as the monitor or with a file stored on the
operator =. For example,
secondary memory. C uses two forms of streams—text and
mine € = 5
binary, as shown in Fig. 2.9.
In a text stream, sequence of characters is divided But what if we want to assign value to variable that
into lines with each line being terminated with a new- is inputted by the user at run-time. This is done by using
line character (\n). On the other hand, a binary stream the scanf function that reads data from the keyboard.
contains data values using their memory representation. Similarly, for outputting results of the program, printf
| 28 | Introduction to C Programming

function is used that sends results out to a terminal. Like program that prints hello world). The control characters
printf and scanf, there are different functions in C that can also be included in the printf statement. These
can carry out the input/output operations. These functions control characters include \n, \t, \r, \a, etc
are collectively known as standard Input/Output Library. After the control string, the function can have as many
A program that uses standard input/output functions must arguments as specified in the control string. The parameter
contain the statement control string in the printf () is nothing but a C string
that contains the text that has to be written on to the
#include <stdio.h>
standard output device.
at the beginning of the program. Note that there must be enough arguments otherwise,
the result will become completely unpredictable. However,
2.12.3 printé£ () if by mistake you specify more number of arguments, the
excess arguments will simply be ignored. The prototype of
The printf function (stands for print formatting) is used
the control string can be as given below.
to display information required by the user and also prints
the values of the variables. For this, the printf function % [flags] [width] [.precision]
[length] specifier

takes data values, converts them to a text stream using Each control string must begin with a % sign. The %
formatting functions specified in a control string and character specifies how the next variable in the list of
passes the resulting text stream to the standard output. variables has to be printed. After % sign follows.
The control string may contain zero or more conversion
Flags specify output justification such as decimal point,
specifications, textual data, and control characters to be
numerical sign, trailing zeros or octal, decimal, or
displayed (Fig. 2.11).
hexadecimal prefixes. Table 2.5 shows the different types
Each data value to be formatted into the text stream
of flags with their decription.
is described using a separate conversion specification in
the control string. The specification in the control string
describes the data value’s type size and specific format
gs inprintf) ee
information as shown in Fig. 2.11. oe. Description — .
The syntax of printf function can be given as
a ae within the data given field width
PELNeeGicontrol string sang, arg2, arg3.,
= (telat nal) 5 Ee Displays the data with its numeric sign (either + or—

The function accepts two parameters—control string Used to provide additional specifiers like o, x, X,
and variable list. The control string may also contain 0, Ox, or OX for octal and hexadecimal values,
text to be printed like instructions to the user, captions, respectively, for values different than zero.
identifiers, or any other text to make the output readable.
The number is left-padded with zeros (0) instead of
In some printf statements you may find only a text string
spaces
that has to be displayed on screen (as seen in the first

Data value’s _

ates The printf () inc


Introduction to C | 29 |

Note that when data is shorter than the specified width


sElela74) Length field in printf () eo
then by default the data is right justified. To left justify the
data use minus sign (—) in the flags field.

:
When the data value to be printed is smaller than the
short int.
width specified; then padding is used to fill the unused
spaces. By default, the data is padded with blank spaces.
int for integer specifiers.
If zero is used in the flag field then the data is padded
When the argument is a long double (used for
with zeros. One thing to remember here is that zero flag is
floating point specifiers)
ignored when used with left justification because adding
zeros after a number changes its value.

Width specifies the minimum number of characters to a Qualifying input


print after being padded with zeros or blank spaces, i.e., it
specifies the minimum number of positions in the output.
If data needs more space than specified, then printf For floating point numbers
overrides the width specified by the user. Width is a very Floating point numbers in exponential format
important field especially when you have to align output in Floating point numbers in the shorter of e
columns. However, if the user does not mention any width format
then the output will take just enough room for data. For octal number
For a sequence of (string of) characters
Precision specifies the maximum number of characters to u For unsigned decimal value
print. For hexadecimal value

e Forinteger specifiers (ad, i1,0,u, x, X): precision Note that if the user specifies a wrong specifier then
flag specifies the minimum number of digits to be some strange things will be seen on the screen and the
written. However, if the value to be written is shorter error might propagate to other values in the printf () list.
than this number, the result is padded with leading The most simple printf statement is
zeros. Otherwise, if the value is longer, it is not printf ("Welcome to the world of C
truncated. language") ;
e For character strings, precision specifies the When executed, the function prompts the message
maximum number of characters to be printed. enclosed in the quotation to be displayed on the screen.
e For floating point numbers, the precision flag For float x = 8900, the following examples show
specifies the number of decimal places to be printed. output under different format specifications:
jonentiaqenn, (Wiel ©3s)
Its format can be given as .m, where m specifies the
number of decimal digits. When no precision modifier is [Perce ie toalte |ereen| tem
specified, printf prints six decimal positions. joeriasia (URI
El sox)
When both width and precision fields are used, width
slo[ofo].]7
|e [a]
must be large enough to contain the integral value of the jopeuiatone (oe) euale Say
number, the decimal point and the number of digits after
the decimal point. Therefore, a conversion specification ar
a ee ea ee
%7.3f means print a floating point value of maximum 7 prant fa0"t6EN"; nx)
digits where 3 digits are allotted for the digits after the SSI atedbal pateleee al]
decimal point. printf ("\n Result: %d%c%f", 12, Nae? 2.3) 7
Result :12a2.3
Length field can be explained as given in Table 2.6.
printf("\n Result: %d %c %f", 12, MEEVEE PIGS) 9
Specifier is used to define the type and the interpretation Result:12 a 2.3
of the value of the corresponding argument (Table 2.7). printf("\n Result: %d\t%c\t%f", 12, ‘a’, 2.3);

Result:12 a 2.3
| 30 | Introduction to C Programming

printf("\n Result: SANESENES 6 kl lic alaer


245.37154); A
ResuLe2 aac, A

printf("\n Result: %5d \t %x \t %#x", 234,


234, 234);
Programming Tip: — char str[] = "Good Morning";
Placing an address Pune.
OO\n ss, ester
Result: 234 EA OxEA
operator with a princi (Nn sZ20s" stx)r
printf("\n The number is %6d", 12);
variablein the printf£("\n %20.10s", str);
The number is 12
printf statement printL("\ns.7.s%,) Stx)s;
printf£("\n The number is %2d", 1234); will generate a run- | print£("\n %-20.10s", str);
The number is 1234
_time error, print£("\n 37s", str);
printf£("\n The number is %6d", 1234);
The number is 1234 Good Morning
print£("\n The number is %-6d", 1234); Good Morning
Maer ining” als) AASV beh ie b indicates 2 Good Morni
white space Good Mo

printf£("\n The number is %06d", 1234); Good Morni


Good Morning .
The number is 001234

printf("\n The price of this item is %09.2f (Note that in the last print f statement the complete string
rupees", 123.456); “Good Morning” is printed. This is because if data needs
The price of this item is 00123.45 rupees
more space than specified, then printf overrides the
width specified by the user.)
printf£("\n This is \’so\’ beautiful") ;

ibguisy, aks Meio joeenbicaie


ent
Programming Tip: 2.12.4 scanf ()
jopastayens (Day Umebieh Eye} \\WEye\\
Not placing a
beautiful") ; The function scanf() stands for scan formatting and is
comma after the
format string in Thacwerse VSO! beaut antl: used to read formatted data from the keyboard. The scanf
a read orwrite printf("\n This is \\ so function takes a text stream from the keyboard, extracts
statement is a _ beautiful "); and formats data from the stream according to a format
compiler error. | This is \ so beautiful control string and then stores the data in specified program
variables. The syntax of the scanf () can be given as,
printf("\n a = |%-+7.2£| b=
SOM
ee fC Se ORO 2, tl pelea eve) ie scanf ("control string", ehaeil, eae, ebee sh.
Pees .argn);
a= +17..20 lon = OC Oil AQ eS RAO)

(Note that in this example, — means left justify, + means Netey The minimum field width and precision
display the sign, 7 specifies the width, and 2 specifies the ro specifiers are usually constants. However,
precision.)
DrAneeL d\n 67-46) \ni 67 .2te \nies Veet nino
2 by using the
2 modifier as shown in the princi ()
\n %10.2e \n %11.4e \n %-10.2e \n %e",
statement below. — -
98.7654, 98.7654, 98.7654, 98.7654,
98.7654, 98.7654, 98.7654, 98.7654);
printé ("ss ne", 10, 4, 1234. 34

98.7654 Here, the minimum field width is 10,


Nis WI the precision is 4, and the value to be
Nels WY displayed iis 1234.34. _-
98.7654
9.88e+01
The control string specifies the type and format of
9.8765e+01
the data that has to be obtained from the keyboard and
9.88e+01
stored in the memory locations pointed by the arguments
9.876540e+01
gliciojil, Guage? ,., argn, 1.é., the arguments are actually
char “chy=) SAa; the variable addresses where each piece of data are to be
print£("\n' sc \n $3¢ \n %5c";, ch, ch, ch); stored.
Introduction to C 31 |

The prototype of the control string can be given as: function is used to store values in memory locations
[=s[*] [width] [modifiers]
type=] associated with variables. For this, the function should
have the address of the variables. The address of the
Here * is an optional argument that suppresses assignment
variable is denoted by an ‘&’ sign followed by the name
of the input field, i.e., it indicates that data should be read
of the variable.
from the stream but ignored (not stored in the memory
location).
, Whenever data isread fror the keyboard,
Width is an optional argument that specifies the maximum _there is always a return haracter from a
number of characters to be read. However, fewer
previous read operation. So we should
always code at least one white:space
characters will be read if the scanf function encounters
a white space or an inconvertible character because the
moment scanf encounters a white space character it will
stop processing further. values. together iina single scanf statement, :
- we must insert a white space between two
Modifiers is an optional argument that can be h, 1, or
fields as shown below:
fields L for the data pointed by the corresponding additional
“scanf ("3d or, &
arguments. Modifier his used for short int or unsigned
Shorsteseiat 1 is used for long int, unsigned long Now let us quickly summarize the rules to use a scanf
int, or double values. Finally, L is used for long function in our C programs.
double data values.
Rule 1: The scanf function works until:

Type specifies the type of data that has to be read. It also (a) the maximum number of characters has been
indicates how this data is expected to be read from the processed,
user. The type specifiers for scanf function are given in (b) a white space character is encountered, or
Table 2.8. (c) an error is detected.
Rule 2: Every variable that has to be processed must have
Table 2.8seit
| for scant () a conversion specification associated with it. Therefore,
the following scanf statement will generate an error as
num3 has no conversion specification associated with it.
scant ("$d $d", S&numl, &num2, &num3);

Rule 3: There must be a variable address for each


conversion specification. Therefore, the following scanf
For floating point numbers statement will generate an error as no variable address is
Floating point numbers in exponential format
given for the third conversion specification.
scanf ("Sd da %d", &mnuml, &num2);
Floating point numbers in the shorter of e format
Remember that the ampersand operator (&) before each
For octal number variable name specifies the address of that variable name.
For a sequence of (string of) characters Rule 4: A fatal error would be generated if the format
string is ended with a white space character.
For unsigned decimal value
Rule 5: The data entered by the user must match the
For hexadecimal value
character specified in the control string (except white
space or a conversion specification), otherwise an error
The scanf function ignores any blank spaces, tabs, and will be generated and scanf will stop its processing. For
example, consider the scanf statement given below.
new lines entered by the user. The function simply returns
the number of input fields successfully scanned and stored. scant ("$d / $d", &numl, &num2);

We will not discuss functions in detail in this chapter. Here, the slashes in the control string are neither white
So understanding scanf function in depth will be a bit space characters nor a part of conversion specification, so
difficult here, but for now just understand that the scanf the users must enter data of the form 21/46.
32 | Introduction to C Programming

Rule 6: Input data values must be separated by spaces. Remember that if an attempt is made to read a value
Rule 7: Any unread data value will be considered as a part that does not match the expected data type, the scanf
of the data input in the next call to scanf. function will not read any further and would immediately
return the values read.
Rule 8: When the field width specifier is used, it should be
large enough to contain the input data size.
2.12.5 Examples printf£/scanf
Look at the code given below that shows how we input
values in variables of different data types. Look at the code given of below that shows how we
output values of variables of different data types.
int num; t
int num;
scant(" 4d ", &num);
scanf(" $d", &num);
The scanf function reads a four-digit value into the PHEinGE (sd), smum)
address or the memory location pointed by num.
The printf function prints an integer value (because
float salary; the type specifier is $d) pointed by num on the screen.
Scant(Was tet esallausy)E-
float salary;
The scanf function reads a floating point number scanf(" $f ", &salary) ;
(because the type specifier is %f) into the address or the joneplinncsed(
US Arnelle rela)
memory location pointed by salary.
The printf function prints the floating point number
char ch; (because the type specifier is %£) pointed by salary on the
scant(" $c ", &ch); screen. Here, the control string specifies that only two
The scanf function reads a single character (because digits must be displayed after the decimal point.
the type specifier is %c) into the address or the memory chan=ch
location pointed by ch. Scant (" %c ", &ch);
ProgrammingTip:
char str{[10]; Afloat specifier joxctloatenE (UREN velay}yr
SCGamin( Vacoeaty, eaters) cannotbeused _~ The printf function prints a
toreadaninteger | single character (because the type
The scanf function reads a string or a sequence of
| a specifier is sc) pointed by ch on
characters (because the type
Programming Tip:
specifier is %s) into the address or the screen.
A compiler error
the memory location pointed by char str[10];
will be generated if
str. Note that in case of reading eyekchane (ey str);
the read and write
parameters are string, we do not use the & sign in The printf function prints a string or a sequence of
not separated by | the scanf function. This will be characters (because the type specifier is ss) pointed by str
commas. discussed in Chapter 6. on the screen.
Look at the code given below
scanf("%2d 5d", &mnuml, S&num2);
which combines reading of variables of different data
types in one single statement. The scanf statement will read two integer numbers.
The first integer number will have two digits while the
int num;
float fnum;
second can have maximum of 5 digits.
Ghaischy. Look at the code given below which combines printing
char str[10]; all these variables of different data types in one single
statement.
scant ("td Sf c %s*, &num, S&Enum, (Melay, Ficia))y
int num;
Look at the scanf statement given below for the same
float fnum;
code. The statement ignores the character variable and
char ch;
does not store it (as it is preceded by *).
char str [20]
scanf("%d %£ %*c Ss", &mum, &fnum, &ch, str) ; double dnum;
Introduction to C | 33 |

short snum; first two digits. The rest of the number will be assigned to
long int lnum;
b. The value 5678 that is unread will be assigned to the
printf ("\n Enter the values : "); first variable in the next call to the scanf function.
scanf ("sd %f %c $s %e thd $ld", énum, &fnum,
&ch, str, &dnum, &Snum, &lnum) ; Notes The %n
specifier is used to assign ‘the
printf ("\n num = $d \n fnum = $f \n ch = $c
‘number of characters read till the point
\n str = %s \n dnum = $e \n snum = $hd \n at which the snwas enco neces to ene
Laahety So Selle Mbit, awielbhin, Kelol,, thee. dnum,
snum, lnum) ;

Inthe printf sta ement, ° \n’, is called


ind is used to print —
, n the new line. The . ednc
i eee i
following ‘ouips vill be generated on7 othe output would be—Hello World! 6
execution of the print function. - because 6(H, e, |, | o,) the number of
characters read before the %n modifier.
Enter the values

2 3456.443 a abcde 24.321E-2 1 12345678 2.2 Write a program to demonstrate the use of printf
statement to print values of variables of different data
num = 2

fnum = 3456.44
types.
#include <stdio.h>
str = abcde main()
dnum = 0.24321 {
snum = 1 // Declare and initialize variables

inum i] 12345678 ime Toh eS YF


PilOatramty =—— 223. 45).
Remember one thing that scanf terminates as soon as Glavelic (eejela S (WAYse
it encounters a white space character so if your enter the double pi = 3.1415926536;
string as abc def, then only abc is assigned to str. long int population
of india =
10000000000;
2.1 Find out the output of the following program.
Chas mest sevens
#include <stdio.h>
main() // Print the values of variables

{ pisint (Nie NUM ede \erAMT «=m ce ec ODE,


alighe. eh, ler = $c \n PI = %e \t POPULATION OF INDIA =

printf ("\n Enter two four digit numbers: "); %$1d \n MESSAGE = %s", num, amt, code, pi,

scanf ("32d %4d",


&a, &b); population
of india, msg) ;

printf ("\n The two numbers are: %d and iX—yetbhank (0)P

Cl = wel Mois }
return 0;
Output
} NUM i= 7,

Sue AMT - 123.45000


CODE =A
>>> Enter two four digit
PE = 3.141590e+00
numbers 1234 5678
POPULATION OF INDIA = 10000000000
The two numbers are : 12
MESSAGE = Hi
and 34
2.3 Write a program to demonstrate the use of printf
w Here, the variable a is assigned
and scanf statements to read and print values of
| the value 12 because it is specified
variables of different data types.
as %2d, so it will accept only the
| 34 | Introduction to C Programming

#include <stdio.h> scanf ("Sf S£ $£", &a, &b, &C);


main () Gia (a 4 1) = ©) /%-
{
int num; // sqrt is a mathematical function defined
float amt; in math.h header file
char code; area = sqrt (S* (S-a) *(S-b)*(S-c));
double pi; jongamancene (Nia, vvererey Fa eel elactexe)
long int population_of india; return 0;
char msg[10]; }
printf ("\n Enter the value of num : "); Output ‘
scanf ("sd", &num); Enter the lengths of the three sides of the
printf ("\n Enter the value of amt : "); triangle: 12 16 20
ScanmCuse came); Area = 96
printf("\n Enter the value of pi: ");
scanf ("%e", &pi); 2.5 Write a program to calculate the distance between two
printf ("\n Enter the population of india : "); points.
scanf("%Sld", &population_of india) ; #include <stdio.h> -
printf("\n Enter the value of code : "); #include <conio.h>
scanf ("%c", &code) ; #include <math.h>
printf("\n Enter the message : ");
Syereimes (MRS msg) ; int main()
{
jonenuiayere (U\Gay INU = Exel Wel PNM ee Ney 128 anME, picth | S62 aiibhe ay
%e \n POPULATION OF INDIA = %ld \n CODE float distance;
= $c \n MESSAGE = $s", num, amt, code, printf ("\n Enter the x and y coordinates
pi, population_of india, msg); Gie Gelaiey tealseisie joeulinis § 8)5
return 0; SCan
mi odaca, scl yale
printf ("\n Enter the x and y coordinates
of the second point :");
Output scanf("%$d %d", &x2, &y2);
Enter the value of num : 5
Enter the value of amt 123.45 // sqrt and pow are mathematical
Enter the value of pi SfAleta) functions defined in math.h header file
Enter the population of india 12345 distance = sqrt (pow( (x2-x1),
Enter the value of code : c 2) +pow((y2-y1),
2));
Enter the message Hello printé£("\n Distance = %£", distance);
return 0; .

}
AMT = 123.45000
PI = 3.141590e+00 Output
POPULATION OF INDIA = 12345
Enter the x and y coordinates of the first
CODE =ic
joOmmMe g 2 SF
MESSAGE = Hello
Enter the x and y coordinates of the second
2.4 Write a program to calculate the area of a triangle ioeskale 2 ey 7
Distance = 2.236068
using Hero’s formula.
#include <stdio.h>
#include <conio.h> 2.12.6 Detecting Errors During Data Input
#include <math.h>
int main () When the scanf function completes reading all the data
{ values, it returns number of values that are successfully
Eloatwal, eb; Io7 areas} read. This return value can be used to determine whether
there was any error while reading the input. For example,
printf ("\n Enter the lengths of the three
the statement,
sides of the triangle: ");
Introduction to C | 35 |

scanf ("sd %£ %c", &a, &b, &c); In Table 2.9, a andb (on which the operator is applied)
will return 3 if the user enters, say, are called operands. Arithmetic operators can be applied
to any integer or floating-point number. The addition,
12542534. K
subtraction, and multiplication (+, -, and *) operators
It will return 1 if the user enters erroneous data like perform the usual arithmetic operations in C programs, so
POVABC 12". 34 you are already familiar with these operators.
This is because a string was entered while the user was However, the operator % must be new to you. The
expecting a floating point value. So, the scanf reads only modulus operator (%) finds the remainder of an integer
first data value correctly and then terminates as soon as it division. This operator can be applied only to integer
encounters a mismatch between the type of data expected operands and cannot be used on float or double operands.
and the type of data entered. Therefore, the code given below generates a compiler
error.

13 OPERATORSINC | #include
#include
<stdio.h>
<conio.h>
An operator is defined as a ‘symbol that specifies the int main ()
mathematical, logical, or relational operation to be {
performed. C language supports a lot of operators to be mIhKeehe G = A005
used in expressions. These operators can be categorized jorailineie (U\iek Ikeswlie Ss Bie, © & Si)¢
into the following major groups: // WRONG. Modulus operator is being applied
to a float operand
e Arithmetic operators
return 0;
@ Relational operators
}
e Equality operators
While performing modulo division, the sign of the
e Logical operators
result is always the sign of the first operand (the dividend).
e Unary operators Therefore,
e Conditional operators
16%3=1-16%3=-1
e Bitwise operators 16% -3 =1-16%-3 =-1
e Assignment operators When both operands of the division operator (/) are
e Comma operator integers, the division is performed as an integer division.
e Sizeof operator Integer division always results in an integer result. So, the
In this section, we will discuss about all these operators. result is always rounded-off by ignoring the remainder.
Therefore,

2.13.1 Arithmetic Operators 9/4=2 and —9/4


= -3
From the above observation, we can conclude two
Consider three variables declared as,
things. If op1 and op2 are integers and the quotient is not
int a=9, b=3, result; an integer, then we have two cases:
We will use these variables to explain arithmetic e If opl and op2 have the same sign, then op1/op2
operators. Table 2.9 shows the arithmetic operators, their is the largest integer less than the true quotient.
syntax, and usage in C language. e Ifop1 and op2 have opposite signs, then op1/op2 is
the smallest integer greater than the true quotient.
Table 2.9 WAiana c operators
Note that it is not possible to divide any number by zero.
Operation : Ope Comment This is an illegal operation that results in a run-time division-
a*b |result=a*b by-zero exception, thereby terminating the program.
a/b | result =a/b Except for modulus operator, all other arithmetic
+ a+b |result=a+b
operators can accept a mix of integer and floating point
numbers. If both operands are integers, the result will be an
a-b |result=a—b
integer. If one or both operands are floating point numbers,
a %b then the result would also be a floating point number.
| 36 | Introduction to C Programming

All the arithmetic operators bind from left to ght. As | Output


in mathematics the multiplication, division, and modulus Enter the first number : 9
operators have higher precedence over the addition and Enter the second number: 7
subtraction operators, i.e., if an arithmetic expression 9-4 7 = 16
consists of a mix of operators, then multiplication, > alae
division, and modulus will be carried out first in a left to 9 Ned aze O28
right order, before any addition and subtraction could be 2a a Deedee as ot)
9 % 7 = 2 (Modulo division)
performed. For example, e 1G
9 / 7 = 1.29 (Normal division)
3 + 4 *-7 ; :
a ee OG 2.7 Write a program to find the number of hours and
E25) minutes, if the user inputs some minutes.
; ve #include<stdio.h>
2.6 Write a program to perform addition, subtraction, ane)
division, integer division, multiplication, and modulo {
division on two integer numbers. int mins, hrs, minutes;
#include <stdio.h> printf ("\n Enter the minutes : “);
#include <conio.h> scanf (“%d”, &minutes) ;
int main()
{ hrs = minutes/60;
mins = minutes%60;
int numl, num; printf(“\n %d minutes = %d hrs and %d
int add_res=0, sub res=0, mul_res=0, mins “, minutes, hrs, mins) ;
iGiv g-eS=0),. MOdiv aces=0); }
Eloat rai, Tes=O0y. 0); Output
elrscr
() ;
: é Enter the minutes : 134
printf("\n Enter the first number : "); ;
134 minutes = 2 hrs and 14 mins
scanf ("%d", &num1);
printf£("\n Enter the second number : "); 2.8 Write a program to subtract two long integers.
scant ("%d", &num2); #include <stdio.h>
#include <conio.h>
add_res= numl + num2; int main()
sub res=numl - num2; {
buh 1a; a aye = sei long aint numl= 91234567, num2) ditf=0)
idiv_res = numl/num2; elinsera Cy;
modiv res = numl$num2; printf ("\n Enter the number: ") ;
fdiv_res = (float)num1/num2; scanf("sld", &num2);
printf ("\n $d + %d = %d", numl, num2, diff = numl - num2;
printf ("\n Difference = 1d", Gift);
add_res) ;
pointe ("Nin td@— Ssde="s0d"s* numl --num2, ESEULIBIOS
sub_ res) ; }
pramtin( \nesd xsd) Fay Soma senum), Output
mul_res) ;
Enter the number: 1234
printf("\n @d / %d = $d (Integer Deere oe
Division)"; muni, mum2, idiiv res) ;
printf ("\n %d %% %d = %d (Moduluo ;
Division)", numl, num2, modiv_res) ; 2.13.2 Relational Operators
printf ("\n *d / #d = %.2£ (Normal Arelational operator, also known as a comparison operator,
Division)", numl, num2, fdiv_res); is an operator that compares two values. Expressions
return 0; that contain relational operators are called relational
} expressions. Relational operators return true or false
Introduction to C | 37 |

value, depending on whether the conditional relationship


Notes Although blank spaces are allowed —
between the two operands holds or not.
between an operand and an operator,
For example, to test the expression, if x is less than y, no space is permitted between the _
relational operator < is used as x < y. This expression will components of an operator (like > = is
return TRUE if x is less than y; otherwise the value of the not allowed, it should be >=). Therefore,
expression will be FALSE. writing, x==y is correct but writing x = = y
Relational operators can be used to determine the is not acceptable in C language.
relationships between the operands. These relationships
are illustrated in Table 2.10. 2.9 Write a program to show the use of relational
operators.
El (syaslt Relational operators ~*~ #include <stdio.h>
main ()

{
aide. SND), W207
jongabayere (a excl ce eyel = yell, Se Wy, Sey) s
printf("\n %d == td = sd", x, y, x==y);
printf ("\n-4d-'="4d'2 4am Ug yi cia
Greater than equalto joneaohert (UMay el ss Sel & CI, Sep 37, Resi)5
printf ("\n $d >= $d = %d", x, y, x>=y);
The relational operators are evaluated from left to right. jopanugj eve (UW Na sad <= sd = sd", xX, y, X<=y) ;
The operands of a relational operator must evaluate to a 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’ < ‘B’, where Ais 65 and B is
LOR a0). = 0)
66 then the result would be 1 as 65 < 66. ILO) cs BOY 2a ab
When arithmetic expressions are used on either side of ALO! Ne ZO) Sah
a relational operator, then first the arithmetic expression
will be evaluated and then the result will be compared.
This is because arithmetic operators have a higher priority
over relational operators.
However, relational operators should not be used for 2.13.3 Equality Operators
comparing strings as this will result in comparing the C language supports two kinds of equality operators to
address of the string and not their contents. You must compare their operands for strict equality or inequality.
be wondering why so? The answer to this question will They are equal to (==) and not equal to (!=) operators.
be clear to you in the later chapters. A few examples of The equality operators have lower precedence than the
relational operators are given below. relational operators.
The equal-to operator (==) returns true (1) if operands
If x=1, y=2, andz = 3,then on both the sides of the operator have the same value;
Expressions that evaluate Expressions that evaluate otherwise, it returns false (0). On the contrary, the not-
to TRUE to FALSE equal-to operator (!=) returns true (1) if the operands do
Note that these expressions Note that these not have the same value; else it returns false (0). Table
are true because their expressions are false 2.11 summarizes equality operators.
value is not zero. because their value is
Zero. eG \(o7aeul Equality operators

(x) (ee= 1)
(x + y) Gin),
beeen Returns 1 if both operands are equal, 0
(z * 9) (Oh xeenya)
otherwise
(Zee Gees a) (ye se) 1)
GZ = axe ey) Returns 1 if operands do not have the same
value, 0 otherwise
| 38 | Introduction to C Programming

2.13.4 Logical Operators The whole expression is true if either b is greater than a
or b is greater than c orb is greater than both a and c.
C language supports three logical operators—togical
AND (&&), logical OR (||), and logical NOT (!). As in Logical NOT
case of arithmetic expressions, the logical expressions are
The logical NOT operator takes a single expression and
evaluated from left to right.
negates the value of the expression. That is, logical NOT
Logical AND produces a zero if the expression evaluates to a non-zero
value and produces a 1 if the expression produces a zero.
Logical AND is a binary operator which simultaneously
In other words, it just reverses the value ofthe expression.
evaluates two values or relational expressions. If both are
The truth table of logical NOT operator is given in
true, then the whole expression is true. If both or one of
Table 2.14.
the operands is false, then the whole expression evaluates
to false. The truth table of logical AND operator is given in
Table 12, Table 2.14 Truth table of logical NOL. <

Now the value of b = 0. This is because value ofa =


10. !a = 0. The value of !a is assigned to b, hence, the
For example,
result.
(Qv<3b) 5EE (bc) Logical expressions operate in a short cut fashion and
The whole expression is true only if both expressions are stop the evaluation when it knows for sure what the final
true, i.e., if bis greater than a and c. outcome would be. For example, in a logical expression
involving logical AND, if the first operand is false, then
Logical OR the second operand is not evaluated as it is for sure that
Logical OR returns a false value if both the operands are the result will be false. Similarly, for a logical expression
false. Otherwise it returns a true value. The truth table of involving logical OR, if the first operand is true, then the
logical OR operator is given in Table 2.13. second operand is not evaluated as it is for sure that the
result will be true.
ieseraey Truth table of logical OR But this approach has a side effect. For example,
consider the following expression:
a _ B :
Ge
> 9S) Se iG =a)

OR
(Ee) eeaeanne

In the above logical AND expression if the first operand


is false then the entire expression will not be evaluated and
thus the value of y will never be incremented. Same is the
case with the logical OR expression. If the first expression
For example,
is true then the second will never be evaluated and value
(ates bb)+ dnleni(bye oe) of y will never be incremented.
Introduction toC | 39 |

2.13.5 Unary Operators is equivalent to writing

Unary operators act on single operands. C language seacee


supports three unary operators unary minus, increment, De ee Geeoe dle

and decrement operators. whereas,

Unary Minus Var =e es

Unary minus (—) operator is strikingly different from the is equivalent to writing
binary arithmetic operator that operates on two operands 2S = Oe ae Abe
and subtracts the second operand from the first operand.
Va;
When an operand is preceded by a minus sign, the unary
The same principle applies to unary decrement
operator negates its value. For example, if a number is
operators. The unary operators have a higher precedence
positive then it becomes negative when preceded with a
than the binary operators. If in an expression we have more
unary minus operator. Similarly, if the number is negative,
than one unary operator then unlike arithmetic operators,
it becomes positive after applying the unary minus
they are evaluated from right to left.
operator. For example,
When applying the increment or decrement operator,
int a, the operand must be a variable. This operator can never
len) be applied to a constant or an expression. Therefore the
The result of this expression is a = -10, because a following codes will generate a compiler error.
variable b has a positive value. After applying unary minus
operator (-) on the operand b, the value becomes —10, Notes When postfix ++ or——isusedwith >
which indicates it as a negative value. a variablein an expression,
then the —

Increment Operator (++) and Decrement


Operator (—-)
The increment operator is a unary operator that increases
the value of its operand by 1. Similarly, the decrement
operator decreases the value of its operand by 1. For _ the variab! : firstincremented or
example, --x is equivalent to writing x = x - 1. / decremented and then the expression
The increment/decrement operators have two variants— is evaluated using. ‘thenew value of the
prefix and postfix. In a prefix expression (++x or --x), ariable. :
the operator is applied before an operand is fetched for
computation and thus, the altered value is used for the 2.10 Write a program to illustrate the use of unary prefix
increment and decrement operators.
computation of the expression in which it occurs. On the
#include <stdio.h>
contrary, in a postfix expression (x++ or x--) an operator
main ()
is applied after an operand is fetched for computation.
Therefore, the unaltered value is used for the computation
{
shale ini Ss skr
of the expression in which it occurs.
Therefore, an important point to note about unary // Using unary prefix increment operator

increment and decrement operators is that ++x is not the printf ("\n The value of num = %d", num) ;
same as x++. Similarly, --x is not the same as x--. Both printf ("\n The value of ++num=%d",
++num) ;
++x and x++ increment the value of x by 1. In the former printf ("\n The new value of num= %d", num) ;

case, the value of x is returned before it is incremented // Using unary prefix decrement operator
whereas, in the latter case, the value of x is returned after
printf ("\n\n The value of num = $d", num) ;
it is incremented. For example,
printf ("\n The value of --num= %d", --num) ;
alinie Se = IO, 375 printf ("\n The new value of num = $d", num) ;
y = Xt++;
| 40 [ Introduction to C Programming

return 0; exp] is evaluated first. If it is true, then exp2 is evaluated


} and becomes the result of the expression, otherwise exp3
is evaluated and becomes the result of the expression. For
Output
example,
The value of num = 3
Larger = "a. > b)erc= aee= b
The value of ++num = 4

The new value of num = 4 The conditional operator is used to find largest of two
given numbers. First exp1, that is (a > b) is evaluated. Ifa
The value of num = 4
is greater than b, then large =a, else large = b. Hence,
The value of --num = 3
large is equal to either a or b but not both.
The new value of num = 3
Hence, conditional operator is used in certain situations,
2.11 Write a program to illustrate the use of unary postfix replacing if-else condition phrases. Conditional
increment and decrement operators. operators make the program code more compact, more
#include <stdio.h> readable, and safer to use, as it is easier to check any error
main () (if present) in one single line itself. Conditional operator is
{ also known as ternary operator as it is neither a unary nor
inte numic= 3; a binary operator; it takes three operands.
Since a conditional operator is itself an expression, it
// Using unary postfix increment operator
can be used as an operand ofanother conditional operation.
printf ("\n The value of num= %d", num) ; That means C allows you to have nested conditional
printf ("\n The value of num++ = $d", num++) ; expressions. Consider the expression given below which
printf ("\n The new value of num= %d", num) ; illustrates this concept.
Int, a= 5) Dea Sa aC=— 7, comalele
// Using unary postfix decrement operator
small
= (arbres (Har<icua:
2.¢) Pal(bra GeelGre))p)ee
printf ("\n\n The value of num= %d", num) ;
2.12 Write a program to determine whether a person is
printf ("\n The value of num= %d", num--) ;
eligible to vote using conditional operator.
printf ("\n The new value of num= %d", num) ;
#include<stdio.h>
return 0; #include<conio.h>
} main ()

{
Output int age;
The value of num = 3 char ch;
Gimser():
The value of num++ = 3
printf(“\n Enter your age : “);
The new value of num = 4
scanf(“%d”", &age);
The value of num = 4 Chv= ilagess= 119)?
hy ene:
printf(“\n Eligible to vote : %c”, ch);
The value of num-- = 4

The new value of num = 3


}
Output
2.13.6 Conditional Operator Been your sages 202s,
Eligible to vote : y
The conditional operator or the ternary (?:) is just like an
if-else statement that can be within expressions. Such 2.13 Write a program to find the largest of three numbers
an operator is useful in situations in which there are two using ternary operator.
or more alternatives for an expression. The syntax of the
#include <stdio.h>.
conditional operator is
#include <conio.h>
exply 7 exp2 exp3 int main()
Introduction to C | 41 |

{ Bitwise OR
int numl, num2, num3, large;
The bitwise OR operator (|) is a small version of the boolean
@ilsacyena(()) 5
OR (||) as it performs operation on bits instead of bytes,
printf("\n Enter the first number: "); chars, integers, etc. When we use the bitwise OR operator,
scant ("Sd", snum1) ; the bit in the first operand is ORed with the corresponding
printf("\n Enter the second number: "); bit in the second operand. The truth table is same as we
scant ("sd", &S&num2); had seen in logical OR operation, i.e., the bitwise OR
printf ("\n Enter the third number: "); operator compares each bit of its first operand with the
scanf("Sd", &num3);
corresponding bit of its second operand. If one or both
bits are 1, the corresponding bit in the result is | and 0
large = numl>num2? (numl>num3?num1:num3) : otherwise. For example,
(num2>num3 ?num2:num3) ;
10101010 & 01010101 = 11111111
printf ("\n The largest number is: %d",
In a C program, the | operator is used as follows.
large);
return’ 0; ’ aligle ew ee cp lopli X0) eS Or
c= alb
}
Output Bitwise XOR

Enter the first number: 12


The bitwise XOR operator (*) performs operation on
individual bits of the operands. When we use the bitwise
Enter the second number: 34
XOR operator, the bit in the first operand is XORed with
Enter the third number: 23
the corresponding bit in the second operand. The truth
The largest number is: 34
table of bitwise XOR operator is as shown in Table 2.15.
The bitwise XOR operator compares each bit of its first
2.13.7 Bitwise Operators operand with the corresponding bit of its second operand.
If one of the bits is 1, the corresponding bit in the result is
As the name suggests, bitwise operators are those
l and 0 otherwise. For example,
operators that perform operations at bit level. These
10101010 * 01010101 = 11111111
operators include: bitwise AND, bitwise OR, bitwise XOR,
and shift operators. The bitwise operators expect their Lela Truth table of bitwise XOR
operands to be integers and treat them as a sequence of
bits.

Bitwise AND

The bitwise AND operator (&) is a small version of the


boolean AND (&&) as it performs operation on bits instead
of bytes, chars, integers, etc. When we use the bitwise
AND operator, the bit in the first operand is ANDed with In a C program, the * operator is used as follows:
the corresponding bit in the second operand. The truth sgh yew Ey INOy, lop ts PAO ee KO)C
table is same as we had seen in logical AND operation, c= a*b
i.e., the bitwise AND operator compares each bit of its first
operand with the corresponding bit of its second operand. Bitwise NOT
If both bits are 1, the corresponding bit in the result is 1 The bitwise NOT, or complement, is a unary operation that
and 0 otherwise. For example, performs logical negation on each bit of the operand. By
10101010 & 01010101 = 00000000 performing negation of each bit, it actually produces the
ls complement of the given binary value. Bitwise NOT
In a C program, the & operator is used as follows. operator sets the bit to | if it was initially 0 and sets it to 0
Titel Os a= 20), C=O; if it was initially 1. For example,
c= a&b; ~10101011 = 01010100
| 42 | Introduction to C Programming

For example,
_Bitwise operators are used for testing the ©
bits or shifting them left or right. Always bale, pie
remember that bitwise operators cannot Ra Oy.
be applied to float or double variables.
assigns the value 10 to variable x. If we have,
ime xk = 2, was, Stin = Op
Shift Operator Sumy =— sce
then sum = 5.
C supports two bitwise shift operators. They are shift-left
(<<) and shift-right (>>). These operations are simple and The assignment operator has right-to-left associativity,
are responsible for shifting bits either to the left or to the so the expression ‘
right. The syntax for a shift operation can be given as el fe lop rs Gt. J0)9

operand op num
is evaluated as
where the bits in operand are shifted left or right depending
on the operator (left if the operator is << and right if the
operator is >>) by the number of places denoted by num. First 10 is assigned to c, then the value of c is assigned
For example, ifwe have x = 0001 1101, then to b. Finally, the value of b is assigned to a. .
The operand to the left of the assignment operator
x << 1 produces 0011 1010
must always be a variable name. C does not allow any
When we apply a left-shift, every bit in x is shifted to the expression, constant, or function to be placed to the left of
left by one place. So, the MSB (most significant bit) of x the assignment operator. Therefore, the statement a + b = 0,
is lost, the LSB of x is set to 0. is invalid in C language.
Therefore, ifwe have x = 0001 1101, then To the right of the assignment operator you may have
x << 3 produces 1010 0000. an arbitrary expression. In that case, the expression would
If you observe carefully, you will notice that shifting once be evaluated and the result would be stored in the location
to the left multiplies the number by 2. Hence, multiple denoted by the variable name.
shifts of 1 to the left, results in multiplying the number by
2 over and over again. Other Assignment Operators
On the contrary, when we apply a shift-right operator, C language supports a set of shorthand assignment
every bit in x is shifted to the right by one place. So, the operators of the form
LSB (least significant bit) of x is lost, the MSB of x is set
variable op = expression
to 0. For example, if we have x = 0001 1101, then
x>>01 produces = 0000 1110 where op is a binary arithmetic operator.
Table 2.16 contains a list of other assignment operators
Similarly, ifwe have x = 0001 1101, then
that are supported by C. .
x << 3 produces 0000 0001. The advantage of using shorthand assignment operators
If you observe carefully, you will notice that shifting are as follows:
once to the right divides the number by 2. Hence, multiple e Shorthand expressions are easier to write as the
shifts of 1 to the right, results in dividing the number by 2 expression on the left side need not be repeated.
over and over again.
e The statement involving shorthand operators are
easier to read as they are more concise.
2.13.8 Assignment Operators e The statement involving shorthand operators are
In C, the assignment operator is responsible for assigning more efficient and easy to understand.
values to the variables. While the equal sign (=) is the
2.14 Write a program to demonstrate the use of assignment
fundamental assignment operator, C language also supports
operators.
other assignment operators that provide shorthand ways to
represent common variable assignments. #include <stdio.h>
When an equal sign is encountered in an expression, the main ()

compiler processes the statement on the right side of the {


int num = 3) num2e= 5
sign and assigns the result to the variable on the left side.
a1qeL 9T'Z

=/ ajqeiuen
=/ uolssaidxa ajqeuen
= ajqeiuen
/ uolssaidxa sapiaiq
au} anjen
Joe ajqelen
Aq ay} anjen
Jo ue uolssaidxa
pue JeOY=e ‘076
“a

SUBISse
BU} YNSaJ
0} JU} "9/QeIeA 1eOL
4= ‘O'€
<G=/e

=/ ajqelen
=/ uolssaidxa ajqeien
= ajqelen
/ uolssasidxa Sapiaiq
ayy anjen
Joe ajqelen
Aq ayy anjen
Jo ue uolssaidxa
pue 4UI =e ‘6
suisse
ay} JaSaj}U!NSaJ
0} ay} ‘a/Geiea qu!q = ‘€
e = :q

= ajqeluen
=, uOIssaidxa ajqelen
= B|QeIEA
, UOISSaJdXa saljdyinyw)
au} anjen
Joe ajqeleA
Aq ayi aNjeA
JO Ue UOIssasdxa
pue SUBIsse
ay} 3/NSaJ
0} BU} "9|GeeA

ajqelen
= a/qeleA
+ UOISSaIdXOsppyay anjeA
Joe ajqeleA
0} ay} aNjeA
JO ue uolssasdxa
pue Ul© = “6

=+
sUBIsse
ay jNSaJ
0} BU} ‘3}QeIeA Ulq = “€

ajqeluen
=+eq

uoIssaidxe
ajqelien
=— uolssaidxa ajqelen
= a|GeIeA
— UOISSaJdXa sJDesQNS
BY} BNIEA
JO 94} uolssaidxa
WOI BY} BNJEA
JO 9U}
sIGelieA
PUE susisse
BY} 2/NS3J
0} JY} “OIQEIICA

a]qeleA
=9 UOISSaIAXa ajqeluen
= aIGeeA
*B UOISSIIAXa WIOjUad
ay} aSIM4gGNY YIM ay) anjen
Jo ajqeien
pue anjeA
$O ju! =e ‘OT
ayy UOIssasdxa
pue UBIsse
ay} yNSaJ
Ul BU} "B|QeeA qu!q = ‘07
e =9 :q

ajqeen
= a/qeleA
y UOISSAIdXa WIOJad
ay} asiMyg qu! =e ‘OT

v
uOISSaidxa = YOX YUM BY} anjeA Jo ajqelen
pue ANjeA
JO
ayy UOIssasdxa
pue UBIsse
aU} 3[NSaJ
Ul au} "9/QeUeA qui4 = ‘OZ

a]qelen
2 =y :q

=>> ajqelen
=>> jUuNOWe ajqelen
>> junowe SWOJIAad
Ue Je IQawU
Ya] YIYs UNOWe)(Sawy
uO ay} anjen
$O UI ‘6 =e
e ajqelueA
pue SUBISse
ay} YNSai eqOJ Buy} "3|QeleA “€ = q Ul

ajqeien
idi=>> ie

=<< junowe =<< ajqelen ajqeien


<< yunowe SWOJJag
Ue we IQawWYYBN Ylys JUNOWe)(Sawy
uo ayy anjea
JO
e ajqelen
pue sUBIsse
ay} IjNSa1 YOeqOJ aU} "2|QeeA

a|qeluen
Introduction to C | 43
|
| 44 [ Introduction to C Programming

printf ("\n Initial value of numl = %d and unsigned int result;


rabies <xollll | “sakbhanil; Tanbi2))A result = sizeof (a);
numl += num2 * 4 - 7;
then result = 2, which is the space required to store the
printf ("\n After the evaluation of the
variable a in memory. Since a is an integer, it requires 2
expression numl = %d and num2 = $d",
numl, num2);
bytes of storage space.
return 0;

} 2.13.11 Operator Precedence Chart

Output C operators have two properties: priority and associativity.


Initial value of numl = 3 and num2 = 5 When an expression has more than one operator then it is
After the evaluation of the expression numl the relative priorities of the operators with respect to each
= WG rarely sable eS other that determine the order in which*the expression
will be evaluated. Associativity defines the direction in
which the operator having the same precedence acts on
2.13.9 Comma Operator
the operands. It can be either left-to-right or right-to-
The comma operator in C takes two operands. It works left. Priority is given precedence over associativity to
by evaluating the first and discarding its value, and then determine the order in which the expressions are evaluated.
evaluates the second and returns the value as the result of Associativity is then applied, if the need arises.
the expression. Comma separated operands when chained Table 2.17 lists the operators that C language supports
together are evaluated in left-to-right sequence with the in the order of their precedence (highest to lowest). The
rightmost value yielding the result of the expression. associativity indicates the order in which the operators of
Among all the operators, the comma operator has the equal precedence in an expression are evaluated.
lowest precedence.
Therefore, when a comma operator is used, the entire MiElsty4sws) Operator precedence
expression evaluates to the value of the right expression.
For example, the following statement first increments a, | Associativity |
Operator|Associativity
then increments b, and then assigns the value b to x. left-to-right left-to-right

iale, =A I= x= (0);
x = (47a, b+=a);
++(postfix)
Now, the value of x = 6. --(postfix)
++(prefix) right-to-left left-to-right
2.13.10 Sizeof Operator --(prefix)
+(unary) - (unary)
The operator sizeof is a unary operator used to calculate | ~~

the size of data types. This operator can be applied to all


(type)
data types. When using this operator, the keyword sizeof *(indirection)
is followed by a type name, variable, or expression. The &(address)
operator returns the size of the variable, data type, or sizeof
expression in bytes, i.e., the sizeof operator is used to left-to-right left-to- ent
determine the amount of memory space that the variable/ left-to-right HI
_|teft-to-right|
expression/data type will take.
When a type name is used, it is enclosed in parentheses,
left-to-right Pied right-to-left
left-to-right right-to-left
but in case of variable names and expressions they can be
specified with or without parentheses. A sizeof expression
returns an unsigned value that specifies the space in
bytes required by the data type, variable, or expression.
For example, sizeof (char) retums 1, ie., the size of a
character data type. If we have, left-to-ign
ighe 2) = AOS
Introduction to C | 45 |

You must be wondering why the priority of the = a+ (b= 11)


assignment operatoris so low. This is because the action of = 0 + 11
assignment is performed only when the entire computation = 11
is done. It is not uncommon foraprogrammer to forget the Oe ee ea ee
priority of the operators while writing any program. So ae eee oer
it is recommended that you use the parentheses operator a ke eae |
to override default priorities. From Table 2.17 you can (Value of. has been incremented butits altered value will

see that the parenthesis operator has the highest priority. else ACE OU ESTs Os
So any operator placed within the parenthesis will be =a) eG ei nd 1
evaluated before any other operator. (Value of a has been incremented and its altered value will
be used for the evaluation of this expression)
Example Expressions Using the Precedence Chart So a car ng
= -3 - -1*1
xena * 44 5°* 6 = Saeed:
= 12+5* 6 Pee)
= 12 + 30
ae 9: ai b acs
9. teneop4 eo yane- [Link] = (a * b) * c (because associativity of *
aoa le gang is from left-to-right)
= 27 * 6 ofan
= 162 10. a && b
Sjmaewsatne $5 7 2 ee
6198-5 <2 Il. aa<b&&c<b
per) 2 =~
a | A cir Tate a ee
ae ee * (4% 5) / 2 =D
2) a)
= GA hip = 0 mee

Sele p93 ae
sty 13. et S ese 5 5 ebeac)
Sree ns 40%. (5 7 2) = (ior 25) 65) ol Ab shee)
BORO Gels = (22 Geo) | er
= 12% 2 aia
=< 14. a <= 10 && x >= 1 &&b
6. vee 3 os ((4 x 5) ji 2) = ((a <= 10) && (x >= ))f) && b

oS AeA 2) = (1 && 1) && 1


=13 ¥02 aa
ee TSpe1x) hh we, MMepeaEd
iis | keke) ait ease)
Take the following variable declaration, = 160m (asOvme | eo
alighe tc) —3. Oy lo) = ell Velie oily 16 x ‘
float siete s5 y = 0.0% Be beDae del er o¥N pre
mete) <6 a4) el mee
; = (OMe yeep at
If we write, oT
al Saber =*cr ats 17. (x > y) + !a || c++
Since the assignment operator works from right-to-left, Ces yee (Vay | ery
therefore = (2 ted) PO
¢ = 7. Thensince b = c, therefore b = 7. Now =1
el c= ley Go el = We

Tjikeera bre .c +610


2.14 Programming Examples
S44 P wince rpl

This is expanded as
Qvetare (beesin = (c = eo ** 20) 2.15 Write
a program to calculate the area of a circle.
eg et RI) #include <stdio.h>
| 46 | Introduction to C Programming

#include <conio.h> return 0;


int main() }

float radius; Output


double area, circumference; Enter any character: A
Giese Ge The character in lower case is: a
printf ("\n Enter the radius of the circle: ");
2.18 Write a program to print the digit at ones place of a
scanf("%S£", &radius) ;
clase) = S\oal4h se aeexeliuis) 2 ieevolinbiss; number.
circumference = 2 * 3.14 * radius; #include <stdio.h>
printf(" Area = %.2le", area); #include <conio.h> \
printf ("\n CIRCUMFERENCE = %.2e", main ()
circumference) ; {
int num, digit_at_ones place;
return 0;
Gilmseri)s
}
printf("\n Enter any number: ");
scanf("%d", &num);
Output
digit _at_ones place = num %° 10;
Enter the radius of the circle:
printf("\n The digit at ones place of %d
Area = 153.86
is %d", num, digit_at_ones place) ;
CIRCUMFERENCE = 4.40e+01
return 0;

2.16 Write a program to print the ASCII value of a }


character.
haracter. Ort
#include <stdio.h> Enter any number: 123

#include “<conio.h> The digit at ones place of 123 is 3


int main()
{ 2.19 Write a program to swap two numbers using a
char ch; temporary variable.
clrscr () ; #include <stdio.h>
pLInteeE("\n Enter any character: "); #include <conio.h>
Scank (Use) Sch) > int main()
printf ("\n The ascii value of $c is: {
Pol aelayprel ay)" int numl, num2, temp;
return 0; elisseri
(5;
} printf ("\n Enter the first number: ");
scanf ("%Sd", &num1) ;°
Output
printf ("\n Enter the second number: ") ;
Enter any character: A scanf ("$d", &num2) ;
The ascii value of A is: 65
Eemp = num;
2.17 Write a program to read a character in upper case numl = num2;
and then print it in lower case. num2=temp;
nel Gdameeeaiouls printf ("\n The first number is $d", num1) ;
#include <conio.h> printf ("\n The second number is $d", num2) ;
int main () return 0;

{ }
char ch;
eCLrsen); Output
printf ("\n Enter any character in upper i
Enter the first number : 3
case: ");
scanf ("$c", &ch); Enter the second number : 5
printf ("\n The character in lower case The first numbereie5
aR exe lassi») 7 The second number is 3
Introduction to C | 47 |

2.20 Write a program to swap two numbers without using


a temporary variable. else (\)s-
printf("\n The size of short integer is:
#include <stdio.h>
sa", sizeof (short int)
);
#include <conio.h> printf("\n The size of unsigned integer
int main() is: $a", sizeof (unsigned int));

{ printf ("\n The size of signed integer is:


int numl, num2; a", sizeof (signed int));
printf("\n The size of integer is: %d",
Elissere'());
sizeof (int) );
printf ("\n Enter the first number: ");
wo printf ("\n The size of long integer is:
scanf ("%d", &num1) ;
sa", sizeof (long int)),;

printf("\n Enter the second number: ");


printf("\n The size of character is: %d",
scanf ("%d", &num2) ;
sizeof (char) );

numl = numl + num2; »* printf ("\n The size of unsigned character

num2= numl —- num2; iss $a", sizeof (unsigned char)


);
printf ("\n The size of signed character
numl = numl —- num2;
is: $a", sizeof (signed char) );
printf ("\n The first number is $d", num1) ;
printf ("\n The second number is $d", num2) ; printf("\n The size of floating point
number is: %d", sizeof (float) );
return 0;
printf("\n The size of double number is:
sa", sizeof (double) ) ;
return 0;
Output
}
Enter the first number: 3
Output
Enter the second number: 5
The size of short integer is: 2
The first number is 5
The size of unsigned integer is: 2
The second number is 3
The size of Signed integer is: 2
2.21 Write a program to convert degrees Fahrenheit into The size of integer is: 2
degrees celsius. The size Op long integer is: 2

#include <stdio.h>
The size Cis character is: 1
#include <conio.h>
The size of unsigned character is: 1
main ()
The size of signed character is: 1
{
float fahrenheit, celsius;
The size of floating point number is: 4
printf ("\n Enter the temperature in
The size of double number is: 8
fahrenheit: ");
scanf ("$£", & fahrenheit); 2.23 Write a program to calculate the total amount of
celsius = (0.56) * (fahrenheit - 32); money in the piggybank, given the coins of Rs 10,
printf ("\n Temperature in degrees celsius
Rsiov RS 2, and Re Tf.
eo ker Celsnus))
#include <stdio.h>
return 0;
#include <conio.h>
}
main ()
2.22 Write a program that displays the size of every data {
type. imt numsokslOcoins), numeor
5 scorns; num)
#include <stdio.h> C12 2Cohorts, Tabi’ ese il,Cloning);
#include <conio.h> Proce EOtaleamt = Ory

int main() elrser (\)-


| 48 | Introduction to C Programming

printf ("\n Enter the number of Rs10 coins scanf("S£i", &tax);


in the piggybank: ");
amt = qty * val;
scanf("sd", &num_of
10 coins) ;
discount
amt = (amt * discount) /100.0;
printf("\n Enter the number of Rs5 coins
sub_ total = amt - discount_amt;
in the piggybank: ");
tax_amt = (sub_total
* tax) /100.0;
scanf("%sd", &num_of
5 coins) ;
total _ amt =sub total + tax_amt;
printf ("\n Enter the number of Rs2 coins
in the piggybank: ");
printf
( "\n\n\n ****** BILL ******M") |
scanf ("sd", &num of 2 coins) ;
prince ( (\nQuantitySold=
tka qty);
printf ("\n Enter the number of Rel coins
printf ("\n
( Price per item: %f", val) ;
in the piggybank: ");
scanf("%d", &num_of
1 coins) ; printf ( ("\n ------------- Wise
print£ ( ("\mAmount:
¢£", amt) ; ~

total amt “= num of 10\coins * 10 + num_ printf ("\n Discount: - %£", discount amt) ;

Ob >scoims <5 nuMTOr


2 Coins == 2) printf ( ("\nDiscounted
Total: £", sub_total) ;

NUDSOheCOlls ; printf ("\nTax:


+ sf", tax_amt) ;
See, S Sete = "); :
josanbehena ( "\n ase

printf("\n Total amount in the piggybank printf ("\n


( Total Amount s£", total_amt) ;
=e ou ete Ot allamamnte))ap EeCucOl;
getch(); }
return 0;
Output
}
Enter the quantity of item sold: 20
Output Enter the value of item: 300
Enter the number of Rs10 coins in the Enter the discount percentage: 10
piggybank: 10 Enter the tax: 12
Enter the number of Rs5 coins in the KAKA KKKKKK BILL KERR KKKKKKKK
KEM

piggybank: 23 Quantity Sold : 20


Enter the number of Rs2 coins in the Price per item : 300
piggybank: 43
Enter the number of Rel coins in the Amount : 6000

piggybank: 6 Discount : - 600


Total amount in the piggybank = 307 Discounted Total : 5400
deeb 8 + 648
2.24 Write a program to calculate the bill amount for an
item given its quantity sold, value, discount, and tax.
Total Amount 6048
#include <stdio.h>
#include
main ()
<conio.h>
(2.15 TYPE CONV! ERSION AND.
{
float total amt, amt, sub total,
discount amt, tax_amt, qty, val,
Till now we have assumed that all the expressions involved
discount, tax;
data of the same type. But what happens when expressions
printf ("\n Enter the quantity of item involve two different data types, like multiplying a floating
sold: "); point number and an integer. Such type of situations are
scanf("S£", &dty); handled either through type conversion or typecasting.
printf("\n Enter the value of item: "); Type conversion or typecasting of variables refers to
scanf("%f£", &val); changing a variable of one data type into another. Type
printf ("\n Enter the discount percentage: "); conversion is done implicitly whereas, typecasting has
scant ("SE", &discount) ; to be done explicitly by the programmer. We will discuss
jouenliahasc
(MH\inl, ddinie(ere siclnien jeebiogs W))5 both of them here.
Introduction to c | 49 |

2.15.1 Type Conversion e If any one operand is double, the other operand is
also converted to double. Hence, the result is also
Type conversion is done when the expression has vari-
of type double.
ables of different data types. To evaluate the expres-
e Ifany one operand is long, the other operand is also
sion, the data type is promoted from lower to higher
converted to long. Hence, the result is also of type
level where the hierarchy of data types (from higher to
long.
lower) can be given as: double, float, long, int, short,
and char. Figure 2.12 shows the conversion hierarchy Figure 2.13 exhibits type conversions in an expression.
of data types.

Higher level

Figure 2.12 aversion hie

Type conversion is automatically done when we assign


an integer value to a floating point variable. Consider the
code given below in which an integer data type is promoted
to float. This is known as promotion (when a lower level
data type is promoted to a higher type).

al aia.

Me
W/ = Bs
He SS A

Now, x = 3.0, as automatically integer value is


The statement i = f results in f to be demoted to type
converted into its equivalent floating point representation.
int, i.e., the fractional part of £ will be lost and i will
In some cases, when an integer is converted into a floating
contain 3 (not 3.5). In this case demotion takes place, i.e.,
point number, the resulting floating point number may
a higher level data type is converted into a lower type.
not exactly match the integer value. This is because the
Whenever demotion occurs, some information is lost. For
floating point number format used internally by the
example, in this case the fractional part of the floating
computer cannot accurately represent every possible
point number is lost.
integer number. So even if the value of x = 2.99999995,
Similarly, if we convert an integer to a short integer or
you must not worry. The loss of accuracy because of this
along int to int, or int to char, the compiler just drops
feature would be always insignificant for the final result.
the extra bits (Fig. 2.14).
Let us summarize how promotion is done:
No compile time warning message is
|
e float operands are converted to double.
e char or short operands whether signed or unsigned
_ generated when information is lost while
demoting the type of data.
are converted to int.
| 50 | Introduction to C Programming

is also done in arithmetic operations to get correct result.


For example, when dividing two integers, the result can be
Q000 0100 | 1101 0010 | | 1101 0010
of floating type. Also when multiplying two integers the
result can be of long int. So to get correct precision value,
Co typecasting can be done. For instance:
int ae=1 5007 .b =. 10m
ELOQE. GES,
res = (float) a/b;

Let us look at some more examples of typecasting:



On sages =~ (aya) asp
Thus we can observe the following changes that are
unavoidable when performing type conversions. 9.5 is converted to 9 by truncation and then assigned
to res.
e When a float value is converted to an integer value, Oca; = (Gine)
a eos 7 (Guns) 4.2 2
the fractional part is truncated.
It is evaluated as 12/4 and the value 3 is assigned to res.
e When a double value is converted to a float value, e res = (double)total/n;
rounding of digits is done. total is converted to double and then division is
e When a long int is converted into int, the excess higher done in floating point mode.
order bits are dropped. e res = (int) (a+b) ;

These changes may cause incorrect results. The value of a+b is converted to integer and then
assigned to res.
emcees a (ineyean ab
2.15.2 Typecasting
a is converted to int and then added with b.
Typecasting is also known as forced conversion. Type- e res = cos((double)x) ;
casting an arithmetic expression tells the compiler to It converts x to double before finding its
represent the value of the expression in a certain way. It cosine value.
is done when the value of a higher data type has to be
2.25. Write a program to convert a floating point number
converted into the value of a lower data type. But this
into the corresponding integer.
cast is under the programmer’s control and not under
#include <stdio.h>
compiler’s control. For example, if we need to explicitly
#include <conio.h>
typecast an integer variable into a floating point variable,
int main()
then the code to perform typecasting can be given as,
{
Eloee Ceuleray = 10000, OO; float f num;

iit Sale;
Inc [Link];
llsatsyene(())
sal = (int) salary;
printf ("\n Enter any floating point number: ");
When floating point numbers are converted to integers scanf("S£", &£ num) ;
(as in type conversion), the digits after the decimal are aLGaui S (SuME)
Ie Tawi
truncated. Therefore, data is lost when floating point printf("\n The integer variant of %f is =
representations are converted to integral representations. el 7 Gesatel, aLTae) 5

So in order to avoid such type of inaccuracies, int type weve (OF

variables must be typecast to float type. }


As we see in the code, typecasting can be done by Output
placing the destination data type in parentheses followed
Enter any floating point number: 23.45
by the variable name that has to be converted. Hence, we
The integer variant of 23.45 is = 23
conclude that typecasting is done to make a variable of
one data type to act like a variable of another type. 2.26. Write a program to convert an integer into the
We can also typecast integer values to its character corresponding floating point number.
equivalent (as per ASCII code) and vice versa. Typecasting #include <stdio.h>
Introduction to C | 51 |

#include <conio.h> printf ("\n Enter the score obtained in


int main () three activities (out of 20): ");

{ scanf ("sd sd sd", &activities scorel,


EUOAE SEemum; &activities score2, &activities_
algae, al,
volley score3) ;

elilsaexena\(())3
exam total = exam_scorel + exam _score2;
printf("\n Enter any integer: "); activities total = (activities! scorel +
scant ("sd", &i num); AGEIVIEVESE SCORE? theaCe Myre LesSCOes) my,
£ num = (float)i_ num;
exam_percent = (float)exam total * EXAMS)
printf ("\n The floating point variant of
WEIGHTAGE / EXAMS TOTAL;
+d is = sf") i num, £ ‘num)y;
SpOLESsR percents (rlloak)ispontcmscOrems
return 0;
SPORTS WEIGHTAGE / SPORTS TOTAL;
} elslguvalieileey josneeciale = (i ikeele) eeieayae os) _
Output total * ACTIVITIES WEIGHTAGE /
ACTIVITIES TOTAL;
Enter any integer: 12
The sEloatang spoant varwvant, of 12 srs =
total percent = exam_percent + sports_
12.00000
jeratelerale, 4 Eller NAlees) joeretetsiale 7
2.27. Write a program to calculate a student’s result based
on two examinations,
one sports event, and three jorcaentene (ai \in KEK KKK KEK KEK KEKE KKK KKK KKK

activities conducted. The weightage of activities = RESULT FORK RK KKK KK KK KK KK I) 5

30%, sports = 20%, and examination


= 50%. printf ("\n Total percent in examintaion

#include <stdio.h> Biel, Shin ISIRSSME)) §

#include <conio.h> printf ("\n Total percent in activities


Si", activities percent) ;
#define ACTIVITIES WEIGHTAGE 30
printf("\n Total percent in sports
#define SPORTS WEIGHTAGE 20
Biel, S[OCIAES: JOSIGOSAE)) 7
#define EXAMS WEIGHTAGE 50
#define EXAMS TOTAL 200 DEAnUE (YN) So ee ee

#define ACTIVITIES TOTAL 60


#define SPORTS TOTAL 50 printf ("\n Total percentage oie, (Owe _
percent) ;
main ()

{ return 0;
Wale pectin Sowell, Elica
wes) Seer,
}
sports score;
iiitmexamMEscOLen maga vitteSmsSCOre2y, Output
EViCa Wallets! SCeres) p Enter the score obtained in two examination
float exam total, activities total; (GEE Cie OO) 3 Ws SY

Ela tOvalepercent, exam percent, Enter the score obtained in sports events
Sports percent, activities percent; (Gule wie SOE Be!
elrser(); Enter the score obtained in three activities
printf ("\n Enter the score obtained in (@ule Cie BO) IWS) ae a7

EWONexXaMmunasrzon (OUubor 100) ir KKEKKKKKKKKKKKKKEKEEK RESULT KEKEKKKKKEKKKKKKKKKK

scanf ("$d d", &exam_scorel, &exam_ Total percent in examintaion: 41.75


score2) ; Total percent in activities : 27
printf ("\n Enter the score obtained in Total percent in sports g a2
sports events (out of 50): ");
scanf("%d", &sports score) ; Total percentage 5 thes
| 52 | Introduction to C Programming

oc was developed in the early 1970s by Dennis just like an if-else statement that can be within
Ritchie at Bell Laboratories. expressions. Conditional operator is also known as
e A function is defined as a group of C statements that ternary operator as it is neither a unary nor a binary
are executed together. The execution of a C program operator; it takes three operands. 7
begins at this function. e The bitwise NOT, or complement, produces the 1s
e Every word in a C program is either a keyword or an complement of the given binary value.
identifier. C has a set of reserved words often known e The comma operator evaluates the first expression
as keywords that cannot be used as an identifier. and discards its value, and then evaluates the
e The difference between signed and unsigned second and returns the value as the result of the
numeric variables is that signed variables can be expression.
either negative or positive but unsigned variables e sizeof is a unary operator used to calculate he size
can only be positive. By default, C takes a signed of data types. This operator can be applied to all
variable.
data types.
e The statement return 0; returns the value 0 to the
e While type conversion is done implicitly, typecasting
operating system to give anindication that there no
has to be done explicitly by the programmer. Type-
errors were encountered during the execution of
casting is done when the value of a higher data type
the program.
has to be converted to a lower datatype. _
e The conditional operator or the ternary (?:) is

ANSI C American National Standards Institute’s Library file The file which comprises of compiled
definition of the C programming ian paee It is the versions of commonly used functions that can be
same as the ISO definition. linked to an object file to make an executable program.
Constant A value that cannot be changed. Library function A function whose source code is
Data type Definition of the data. For example, int, char, stored in the external library file.
float. Linker The tool that connects object code and libraries
Escape sequence Control cones that comprises of to form a complete, executable program.
combinations of a backslash followed by letters or Operator precedence The order in which operators
digits which represent non-printing characters. are applied to operands during the evaluation Of an
Expression A sequence of operators and operands that expression.
may yield a single value as the result of its computation. Preprocessor A processor that manipulates the initial
Executable program Program which will run in the directives of the source file. The source file contains
environment of the operating system or within an instructions that specifies how the source file shall be
appropriate run time environment. processed and compiled.
Floating-point number Number that comprises of a Preprocessor directive Instructions in the source file
decimal place and exponent. that specifies how the ile shall be processed and
Format specification A string which controls the compiled.
manner in which input or output of values has to be Program A text file that contains the source code to be
done. compiled.
Identifier The names used to refer to stored data Runtime error A program that is encountered when a
values as in case of constants, variables, or functions. program is executed.
Integer A number that has no fractional part. Source code A text file that contains the source Code
Keyword A word which has a predefined meaning to to be compiled.
a C compiler and therefore must not be used for any Statement A simple:statement in C magia that is
other purpose. followed by a semicolon.
Introduction to C | 53 |

Syntax error An error or mistake in the source code Variable An identifier (and storage) for a data type.
that prevents the compiler from converting it into The value of a variable may change as the program
object code. runs.

Fill in the Blanks 24. The specification is used to read/write a


short integer.
. C was developed by ‘
_ 25. ine specification is — to oe a
is a group of C statements that are:
hexadecimal integer. _
executed together.
EXERCISES
. Execution of the C program begins at
26. To print the data left-justified,
tion is used.
Soecae
:
. In memory characters are stored as
. The statement return 0, returns 0 to the - Multiple Choice Questions
wnub finds the remainder of an_ integer
1. The operator which compares two values is
division.
(a) assignment (b) relational
operator reverses the value of the
(c) unary (d) equal
expression.
2. Which operator is used to simultaneously evaluate
. sizeofis a operator used to calculate the
two expressions with relational operators?
_ size of data types.
(a) AND (b) OR
. is Iso known as forced conversion.
‘The incti n scai f() returns (c) NOT (d) all of these:
3. Ternary operator pede on how many
:
operands?
:
© oe oe
(a) i
netion prints data on the monitor.
establishes the original value for a 4. Which operator aa the 1s complement of
variable. the given binary value? _
. Character constants are quoted using (a) logical AND (b) bitwise AND
. AC program ends with a (c) logical OR (c) bitwise OR
file contains mathematical functions. 5. Which operator has the lowest precedence?

causes the cursor to move to the next (a) sizeof (b) unary
line. (c) assignment (d) comma
. Floating point values denote Nelucs by . Short integer has which conversion character
default. associated with it

A iable can be made constantbby d ff) %e (b) %d


with the qualifier _ (c) %hd (d) %f
initialization. . Which of the following is not a character
. The sign of the result is positive in modulo division constant?
it. _ (a) gee (b) ky

. Associativity of operators defines on (d)


can be used to change the order of 8. Which of the following is not a floating point
_ evaluation expressions. constant?
_____ operator returns the number of bytes (a) 20 (b) -4.5
occupied by the operand.
(2) a (d) pi
54 | Introduction to C Programming

9. Identify the invalid variable names. 21. The variable amt is same as AMT in C.
7, (a) [Link] (b) A+B 22. void is a data type in C.
Lil
(c) Samt (d) Floats 23. The function scanf can be oe to read oe on
10. Which operator cannot be used with float value at a time.
me
Li operands? 24. All arithmetic operators have same precedence.
=<
Lid OR ur 25. The modulus operator can be used ony with ©
(c) % (cd) * integers.
11. Identify the erroneous expression. 26. The expression containing all integer operandsis
(a) x=y=2, 4; (b) res=t++a*5; called an integer expression.

(c) res=/4; (d) res =at+—b *2


Review Questions
State True or False 1. What are header files? Why are they important?
Can we write a C program witho t usi
1. We can have only onefunction in a C program.
header file?_ /
2. Header files are used to store program’s source .
2. What arevariables?
code.
3. Explain the difference between declaration -anc :
3. Keywords are case sensitive.
_ definition. _
4. Variable first is same as First.
4. How is memory reserved using a deciag _
5. An identifier can contain any valid printable ASCII —
statement?
character.
5. What does the data type of a variable signify?
6. Signed variables can increase the maximum
6. Give the structure of aC program.
positive range.
Z What do you understand by identifiers ane
7. Commented statements are not executed by the keywords? .
compiler.
8. Write a short note on basic data types that the
8. Samount is a valid identifier in C. _ C language supports.
9. Comments cannot be nested. 9. Why do we need signed and unsigned char?
10. The equality operators have higher precedence 10. Explain the terms variables and constants. How
than the relational operators. many type ofvariables are supported by Ce
11. Shifting once to the left multiplies the number by 11. Why do we include <stdio.h> in our programs?
2
12. Write a short note on operators available in C
12. printf("Sd", scanf("%d", & num)); is a valid C language. |
statement.
13. Give the operator precedence chart.
13. 1,234 is a valid integer constant.
14. Evaluate the expression: (x > y) + ++a || !c
14. Aprintf statement can generate only one line
15. Differentiate between pees e and type
of output.
conversion. _
15. [Link] used to store the source code of the
16. Write a program to read an ihiceer Then display —
program.
the value of that integer in decimal, octal, and -
16. The closing brace of main () is the logical end of hexadecimal notation.
the program.
17. Write short notes on printf and scan
17. The declaration section gives instructions to the
functions.
computer.
18. Explain the utility of #define and ineliae
18. Any valid printable ASCII character can be used
statements. _
for a variable name.
19. Write a program that prints floating point
19. Declaration of variables can be done anywhere in
value in exponential format with the following —
the program.
specifications: .
20. Underscore can be used anywhere in the variable
(a) correct to two decimal places;
name.
(b) correct to four decimal places; and complex a b;

(c) correct to eight decimal places. a,b : INTEGER

long int a;b;


20. Write a program to read 10 integers. Display
_ these numbers by printing three numbers in a line 31. Find error(s) in the following code.
int a = 9;
separated by commas.

EXERCISES
4. Write a program to print the count of even numbers
between 1 and 200. Also print their sum.
22. Write a program to count number of vowels in a 32. Find error(s) in the following scanf statement.
text. Z scanf("SdSf", &marks, &avg);
23. Write a program to read the address of a user.
Display the result by breaking it into multiple lines. Give the output of the following programs.
24. Write a program to read two floating point 1. #include <stdio.h>
numbers. Add these numbers and assign the result main()
to an integer. Finally display the value of all the {
three variables. OC x3 eo
int a, b;
20. Write a program to read a floating point number.
Display the rightmost digit of the integral part of a=-k*2+y/5- Z* y;
the number. b = t4x * (y - 3) / 2- ae * y;
26. Write a program to calculate simple interest and printi(\n a = 20a"; a4);
_ compound interest. Printh("\n 6 = 3d’, b);

7 Write a program to calculate salary of an employee,


return 0;

}
given his basic pay (to be entered by the user),
HRA = 10% of the basic pay, TA = 5% of basic pay. 2. #include 2stqio0.
he
Define HRA and TA as constants and use them to main()
calculate the salary of the employee.
{
28. Write a programto prepare a grocery bill. For that fmt Ab Ss;
enter the name of the items purchased, quantity — char c = ‘A’;
in which it is purchased, and its price per unit. G@ = 5 + Gc;
_ Then display the bill in the following format. printt("\n a = <a", a);
ORR KKEREKKRKERK BOT LL RE RRRKKHRKEKER return 0;

Item Quantity © Price Amount


}
3. #include <stdio.h>
Total Amount to be paid main()
{
os 29.
Write a C program using printf statement to ant a;
print BYE in the following format. printf ("\n a", 1/3 + 1/3);
BBB % Y EEE Printt("\n sf", 1.0/3.0 + 1.0/3.
Sb Ye 8 Gs 15/10.0 + 3/2;
BBB Y EEEE print£("\n $d", a);
BSB x E rerurn 0;
BBB : EEEE See

30. Find errors in the following declaration


statements: 4. #include <stdio.h>

Tne a: int main ()

floata b; {
ano 4a = 4);
double = a, b;
56 Introduction to C Programming
PLSLYI ESD
aS

2
yo <
<
S257 zei SY
a vi
Za
. o —

SAO
~

EXERCISES
NZ

aoe ZL)
SZ
OT) é
UCLX|, BR
Y
DU LES
eo: a WOCoas 7
Z < ) SZ < -
. ;
oo 2 iN
ne
OH

=-
xo
SS

C7 ‘ US TD og

Wwe 7

A << i : C ><
a oe Loe We
EN 2 g © NS
eS aN CU SS

ENG
Sz OO
UN < pe y . Fe eo,
Lee - 2 d
De 7
277 Le
7 sey CT . : Z : 7 i
; S : ‘ - poe
© a we 7 te Co
a7 . Z LK
AW Gd

Co
SS “ Z Ss ZT
GSES
a « & Z : SZ Z Ze GoUS URI
_
xe CES
LEY ye Uyex ES y Z
Se ‘
< Sy HESS ERSY ye aS
ES § SS SZ
ps < See SE g SZ I. SUT 2 Ay Sy eC ES — 7 CS
i
S77 Dp NEES S77 5 : . Ay CaN 7 oo g i no é
ee :
@ YES oy
: Yd27 ok
BRU RG é s < SS)
LUNES DOO
Ue
— oo em
LO COC
oT ZT
2

ISTRY
2
77
Z
:
SN OT
2G
Ue
é
>
<
5
ye
Ui ST. COU
ISIN
< -
:
. _ 7SDee :
Yoo
A
ESS
Ny ee
y <
A
EX
ROR
a
SSN
ee
UO
UW
_
Y Z
DAT | SAS
2 © : oO
. - a ; ee

7\
ON

5 y a
- a q «
g

iN
VU Cr
YY
ao LT)
WD
YR y : .
ENG:
SZ
ASE NS EN oO
DENN ‘ . vK ESE REEN
NI oN C
L
OZ 7 : 2 < Oo}
e . we S
27 S Le SENS: x - GE SE N

we C2
/ ‘ .
:
SS
— 8
LT IGG °c; ~—r—e—eC'" @ <2 CT :
0 aS OOK Le .
Sy << Co EN ces SEN > ENG: .
EN NON: NN oN . g WO
Sea
eN \
a

SUS
<<
<
3 © yp oO @ UO

BY 7 7 Z So
Oe Py
—-— oO _
Oe
NZS
. < » pO ZF 7\0 Ss
:
SO: Oo : d LE) ee Ze Z é as < ESTES NZ NG NANA NE ZN ENG
Og NW oT pO
oS

a <<

7 7

Wie
Go 2

<<
cS
_Introduction toC_| 57 |

ta | int mn = -2; printt("\n a *b = 2d", a%b ;


o printf£("\n n = %a", -n); - printf("\n a / b= sd", a/b),
~~ _ xeturn 0; peintf("\n a 3b = di, ab),
tr ; printf ("\n a && b = %d", a*&&b);
KI return 0;
fam 15. #include <stdio.h> L
| int main()
{ 21. #include <stdio.h>
int a= 2, b= 3, «, d; int main()
C = att; 7 {
a vib, : intia = 2.

printé("\n C= | % Qu
\" Qs | ole e Q ee a@=a + 3*a++;
return 0; Prince (nh aq sa) ae
, | return 0,

16. #include <stdio.h>


int main () 42. #include <stdio. be
t. _ ihe meind)
int _ = 30; -— _ {
Prince\n = sa", 2); int result;
return 0; 7 result =3+5-1*17% -13;
| - print£("%d", result
result =3*2+ (15 /
417.#include <stdio.h> printf ("Sa", result);
int main () result = 18/9/3%42*3*5% 104)
_ printf ("%d", result) ;
return 0;

= $d b = $d", 2b 23. #include <stdio. ts


int main()
{
int n= 2;
printf
("\n $d $d $d", ni+,
return 0; _

24. Hinclude <stdio. bo


ant main ()
ae |

int a = 2,65 = 3,c = 4;


a — ,

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


return 0;
tne a = 2) bb - 3; }
printf ("\n 6d", ++a - b);
return 0; 25. #include <stdio.h>
int main ()
{ .
int num = 070;
printf ("\n num = Sd", num);
printf ("\n num = 40", num);
printf(*\n num = x", mum);
58 Introduction to C Programming

WK és OS SE SY YO USIIS
EG SNES WZ ~ OO — Z — A

:
Ss Oe CU
LC SES
« & DROS
Zi ONINBS N Ce
&
SZ y LO, _
Ze
aN <oo
yo oo
Oe O27 7 «
Oe ee x S LSU. We < yD
SeSS

yy iw
Zo og
7 <j,
SY SG
<ENTRY
© ae
ONG 7 &
SZ < SE
< oo |e S777, 7
main()
main — : . —rti‘“_i™OCN”ONOCC—C————CTCUCUC
SR a S
7
2

< SS S
oe SY
©
co

EXERCISES
eo Oe Ok Ne ae Lee ‘ ILE Lr SS
2 NY NUNN pNG,: i z US ji Zi EEN i a
\ EO Z Se
PR
& ENE Ce I OS a~ CO = is SSS . 7]
Oo TRZ
ENING LEX < A GUN ES yO Z ‘
WT DO aS < A y
S CR
UR CZ Do < Z Wo
LY CU.
e420. Z y < y i EO) ————s—ais oO Zi
UT SSIES<— Die Cie 2 SES as Si. SE ES as QUT WMoO
Lo
6 Sa . 2 OO ZN ae S220" Ss
<Z
Se iN S77
LO! a ot ng”) COCO
a
Li
< DTC <

O~™w™~O—O—OCC_CSs=CCS
<7
TaN
. Lo ay oO =
TT
7 ~~
Oe
—r—C—~—
WO
<yO
DD
y
/ .—C—rti‘“COiCrw
Ro7 OG : LU
DO NZ a — LS. y
ram LOS
Shee
: & SZ :
TUT es PRR S yO> < .
A>

int é ("\r
Se SS e ‘ Z Ue

— rr—SS ~~ 7 7
FTE
y a Se
)
. OZ\
7 a Us
aS. Se NZ <
NGN oO
TINS HENLE NEES JUi Si De
oC aU oe 2... Ca Lo
2
Welc
Bre
N22
Zs
CaN
Le
|G
Gi
a
S US
0G
- Ss Wy Z SAD
> fC
UIT TD
Ge fe S277
Zi tip
Ve
.
ey zy Re
NaN
V0 aN S Z : Y LZ zy
S : UNG
oN < AS VR~\ UNG, : aN
oSap ae SSCS eG OG GY
YAU
ONES OG Bs Nw < : I SHY NG SS Sae
iL {("\n $-40. | Welcome IN <
pO Ce Sr Ye
voc Z CO. Cc Cc
Se EERE

. .=2=—emE / -
% 40. s CS We Dy
c x eS Ce CS a ee
SN 1 VS ES Seo 2) b \
OO > i here 2
yf} aorammni — OO : Do
—.
a Oo;
J
> :
aS SEE WEN
y Ye BN4iN
UY) YS s S
5 A
SO
ONG Ce Z s oO de ( ESL OG a= A K s ‘ SZ BX\

Ge>
0
-S TO
SS ENS
7 Ys
Se
Y NU, A
7 UNOS \“ Up
: 7 SEES A 7,~ VY
Cg S26 De
< 2
ae
- ZS : . Zi o
ZT Zi S i ee Se cy Sas
OE
SAN GS
Ss
SK ° GN A ; CARG oe
Ae LENNZS SO
SO BR
y : Do
wy
PG
Ze TJ Lo
aes
ey
<
< <7
A
NZ
SZ
S GOO
SS
< 2 y BS
Z oo
_. A oe
SZ,
\p <7
Y
PE
ee
DOO
SF
<
SEN DC
TENS

So Z
Za <
<< —
<2
\ ON
]
-.
7 vo
oe Zs
\ Ce Zs

AST
ERO
< NEN
i
UU
Zo< |
~ We
Co ~
LS
TS
Ze oN XS
O70
Ae SC \ <
\ \
SN
BO NUS
DOS NG
TT
NAT ONG
WSS
SS ENG CO
ENS NS SANA Ne
Al..1HOW TO WRITE, COMPILE, AND — Step 2: Type the code as shown below and save it in a file
___ EXECUTEAC PROGRAM IN UNIX, (e.g., firstprog.c)
#include<stdio.h>
_ LINUX, AND UBUNTU | main ()
{
Writing, Compiling, and Executing a C Program printf (“Welcome to the World of Programming
in Unix and Linux eG

}
To execute a C program first make sure that C compiler
gcc is installed on your machine. This is done by writing Step 3: Compile the program using gcc. GCC is a compiler
that is installed by default in Ubuntu. For compiling write
the $ whereis cc or $ which cc command in the command
the following command:
shell. If gcc is present then the complete path of the
compiler will be displayed on screen. In case the compiler gcc firstprog.c -o firstprogram
is present, follow the steps given below to write and In the above command, gcc is the compiler; firstprog.c
execute the program. is the name of the file to be compiled and the filename
Step 1: Open the Vim editor and type the program. For this following —o specifies the filename of the output. When
first type the following command in the command shell. you execute this command, the compiler will generate
Sevam farstprog.c
an executable file in case there are no syntax or semantic
errors in the program. If there are errors, the compiler will
Now when the editor gets opened type the program given notify you about the errors and you will then have to fix
below. them before re-compiling the code.
#include<stdio.h>
Step 4: Execute the program simply by typing the
main ()
command given below.
{
printf (“Welcome to the World of Programming ./firstprogram
ls) 3

}
A1.2 BIT LEVEL PROGRAMMING
Step 2: Compile the program using cc or gcc command.
The command will create the [Link] file. A C programmer usually does not need to care about
operations at the bit level. He has to think only in terms of
SCC EILTsSEprogac
int and double, or even higher level data types composed
Step 3: Execute the C Program. The program can be of a combination of these. However, at times it becomes
executed in two ways. First, by executing the [Link] to necessary to go to the level of an individual bit. For
see the output. Second, by renaming it to another file and example, in case of exclusive-OR (XOR) encryption or
executing it as shown below. when dealing with data compression, a programmer needs
to operate on individual bits of the data and thus needs to
Si e/a sOule
do programming at the bit level. Moreover, bit operations
or
can be used to speed up your program.
S mv [Link] firstprogram
S ./firstprogram
Thinking About Bits
This will print Welcome to the World of Program-
ming .... on the screen. The byte is the lowest level at which data can be accessed.
C does not support bit type. Therefore, we cannot perform
any operation on an individual bit. Even a bitwise operator
Writing, Compiling, and Executing a C Program
will be applied to, at a minimum, an entire byte at a time.
on Ubuntu We have already studied bitwise NOT, AND, OR, and
XOR operators in Chapter 1. To summarize:
Step 1: Open a text editor to write the C program. You can
choose Vim, or gedit, or any other editor available to you. e The bitwise NOT ("), or complement, is a unary
operator used to perform logical negation on each
| 60 | Introduction to C Programming

bit thereby resulting in 1s complement of the given not of interest. In this case, the 0 values mask the bits that
binary value. Digits that were 0s become Is, and are not of interest.
vice versa. For example: The bitwise AND can also be combined with the bitwise
D (AMO) =» @aloyal NOT to clear bits.

e A bitwise OR (|) takes two bit patterns of equal


length, and produces another one of the same length Al. 3 BITWISE SHIFT OPERATORS —
by performing the logical inclusive OR operation
In bitwise shift operations, the digits are moved, or ie
on each pair of corresponding bits. In each pair, the
to the left or right. The CPU registers have a fixed number
result is | if the first bit is 1 OR the second bit is 1
of available bits for storing numerals, so when perform
OR both bits are 1, and otherwise the result is 0.
shift operations; some bits will be ‘shifted out’ of the
100) OL01 s2201 register at one end, while the same number of bits are
‘shifted in’ from the other end.
e A bitwise exclusive or (*) takes two bit patterns of
In an arithmetic shift, the bits that are shifted out of
equal length and performs the logical XOR operation
either end are discarded. There are two types of arithmetic
on each pair of corresponding bits. In the result, a bit
shift: left arithmetic shift and a right arithmetic shift.
is set to 1 if the two bits are different, and 0 if they
In a left arithmetic shift, zeros are shifted in on the right.
are the same.
For example, consider the register with the following bit
The XOR operation is generally used by assembly pattern:
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 7 6 5 4 3 2 il 0
operation requires fewer CPU clock cycles when
compared with the sequence of operations that has AE eae Re a
to be performed to load a zero value and save it to wi 6 5 4 3 2 1 0
the register. The bitwise XOR is also used to toggle
Note that in arithmetic shift left, the leftmost digit was
flags in a set of bits. For example,
shifted past the end of the register, and a new 0 was shifted
1010
A
0011 = 1001 into the rightmost position. The general form of doing a
left shift can be given as
e Abitwise AND (&) takes two bit patterns of equal
length and performs the logical AND operation on each op << n

pair of corresponding bits. In each pair, the resultant Here, op is an integer expression that has to be shifted and
bit is set to 1 if the first bit is 1 AND the second bit n is the number of bit positions to be shifted. For example,
is 1. Otherwise, it is set to 0. For example: if we write

1010 & 0011 = 0010 unsigned int x = 11000101;


Then x << 2 = 00010100
The bitwise AND is commonly used to perform
bit masking. This is done to isolate part of a string If a right arithmetic shift is performed on an unsigned
integer then zeros are shifted on the left.
of bits, or to determine whether a particular bit is |
or 0. For example, to determine if the second bit is
1, you can straightaway do a bitwise AND to it and _, pee ERERERESESEES
another bit pattern containing | in the second bit. For oy, 6 5 4 3 2 dl, 0

oy a Ee a ee oe
example,
1010 & 0010 = 0010
7 6 5 4 3 2 HE 0
Since the result is 0010 (non-zero), it clearly indicates
that the second bit in the original pattern was 1. Such The general form of an arithmetic right shift can be
an operation is called bit masking because it masks given as:
the portions that should not be altered or which are op >>n
Introduction toc | 61 |

Here, op is an integer expression that has to be shifted Note that in arithmetic shift right operation, bits in op are
and n is the number of bit positions to be shifted. For shifted to right by n positions. In this process, the rightmost
example, if we write n bits will be lost and zeros will be shifted in the leftmost n
unsigned int x = 11000101; bits. (This is true for unsigned integers, for signed integers
Then x >> 2 = 00110001 the shift right operation is machine dependent).

Points to Remember

e@ op and n can be constants or variables. The left and right shiftoperators will result
Notey
e n cannot be negative. i in significantly faster an calculating |
e n should not exceed the number of bits used to and then multiplyi er of two.
represent op.
e Left shifting is the equivalent of multiplying by a Have you wondered what will happen if you shift a
power of 2. number like 128 and storing it ina single byte: 10000000?
e Right shift will be the equivalent of integer division Since, 128 * 2 = 256, and a register is incapable of storing
by 2. a number that is bigger than a single byte, so it should not
be surprising that the result is 00000000.
CHAPTER

Decision Control and Looping


Statements |

Takeaways
e Decision Control Statements — e Conditional Branching Statements e Iterative Statements
e Nested Loops e Break, Continue, and Goto Statements

3.1 INTRODUCTION TO DECISION e if statement

CONTROL STATEMENTS e if-else statement

e if-else-if statement
Till now we know that the code in the C program is executed
® switch statement
sequentially from the first line of the program to its last
line, i.e., the second statement is executed after the first,
the third statement is executed after the second, and so on. ~ Selection/branching ©
Although this is true, but in some cases we want only _ Statement —

selected statements to be executed. Such type of conditional


processing extends the usefulness of programs. It allows
the programmers to build programs that determine which ~ Conditional Unconditional
statements of the code should be executed and which pe
should be ignored.
C supports two types of decision control statements
that can alter the flow of a sequence of instructions. These if | if-else |
include conditional type branching and unconditional type
iai4'i¢-Jee8) Decision control statements —
branching. Figure 3.1 shows the categorization of decision
control statements in C language.

3.2.1 if Statement
3.2 CONDITIONAL BRANCHING The if statement is the simplest form of decision control
STATEMENTS statements that is frequently used in decision making. The
The conditional branching statements help to jump from general form of a simple if statement is shown in Fig. 3.2.
one part of the program to another depending on whether The if structure may include one statement or n
a particular condition is satisfied or not. These decision statements enclosed within curly brackets. First the test
control statements include: expression is evaluated. If the test expression is true, the
Decision Control and Looping Statements | 63 |

statement of if block (statement 1 to n) are executed 3.1. Write a program to determine whether a person is
otherwise these statements will be skipped and the eligible to vote.
execution will jump to statement x.
#include <stdio.h>
#include <conio.h>

|
main ()

{
SYNTAX OF IF STATEMENT Test FALSE int age;

if (test expression)
~ Expression printf("\n
scant ("sd";
Enter
&age") ;
the age: ");

{
if (age >= 18)
statement
1;

statement
n;
StatementBlock1 printf ("\n You are eligible to vote");
getch()
}
statement
x; return 0;

}
Output
Enter the age: 28
You are eligible to vote
The statement if construct is any valid C
in an
e statement block contains only one
language statement and the test
nent, putting curly brackets becomes
Poalioriiis Tip:a expression is any valid C -— optional. Iftherei is more than. 1 statement in
language expression that may
the statement block, putting saebrackets
include logical operators. Note becomes mandatory.
that there is no semicolon after
_ the test expression. This is
because the condition and 3.2. Write a program to determine the character entered by
statement should be put together the user.
#include <stdio.h>
as a single statement.
#include <ctype.h>
#include <stdio.h> #include <conio.h>
int main () main ()
{ {
int x=10; // Initialize the value of x char ch;
if ( x>0) // Test the value of x printf ("\n Press any key: ");
X++; // Increment xifitis>0 scant ("%c", &ch);
jouerbgiene (Him, Se =a “erolll, sie) if (isalpha
(ch) >0)
printf ("\n The user has entered a
// Print the value of x
character") ;
Tetunn OF
if (isdigit
(ch) >0)
} printf ("\n The user has entered a digit");
Output if (isprint
(ch) >0)
printf("\n The user has entered a printable
character") ;
In the above code, we take a variable x and initialize if (ispunct
(ch) >0)
it to 10. In the test expression we check if the value of x printf ("\n The user has entered a
is greater than 0. If the test expression evaluates to true punctuation mark");
then the value of x is incremented. Then the value of x is if (isspace
(ch) >0)

printed on the screen. The output of this program is printf("\n The user has entered a white
space character") ;
pS LAL
getch
() ;
Observe that the printf statement will be executed even rgerebharn, (0),
if the test expression is false. }
64 | Introduction to C Programming

Output printf ("\n Data read successfully") ;

Press any key: 3 else

The user has entered a digit DEINes ("\n) Enron sinedata srnput)s,

Now let us write a program to detect errors during data }


input. But before doing this we must remember that when
Output
the scanf() function completes its action, it returns the
Enter an int and a char value: 2A
number of items that are successfully read. We can use this
Data read successfully
returned value to test if any error has occurred during data
input. For example, consider the following function:
3.2.2 if-else Statement
Sean fiQusduss tac Cl erCcymEsOl msc)ns

If the user enters: We have studied that the if statement plays a vital
role in conditional branching. Its usage is very simple,
ge glee aaa
the test expression is evaluated, if the result is true, the
then the scanf() will return 3, since three values have statement(s) followed by the expression is executed else
been successfully read. But had the user entered, if the expression is false, the statement is skipped by
1 abe A the compiler.
But what if you want a separate set of statements to be
then the scanf() will immediately terminate when it
executed if the expression returns a zero value? In such
encounters abc as it was expecting a floating point value
cases. we use» an if-else
and print an error message. So after understanding this
rather than using
statement
concept, let us write a program code to detect an error in
simple if statement. The general
data input.
form of a simple if-else
#include <stdio.h> statement is shown in Fig. 3.3.
main () In the above syntax, we have written statement
{ block. A statement block may include one or more
int num; statements. According to the if-else construct, first
Chamwel- the test expression is evaluated. If the expression is true,
printf ("\n Enter an int and a char value: "); statement block 1 is executed and statement block 2
// Check the return value of scanf()
is skipped. Otherwise, if the expression is false, statement
block 2 is executed and statement block 1 is ignored.
if (scanf (“$d $c", &num, &ch) ==2)
Now in any case after the statement block 1 or 2 gets

SYNTAX OF IF—-ELSE STATEMENT


if (test expression)
{
statement block 1;
}
else
{ {

statement block 2;
}
Sitatbementsxc;

Figure 3.3
Decision Control and Looping Statements | 65 |

executed the control will pass to statement x. Therefore, #include <stdio.h>


statement x is executed in every case. ERE REIS! sloth
main ()
3.3 Write a program to calculate x = (md — bn)/(ad — cb). {
#include<[Link]> int num;
#include<[Link] elrscr();
main () printf ("\n Enter any number: ");
{ scanf ("%3d", &num) ;
aE El, Id, ty, Cl, i, sake
Piloatx<- nlae (ewes = (0)
clrser(); printf("\n $d is an even number", num);
printf (“\n Enter the ames form a,b, Gy.a,m else
andn: “); printf ("\n *d is an odd number", num);
Scant (“td td td! td sdezd4, asa, eSb,uk&c, iGSEwNGD,
&d, &M, &n); }
if(a*d - c*b != 0)
x = (float) (m*d - b*n) / (float)
(a*d - cb); Output
printf (“\n The value of expression = %.2f”, x); Enter any number: 11
} 11 is an odd number

Output 3.6 Write a program to enter any character. If the entered


Enter the values for a,b,c,d,mandn:524363 character is in lower case then convert it into upper
The value of expression = 1.71 case and if it is a lower case character then convert it
into upper case.
3.4 Wririte a program to find the number of people who epeneey Ate cine
voted.
#include <conio.h>
#include<stdio.h>
int main ()
#include<conio.h>
main ()
Ghaxrchy
{
ClinseniOk
is
int age, count=0;
char ch; printf("\n
"
Enter any character: . W
");.
scanf("%c", &ch);
Gillveskene (Os
for (1=0;1<20;1++)
f LECH e>— WAS ce Cha= 7)
scanf ("$d $c”, &age, &Ch) ; printf ("\n The entered character was in
if (age>=18 && ch=='n’) upper case. In lower case it is: %c",

count++; (ch+32) ) ;
} else
printf ("\n Total persons surveyed = 20”); printf ("\n The entered character was in
print£("\n No. of people who were lower case. In upper case it is: %c",
eligible to vote but did not vote = %d”, (ch-32));
count) ; BQewIag Os

} }
Output Output
eee sey eb omyars4 en 9788 ys O0nmm2, By, e45en Enter any character: a
Simm IS6iye ain 944 hon253 nV 698 y852) ny, 42 The entered character was in lower case. In
TAO NSEyanec) Te Onan Ts upper case it is: A
Total persons surveyed = 20
3.7 Write a program to enter a character and then
No. of people who were eligible to vote but
did not vote = 10 determine whether it is a vowel or not.
#include <stdio.h>
3.5 Write a program to find whether the given number is #includelleconio:h>
even or odd. main ()
| 66 | Introduction to C Programming

{ The compiler cannot detect such


char chi kinds of errors and thus the
ellsasehe(() ? programmer should carefully use
the operators. The program code
printf ("\n Enter any character: "); given below shows the outcome
scant ("%e", &ch);
of mishandling the assignment
and the comparison operators.
De(Ch Ste ?||\|chrs=seheliicheamae *iltciiseanct
} kiaLarteal |) Reheat Hilieliee"3 |chee1! #include <stdio.h>
|, ch=="O%. || ch==!U".) main ()
{ t

joreaianeie (Mn, eel SiG) el WOM elal) 5


TN ES Se a ye hy
else
nae (56 ye)
printf("\n %c is not a vowel") ; printf ("\n EQUAL") ;
getch(); else
printf ("\n NOT EQUAL") ;
rewunm Oy

} }
Output
Output
Enter any character: v
EQUAL
v is not a vowel #include <stdio.h>
main ()
3.8 Write a program to find whether a given year is a leap
year or not. {
GNIS Sees 2D Sy es. She
#include <stdio.h>
#include <conio.h> SE (62 =e 4)

int main() printé ("\n EQUAL") ;


else
{
int year; printf ("\n NOT EQUAL");

elleserm())- }
printf("\n Enter any year: ");
Output
scanf ("$d", &year) ;
if ((year%4 == 0) && ((year%100 !=0) || NOT EQUAL
(year%400 == 0)))
printf ("\n Leap Year") ;
3.2.3 if-else-if Statement
else
printf ("\n Not A Leap Year") ; C language supports if-else-if statements to test
return 0; additional conditions apart from the initial test expression.
} The if-else-if construct works in the same way as a
normal if statement. if-else-if construct is also known
Output
as nested if construct. Its construct is given in Fig. 3.4.
Enter any year: 1996
It is not necessary that every if statement should have
Leap Year
» an else block as C supports
Pitfall A very common pitfall is to use assignment operator simple if statements. After the
(=) instead of comparison operator (==). For example, first test expression or the first if
consider the statement branch, the programmer can have
ale (@) = 110) as many else-if branches as he
joncabaleis (Urol Vein wants depending on _ the
Here, the statement does not test whether a is equal to expressions that have to be tested.
10 or not. Rather the value 10 is assigned to a and then the For example, the following code
value is returned to the if construct for testing. Since the tests whether a number entered by the user is negative,
value of a is non-zero, the if construct returns a1. positive, or equal to zero.
Decision Control and Looping Statements | 67 |

FALSE
SYNTAX OF IF-ELSE-IF STATEMENT
if ( test expression 1)
{ TRUE
statement block 1;
}
elseif ( test expression
2)
_ FALSE
{
statement block 2; TRUE
}

else ‘ _ StatementBlock2 tementBlockX


{
statement Block Xx;
}
Statement
Y;
Statement
é

Sate i f-clse-if statement construct

3.9 Write a program to demonstrate the use of nested if else if (num>0)


structure. printf("\n The number is positive") ;
#include <stdio.h> else
main () printf("\n The number is negative") ;
{ recurn 10}
sRAV Oe Lh }
printf ("\n Enter two numbers: ");
scanf ("$d %d", &x, &y); Output
Ve (Ge == iY, Enter any number: 0
printf("\n The two numbers are equal"); The number is equal to zero
elsesii (xs) y)
3.11 Acompany decides to give bonus to all its employees
prantr(\n 2d ase Greater, Ehan 7d"eex, oy);
else on Diwali. A 5% bonus on salary is given to the
primtt("\n 4d is less than 7d", x, y); male workers and 10% bonus on salary to the female
return 0; workers. Write a program to enter the salary and sex
} of the employee. If the salary of the employee is less
than Rs 10,000 then the employee gets an extra 2%
Output
bonus on salary. Calculate the bonus that has to be
Enter two numbers: 12 23
given to the employee and display the salary that the
12 is less than 23
employee will get.
3.10 Write a program to test whether a number entered is #include <stdio.h>
positive, negative or equal to zero. #include <conio.h>

#include <stdio.h> main()

main () {
char ch;

int num; float sal, bonus, amt_to


be paid;

printf ("\n Enter any printf("\n Enter the sex of the employee (m
number: "); ee Mig SAD))ic

scanf("%d", &num) ; scant ("so ech) >

e(num==0)) printf ("\n Enter the salary of the employee: ");


printf ("\n The value is scanf("%f", &sal);
equal to zero"); sheielal =, Min’))
| 68 |_Introduction to C Programming

bonus = 0.05 * sal; else

else joxeauaete (al iNet) &


raaebuaay. (0)6
DOnUSH— OL WOMAm sally
if (sal < 10000)
}
bonus += 0.20 * sal; Output
amt_to_
be paid = sal + bonus; Enter the marks obtained: 55
jorenamyene
(UIN\el Syeulebeyy = Sue" Grell)s SECOND DIVISION

printe
(" \neBonus =) Sa mbonus)sy:
BILE
(1) 1 I IO IOI aeden) Eye, TheAND operand. (&&) is used to form
e
AZ
°\
compound relation1 expressian. In, the
printf ("\n Amount. to be paid: Sf", amt_to_
following expressi io |.
be paid) ;
af (60 < marks « 75) |
getch() ; _ The correct way to writeis as‘
return 0; if ((marks = 60) && (
}
3.13 Write a program to calculate tax, given the following
Output
conditions: .
Enter the sex of the employee (m or f): f
e if income is less than 150,000 then no tax
Enter the salary of the employee: 12000
e if taxable income is in the range 150,001—300,000
Salary = 12000
then charge 10% tax
Bonus = 1200
KKKEKKKKKKKKKKKKKEKKEKKEKKKEKKEK
e if taxable income is in the range 300,001—500,000
then charge 20% tax
Amount to be paid: 13200
e if taxable income is above 500,001 then charge
In the program to test whether a number is positive or 30% tax
negative, if the first test expression evaluates a true value #include <stdio.h>
then rest of the statements in the code will be ignored #include <conio.h>
and after executing the printf statement which displays #define MIN1 150001
"The value is equal to zero", the control will jump #define MAX1 300000
to return 0 statement. Consider the following example #define RATE1 0.10
which shows usage of the if-else-if statement. #define MIN2 300001
#define MAX2 500000
3.12 Write a program to display the examination result.
#define RATE2 0.20
#include <stdio.h>
#define MIN3 500001
main ()
#define RATE3 0.30
{
int marks;
printf("\n Enter the marks obtained: "); main ()
scanf ("%$d", &marks) ; {
i (Marks =) 7/5) double income, taxable income;
pEine
& (UVa DLS TENG iL ONED) i elrseri()s
Pee else if ( marks >= 60 && printf("\n Enter the income: ");
‘Programming Tip: marks <75) scanf ("Slf£", &income) ;
| pxrintf("\n FIRST
DIVISION") ;
taxable income = income - 150000;
else if ( marks >= 50 &&
if (taxable income <= 0)
marks < 60)
PLEInes
(i \neNO) TAX)
toute,are @liminated” printf ("\n SECOND
else if (taxable income >= MIN1 && taxable
and th sfficiency __ DIVISION");
income < MAX1) =
: of the program is || else if ( marks >= 40 &&
| marks < 50) tax = (taxable income - MIN1) * RATE1;
printf ("\n THIRD else if (taxable _income >= MIN2 && taxable_
DIVISION") ; income < MAX2)
Decision Control and Looping Statements | 69 |

tax = (taxable_income - MIN2) * RATE2; 3.15 Write a program to input three numbers and then
else find largest of them using && operator.
tax = (taxable income - MIN3) * RATE3; #include <stdio.h>
jonetiatess (On, SH = CEU ear) 0 #include <conio.h>
getch(); main ()
return 0; {
int numl, num2, num3;
} Gilsagiexete
()
Output printf("\n Enter the first number: ");
no " .

Enter the income: 900000 LET SCE OEE


iN printf ("\n Enter the second number: ");
TAX = 74999.70
scanf("%d", &mum2) ;
3.14 Write a program to find the greatest among three printf ("\n. Enver thes thirdynumberx: 4-0)
numbers. scanf ("$d", &num3) ;
#include <stdio.h>
Eanelude <conio hs ’ if (numlsnum2 && numl>num3)
int main() printf("\n @d is the largest number", num1);
f if(num2snum1l && mnum2snum3)
fe umd / nun) umd , i620; printf ("\n %*d is the largest number", num2) ;
a LR tf = Uy EE

Guliaereia(() 5 :
peared (Giuwenverkthe.£ iratnumber -o1): printf ("\n %*d is the largest number", num3);
Cisicela) ¢
scanf("%d", &num1);
. return 0;
printf ("\n Enter the second number: ") ; }
scanf ("%d", &num2) ;
printf ("\n Enter the third number: "); Output
scanf("sd", &num3); Enter the first number: 12
if (num1>num2) Enter the second number: 23
{ Enter the third number: 9
ae Care) 23 is the largest number

printf ("\n sd is greater than *d and %d", 3.16 Write a program to enter the marks of a student in
uml, num2, num3) ; four subjects. Then calculate the total, aggregate,
else
and display the grades obtained by the student.
printf ("\n %d is greater than %d and %d",
#include <stdio.h>
num3, numl, num2) ;
#include <conio.h>
main ()
}
else if (num2>snum3)
{
int marks1, marks2, marks3, marks4, total =0;
printf ("\n %d is greater than *d and 7d",
num2, numl, num3); ter lontNisp 05)
else elxrser();

printf("\n ¢d is greater
than 3d and $d", num3, printf ("\n Enter the marks inMathematics:
") ;
numl, num2) ; scanf("%d", &marks1);
return 0; printf ("\n Enter the marks in Science: ");
} scant ("%Sd", &marks2) ;

Output printf ("\n Enter the marks in Social


Science: ");
Enter he
the first
first number: 12
nu scanf ("$d", &marks3);
Enter the second number: 23
; printf ("\n Enter the marks in Computer
Enter the third number: 9
Science: ");
23 is greater than 12 and 9
| 70 | Introduction to C Programming

scanf("%d", &marks4) ; else if (D == 0)


total = marksl + marks2 + marks3 + marks4; {
avg = total/4; printf ("\n EQUAL ROOTS") ;

prinkkh ("\n Total = sd, "totale rootl = -b/deno;

printf£("\n Aggregate = %.2f£", avg); print£("\n ROOTI = %£ \t ROOT s24egsc",


raeleVetl,. Ieloe”))F

ie(Genie; Se “7/5))) }
else
printf ("\n DISTINCTION") ;
jopeaiatesre (Oia IMAGINARY ROOTS") ;
else if (avg>=60 && avg<75)
getch();
printf ("\n FIRST DIVISION"); ‘

}
else if (avg>=50 && avg<60)
printf ("\n SECOND DIVISION") ; Output :
else if (avg>=40 && avg<50) Enter the values of a, b, andc:3 4 5
printf ("\n THIRD DIVISION") ; IMAGINARY ROOTS
else
Let us now summarize the rules for using if, if-else,
jorcnighee (May IDA es
and if-else-if statements. :
return 0;

} Rule 1: The expression must be enclosed in parentheses.


Rule 2: No semicolon is placed after the if/if-else/
Output
if-else-if statement. Semicolon is placed only at the
Enter the marks in Mathematics: 90
end of statements in the statement block.
Enter the marks n Science: 91
Enter the marks in Social Science: 92 Rule 3: A statement block begins and ends with a curly
Enter the marks in Computer Science: 93 brace. No semicolon is placed after the opening/closing
TOTAL = 366 braces.
AGGREGATE = 91.00
DISTINCTION Dangling Else Problem
3.17 Write a program to calculate the roots of a quadratic With nesting of if-else statements, we often encounter
equation. » a problem known as dangling
#include <stdio.h> else problem. This problem
#include <math.h> is created when there is no
#include <conio.h> matching else for every if
void main () statement. In such cases, C
: tou:
use positive.
always pair an else statement
{ statements Raa sa : ae
LIGNE. Gly Jol, els rather than using- i. es nn pease af
float D, deno, rootl, root2; “compound negative |° atement in the current block.
elrsexr();
| Consider the following code
which shows such a scenario:
printf ("\nEnter the values ofa, b, andc:");
scant ("Sd td td", &a, &b, &c);
Te (atesy b)
Dea (Ome mo)ee=s (4a ea aC)
ihe (sy Seed)
printf("\n a is greater than b and c");
else
printf ("\naisnot greater thanbandca");
petite @\n REAL ROOTS");
rootl = (-b + sqrt(D)) / deno;
The problem is that both the outer if statement and
the inner if statement might conceivably own the else
root2 = (-b - sgqrt(D)) / deno;
clause. The C solution to pair the if-construct with the
printf ("\n ROOT1 = %f \t ROOT 2 = %£",
nearest if may not always be correct. So the programmer
LOOEL, LOOP?) ;
must always see that every if statement is paired with an
appropriate else statement.
Decision Control and Looping Statements | 71 |

Comparing Floating Point Numbers if (fabs(res2 - resl) < EPSILON)

printf ("EQUAL") ;
Never test floating point numbers for exact equality. This
else
is because floating point numbers are just approximations,
printf ("NOT EQUAL");
so it is always better to test floating point numbers for
return 0;
‘approximately equal’ rather than testing for exactly equal.
We can test for approximate equality by subtracting }
the two floating point numbers (that are to be tested) and Also note that adding a very small floating point value
comparing their absolute value of the difference against a to a very large floating point value or subtracting floating
very small number, epsilon. For example, consider the code point numbers of widely differing magnitudes may not
given below which compares two floating point numbers. have any effect. This is because adding/subtracting two
Note that epsilon is chosen by the programmer to be small floating point numbers that differ in magnitude by more
enough so that the two numbers can be considered equal. than the precision of the data type used will not affect the
#include <stdio.h>
larger number.
#include <math.h>
#define EPSILON 1.0e-5 3.2.4 Switch Case
main () A switchcase statement is a multi-way decision statement
{ that is a simplified version of an
double numl = 10.0, num2 = 9.5; _ if-else block that evaluates
double resl, res2; only one variable. The general
resl = num2 / numl * num; form of a switch statement is
res2 = num2; use default labelin | shown in Fig. 3.5.
a switch statement. - Table 3.1 compares general
/* fabs() is a C library function that form of a switch statement with
returns the floating point absolute value */ that of an if-else statement.

!
TRUE , ™

Syntax of Switch Statement

ce
switch ( variable)
{ TRUE
case valuel:
Statement Block 1;break;
break;
FALSE
case value2: Statement Block 2
Statement Block 2;break;
break;
|FALSE
case valueN:

Tt ge ey
Statement Block N; break;
break;
default:
Statement Block D;
break; break; StatementBlockN FALSE
}
Statement
X; Statement Block D

fafatig-eyey The switch statement construct


| 72 | Introduction to C Programming

AE) (cei) Comparison between the s example, if the value of switch


else construct 2 statement matched with that of
case 2, then all the statements in
Generalized switch _ | Generalizedif-else _— case 2 as well as rest of the cases
Woe
statement : _ / statement :
including default will be
switch(x) { if(exp1) { _ ofinstructions. — executed. The break statement
_ Aswitch-case ~ — tells the compiler to jump out of
caseals // do, this Hifi ele) telaale)
Casén2:4i//) do, this } else if(exp2) { statement is a the switch case statement and
Case.3: 6// do thi /praeo ehus execute the statement following
} else if(exp3) { the switch case construct. Thus,
default: Wij COw clase) the keyword break is used to
/iaoerhis } | break out of the case statements. It
} | indicates the end of a case and
one variable. prevents the program from falling
Here, statement blocks refer to statement lists that may through and executing the code
contain zero or more statements. These statements in the in all the rest of the case statements.
block are not enclosed within opening and closing braces. Consider the following example of switch statement:
The power of nested if-else statements lies in the fact Chari gradce—sa Gur,
that it can evaluate more than one expression in a single logical switch (grade)
structure. Switch statements are mostly used in two situations: {
e When there is only one variable to evaluate in the Cas em Ome:

expression. printf ("\n Outstanding") ;


break;
e When many conditions are being tested for.
When there are many conditions to test, using the if case “A”:
and else-if construct becomes a bit complicated and printf ("\n Excellent") ;
confusing. Therefore, switch case statements are often break;
used as an alternative to long if statements that compare Cases BS:
a variable to several integral values (integral values are printf ("\n Good") ;
those values that can be expressed as an integer, such as break;
the value of a char). Switch statements are also used to
CasemGa:
handle the input given by the user.
joueauiatete (W\iak Ise\slseW))5
We have already seen the syntax of the switch
break ;
statement. The switch case statement compares the value
case RE:
of the variable given in the switch statement with the
printf ("\n Fail");
value of each case statement that follows. When the value
break;
of the switch and the case statement matches, the statement
default:
block of that particular case is executed.
printf ("\n Invalid Grade");
Did you notice the keyword default in the syntax of
break;
the switch case statement? Default is also a case that is
executed when the value of the variable does not match }
with any of the values of the case statement, 1.e., the default Output
case is executed when there is no match found between
Fair
the values of switch and case statements and thus there are
no statements to be executed. Although the default case 3.18 Write a program to demonstrate the use of switch
is optional, it is always recommended to include it as it statement without a break.
handles any unexpected cases.
#include <stdio.h>
In the syntax of the switch case statement, we have used
another keyword break. The break statement must be main ()

used at the end of each case because if it were not used, {


then all the cases from the one met will be executed. For abate: (ysj\euoim =! ay
Decision Control and Looping Statements | 73 |

switch (option) e The default label can be placed anywhere in the


{ switch statement. But the most appropriate
case 1: printf("\n In case 1"); position of default case is at the end of the switch
case 2: printf("\n In case 2"); case Statement.
default: printf("\n In case default") ; e There can be only one default label in a switch
} statement.
return 0; e C permits nested switch statements, i.e., a switch
} statement within another switch statement.

3.19 Write a program to determine whether an entered


Output
character is a vowel or not.
In case 1
#include <stdio.h>
In case 2
int main()
In case default
{
Had the value of option been 2, then the output would char ch;
have been
printf("\n Enter any character: ");
In case 2 Scant (Ute ech))i;
In case default switch (ch)
And if option was equal to 3 or any other value then {
only the default case would have been executed, thereby CaS Cu Awe:
printing Casemecuas:

In case default printf ("\n%cis


VOWEL", ch) ;
break;
To summarize the switch case construct, let us go
case ‘E’:;
through the following rules:
case ‘e’:
e The control expression that follows the keyword print£ ("\n%¢is
VOWEL", ch) ;
switch must be of integral type (i.e., either be an break;
integer or any value that can be converted to an
case ‘I’:
integer.
case ‘i’;
e Each case label should be
joremiajere (Wis, 2p i Se WYONMSILY, Cis) 9
followed with a constant or a
break;
constant expression.
Case Oe:
e Every case label must evaluate
Caseeo-e:
to a unique constant expres-
joresawese
(UINGal <5 Gi als) WYO, Clay)5
sion value.
break;
e Case labels must end with a
Case eu:
colon.
casey su:
e Two case labels may have the
jonoasayene
(YO \iay 2s ey als WWO\NNaIEM, Gln)§
same set of actions associated
break;
with it.
default: printf("%c is not a vowel", ch);
e The default label is optional
and is executed only when }
return 0;
the value of the expression
does not match with any }
labelled constant expression. Output
It is recommended to have a
Enter any character: E
default case in every switch
E is a VOWEL
case statement.
| 74 [ Introduction to C Programming

3.20 Write a program to enter a number from 1-7 and case 9:


display the corresponding day of the week using printf ("\n ODD") ;
; break;
switch case statement. eS
; A case 2:
#include <stdio.h>
’ ; Caserais
#include <conio.h>
case 6:
int main()
case 8:
case 10:
aay, print£("\n EVEN");
elirseri()i
default
printf("\n Enter any number from 1 to 7: "); printf ("\n INVALID INPUT");;
scanf ("%d", &day) ; break;
}
switch (day) }
{
case 1: printf("\n SUNDAY") ; OR
break; #include <stdio.h>
case 2: printf("\n MONDAY") ; main () e
break; {
case 3: printf("\n TUESDAY") ; int num, rem;
break; Deince (UN Bnterwany aiumoersn (Clit Ou tO) ema)
E,

case 4: printf£("\n WEDNESDAY"); scanf ("$", &num) ;


break; rem = num%2;

case 5: printf ("\n THURSDAY") ; switch (rem)


break; {
case 6: printf("\n FRIDAY"); ete
eae printf ("\n EVEN") ;
break;
case 7: printf£("\n SATURDAY"); cag
Casemis:
break; j
jonentioneye (Gay CBI")
default: printf ("\n Wrong Number");
break;

sae\eibhany (Oe }

}
Output
Output Enter any number from 1 to 10: 7
Enter any number from 1 to 7: 5 ODD

THURSDAY Note that there is no break statement after case A, so if


3.21 Write a program that accepts a number from 1 to _ the character ‘A’ is entered, then the control will execute
10. Print whether the number is even or odd using a the statements given in case ‘a’.
Eich ease Coneiuct For example, consider a simple calculator program
SeTiGe stators that can be used to add, multiply, subtract, and divide two
main () integers.
{
int num; Advantages of using a Switch Case Statement
intf("\n Ent mb TP EO WTO) ele
igen A ieuae SG Seg Pea Switch case statement is preferred by programmers due
scanf("%S", &num) ;
: to the following reasons:
switch (num)
{ e Easy to debug.
ee e Easy to read and understand.
ee e Ease of maintenance as compared with its equivalent
case 7: if-else statements.
Decision Control and Looping Statements | 75 |

e Like if-else statements, switch statements can this condition which determines when the loop will end.
also be nested. The while loop will execute as long as the condition is
e Executes faster than its equivalent if-else true. Note if the condition is
Programming Tip:
construct. never updated and the condition
Check that the
relational operat o «Cnever becomes false then the
is not mistyped _ computer will run into an infinite
3.3. ITERATIVE STATEMENTS asanassignment _—‘!oop which is never desirable.
Iterative statements are used to repeat the execution of a operator. A while loop is also referred
list of statements, depending on the value of an integer to as a top-checking loop since
expression. C language supports three types of iterative control condition is placed as the
statements also known as looping statements. They are: first line of the code. If the control condition evaluates to
false, then the statements enclosed in the loop are never
e@ While loop
executed.
® Do-while loop For example, look at the following code which prints
e For loop first 10 numbers using a while loop.
In this section, we will discuss all these statements. #include <stdio.h>
int main ()

3.3.1 while loop {


Tyate est = Ole // initialize loop variable
The While loop provides a mechanism to repeat one or while (i<=10) // test the condition
more statements while a particular condition is true. { // execute the loop
Figure 3.6 shows the syntax and general form of statements
representation of a While loop. jonaalioheas
(WY RPM, aL)p
In the while loop, the condition ah ih ee alee // condition updated
ramming Tip: is tested before any of the }
ive statements statements in the statement block getch();

2wey ed to repeat is executed. If the condition is meee unga (OF

_eoecunon ofa true, only then the statements }


a - statements, —_ will be executed otherwise if the Output
_dependingonthe | at
: condition is false, the control
valueofaninteger . pe ORR 25 SAA SSiGr Smee eLO
— _ will jump to statement y, which is
_ expression.
: . the immediate statement outside Initially i = 0 and is less than 10, i.e., the condition is
the while loop block. true, so in the while loop the value of i is printed and the
From the flowchart diagram, it is clear that we need to condition is updated so that with every execution of the
constantly update the condition of the while loop. It is

Syntax of While Loop


statement x;
while (condition)
{
statement block;
}
statement y;

Statement y

Sete The while loop construct _


| 76 |_Introduction to C Programming

loop, the condition becomes more approachable. Let us


look at some more programming examples that illustrate
joneatiaiess ("Nay SIUM Se eyel, Siuim)
the use of while loop.
return 0;
3.22 Write a program to calculate the sum of first 10 }
numbers.
Output
#include <stdio.h>
int main() Enter the value of m: 7
Enter the value of n: 11
{
Imted: = 0, sum = O- SUM = 45

while (i<=10)
3.25 Write a program to display the largest of 6 numbers
{ using ternary operator.
sum = sum + i;
#include <stdio.h>
aetestedle eg is // condition updated
#include <conio.h>
} int main()
printf ("\n SUM = 3d", Sum);
return 0;
{
Sins 0) dleugee ail, sails :
} ellirser
() >
Output
while (i<=5)
SUMe=—55
{
3.23 Write a program to print 20 horizontal asterisks(*). printf ("\n Enter the number: ");
#include <stdio.h> scanf ("%d", &num) ;
main() large = num>large?num: large;
{ 1++;
int i=1; }
while (i<=20) printf ("\n The largest of five numbers
{ entered is: %d", large);
DEIMe flux) i return 0;
1++; }
}
return 0;
Output
} Enter the number : 29
Enter the number : 15
Output Enter the number : 17
KRKKKKKKKKKKKKKKKKKKK Enter the number : 19
Enter the number : 25
3.24 Write a program to calculate the sum of numbers
The largest of five numbers entered is: 29
from m to n.
#include <stdio.h> 3.26 Write a program to read the numbers until —1 is
int main () encountered. Also count the negative, positive, and
{ zeros entered by the user.
Tole 1M, To, Sei SOx #include <stdio.h>
Gilgen). #include <conio.h>
printf ("\n Enter the value of m: "); int main()
scanf("d", &m);
{
int num;
printf("\n Enter the value of n: "); int negatives=0, positives=0, zeros=0;
scant ("Sd", &n); elagicyere\(()) 5

while (m<=n) printf ("\n Enter -1 to exit....");


printf("\n\n Enter any number: ");
scanf ("%d", &num) ;
Decision Control and Looping Statements | 77 |

}
while(num != -1)
avg = (float) sum/count;
{ printf ("\n SUM=%d",
sum) ;
if (num>0)
printf ("\nAVERGAE
= %f", avg) ;
positives++;
1aaVepnam Os
else if (num<0)
negatives++; }
else
Output
ZeLOS++;
printf ("\n\n Enter any number: "); Enter any number. Enter -1 to STOP: 23

scanf ("%d", &num) ; Enter any number. Enter -1 to STOP: 13

} Enter any number. Enter -1 to STOP: 3


printf£("\n Count of positive numbers entered Enter any number. Enter -1 to STOP: 53
= $d", positives);
Enter any number. Enter -1 to STOP: 4
printf ("\n Count of negative numbers entered
Enter any number. Enter’ -1 to STOP: 63
= $d", negatives);
Enter any number. Enter -1 to STOP: -23
joverirayers (@\al Cloybuays oe zeros entered = %d",
Zeros); Enter any number. Enter -1 to STOP: -6

getch(); Enter any number. Enter -1 to STOP: -1


return 0; SUM
= 130

} AVERAGE = 16.25

Output Thus, we see that while loop is very useful for


Enter any number: -12 designing interactive programs in which the number of
Enter any number: 108 times the statements in the loop has to be executed is not
Enter any number: -24 known in advance. The program will execute until the user
Enter any number: 99
wants to stop by entering -1.
Ehnter any number: -23 Now look at the code given below which makes the
Enter any number: 101
computer hang up in an infinite loop. The code given
Enter any number: -1
below is supposed to calculate the average of first 10
Count of positive numbers entered i WwW
numbers, but since the condition never becomes false, the

Count of negative numbers entered i] WwW


output will not be generated and the intended task will not
Count of zeros entered = 0
be performed.
#include <stdio.h>
3.27 Write a program to calculate the average of numbers
int main ()
entered by the user.
#include <stdio.h>
int 21 = 0) sum =0;%
int main()
float avg = 0.0;
{
Tne enuneSsune=—O,ecount = 0;
while (i<=10)
float avg;
{
printf ("\n Enter any number.
sum = sum + i;
Enter —leto: STOR: );
}
scanf ("%$d", &num) ;
avg = sum/10;
while(num != -1) printf ("\n The sum of first 10 numbers =
{ $a", sum);
count++; printf ("\n The average of first 10 numbers =
a logical error as it. | sum = sum + num; el 5 Ehie))F
changes the output | printf ("\n Enter any number. igebran (0)f
of the program. : Enter -1to STOP: ") ; }
scant ("%d", &num);
| 78 | Introduction to C Programming

3.3.2 do-while Loop The major disadvantage of using a do-while loop


is that it always executes at least once, even if the user
The do-while loop is similar to the while loop. The only enters some invalid data, the loop will execute. One
difference is that in a do-while loop, the test condition is complete execution of the loop takes place before the first
tested at the end of the loop. Now that the test condition comparison is actually done. However, do-while loops
is tested at the end, this clearly means that the body of the are widely used to print a list of options for a menu-driven
loop gets executed at least one time (even if the condition program. For example, look at the following code.
is false). Figure 3.7 shows the syntax and general form of
#include <stdio.h>
representation of a do-while loop.
int main()
Note that the test condition is enclosed in parentheses { t
and followed by a semicolon. The statements in the cua “ah a= (Ole
statement block are enclosed within curly brackets. The do
curly bracket is optional if there is only one statement in {
the body of the do-while loop. printi(tin tat oie
Like the while loop, the do-while loop continues i) =als eel
} while (i<=10) ;
to execute whiist a condition is true. There is no choice
return 0;
whether to execute the loop or not because the loop will be
}
executed at least once irrespective of whether the condition
is true or false. Hence, entry in the loop is automatic. What do you think will be the output? The code will
There is only one choice: to continue or to exit. The do- print numbers from 0-11 and not till 10.
while loop will continue to execute while the condition is 3.28 Write a program to calculate the average of first n
true and when the condition becomes false, the control will numbers.
jump to statement following the do-while loop. #include <stdio.h>
Similar to the while loop, the do-while is an indefinite int main()

loop as the loop can execute until the user wants to stop. 5
| int n, i = 0, sum =0;
The number of times the loop has to be executed can thus
| float avg = 0.0;
be determined at the run time. However, unlike the while | printf("\n Enter the value
loop, the do-while loop is a bottom-checking loop, since | Of ne |r

the control expression is placed after the body of the loop. scant ("%d", &n);

Syntax of do-while Loop


statement
x;
do
{
statement block;
}while (condition) ;

statement
y;

Condition

aPC WAR do-while construct


Decision Control and Looping Statements | 79 |

3.30 Write a program to list all the leap years from 1900
to 2100.
sum = sum + i;
#include <stdio.h>
all ca a ale
#include <conio.h>
} while (i<=n) ;
int main()
{
avg = sum/n;
int m=1900, n=2100;
printf ("\n The sum of first n numbers = $d",
Gulsasyere (2
sum);
print£("\n The average of first %d numbers =
Ge, ial ENS)
return 0;
_ 1if(i%4 == 0)
} printf("\n %d is a leap

Output | year",m);
' else
Enter the value of n: 18
jouaaligiese (Way BxCl aS) aaveies €)
The sum of first n numbers = 171 once, then.
: oo _ lea ear", m);
The average of first %d numbers = 9.00 »do-while PY
m = m+l1;

3.29 Write a program using do-while loop to display the }while (m<=n) ;
return 0;
square and cube of first n natural numbers.
#include <stdio.h>
#include <conio.h> 3.31 Write a program to read a character until a * is
#include <math.h>
encountered. Also count the number of upper case,
int main()
lower case, and numbers entered by the users.
#include <stdio.h>
SLGNG ali, 3@hy
#include <conio.h>
(eulhatsyere(())f
int main()

printf ("\n Enter the value of n: ");


{
Ghaieehy
Scaniizaiye <m)y
int lowers = 0, uppers = 0, numbers = 0;
a a a relies
llaasxese (())ag
i=1;
do
printf ("\n Enter any character: ");
scanf("%c,
ne
&ch);
_ProgrammingTip: = printf("\n | \t %d \t | \t
eal wer hh Mea eidi \euilttet de
do
pow(i,2), pow(i,3));
i++;
{
Ick (Chi gs=7Ae RCS hia= 474)
| } while (i<n) ;
uppers++;
printf ("\n ---------------
se (El Sala’ Gs Claca!
"7))
lowers++;
return 0;
ne(Ela SSO Gis Cla’
©)”})
} numbers++;

Output
flush (stdin):
Enter the value of n: 5
/* The function is used to clear the
standard input file. */
| 1 | L | ae printf("\n Enter another character. Enter *
| 2 | 4 | eer PORexab ee
| 3 | 9 | BAM 9)
scanmi@s
ci ech
| 4 | 16 | 64
} while(eh, l= WH! )g
| 5 | 25 | a5 10
| 80 | Introduction to C Programming

printf ("\n Total count of lower case printf ("\n\n Enter any number: ");
characters entered = %d", lowers) ; scanf ("%d", &num) ;
printf("\n Total count of upper case } while(num != -1);
characters entered = %d", uppers) ;
printf ("\n Total count of numbers entered = mean positives = sum_positives/positives;
sa", numbers) ;
mean negatives = sum_negatives/negatives;
return 0;
printf("\n Sum of all positive numbers
} entered = %d", sum positives) ;
Output printf("\n Mean of all positive numbers
entered = %f", mean_positives) ;
Enter any character: O
Enter another character. Enter * to exit.
printf("\n Sum of all negative numbers
Enter another character. Enter * to exit.
entered = %d", sum negatives) ;
Enter another character. Enter * to exit.
printf ("\n Mean of all negative numbers
Enter another character. Enter * to exit.
entered = %f", mean _negatives) ;
Enter another character. Enter * to exit.
return 0;
Enter another character. Enter * to exit. irs
©)
ys)
{OH
tosh
E>
}
Total count of lower case characters entered = 3 Output
Total count of upper case characters entered = 3 Enter -1 to exit...
Total count of numbers entered = 0 Enter any number:
Enter any number: 8
3.32 Write a program to read the numbers until —1 is
Enter any number:
encountered. Also calculate the sum and mean of all Enter any number: -6
positive numbers entered and the sum and mean of Enter any number: -5
all negative numbers entered separately. Enter any number: -4
#include <stdio.h> Enter any number: -1
#include <conio.h> Sum of all positive numbers entered = 24
int main () Mean of all positive numbers entered = 8.000
Sum of all negative numbers entered = -15
{
int num; Mean of all negative numbers entered =

int sum_negatives=0,
sum positives=0; -5.000
int positives = 0, negatives = 0;
float mean_positives = 0.0, mean_negatives 3.3.3 for Loop
=O) 1Or
elliaevere(())5 Like the while and do-while loop, the for loop provides
a mechanism to repeat a task until a particular condition
jorestaiere
(TUNin Iiglecee Sil (ee. Crraheg
so Ui is true. for loop is usually known as a determinate or
printf("\n\n Enter any number: ") ; definite loop because the programmer knows exactly how
scanf ("%d", &num) ; many times the loop will repeat. The number of times the
loop has to be executed can be determined mathematically
do by checking the logic of the loop. The syntax and general
{ form of a for loop is as given in Fig. 3.8.
if (num>0) When a for loop is used, the loop variable is initialized
only once. With every iteration of the loop, the value of
sum positives += num;
the loop variable is updated and the condition is checked.
positives++;
If the condition is true, the statement block of the loop is
} executed, else the statements comprising the statement
else if (num<0)
block of the for loop are skipped and the control jumps to
{
sum negatives += num; the immediate statement following the for loop body.
negatives++; In the syntax of the for loop, initialization of the
loop variable allows the programmer to give it a value.
Decision Control and Looping Statements | 81 |

Initialization
_
ofloopvariable
Syntax of for Loop
for (initialization; condition;
increment /decrement/update) Controlling
{
a
statement block;
}
Statement
Y;

Update th

Figure E64 for loop construct

Second, the condition specifies that while the conditional printf ("\n Enter the value of n :");
expression is TRUE the loop should continue to repeat scanf("%Sd", &n);
itself. Every iteration of the loop must make the condition
near to approachable. So, with every iteration, the loop for (i=0;i<=n;i++)
variable must be updated. Updating the loop variable may jorciimyese
(MW\in Sxell ai)¢
return 07
include incrementing the loop variable, decrementing the
loop variable or setting it to some other value like, i +=2, }
where i is the loop variable. In the code, i is the loop variable. Initially, it is
Note that every section of the for loop is separated initialized with value zero. Suppose the user enters 10 as
from the other with a semicolon. It is possible that one the value for n. Then the condition is checked, since the
of the sections may be empty, though the semicolons condition is true as i is less than n, the statement in the
still have to be there. However, if the condition is empty, for loop is executed and the value of i is printed. After
it is evaluated as TRUE and the loop will repeat until every iteration, the value of i is incremented. When i=n,
something else stops it. the control jumps to the return 0 statement.
The for loop is widely used to execute a single or a
group of statements a limited number of times. Another Points to Remember About for Loop
point to consider is that in a for loop, condition is tested
e Ina for loop, any or all the
before the statements contained in the body are executed.
expressions can be omitted.
So if the condition does not hold true, then the body of the
In case all the expressions
for loop may never get executed.
are omitted, then there
Look at the following code which prints the first n must be two semicolons in
numbers using a for loop. the for statement.
#include <stdio.h> e There must be no _ ine for statement. |
int main() semicolon after a for
statement. If you do that,
nae: I. hele then you are sure to get
| 82 | Introduction to C Programming

some unexpected results. Consider the following aig sk==(0).9


for (;i<10;1i++)
code.
PHINEL(Mtas, vi);
#include <stdio.h>
return 0;
main ()
}
{
Tighen waite Programming Tip: e Multiple conditions in the test
for (1=0;1<10;1i++); Although we expression can be tested by
jencauayese
(US eyelli ar)5p can place the using the logical operator (&&
return 0;
initialization, testing Of ales
} andupdating = =8 , If the loop controlling vari-
In this code, the loop initializes i to 0 and increments the loop control able is updated within the
its value. Since a semicolon is placed after the loop, it variable outside the
statement block, then the
means that loop does not contain any statement. So even
for loop, but try to
avoid it as much as third part can be skipped.
if the condition is true, no statement is executed. The loop
possible.
continues till i becomes 10 and the moment i=10, the
statement following the for loop is executed and the value
of i (10) is printed on the screen. This is shown in the code given below. :
When we place a semicolon after the for statement, then #include <stdio.h>
the compiler will not generate any error message. Rather main ()
it will treat the statement as a null statement. Usually such {
type of null statement is used to generate some time delays. abighe, at==(0)6

For example, the following code produces no output and Lomi —0)~)

simply delays further processing. {


jopaninaene(UP eyoll) al)
#include <stdio.h> i = i +3;
main ()
}
{ return 0;
TglE: aLF
}
for (i=10000;1i>0;i--);
josensalese
(U) Sxell 2 ut)e e Multiple statements can be included in the third part
return 0; of the for statement by using the comma operator.
} For example, the for statement given below is valid
e Multiple initializations must be separated with a inc.
comma operator as shown in the following code fon (i=0 dsl Orde dit dt edie)
segment.
e The controlling variable can .
#include <stdio.h> Programming Tip:
also be incremented/decre-
main () Although placing
_an arithmetic mented by values other than
{ 1. This is shown in the code
jie n, Sum expression in
for(i=0, sum=0;1<10;1i++) initialization and below which prints all odd
sum += i; updating section numbers from 0 to 10.
jorgamahene
(IU oll feibini)¢ of the for loop is #include <stdio.h>
return 0; permissible, but bari
try to avoid them {
}
as they may cause .
‘| Malham ie
e If there is no initialization to be done, then the some round-off :
initialization statement can be skipped by giving and/ortruncation | £O* (t=1it<=10;i+=2)
only a semicolon. This is shown in the following errors. printf(" $d", i);
rectus (0).
code.
}
#include <stdio.h>
e Ifthe for loop contains nothing but two semicolons,
main ()
that is no initialization, condition testing and
{ updating of the loop control variable then the for
Decision Control and Looping Statements | 83 |

loop may become an infinite loop if no stopping counter-controlled loop in which the counter is assigned
condition is specified in the body of the loop. For a constant or a value is also known as a definite repetition
example, the following code will infinitely print c loop.
Programming on the computer screen.
#include <stdio.h>
LEI EEWA| Comparison
ofpre-test and post-test loops
main ()

{ Feature Pre-test Loop | Post-test Loop


Lows:;.) Initialization 1
printf(" C Programming") ;
Number of tests N+1
return 0;

} Statements executed

e Never use a floating point variable as the loop Loop control


: N
control variable. This is because floating point variable update
values are just approximations and therefore may
Minimum iterations
result in imprecise values and thus inaccurate test
for termination. For example, the following code
will result in an infinite loop because of inaccuracies
When we do not know in advance the number of times
of floating point numbers.
the loop will be executed, we use a sentinel controlled
#include <stdio.h> loop. In such a loop, a special value called the sentinel
main () value is used to change the loop control expression from
{ true to false. For example, when data is read from the
fil Oaitea els;
user, the user may be notified that when they want the
LOR GL=A OO as =—sI0Fy)
execution to stop, they may enter -1. This -1 is called the
{ sentinel value. A sentinel-controlled loop is often useful
prinbe(™ sf", 4);
for indefinite repetition loops.
i = (float)i/10;
If your requirement is to have a counter-controlled
} loop, then choose for loop, else if you need to have a
return 0;
sentinel-controlled loop, then go for either a while loop
} or a do-while loop. Although a sentinel-controlled loop
Selecting an appropriate loop Loops can be entry- can be implemented using for loop, but while and do-
controlled (also known as pre-test) or entry-controlled while loop offers better option.
(also known as post-test). While in entry-controlled loop,
condition is tested before the loop starts, the exit-controlled
loop, on the other hand, tests the condition after the loop
3.4 NESTED LOOPS
is executed. If the condition is not met in entry-controlled C allows its users to have nested loops, 1.e., loops that can
loop, then the loop will never execute. However, in case of be placed inside other loops. Although this feature will
post-test, the body of the loop is executed unconditionally work with any loop like while, do-while, and for but
for the first time. it is most commonly used with the for loop, because this
is easiest to control. A for loop can be used to control
If your requirement is to have a pre-test loop, then
the number of times that a particular set of statements will
choose either for loop or while loop. In case you need to
be executed. Another outer loop could be used to control
have a post-test loop then choose a do-while loop.
the number of times that a while loop is repeated.
Look at Table 3.2 which shows a comparison between
In C, loops can be nested to any desired level. However,
a pre-test loop and a post-test loop. the loops should be properly indented in order to enable the
When we know in advance the number of times, the reader to easily determine which statements are contained
loop should be executed, we use a counter-controlled loop. within each for statement. To see the benefit of nesting
The counter is a variable that must be initialized, tested, loops, we will see some programs that exhibit the use of
and updated for performing the loop operations. Such a nested loops.
| 84 | Introduction to C Programming

3.33. Write a program to print the following pattern. for (j=1;j<=1;j3++)


pigeniter (ua)is
Pass 1-12345
Pass 2-12345 }
return 0;
Pass 3- 12345
}
Pass 4- 12345
Pass 5- 12345 3.36 Write a program to print the following pattern.
1
#include <stdio.h>
main ()
|W
123
{
rhaye ele Shi 1234 y
for (i=1;i1<=5;i++) 12345
{ #include <stdio.h>
printf("\n Pass %d- ",i); main ()
for (j=1;4<=5;4++)
{
jopsabateng(M) Lxel gh)# AE by Fe
} for (i=1;1<=5;1++)
return 0;
{
} jonaalanyere((M\
sai) jac
for (j=1;4<=1;j3++)
3.34 Write a program to print the following pattern.
jonesmaltene (MSE aN)e
28 6 8 28OK2B262BOK

98 262K28OK38OK3KOKOK }
return 0;
28 2K 6 28OBA 28OKOK

2 2 OR 2 8 a oe28ok
}
98 6 8 28OK 8 8 OkOK 3.37 Write a program to print the following pattern.
1
#include <stdio.h>
22
main()
333
{ 4444
TOG. hee Sih
for (i=1;i<=5;i++)
55555
{ #include <stdio.h>
jonah ayears (WGI) ee main ()
for (j=Lpj<=5;
j++) {
poreshahere (Wk) whats, al, “5

} for (l=1;1<=5;1++)
return 0; {
} joranlimese (UNAM)
LOMA (Sis alice lee cee)
3.35 Write a program to print the following pattern. joncabigiene (MICO al)
*

*
}
return 0;
kK
}
kK
KKK 3.38 Write a program to print the following pattern.
0
#include <stdio.h> 12
main() 345
{ 6789
The Hey 3p
#include <stdio.h>
for (1=1;1<=5;1++)
main ()
{
jopenliohons (Ha) + {
Decision Control and Looping Statements | 85 |

int i, j, count=0; 3.41 Write a program to print the following pattern.


for (1=1;1<=5;1i++)
1
{ ro
joueakaione (@\ra)) 5
Ws Seo |
ene (a) abe sical pas)
12343241
printf ("%d", count++);
123454321
}
1geuaaay Os #include <stdio.h>
} #define N 5
main ()
3.39 Write a program to print the following pattern.
{
A
bikahe tsb |Jl, ace ae
AB ieoue (teal p ahkS—iNip
slates)
ABC
{
ABCD for (k=N;k>=1;k--)
ABCDE jorenui@iese
(WY 4) ¢
ABCDEF for (j=1;j<=1;
4++)

#include <stdio.h> jorerumEsé (eel 5) 5

main() for (l=j-2;1>0;1--)


foresees (WEoll Al\eg
{
Ghatawlen ay joueatiajerc (Mail) 6

for (1=65;1<=70;1++) }
return 0;
{
joveniauee (Lia) 5 }
for (j=65;j}<=1;j++) 3.42 Write a program to print the following pattern.
SUMEIE (FRY, Sy
1
} DP)
return OF
eee
} 4444
3.40 Write a program to print the following pattern. 55555
1 #include <stdio.h>
i #define N 5
Ie23 main ()
1234 {
12345 SHOE Ib, Jy be, GOUMESS, CF
for (i=1;1<=N;1i++)
#include <stdio.h>
{
#define N 5
for (k=1;k<=count
; k++)
main()
jorcskaice (UO)
{ OTE Gl = salts)
Sole Ghp “jy tise
joreriateie
(ME ACl" , at)p
for (i=1;i<=N;1++)
joiestintese
(™ Vial) 5
{ aa
for (k=N;k>=1;k--)
}
joseationcne(4 W))5 return 0;
fOr (j=l; j<=1; J++)
}
japanlie
yetaE el We ap)ar
jopeabahess
(UW\imw)) 3.43 Write a program to print the multiplication table of
} n, where n is entered by the user.
return 0; #include <stdio.h>
int main()
}
| 86 |_Introduction to C Programming

{ #include<stdio.h>
tnt. Wp; #include<conio.h>
printf ("\n Enter any number: ") ; main ()
scant "sd", on)’; {
intenum, 1, count=07;
printf ("\n Multiplication table of %d", n); Girseni():
prance (\n KOR KK KR RRR RK KKM) for (i=1;i<=100;i++)

for (i=0;i<=20; i++) if (i$2==0 && i%3!=0)


jouerionese (UNE Pyel « exok S Excl, fay, al, (Ge) te a)he count++;
return 0; printf(“\n Count = %d”, count);
} } ;
Output Output
Enter any number: 2 Count = 34
Multiplication table of 2
KOK KK KKK KK KKK KK KKK KKK KKK 3.46 Write a program using for loop to calculate the

2X0=0 average of first


n natural numbers.
Amd Ss PZ #include <stdio.h>
Bee #include <conio.h>
2X 207 = "20 int main()

3.44 Write a program using for loop to print all the


{
Nc nse ach ee
numbers from m to n, thereby classifying them as float avg =-0.0;
even or odd clrser();
#include <stdio.h>

#include <conio.h> print£("\n Enter the value of n: ");


int main() scanf("$d", &n);

sige; a8.) [idieeiels for (i=1;1i<=n;i++)


elrser () ; sum = sum + i;
avg = sum/n;
printf ("\n Enter the value of m: "); printf("\n The sum of first n natural
scanf("%d", &m); numbers = %d", sum);
printf ("\n Enter the value n: "); printf ("\n The average of first n natural
scan=("Sd", &n)); numbers = %f", avg);
for (i=m; i<=n; i++) return 0;

{ }
alte (SEA eS. 0)
printf ("\n *d is even",i); Output
else Enter the value of n: 10
printf ("\n $d is odd", i); The sum of first n natural numbers = 55
} The average of first n natural numbers =

return 0; 5.500

} 3.47 Write a program using for loop to calculate factorial


Output of a number.
Enter the value of m: 5
#include <stdio.h>
Enter the value of n: 7
#include <conio.h>
5 is odd ! int main()

6 is even {
wAseacdd intefac’ = 1, num;
@lheseie(() 5
3.45 Write a program to count the numbers in the range |
to 100 that are divisible by 2 but not by 3. printf ("\n Enter the number: ");
Decision Control and Looping Statements | 87 |
scanf ("%d", &num) ; #include <stdio.h>
#include <conio.h>
int main()

{
shoe boyblig,, abe
int primes=0, composites=0, flag=0;
for(int i=1; i<=num;i++)
elrsen ()
HENGE, Ey CYS 39 ALA
} print£("\n Enter -1 to exit...");
jouenliatese (Wel inereixeranleul wens Gyol: aleja Syoll Ul waaay
a
printf ("\n\n Enter any number:") ;
fact) ;
scanf ("$d", &num) ;
return 0;

} do

Output {
for (i=2; i<=num%$2;1i++)
Enter the number: 5
{
Pactouialmomois. s1210 if (num%i==0)

3.48 Write a program to classify a given number as prime i


fiillagzd;
or composite.
break;
#include <stdio.h>
#include <conio.h>
}
int main ()
if (£lag==0)
{ primes++;
shige, ieileYe, =) Op aby newer else
Gllrsex
(\i composites++;

printf("\n Enter any number: ") ; flag=0;


scanf ("$d", &num); printf ("\n\n Enter any number: ");
for(i=2; i<num/2;i++) scanf ("%d", &num) ;
{ } while(num != -1);
i£(numsi == 0) printf("\n Count of prime numbers entered =

: $a", primes) ;

flag =; printf ("\n Count of composite numbers


break; entered = %d", composites);

} recuEn Ol;

} }
aie (ieIle%s; Se il), 3.50 Write a program to calculate pow(x,n), to
printf ("\n %d is a composite number", num);
calculate x”.
else #include <stdio.h>
printf("\n %d is a prime number", num); #include <conio.h>
return 0; #include <math.h>
} int main()

Output
{
Soe ak, ialbhig, ine
Enter the number: 5 VOnGmamee resuLta—e-
5 is a prime number elrser ());

3.49 Write a program using do-while loop to read the


printf ("\n Enter the number: ");
numbers until —1 is encountered. Also count the
scant ("%d", &num);
number of prime numbers and composite numbers printf ("\n Till which power to calculate:
entered by the user
| 88 | Introduction to C Programming

scant ("Sd", &n); sumofdigits += temp;


num = num/10;
for (i=1; i<=n;i++) }
result = result * num; print£ ("\n The sum of digits = sdl’,
sumofdigits) ;
primer (Nn powlitdha sd) s— [Link], = 1, return 0;
result); }
return 0;
Output
}
Enter the number: 123
Output The sum of digits = 6
Enter the number: 2
3.53 Write a program to enter a decimal number. Calculate
Till which power to calculate: 5
OW (2, BS), a 3
and display the binary equivalent of this number.
#include <stdio.h>
3.51 Write a program to print the reverse of a number. #include <conio.h>
#include <stdio.h> #include <math.h>
#include <conio.h>
int main() int main()
{
int num, temp; int decimal_num, remainder, binary num = 0,
lacey) A sl = Op
clrser();
printf("\n Enter the number: ");
scanf("%d", &num); printf ("\n Enter the decimal number: ");
printf("\n The reversed number is: "); scanf("%d", &decimal_num) ;
while (num != 0) while (decimal num != 0)
{ {
temp = num%10; remainder = decimal _num%2;
printf ("Sd",temp) ; binary num += remainder*pow(10,i) ;
num = num/10; decimal num = decimal _num/2;
} 1++;
return 0;
}
} printf("\n The binary equivalent = %d",
binary num) ;
Output
ig erebaa (0)5
Enter the number: 123
}
The reversed number is: 321
Output
3.52 Write a program to enter a number and then calculate
Enter the decimal number: 7
the sum of its digits.
The binary equivalent = 111
#include <stdio.h>
#include <conio.h> 3.54 Write a program to enter a decimal number. Calculate
int main() and display the octal equivalent of this number.
{ #include <stdio.h>
int num, temp, sumofdigits = 0; #include <conio.h>
Giliacesori(: #include <math.h>
printf ("\n Enter the number: ");
scanf("%d", &num) ; int main()

while(num != 0) int decimal_num, remainder, octal _num=0,


{ 1 = 0;
temp = num%s10; clrscr();
Decision Control and Looping Statements 89 |

printf("\n Enter the decimal number:


") ; int main()
scanf("%d", &decimal_num) ;
while (decimal num != 0) int decimal _num= 0, remainder, octal_num,
{ Ory
remainder = decimal_num%8; Gilkescra(()i
octal _num += remainder*pow(10,i);
decimal_num = decimal_num/8; printf ("\n Enter the octal number: ") ;
i++; scanf("%d", &octal_num) ;

} while (octal_num != 0)

printf ("\n The octal equivalent = %d", {


octal num) ; A remainder = octal_num%10;
Betuin 0; decimal num += remainder*pow(8,i) ;
octal_num = octal _num/10;
}
1++;
Output }
Enter the decimal number: 18 printf("\n The decimal equivalent = %d",

The octal equivalent = 22 decimal num) ;


return 0;
3.55 Write a program to enter a binary number. Calculate }
and display the decimal equivalent of this number.
#include <stdio.h>
Output
#include <conio.h> Enter the octal number: 22
#include <math.h> The decimal equivalent = 18

3.57 Write a program to enter a hexadecimal number.


int main ()
Calculate and display the decimal equivalent of this
int decimal num=0, remainder,
binary num,
number.
#include <stdio.h>
i=0;
#include <conio.h>
Gilaseia())) +
#include <math.h>

printf ("\n Enter the binary number: ") ;


int main ()
scanf("%d", &binary num) ;
while (binary num != 0)
int decimal _num= 0, remainder, hex_num, i
{
remainder = binary num%10;
elcser (\);
decimal num += remainder*pow(2,1i) ;
binary_num = binary num/10; printf ("\n Enter the hexadecimal number: ") ;
1++; scanf("%d", &hex_num) ;
} while (hex_num != 0)
printf ("\n The decimal equivalent of = %d",
{
decimal_num) ; remainder = hex _num%10;
return 0; decimal num += remainder*pow(16,1i) ;
} hex_num = hex _num/10;
1++;
Output
}
Enter the binary number : 111 printf ("\n The decimal equivalent = %d",
The decimal equivalent = 7 decimal num) ;
return 0;
3.56 Write a program to enter an octal number. Calculate
and display the decimal equivalent of this number.
}
#include <stdio.h> Output
#include <conio.h> Enter the hexadecimal number : 39
#include <math.h> The decimal equivalent = 57
| 90 | Introduction to C Programming

3.58 Write a program to calculate GCD of two numbers. scanf("¢d", &n);


#include <stdio.h>
#include <conio.h> for (i=1.0;i<=n;1i++)

int main () { a=1/i;


sum = sum +a;

int numl, num2, temp;


}
printf ("\n The sum of series 1/1 + 1/2 +
int dividend, divisor, remainder;
HEL /faxel = ee ily iol) 9
Glaeser).
return 0;

printf ("\n Enter the first number: ");


} :
scanf("%d", &num1); Output
printf("\n Enter the second number: ") ; milia tater aia Bo Ramee

scanf("sd", snum2); The [Link] series) 1/1s + 1/2 +052. 4 1/5 =1222838

: : 1 1 1
if (num1>num2) 3.60 Write a programto sum the series re ep se
{ 1 2, 3
dividend = numl; #include <stdio.h> «
divisor = num2; #include <math.h>
} #include <conio.h>
else main ()

{ {
dividend = num2; Sea Tal
divisor = numl; float wSsum=On
0; nal. ly
} elrser();
printf("\n Enter the value of n: ");
while (divisor) scanf ("%d", &n);
{ for (1=1.0;i<=n; i++)
remainder = dividend%divisor; { a=1/pow(i,2);
dividend = divisor; sum => sum tai;
divisor = remainder; }
} perenne (U\iay He ein) Oe Ceres We a 7” Be =
printf ("\n GCD of $d and $d is = %d", numl, th" sum): .
wa l/h 2 = orn
num2, dividend) ; return 0;
return 0; }

} Output
Output Enter the value of n: 5
: 2 2 2
Rnternthentivese number: 62 The sum of series 1/1° + 1/ 2° +... 1/n* = 1.4636

Enter the second number: 14 ; aby line 2 n


COND ENGL OLA Gee = 5 3.61 Write a program to sum the series — + —--- :
; 21% 308m (HPL)
: : | 1 ;
3.59 Write
a program to sum the series 1+ —+—---+—- He LEC See canes>
Dp n #include <conio.h>
#include <stdio.h> main ()
#include <conio.h> {

{ float sum=0.0,
a, i;
int n; ollbigisxena()
float Ssum=0.0), ay i printf("\n Enter the value of n: ");

clrscr
() ; scanf ("%d", &n);
foriGai.
Op t<=ni asp)

printf("\n Enter the value of n: "); { a= i/(i+l);


Decision Control and Looping Statements | 91

Se hey, term = pow(i,3);


} sum += term;
printf ("\n The sum of
series 1/2 + 2/3 + }
= $£",n,n+1,sum) ; De untine PO? ae ee eee retire
iajebhaal 03 return 0);

Output Output
Enter the value of n :5 Enter the value of n:5
The sum of series 1/2 + 2/3 + .... = 2.681+E Epa g2? Fy eeene nite ewes D5

3 6a WHiES program io eUnuHiseeies {iiyey rnBa 3.64 Write a program to calculate sum of squares of first
oes n even numbers.
#include <stdio.h> #include <stdio.h>
#include <conio.h> #include <conio.h>
#include <math.h> #include <math.h>
main ()
{ main ()

int n, NUM; {
float i,sum=0.0; ame aly, Tay
Giles ere (ie int term, sum = 0;
printf ("\n Enter the value of n: "); eAlagsyexe
(())
scanf("%d", &n); printf ("\n Enter the value of n: ");
for (f=1 .0;1<=n; i++) scanf("%d", &n);
{ for (1=1 ;i<=n;1++)

NUM = pow(i,i); {
sum += (float) NUM/i; abe (GL32 se ©)
} { term = pow(i,2);
jouestiaiene
(A \eay ab//al ey Ds eS /eh = Sf", sum += term;
sum) ; }
igeeubaal, (Oy, }
} Prince Wn 27444 4 6" A ee er
ineeibhaay (0)5
Output }
Enter the value of n:5
eet ere 27a ok. 704000 Output
Enter th 1 fn: 5
3.63 Write a program to calculate sum of cubes of first n Ar. sake Pook Ps,
De Sede PO tee Nae =A 2
numbers.
seit Pron cea 3.65 Write a program to find whether the given number is
Programming Tip: an Armstrong number or not.
#include <conio.h>
It is alogical error Panciude math le #include <stdio.h>
#include <conio.h>
dfloopice trol #include <math.h>
main ()
variable in the main ()
while/do-while {
ee TAME dbp AGL
loop. Without an , Lae iain, SUMNEO, 7, Ia
iitatenrn Sum: = 10). ‘ area as
update statement, elrser();
“thel ill , Cllaseret))+
‘the oe |printf ("\n Enter the value printé("\n Enter the number: ");
_ become an infinite | ee iy: scanf("$d", &num) ;
loop : n=num;
scant ("Sd", &n); '
for (1=1;1<=n;i++) while (n>0)
{
92 | Introduction to C Programming

r=n$10; scanf ("$1£", &ROT);


sum += pow(r,3); printf ("\n Enter the number of years for
n=n/10; which investment has to be done: ");
} scanf("%d", &yrs);
if (sum==num)
printf ("\n %d is an Armstrong number", num); futureVal=initVal;
else printf ("\n YEAR \t\t VALUE") ;
printf ("\n %d is not an Armstrong number", printf ("\n oo a
num) ; for (i=1;1<=yrs;1++)

return 0; {
} futureVal = futureVal * (1 + ROI/100.0);
jovanatens (Nia Sau eth, ea paehukEure Valyy
Output }
Enter the number : 432 return 0;
432 is not an Armstrong number }

3.66 Write a program to print the multiplication table. Output


#include <stdio.h> Enter the investment value: 20000.
#include <conio.h> Enter the rate of interest: 12
int main () Enter the number of years for which
{ investment has to be done: 5
int i, ji YEAR VALUE
clrser();

for (1=1;1<=20;1++) 1 22400.00


{ 2 25088.00
printf ("\n\n\n\t\t Multiplication table of 3 28098.56
*a", i); 4 31470.38
printf ("\n SER ok keke) : 5 35246.83

for (j=1; j}<=20;


j++)
prince\e dz ae = &d", 1,4, G*)))s 3.68 Write a program to generate calendar of a month
} given the start day of the week and the number of
getch(); days in that month.
return 0; #include <stdio.h>
} main ()
{
Output int i, j, startDay, num
_of_ days;
Multiplication table of 1 printf ("\n Enter the starting day of the
BEES RFE I SORE Se See ee a week (it to rh) : Ww)

Ra kod Lie ae ut Se xis 1*4=4 scant ("%d", &startDay) ;

3.67 Write a program using for loop to calculate the ee 4cos ae Se ee


value of an investment, given' the initial value of scanf("sd", &num
of days) ;
investment and the annual interest. Calculate the
value of investment overa period oftime. printf(" Sun Mon Tue Wed Thurs Fri Sat\n") ;
#include <stdio.h> printf ("\n ny),
main () for (i=0;i<startDay-1;
i++)
{ PEINEE ( MNS
double initVal, futureVal, ROI; for (j=1;j<=num_of_days;j++)
ZNaho, aiacisiy Bhs {
printf ("\n Enter the investment value: "); if (i>6)
Scant ("Sli", &inieVal) >; {
printf ("\n Enter the rate of interest: "); printf("\n");
Decision Control and Looping Statements _| 93 |

i=1; joneanayeve (Ugh exolll' al))e


} ah ay) ee ee
else }
1++; return 0;
jonealratese
(ME ACh Di aya }
} Note that the code is meant to print first 10 numbers
return 0;
using a while loop, but it will actually print only numbers
}
from 0 to 4. As soon as i becomes equal to 5, the break
Output statement is executed and the control jumps to the
Enter the starting day of the (week (> tomy)ica 5 statement following the while loop.
ENter the number of days in that month : 31 Hence, the break statement is used to exit a loop from
any point within its body, bypassing its normal termination
Sun Mon Tue Wed Thurs Fri Sat expression. When the break statement is encountered
il 2 3 4 5 6 7 inside a loop, the loop is immediately terminated, and
program control is passed to the next statement following
the loop. Figure 3.9 shows the transfer of control when the
3 5 br eak AND continue - break statement is encountered.
STATEMENTS
3.5.1 break Statement

In C, the break statement is used to terminate the execution


_ of the nearest enclosing loop
_ in which it appears. We have
already seen its usage in the
_ switch statement. The break
_ to terminate the statement is widely used with
xecution of the _ for loop, while loop, and do-
while loop. When compiler
encounters a break statement,
the control passes to the statement
that follows the loop in which the
break statement appears. Its syntax is quite simple, just
type keyword break followed with a semicolon.
break;

In switch statement, if the break statement is missing


then every case from the matched case label till the end
of the switch, including the default, is executed.
This example given below shows the manner in which
break statement is used to terminate the statement in
which it is embedded. Figure 3.9 breakstatement == 2 .
#include <stdio.h>
int main ()
3.5.2 continue Statement
{
shale, al = (6 Like the break statement, the continue statement can
while (i<=10)
only appear in the body of a loop. When the compiler
{ encounters a continue statement then the rest of the
sites (@15==5))
statements in the loop are skipped and the control is
break;
unconditionally transferred to the loop-continuation
| 94a. Introduction to C Programming

simple, just type keyword continue followed with a while(...)


semicolon.
eee ee

continue; if (condition) ig (condition) -


continue; continue;
Again like the break statement, ee ee ee

Programming Tip: the continue statement cannot i

When the compiler be used without an enclosing for,


encounters a while, or do-while statements. (Transfers the control to Hraneter: the controla
the condition expression
cont inue When the continue statement is of the dé-whileoop)
of the while loop)
starement then encountered in the while loop
the rest of the :
: and in the do-while, the control
statements in the ; fered h i
loop are skipped 1s transferred to the code that

and the control is tests the controlling expression. for(...) for...)


unconditionally However, if placed with a for RNa Ke Oe a 0s Se we eee

transferred to the loop, the continue statement for(...)-


loop-continuation causes a branch to the code that continue; oo
portion of the updates the loop variable. For ‘Lf (condition) |
nearest loop. a 2
example, look at the following
code. (
the condition expression
#include <stdio.h> }
of the for loop) (Transfers the control to
int main ()

{ the condition expression :


shale, Sls of the for loop) -
for(i=0; i<= 10; i++)
{ Figure 3.10 ‘The continue statement
LE (1==5)
continue;
joeiigteie (OVE eel ah)7 Hence, we conclude that the continue statement is
dee tee lie somewhat the opposite of the break statement. It forces
} the next iteration of the loop to take place, skipping
return 0;
any code in between itself and the test condition of the
} loop. The continue statement is usually used to restart
The code given here is meant to print numbers from 0 a statement sequence when an error occurs. Look at the
to 10. But as soon as i becomes equal to 5, the continue program code given below that demonstrates the use of
statement is encountered, so rest of the statements in break and continue statements.
the for loop are skipped and the control passes to the
69. Write a program to calculate square root of a number.
expression that increments the value of 1. The output of
#include <stdio.h>
this program would thus be #include <math.h>
main ()
Programming Tip: Oe 2 Sen A ee Oper esOia im 1)
As far as possible, {
try not to use (Note that there is no 5 in the se- int num;

goto, break, ries. It could not be printed, as do


and continue continue caused early incremen- {
statements as they tation of i and skipping of the
printf ("\n Enter any number. Enter 999 to
violate the rules SEODE ar
statement that printed the value of
ofstructured scanf ("$d", &num);
programming. ion screen).
ne if (num == 999)
Figure 3.10 illustrates the use of break; // quit the loop
continue statement in loops. LE Gaume <0)
Decision Control and Looping Statements | 95 |

{ The goto statement is often combined with the if


printf ("\n Square root of negative numbers statement to cause a conditional transfer of control.
is not defined");
if condition then goto label
continue; // skip the following statements
} In this book, we will not use the goto statement because
printf ("\n The square root of %d, is %f", computer scientists usually avoid this statement in favour
num, sqrt (num) ) ; of the ‘structured programming’ paradigm. Some scientists
}while(1) ; think that the goto statement should be abolished from
ASE Waagial, (0) higher-level languages because they complicate the task
} of analysing and verifying the correctness of programs
(particularly those involving loops).
Moreover, structured program theorem proves that the
3.6 goto STATEMENT availability of the goto state-
The goto statement is used to transfer control to a ment is not necessary to write
Programming Tip:
specified label. However, the label must reside in the Follow proper programs, as combination of se-
same function and can appear only before one statement indentation for quence, selection, and repetition
in the same function. The syntax of goto statement is as better clarity, constructs are sufficient to per-
shown in Fig. 3.11. readability, and form any computation. The code
Here, label is an identifier that specifies the place _ understanding of given below demonstrates the use
NS

where the branch is to be made. label can be any valid


the loops. — of a goto statement. The program
calculates the sum of all positive
variable name that is followed by a colon (:). The label
numbers entered by the user.
is placed immediately before the statement where the
control has to be transferred. #include <stdio.h>

The label can be placed anywhere in the program main ()

either before or after the goto statement. Whenever the {


His Wii, CGeIN=OR
goto statement is encountered the control is immediately
read: // label for goto statement
transferred to the statements following the label. printf ("\n Enter the number. Enter 999 to
Therefore, goto statement breaks the normal sequential end: ");
execution of the program. If the label is placed after the scanf("%d", &num);
goto statement, then it is called a forward jump and in if (num != 999)
case it is located before the goto statement, it is said to be {
a backward jump. if (num < 0)
goto read; // jump to label- read
sum += num;
goto read; // jump to label- read
}
printf ("\n Sum of the numbers entered by the
wisiere ale) = cll eiut)) &
Tajewugay (0).p

Conclusion
e It is not necessary to use goto statement, as it can
always be eliminated by rearranging the code.
e Using the goto statement violates the rules of
structured programming.
Backward jump e It is good programming style to use the break,
artes Thegoto statement continue, and return statements in preference to
goto whenever possible.
| 96 | Introduction to C Programming

© goto statements make the program code complicated jeresnajene (W\io (SHUM S| Sol", Sivan)7
return 0;
and render the program unreadable.
}
Now let us see how we can eliminate continue
statement from our programs. Let us first write a program
that calculates the average of all non-zero numbers
entered by the user using the continue statement. The
second program will do the same job but without using
In structured programming, you must prefer to use if and
continue.
if-else construct to avoid such statements. For example, i
look at the following code which calculates the sum of #include <stdio.h>

numbers entered by the user. The first version uses the main ()

break statement. The second version replaces break by {


if-else construct. Le tain, Swine, slleSeiy,- cewiaicsO.
float avg;
// Uses break statement
// £ilag Will’ be wised "torexit, from thes loop
#include <stdio.h>
while (flag==1)
main ()
{
{
printf("\n Enter any number. Enter 999 to
int num, sum=0;
Stop ae;
while (1)
scanf ("%$d", &num) ;
{
Tae (Ganbti—=e=(0)))
printf ("\n Enter any number. Enter 999 to
continue; // skip the following statements
Sieejos
Y)) 4
if (num! =999)
scanf("Sd", &num);
if (num==999) {
sum+=num;
break; // quit the loop
count++;
sum+=num;
} }
else
paint sUMe= scl! ssumr
iESISO p
return 0;
// set loop cntl var to jump out of loop
}
}
piste
i (“\aeSUMs —s.5clt sum);
// Same program without using break
BN; = (Geiloete) sum/count ;
statement
printf("\n Average = &£", avg);
#include <stdio.h>
were hain, Op
main ()
}
{
IME Waihi, SOMO, dtlewis
// Same program without using continue statement
// flag will be used to exit from the loop
#include <stdio.h>
while (flag==1) // loop control variable
main ()
{
printf("\n Enter any number. Enter 999 to {
int num, sum=0, flag=1, count=0;
Sieqae "yp
float avg;
scanf("%d", &num);
if (num! =999) // flag will be used to exit from the loop

sum+=num; while (flag==1)

else {
Evag=OF // to quit the loop printf ("\n Enter any number. Enter 999 to

} SieoOs. ™))-g
Decision Control and Looping Statements | 97 |
scanf ("%d", &num); class will comprise of all the valid values. The second
if (num! =0) class contains input data below the lower limit. The third
{ class contains input data above the maximum limit.
if (num! =999)
Step 2: Pick any one data value from each class. Execute
{ the program with these three data values and check if the
sum+=num;
result is correct.
count++;
If the result is correct in all three cases, the program
}
has high probability to give accurate results with any
else
input value. But if the result differs from the one that is
i lag=O0}
expected, the programmer knows specially the source and
reason for defect. So, in the above example the program
}
can be checked with three values like —1, 500, and 1100.
print£é("\n SUM = $d", sum);
avg = (£loat) sum/count ;
printf ("\n Average = &f", avg); Second Strategy
return 0) The second strategy emphasizes checking program at the
} extreme ends (boundaries) of input domain as most of
the errors occur there. In this technique perform the steps
given below.
3.7. BUILDING A ROBUST
C PROGRAM
e First, check the program with any value within the
Even a small and simple program that is executing
input domain say, 500.
properly may have some defects in it. For example, the
e Second, check the program with an input of | and
program executing without errors may give a result that is
1000 as both these values form the boundary of the
completely unexpected or incorrect. So, the programmers
input domain.
must test the program to ensure that the program is giving
e Third, check the program with values just below the
correct result with any input. For example, if you have
extreme values. For example, with input values 0
written a program that accepts numbers from | to 1000,
and 999.
then it is not possible to observe the outputs for all the
valid values and even the ones that are invalid. So, two e Fourth, check the program with values just above
simple strategies that can be followed are given below. the extreme values. For example, with input values
2 and 1001.

First Strategy Make sure that every program that you write is tested
simultaneously as per these guidelines.
Step 1: Divide the input data in three classes. The first

Lu
— F
_Oo

O
peat
Nn
f=
<
O
a.
| 98 |Introduction
toC Programming

> Break statement Statement used to terminate the ex- function and can appear only before one statement in
[a ecution of the nearest enclosing loop in which it appears. the same function. .
ct
—) Conditional branching Conditional branching state- If statement Simplest form of decision control state-
7a)
Oo ments is used to jump from one part of the program to ment that is frequently used in decision making.
oe another depending on whether a particular condition If-else-if statement Decision control statement
Oo is satisfied or not. that works in the same way as anormal if statement.
Continue statement Statement that can appear in the It is also known as nested if construct.
body of a loop. When the compiler encounters a con-
If-else statement Decision control statement in
tinue statement then the rest of the statements in
which first the test expression is evaluated. If the ex-
the loop are skipped and the control is uncondition-
pression is true, statement block 1 is executed and
ally transferred to the loop-continuation portion of the
statement block 2 is skipped. Otherwise, if the ex-
nearest enclosing loop.
pression is false, statement block 2 is executed and
Dangling else problem Problem encountered with
statement block 1 is ignored.
nesting of if-else statements which is created when
there is no matching else for every if statement.
Iterative statement Statements used to repeat the
execution of a list of statements, depending on the
Do-while loop The do-while loop is similar to the
value of an integer expression.
while loop. The only difference is that in a do-while
loop, the test condition is tested at the end of the loop. Nested loop Loops placed inside other loops.
For loop: The mechanism used to repeat a task until a Switch case statement A switch case statement
particular condition is true. For loop is usually known as is a multi-way decision statement that is a simplified
a determinate or definite loop because the programmer version of an if-else block that evaluates only one
knows exactly how many times the loop will repeat. variable.
Goto statement It is used to transfer control to a speci- While loop The mechanism used to repeat one or
fied label. However, the label must reside in the same more statements while a particular condition is true.

Fill in the Blanks

R . Dangling else problem occurs when : 9. statements are used to repeat the
2. The switch-case control expression must be of execution of a list of statements.
type. 10. In loop, the entry is automatic and
EXERCISES
3. In a do-while loop, if the body of the loop is there is only a choice to continue it further or not.
executed n times, the test condition is evaluated 11. When we do not know in advance the number
times. of times the loop willbe executed, we use a
4. The statement is used to. skip loop.
statements in a loop. 12. The statement is used to transfer
control to a specified label. : :
5. A loop that always satisfies the test condition is
known as a loop. 13. _statement violates the rules of |
structured programming.
6. In a counter-controlled loop,
variable is used to count the number of times the
loop will execute. State True or False
ve statements help to jump from one 1. Decision control statements are used to repeat the
part of the program to another depending on execution of alist of statements. _
whether a particular condition is satisfied or not.
2. The expression in a selection statement can have
8. The control expression that follows the keyword
no side effects. .
switch must be of type.
Decision Control and Looping Statements | 99 |

wn 2 Compare the use of if- else constru


_ of ternary operator.
a _ 3. Explain the importan
=x ; statement. In v
nr
=
Li

1.
_ second number. —
[9. Write a program usin
menu that offers. 5opti
calculate total, ‘calculate ave
smallest, and display the largestvalue.
|100 | Introduction to C Programming

n 20. Write a program to display the sin(x) value where x So. Write a program to calculate parking charges of
ranges from 0 to 360 in steps of 15. a vehicle. Enter the type of vehicle as a character
0
(like c for car, b for bus, etc.) and number of hours —
[oO 21. Write a program to display the cos(x), tan(x) value
an where x ranges from 0 to 360 in steps of 15. then calculate charges as given below:

<
. Liu 7
go. Write a program to calculate electricity bill based e Truck/bus — 20 Rs per hour
on the following information. e Car—10 Rs per hour
e Scooter/ Cycle/ Motor cycle — 5 Rs per hour
Consumption Rate of Charge 34. Modify the above program to calculate the park-
Unit ing charges. Read the hours and minutes when the
Rs 3 per unit vehicle enters the parking lot. When the vehicle
is leaving, enter its leaving time. Calculate the dif.
151-350 Rs 100 plus Rs 3.75 per unit
ference between the two timings to calculate the _
exceeding 150 units
number of hours and minutes for which the vehi- -
301 — 450 Rs 250 plus Rs 4 per unit cle was parked. Finally calculate the charges based
exceeding 350 units on following rules and then display the result on
451-600 Rs 300 plus Rs 4.25 per unit the screen. «
exceeding 450 units
Vehicle Name Rate till | Rate after D
Above 600 Rs 400 plus Rs 5 per unit
3 hours 3 hours
exceeding 600 units
Truck/bus
23. Write a program to read an angle from the user
and then display its quadrant. Cycle/ Motor cycle/ | 5
24. Write a program that accepts the current date and Scooter
the date of birth of the user. Then calculate the
age of the user and display it on the screen. Note 35. Write a program to read month of the year as an
that the date should be displayed in the format integer. Then display the name of the month.
specified as dd/mm/yy. 36. Write a program to print the sum of all odd ©
20. A class has 50 students. Every student is supposed numbers from 1 to 100.
to give three examinations. Write a program to 37. Write an interactive program to read an integer.
read the marks obtained by each student in all If it is positive then display the corresponding
three examinations. Calculate and display the total binary representation of that number. The user
marks and average of each student in the class. must enter 999 to stop. In case the user enters a
26. Write a program in which the control variable is negative number then ignore that input and ask
updated in the statements of the for loop. the user to re-enter any different number.
27. What is a null statement? How can it be useful in 38. Write a program to print 20 asterisks.
our programs? 39. Change the following for loop into a while loop.
23. Write a short note on goto statement. Why should Also convert the for loop into a do-while loop. ©
it be avoided? irc 4;
29. Write a program which demonstrates the use of for (4=10;1>0;1--)
goto, break, and continue statements Prancl Sd", 1);

30. In what situation will you prefer to use for, while 40. Change the following do-while loop into a for |
and, do-while loop? loop. Also re-write the code by changing the sh
si. Can we use a for loop when the number of while loop into a for loop. _
iterations is not known in advance? If yes, give a
int num;
program that illustrates how this can be done.
printf (“\n Enter any number. Enter 999
32. Write a program that displays all the numbers to stop ; %) -
from 1-100 that are not divisible by 2 as well as by scanf(“%d”, &num);
3.
do 45. Write a program to generate the following pattern:
{ kekK

printt ("sd”, x):


yr
printf (\5 Enter any number. Enter 299) tr
to stop . *); #x*

EXERCISES
scanf (“%d”, &num); FA
+

jebiletoum | l= 999); 46. Write a program to generate the following patie


a1. Write a program that accepts any ‘number and S ek $

prints the number of digits in that number. * S $ *

> &¢ *
42, Change the following white loop into a do- while
7 > fF
loop. Also convert the while loop into a for loop. S x *® & S

int num; 47. Write programs to Sn the fohewns


prints (\\n Enter any number. ‘Enter 999 sequence of numbers. © _
tO Stop _2 :
1, 6, 27, 64,
scanf (“%sq”, gnum) ;
— oo 8. a e S17,
while(num != 999) -2, -4, eee-8, -10, -12, =
1, 4,7, 10;
printi( sd", x);
48. Write a program that reads integers until the
printf (“\n Enter any number. Enter 999
user wants to stop. When the user stops entering
to stop 1:
_ numbers, display the cee of all the numbers
scant (“sd" , num); entered.
} 49. Write a program to print the sum of the fellowine
. The following for loops are written to print series:
imbers from 1 to 10 e these loops corrent? x +x -= x 3.
Justify your answer. 1+ (142) = io) +0

1 - x + x/2! - x°/3! +.
neIollowing pattern: -
50. Write a program to printthe
*

* *

* +

A
+

+ *~

et
ee
(c)int 1)
51. Write a prog to one the iow pattern:
for (i=1;i<=10; ie) 1
212
“ovintii sd’, 1); 32423
itt; 52. Write a program to read a 5-digit number and
~ then display the number in the following formats. ©
For example, the user entered 12345, a result
: Write a| program to generate the following pattern: should be
ke is 1
2345. 2.
345 423
4S 1234
= 12345
|102 | Introduction to C Programming

Program Output : cise


n-
nv : : C=20;
“ nie the output of the following program codes. printe('\n7a = 40 \e p = 4a (ce = ea
oO 1. include <stdio.h> a6, ei
fe
Lil S
main () return 0;
>< { }
Lad int a= 2, b= 3, c= 4;

ti{ ct= 100) 5. #include <stdio.h>


ae oo main ()
else { i

BG int a = 2, b = 3, 6 = 4;
if(a +b c 10) sf) ;

FT if (b)
S = 20;
( Calo:
b = ++¢;
: else
Prince’ \n a = sd \t b = $4 (tb c = Sa! bon,
a bo; Tee
printé(! \n a = @d (6 b = 20-\6
. 6 = 4a),
return 0;
- 4, bo, 6);
}: : return 0;
2. #include <stdio.h> .
main()

A : : 6. #include <stdio.h>
ont a = 2.6 = 3) c= 4: ;
_ -_ main
; ()
Lf (b==2)

ae int a =2, b= 3, ¢ = 4;
ey if(a w= 6 || b oe 6 eh © = 6)
¢=10; _ if(a && bb)
printh("\na= 2d \t & = ta \c co = Ga", cei6.
a, b, @) i : else

Teun oO; c=20; /

- printf(" \n a = $d \t b = %d \t c = $a",
] : ( a, b, Cc);
3. #include <stdio.h> - return0;
main ()
Lo
{
Ape a= 2, b = 2) c= 4; 7. #include <stdio.h>
_ Lf (a&&b) main ()
c=10; c
else ant a= 2, b= 3, ¢ = 4:
c=20; i£( as b)
Orintt("\n a = 3d \t b = 4d \t c = Sd" , C++;
a, b, 2); printf(" \n a = %d \t b = &d \t c = Sa”
recurh 0; 7a, bo.
3 return 0;
ee
4. #include <stdio.h>
-main() 8. #include <stdio.h>
4 main ()
int a = 2. b = 3, ¢ = 4; {
if (a | | bo ime a-2, b= 2, ¢ = 4;
Decision Control and Looping Statements 103 |

int num = 10;


printé ("\n 3d”, a>100);
4
13.#include <stdio.h>
EXERCISES
printf(" \n a = $d \t b = $d \t © = 4a", main()
a, b,c); : {
return 0; printt ("HELLO”) ;
o Jf (lL)
printf ("WORLD”) ;
. switch (ch)
{ | 14.#include <stdio.h>
aint
Case a
case ‘A’: — o
printf ("\n ai: int 4a = 3;
case ‘b’; . ee
case ‘Bb’: | prince ( "\n LESS”) ;
~Printi(’\p BY af (a < 20) -_ ae
default: Prince (O\n LESS”);
printf ("\n DEFAULT”); £4< 20)
printf (*\n_ LESS") ;
[Link] o.
{ 4S include egtdio he
case ‘a’: main () 7 —
case ‘A’;
{ : : _ ; a
princi
("\n At) tnt a-10, 5-20 c 30, d=40) ; _
case ‘b’: iff c¢ < d
Case 8 - : af ( c « b)
| printf ("\n B”); pret nc;
break else if(a < ©)
-printi(’\n a”)
printf ("\n DEFAUL "), ifla > b)
BY) ;
else _

ewitch (ch) printé ("\n an;

_ case ‘a’:
Cage A. —16.#include <stdio.h>
printé("\n AY); main ()
break; -
char ch = ‘yy;
case ‘hb’:
switch (ch)
| case 8.
Printi(’\n 87); {
default:
: break;
printf ('\n YES OR NO”);
deteult:
Case (“Y';
prince ("\n DEFAULT” ) ;
_printi("YES”);
break;
Case N’:
‘12.#include <stdio.h>
Prints ('NO”);
void main ()
break;
{
|104 | Introduction to C Programming

es la eekee

“EXERCISES
| 7
ce #include <stdio. hp

: int i=0;
return QO; oe _— aS

printf
oe("\n 3d”,i);
ca |
neludeya oe

- dwhile(i<=0);
mtf("\n STOP”)
for (;--num;) : —

ee -23.#include <stdio.h>
xeturn 0;
‘main().
- ‘
— int i, j-
19. 4include <stdio.h> _ fo (i= o; i<=10; tee)

" printé("\n") ;
ant num=10; for (j= 0;j<= 10; ae
for (; !num;num++)
“ printt(™ 0
ntf(" $d", prince (\

a
jude <stdio.h>
- ‘vo: d main()

int num = 10
Co. - ae
ile (r>=0) ~~ .

area = eos #2; — 25. #include <stdio.h>


printf("\n Area = %f", area); main ()
} _ .
return 0; _ ] printt ("HELLO");
_ if (i)
_ / princ’ ("WORLD") ;
21.#include <stdio.h>_ }
main ()
{ fe 26.#include <stdio.h>
int fn0. : : main ()

while (i==0) — _ oe
{ - - int x=-1;
(n<10)
thie cy)
Decision Control and Looping Statements | 105 |

printé("\n SMALL” ) ; for (num++; num<=10 0; num=100)


else printi(, 4d", num) ’

printf ("\n LARGE”) ; return 0;

}
27.#include <stdio.h> 31.#include <stdio.h>
Main() main() ©
{ {
char ch -63; while (1);
t mum = -36; ‘printi(’Hi’),
signed int unum = -{8; return O;
if(ch > num) }
Orinte AY). 32.#include <stdio.h>
if(ch > unum) main ()
printt ("RB"); 7
| else . aint i=0;
peinte ("Cc"); char c ='0'>
while (i<10)
else {
{ Pointe (sc, cy i iG
Prince ("dD"); i++;
-
if (num < unum)
princtl (%E"); veturn 0;
else }
Brnte ro:
33.#include <stdio.h>
main()
i
ant is0-
do

{
Lf (1>10)
for (; ++num;num-=2) continue;
Printit(’ <d”, num); its;
> return 0; }while (i<20);
} printf("\n i=%d”, 1);

&£ 29.#include <s


1 _
tdio.h> 34.#include <stdio.h>
main () main()
4 {
int num=10; Ame i=l;

Orie) for(;i<=l;i++) {
princi ("HI!)”); Pence ("\n 2d” ,1);
weturn 0, printi(’\n StoP”);
}
clude <stdio.h> 35.#include <stdio.h>
ao
main ()
int i, 3;
int num=10; for (i=10-1-20;1--)
|106 Introduction to CProgramming

on {
9. int i;
| - print’ ti\n7) : : é for (i=10;i>5;1-=2)
S fox (j=i7j>=0;j--) printt ("sd") 17;
oc printi((4d", 7);
x
[Link] i;
iw }
for (1210;155;)
Give the functionality of the following loops given. printt("sd", 1);
1 int i=1, sum=0;
while Gicio) Find errors in the following codes.
4 1. #include <stdio.h>
sum ¢=i; main ()
f 5? {
} int i=1;
while (i<=10)
2. int i, sum=0; (
for (i=1l;i<=10) .
> : ted:
sum+=i;
DPEAnCtE ('Sd!, 1):

$3: int i; A Att;


for (is1;i<=10;i++) }
i--; - }
2. include <stdio.h>
4. int i-10; main ()
do {
[ pripteitsd’. 2: int i:
\ while (i>0) ; for (i=0,i<=10;i++)
Peintt ('sd", i);
5. int i=10; }
ae
{ printf ("sa", 4); 3. #include <stdio
he

} while (i<5); ee

6. int i=1, n=10, sum=0; oe ee


while (ic=n) p
{ : Prince cisd", i);
sum+=i; :
: ide:
while (i=10)
}

7, int i, sum=0; 4. #include <stdio.h>


for (1=1;;i++) main ()
sum+=i; {

105 1 4-
8. int i=10; for (i=1,4=0;14+5<=10;1+4)
while (i-->0) printl('20a' .1)%
printé( sd", i); j+=2;
}
- ANNEXURE2 ©

The typical meaning of ‘algorithm’ is a formally defined


procedure for performing some calculation. If a procedure
is formally defined, then it must be implemented using
some formal language, and such a language is often
known as a programming language. In general terms, an
algorithm provides a blueprint to write a program to solve
a particular problem. It is considered to be an effective
procedure for solving a problem in finite number of steps.
That is, a well-defined algorithm always provides an
answer and is guaranteed to terminate.
IF condition then process
Algorithms are mainly used to achieve software re-use.
Once we have an idea or a blueprint of a solution, we can A condition in this context is any statement that may
implement in any high level language like C, C++, Java, evaluate either to a true value or a false value. In the above
so on and so forth. example, a variable x can either be equal to y or not equal
An algorithm is basically a set of instructions that solve to y. However, it cannot be both true and false. If the
a problem. It is not uncommon to have multiple algorithms condition is true then the process is executed.
to tackle the same problem but the choice of a particular A decision statement can also be stated in the following
algorithm must depend on the time and space complexity manner:
of the algorithm. In this section, we will read how we can IF condition
analyse algorithms to determine which one is the most Then process1

efficient, but first let us look at few examples of algorithm. ELSE process2
This form is popularly known as the if-else construct.
Here, if the condition is true then process1 is executed
else process2 is executed. Look at Fig. A2.2 that shows
Any algorithm has a finite number of steps and some an algorithm to check if two numbers are equal.
steps may involve decision making, repetition. Broadly
speaking, an algorithm exhibits three key features that can
be given as:
e Sequence
e Decision
e Repetition

Sequence
Sequence means that each step of the algorithm is executed
in the specified order. Let us write an algorithm to add two
[Link]. Algorithm tot or equality of tw
numbers. This algorithm performs the steps in a purely numbers
sequential order. Refer Fig. A.2.1.

Decision Repetition
Decision statements are used when the outcome of the Repetition which involves executing one or more steps for
process depends on some condition. For example, ifx = y, a number of times can be implemented using constructs
then print “EQUAL”. So the general form of IF construct like the while, do-while, and for loops. These loops
can be given as: executed one or more steps until some condition is true.
108 | Introduction to C Programming

Figure A2.3 shows an algorithm that prints first 10 natural then PRINT A

Above75
|0
numbers. Step 4: IF M>=50 AND M<60
then PRINT B
Step 5: IF M>=40 AND M<50

(0 natural numbers — then PRINT C 50-60 iB


ZE] SETI = 0,
ELSE
PRINT D
40-50 0G Cc
Less than 40 ro
Step 6: END

Write an algorithm to find sum of first N natural numbers.


Step 4: END.
Step _i) Input N
t
Step 2: SET I = 0, SUM = 0
atiticy-veew Algorithm to print first 10 natural numbers Step 3: Repeat Steps 3 and 4 while I <=N
Step 4: SET SUM = SUM+I |
Ciagieeene ote
A2.3 SOME MORE ALGORITHMS Step 5: PRINT SUM
Step 6: END
Let us write some more algorithms i

Write an algorithm for interchanging/swapping two values.


A2.4 TIME AND SPACE COMPLEXITY OF
Step 1: Input first number as A
Step 2: Input second number as B
ALGORITHM 7
Step 3: SET TEMP =A To analyse an algorithm means determining the amount
Step 4: SET A=B
of resources (such as time and storage) needed to execute
Step) 5) SEL B= TEMP
it. Algorithms are generally designed to work with an
Step 6: PRINT A, B
arbitrary number of inputs, so the efficiency or complexity
Seep 7: END
of an algorithm is stated in terms of time complexity and
Write an algorithm to find larger of two numbers. space complexity.
Step 1: Input first number as A The time complexity of an algorithm is basically the
Step 2: Input second number as B running time of the program as a function of the input size.
Step, 3%) LE A>B On similar grounds, space complexity of an algorithm
then PRINT A
is the amount of computer memory required during the
ELSE
program execution, as a function of the input size.
IF A<B
In other words, the number of machine instructions
then PRINT B
which a program executes during its execution is called its
ELSE
PRINT “The numbers are equal”
time complexity. This number is primarily dependant on
Step 4: END the size of the program’s input and the algorithm used.
Generally, the space needed by a program depends on
Write an algorithm to find whether a number is even or
two main parts:
odd.
e Fixed part, that varies with problem to problem.
Step 1: Input the first number as A
Stepr 2: LB Az2 =0
It includes space needed for storing instructions,
Then Print “EVEN” constants, variables and structured variables (such
ELSE as arrays, structures).
PRINT “ODD” e Variable part, that varies from program to program.
Step 3: END It includes space needed for recursion stack and
Write an algorithm to print the grade obtained by a student for structured variables that are allocated space
using the following rules. dynamically during the run-time of the program.
Step 1: Enter the Marks obtained as M However, running time requirements are more critical
Step 2: IF M>75 than memory requirements. Therefore, do not worry much
then PRINT O about the memory requirement. In this section, we will thus
Step 3: IF M>=60 AND M<75 concentrate on running time efficiency of the algorithm.
Decision Control and Looping Statements | 109 |

Expressing Time and Space Complexity But, calculating efficiency is not as simple as given in the
example above. Consider the loop given below.
The time and space complexity can be expressed using a
for (1=0;1<100;1+=2)
function £ (n) where n is the input size for a given instance
statement block;
of the problem being solved. Expressing the complexity is
badly needed when: Here the number of iterations is just half the number of
the loop factor. So, here the efficiency can be given as
e We want to predict the rate of growth of complexity
as the size of the problem increases. £(n) = n/2

e When there are multiple algorithms that find a


Logarithmic Loops
solution to a given problem and we need to find the
algorithm that is most efficient. We have seen that in linear loops, the loop update either
adds or subtracts. However in logarithmic loops, the loop
The most widely used notation to express this function
controlling variable is either multiplied or divided during
f(n) iS Big Oh notation. The Big Oh notation
each iteration of the loop. For example, look at the loops
provides the upper bound for the complexity. given below.
fOr (a — Te 1 OOeis—2)) for (i=0;1<100;i/=2)
Algorithm Efficiency statement block; statement block;

If a function is linear (without any loops or recursions), If we consider the first for loop in which the loop
the efficiency of that algorithm or the running time of that controlling variable i is multiplied by 2 after each
algorithm can be given as the number of instructions it iteration of the loop, the loop will be executed only 10
contains. However, if an algorithm contains certain loops times and not 100 times. Therefore, putting this analysis in
or recursive functions then the efficiency of that algorithm general terms, we can conclude that the iterations in loops
may vary depending on the number of loops and the that divides/multiplies the loop controlling variables, the
running time of each loop in the algorithm. The efficiency efficiency can be given as
of an algorithm is expressed in terms of the number of i (n=) log en
elements that has to be processed. So, ifn is the number of
elements, then the efficiency can be stated as Nested Loops
f(n) = efficiency Loops that contain loops are known as nested loops. In
order to analyse nested loops, we need to determine the
Let us consider different cases in which loops determine
number of iterations each loop completes. The total is then
the efficiency of the algorithm.
obtained as the product of the number of iterations in the
Linear Loops inner loop and in the outer loop.
Total no. of iterations = no. of iterations
To calculate the efficiency of an algorithm that has a single
in inner loop * no. of iterations in
loop, we need to first determine the number of times the
outer loop
statements in the loop will be executed. This is because
the number of iterations is directly proportional to the In case of nested loops, we will analyse the efficiency
loop factor. Higher the loop factor more is the number of of the algorithm based on whether it’s a linear logarithmic,
iterations. For example, consider the loop given below. quadratic or dependent quadratic nested loop.

for (i=0;1<100;1i++) Linear Logarithmic


statement block;
Consider the code given below in which the loop controlling
Here 100 is the loop factor. We have said above that variable of the inner loop is multiplied after each iteration.
efficiency is directly proportional to the number of The number of iterations in the inner loop is log 10. This
iterations. Hence the general formula in case of linear inner loop is controlled by an outer loop which iterates 10
loops may be given as times. Therefore, according to the formula, the number of
iei((igi))) Gal iterations for this code can be given as
OP OG= 0
|110 | Introduction to C Programming

for(i=0
7i<1 10) 4+) the inner loop is dependent on the outer loop. Consider the
FOL alee a LO; min) code given below which shows such an example.
statement block;
for (i=0;1<10;1i++)
Talking in more general terms, the efficiency of such loops for (j=1; j<i;j++)
can be given as f(n) = n log n. statement block;

Quadratic Loop In this code, the inner loop will execute just once in the
first iteration, twice in the second iteration, thrice in the
In a quadratic loop, the number of iterations in the inner
third iteration, so on and so forth. In this way the number
loop is equal to that in the outer loop. Consider the code
of iterations can be calculated as, ‘
given below in which the outer loop executes 10 times
and for each iteration of the outer loop, the inner loop also 1 +2 +4 3. + 4 +9e5)4req 9+; LOH 55

executes 10 times. Therefore, the efficiency here is 100. If we calculate the average of this loop (55/10 = 5.5), we
for (1=0;1<10;1i++) will observe that it is equal to the number of iterations in
Form (Gais) sh
0) aa) the outer loop (10) plus 1 divided by 2. In general terms,
statement block;
the inner loop iterates (n + 1) /2 times. Therefore, the
The generalized formula for quadratic loop can be given efficiency of such a code (number of iterations in inner
as,f(n) = n?. loop * no. of iterations in outer loop) can be given as
12(Gq) = sah (Ga) 23) ah) e/2
Dependent Quadratic
In a dependent quadratic loop, the number of iterations in
Case Study
for Chapters 2 and 3

We have learnt the basics of programming in C language


and the concepts to write decision-making programs, let
us now apply our learning to write some useful programs.

Roman numerals are written as combinations of the seven | o |cM |


letters. These letters include: XXIII | 80 ee)

: xxIV |90| MDC_|

1. Write a program to show the Roman number


representation of a given number.
If smaller numbers follow larger numbers, the numbers
are added. Otherwise, if a smaller number precedes a #include <stdio.h>
larger number, the smaller number is subtracted from the #include <conio.h>
main ()
larger. For example, to convert 1,100 in Roman numerals,
you would write M for 1000 and then a C after it for 100.
{
int number;
Therefore, 1100 = MC in Roman numerals. Some more
int ones, tens, hundreds, thousand;
examples include: (eulsetsyele
(())9
e Vil =5+2=7 print£("\n Enter any number (1-3000):
");
e IX=10-1=9 scanf ("%d", &number) ;
if (number==0 | | number>3000)
e XL=50-10 = 40 printf ("\n INVALID NUMBER") ;
e CX= 100+10
= 111 thousand = number/1000;
e MCMLXXXIV = 1000+(1000-100)+50+30+(5-1) = 1984 hundreds = ((number/100) %10) ;
tens = ((number/10)
$10) ;
Roman Numeral Table ones = ((number/1) $10) ;

(et ean 14 ae ((elaveybleretave! Sul)

reff Pr [afo print ("NM")


|3 |16 else if (thousand ==2)
|112 |_Introduction to C Programming

printf ("MM") ; else if (ones == 6)


else if (thousand ==3) joreuuoere (Myr) §
printf ("MMM") ; else if (ones == 7)
fonealiokous (UAYArIe)) &
if (hundreds == 1) else if (ones ==8)
joreauiajeae (UIE) 5 jonealigtene (UhyAraae!)))
else if (hundreds == 2) else if (ones == 9)
jopentiahene (MEE) & jonaaloatese (WIDE
else if (hundreds == 3) getch();
jopethajene, (UKelClen))) 5
;
else if (hundreds == 4)
jopeshalers (WED)
Output
else if (hundreds ==5) Enter any number (1-3000): 139
jorerhatese (MDM) 5 CXXXIX
else if (hundreds == 6)
TORaULIGNEEE ((VBYSU)
else if (hundreds == 7) Program
to Find the Day of agiven Date _
jeiesayere (WDCC) 5
Given below is an algorithm to calculate the day of the
else if (hundreds ==8)
week:
prance ("DECEM)i;
else if (hundreds == 9) 1. Centuries: Use the centuries table given below to
jonaueatene
(MYG MM) e calculate the century.

Centuries table

if (tens == 1)
jorg:ahena((W<W)) ©
else if (tens == 2)
jOne tMeae(MDOKD) 6 0
else if (tens == 3) 6
jokesliohens ((Ubo.o.<))
4
else if (tens == 4)
2
jovaubalese
(Ub di) oF
else if (tens ==5) 0
jorentionene ((Wit)))) 5 6
else if (tens == 6)
4
jouanuiglese (Vitp,<U)
2
else if (tens == 7)
joucalintese (([Link]))
else if (tens ==8) 2. Years: We know that there are 365 days in a year, that
jorealimese (Mi,;O%0)) 5 is, 52 weeks plus 1 day. Each year starts on the day of
else if (tens == 9) the week after that starting the preceding year. Each
jorensanese (Ue) g leap year has one more day than a common year.
If we know on which day a century starts (from
if (ones == 1)
above), and we add the number of years elapsed
jonanbiatese (Ward).
since the start of the century, plus the number
else if (ones == 2)
of leap years that have elapsed since the start of
jorcabionese
((/aeIc!))
else if (ones == 3)
the century, we get the day of the week on which
joreutiajese
(VYIieI") p the year starts. Where year is the last two digits of
else if (ones == 4) the year.
jopenimeie (Many) 9 3. Months: Use the months table to find the day of the
else if (ones ==5) week a month starts.
jopentignere (Why) &
Case Study for Chapters 2 and 3 113 |
Months table 2. Write a program to find out the day for a given date.
January 1 (in leap year 6) #include <stdio.h>

February 4 (in leap year 2) #include <stdlib.h>


#include <conio.h>
March 4 main ()

April 0 {
. A int dd,mm,yy,year,month, day,i,n;
ay Gilsecrere() 3
June 5 printf("\n Enter the date: ");
ge 6 Xs scanf("%d %d %d", &dd, &mm, &yy) ;
if( dd>31 || mm>12)
August 3 {
September 6 print£(" INVALID INPUT ") ;
getch();
October al exit (0);

November 4 }

December 6 Acasa Ma
year = year/4;
year = year+yy-1900;
4. Day of the month: Once we know on which day of switch (mm)
the week the month starts, we simply add the day of {
the month to find the final result. case 1:
Casemuor
Days table month = 1;
Sunday break;
CASS 2s
NOSEICGNY) Cas emor:
Tuesday Caseman:

Wednesday month = 4;

Thursday gag)
Case 7/2
Friday case 4:

Saturday month =" OF-


break;

Let us calculate the day of April 24, 1982. Ce oea


month 2.
1. Find the century value of 1900s from the centuries break;
table: 0 case 6:
2. Last two digits give the value of year: 82 month = 5;
3. Divide the 82 by 4: 82/4 = 20.5 and drop the fractional SEeCela
Cases:
part: 20
MONE emo
4. Find the value of April in the months table: 0 ioeeaiee
5. Add all numbers from steps 1-4 to the day of the case 9:
month (in this case, 24): 0+82+20+6+24=132. case 12:
6. Divide the result of step 5 by 7 and find the remainder: month = 6;
132/7=18 remainder 6. break;
7. Look up the days table for the remainder obtained. }
year = year+month;
6=Friday.
year = year+dd;
That the values in the centuries table, months table, and day = years7;
days table are pre-determined. We will only be using switch (day)
them to calculate the day of a particular date.
|114 [Link] to C Programming

{ printf ("\n WEDNESDAY") ;


case 0: break;
// Since 7%7 = 0, case 0 means it’s case "5:
a Saturday pLinté (\n THURSDAY");
printf("\n SATURDAY"); break;
break; case 6:
Gas ema: piste (Nn ERT DAY)
printf ("\n SUNDAY") ; break;
break; }
GAGE Ze getch() ; :
printf ("\n MONDAY") ; return 10
break; }
case 3:
prints Cn TUESDAY") Output
break; Enter the date: 29 10 1981
case 4: THURSDAY
CHAPTER

Functions
®

Takeaways
_¢@ Function Declaration
© Call-by-Value and Call-by-Referen
a .

call the same function multiple times until the condition


holds true.
C enables programmers to break up a program into
segments commonly known as functions, each of which
can be written more or less independently of the others.
Every function in the program is supposed to perform a
well-defined task. Therefore, the program code of one
function is completely insulated from the other functions.
Every function interfaces to the outside world in terms
of how information is transferred to it and how results
generated by the function are transmitted back from it. This
interface is basically specified by the function name. For Figure 4.1
example, look at Fig. 4.1 which explains how the main ()
calls another function to perform a well-defined task. Another point is that it is not only the main() that
From the figure we see that main() calls the function can call other functions. A function can call any other
named funcl (). Therefore, main () is knownas the calling function. For example, look at Fig. 4.2 which shows one
function and func1() is known as the called function. The function calling another, and this function in turn calling
moment the compiler encounters a function call, instead of some other function. From this we see that every function
executing the next statement in the calling function, the encapsulates a set of operations and when called it returns
control jumps to the statements that are a part of the called information to the calling program.
function. After the called function is executed, the control
is returned back to the calling program.
It is not necessary that the main() can call only one 4.1.1 Why are Functions Needed?
function, it can call as many functions as it wants and as Let us analyse the reasons for segmenting a program
many times as it wants. For example, a function call placed into manageable chunks as it is an important aspect to
within a for loop, while loop, or do-while loop may programming.
|116 | Introduction to C Programming

-feburn; reuurn;

Figure 4.2 i ing another function

e Dividing the program into separate well-defined working on that project can divide the workload by
functions facilitates each function to be written writing different functions.
and tested separately. This simplifies the process of e Like C libraries, programmers can also write their
getting the total program to work. Figure 4.3 shows functions and use them from different points in the
that the main() calls other functions for dividing the main program or any other program that needs its
entire code into smaller sections (or functions). This functionalities.
approach is referred to as the top-down approach.
Consider a program that executes a set of instructions
repeatedly n times, though not continuously. In case the
_ Main function instructions had to be repeated continuously for n times,
they can better be placed within a loop. But if these
instructions have to be executed abruptly from anywhere
FunctionA within the program code, then instead of writing these
instructions wherever they are required, a better idea is to
place these instructions in a function and call that function
wherever required. Figure 4.4 explains this concept.

Figure 4.3 Miryzeluiy approach ofsolving aproblem

e Understanding, coding, and testing multiple separate


functions are far easier than doing the same for one
huge function.
e Ifa big program has to be developed without the use
of any function other than main (), then there will be
countless lines in the main() and maintaining this -veturn 0;
program will be very difficult. A large program size
is a Serious issue in micro-computers where memory
space is limited. art a-wa Function funci()called twice from main()
e All the libraries in C contain a set of functions that
the programmers are free to use in their programs.
These functions have been pre-written and pre- 4.2 USING FUNCTIONS
tested, so the programmers can use them without
In the first chapter we have said that when we execute a C
worrying about their code details. This speeds up
program, the operating system calls the main () function of
program development, by allowing the programmer
to concentrate only on the code that he has to write. the program which marks the entry point for the execution.
When the program is executed, the main() returns some
e When a big program is broken into comparatively
value to the operating system.
smaller functions, then different programmers
Functions | 117 |

Any function (including main) can be compared to Every function must have a different name that indicates
a black box that takes in input, processes it, and then the particular job that the function does.
produces the result. However, we may also have a function return _data_ type specifies the data type of the value
that does not take any inputs at all, or the one that does not that will be returned to the calling function as a result of
return anything at all. the processing performed by the called function.
While using functions we will be using the following data_type variablel, data type variable2,

terminologies: is a list of variables of specified data types. These variables


are passed from the calling function to the called function.
e A function f that uses another function g, is known
They are also known as arguments or parameters that the
as the calling function and g is known as the called
called function accepts to perform its task. Table 4.1 shows
function. ‘
examples of valid function declarations in C.
e The inputs that the function takes are known as
arguments/parameters. ble 4 : | Valid function declarations
e When a called function returns some result back to
the calling function, it is Said to return that result. - Function Declaration _ Use of the Function |
Converts a character to upper case.
e The calling function may or may not pass parameters
The function receives a character as
to the called function. If the called function accepts Return data type an argument, converts it into upper
arguments, the calling function will pass parameters, case and returns the converted
else it will not do so. char convert_to_ character back to the calling
e Function declaration is a declaration statement that uppercase (char ch); program.
identifies a function with its name, a list of arguments Calculates average of two numbers
Function name aand b received as arguments. The
that it accepts, and the type of data it returns.
function returns a floating point
e Function definition consists of a function header float avg (int a, int b); value.
that identifies the function, followed by the body of int find_largest (int Finds the largest of three
the function containing the executable code for that a, int b, int c); numbers—a, b, and c received as
function. arguments. An integer value which

DECLARATION/
Data type of is the largest of the three numbers
variable is returned to the calling function.
double multiply Multiplies two floating point
(float a, float b); numbers a and b that are received
as arguments and returns a
Before using the function, the compiler must know about js Variable 1
double value.
the number of parameters and type of parameters that void swap Swaps or interchanges the value of
the function expects to receive and the data type of the (int a, int b); integer variables a and b received
value that it will return to the calling program. Placing as arguments. The function returns
the function declaration statement prior to its use enables no value, therefore the data type is
the compiler to make a check on the arguments used while void.
calling that function. void print(void); The function is used to print
The general format for declaring a function that accepts information on screen. The
some arguments and returns some value as a result can be function neither accepts any
given as: value as argument nor returns
any value. Therefore, the return
return_data_type function_name(data_type
type is void and the argument list
variablel, data_type variable2,...)j; contains void data type.
Here, function name is a valid name for the function.
Things to remember about function declaration
Naming a function follows the same rules as naming
variables. A function should have a meaningful name that e After the declaration of every function, there should
must clarify the task that the function will perform. The be a semicolon. If the semicolon is missing, the
function name is used to call it for execution in a program. compiler will generate an error message.
|118 | Introduction to C Programming

e The function is declaration global. Therefore, the


declared function can be called from any point in the
program.
e Use of argument names in the return( variable) ;
Programming Tip: . ;
Though optional, function declaration statement
Wee areurment names : : :
is optional. So both declaratio n The number of arguments and
inthe funchon _ statements are valid in C. Programming Tip: the order of arguments in the
The parameter function header must be same
declaration. rr (int, char, float); list in the function as that given in the function
definition as well as declaration statement.
or function declaration | While return data_ type
int func(int num, char ch, float fnum); must match. function name(data_ type
e A function cannot be declared within the body of variablel,
data _ type variable2,..)
another function. is known as the function header, the rest of the portion
e A function having void as its return type cannot comprising of program statements within { } is the function
return any value. body which contains the code to perform the specific task.
The function header is same as that of function
e A function having void as its parameter list cannot
declaration. The only difference between the two is that
accept any value. So the function declared as
a function header is not followed by a semicolon. The
void print (void) ;
list of variables in the function header is known as the
or formal parameter list. The parameter list may have zero
void print() or more parameters of any data type. The function body
contains instructions to perform the desired computation
does not accept any input/arguments from the calling in a function.
function. Programming Tip: The function definition itself
e If the function declaration does not specify any A function can can act as an implicit function
return type, then by default, the function returns an bedefinedeither = declaration. So the programmer
integer value. Therefore when a function is declared before or afterthe = may skip the function declaration
as main(). ' statement in case the function is
sum(int a, int b); defined before being used.
then the function sum accepts two integer values
Notes _ The argument names in the function
from the calling function and in turn returns an
declaration and function definition need —
integer value to the caller.
not be the same. However, the data types
e Some compilers make it compulsory to declare of the arguments must match with that
the function before its usage while other compilers specified in function declarat tion as well
make it optional. However, it is good to always as function definition.
declare the function before its usage as it allows
error checking on the arguments in the function call.
4.5 FUNCTION CALL
4.4 FUNCTION DEFINITION The function call statement invokes the function. When
a function is invoked the compiler jumps to the called
When a function is defined, space is allocated for that
function to execute the statements that are a part of that
function in the memory. A function
Programming Tip: ae : function. Once the called function is executed, the program
8 aug definition comprises two parts:
It is an error to control passes back to the calling function.
place a semicolon ~ e Function header Function call statement has the following syntax:
after the function e Function body
function name(variablel,
variable2, ...);
header in the The syntax of a function defini-
function definition. When the function declaration is present before the
tion can be given as:
function call, the compiler can check if the correct number
return _data_type function_name(data_type and type of arguments are used in the function call and the
variablel, data_type variable2,...) returned value, if any, is being used reasonably.
Functions | 119 |

Function definitions are often placed in a separate If the return type of the function is not void, then the
header file which can be included in other C source files value returned by the called function may be assigned
that wish to use the functions. For example, the header to some variable as shown in the following statement.
file stdio.h contains the definition of scanf and printf variable name = function name(variablel,
functions. We simply include this header file and call these variable2, ...);
functions without worrying about the code to implement
Let us now try writing a program using function.
their functionality.
4.1 Write a program to add two integers using functions.
Note, List of va ri blesused in function cal #include <stdio.h>
// FUNCTION DECLARATION

actual bararneter list may sehtein probe rine, Siuhiu(stidhe Ely sighs, lop)
— names, expressions, or constants. int main()
{
int numl, num2, total = 0;
4.5.1 Points to Remember While Calling a printf ("\n Enter the first number: ");
scanf ("$d", &num1) ;
Function
printf ("\n Enter the second number: ");
The following points are to be kept in mind while calling scanf ("%d", &num2) ;
a function: total = sum(numl1, num2);
// FUNCTION CALL
e Function name and the number and type of arguments
jonaaliahone (U\wal nojerall Ee Exol tcoyee\it))
in the function call must be same giebhag, {0)F
as that given in the function }
declaration and function header
// FUNCTION DEFINITION
of the function definition.
Haale, Sy (alae EY, sale. 15) // FUNCTION HEADER
elf by mistake the parameters { // FUNCTION BODY

passed to a function are more int result;


resulle =a + bi
than what it is specified to return result;
accept then the extra arguments }
will be discarded.
Output
e If by mistake the parameters passed to a function
Enter the first number: 20
are less than what it is specified to accept then the Enter the second number: 30
unmatched argument will be initialized to some ioe dl w= SC

garbage value. The variables declared within


e Names (and not the types) of variables in function Programming Tip: the function and its parameters
declaration, function call, and header of function It is an error to use are local to that function. The
definition may vary. "void as the return—
programmer may use same names
_ type when the
e Ifthe data type of the argument passed does not match _ for variables in other functions.
with that specified in the function declaration then This eliminates the need for
either the unmatched argument will be initialized to _| thinking and keeping unique
some garbage value or compile time error will be names for variables declared in
generated. all the functions in the program.
e Arguments may be passed in the form of expressions In the function sum(), we have declared a variable result
to the called function. In such cases, arguments are just like any other variable. Variables declared within a
first evaluated and converted to the type of formal function are called automatic local variables because of
parameter and then the body of the function gets two reasons.

executed. First, they are local to the function. So, their effect
e The parameter list must be separated with commas. (in terms of scope, lifetime, or accessibility) is
|120 | Introduction to C Programming —_

limited to the function. Any change made to these A function may have more than one return statement. For
variables is visible only in that function. example, consider the program
e Second, they are automatically created whenever the Programming Tip: given below.
function is called and they cease to exist at the end When the value
#include <stdio.h>
of the function. returned by a #include <conio.h>
function is assigned int check relation(int a,
Notey A function cannot be used on the left side to a variable, then Tc Jee
of an assignment statement. Therefore the returned value // FUNCTION DECLARATION

is converted to the main ()


writing, func(10) = 100; is invalid in
C, where func is a function that accepts an type of the variable ‘
int a=3, b=5, res;
integer value. receiving it.
elrser()::
res = check relation(a, b);
// FUNCTION CALL
4.6 return STATEMENT if (res==0) // Test the returned value
printf ("\n EQUAL") ;
The return statement is used to terminate the execution
if (res==1)
of a function and returns control to the calling function. printf("\n a is greater thar b");
When the return statement is encountered, the program if (res==-1)
execution resumes in the calling function at the point im- prinké("\n a as, less than b=
mediately following the function call. Refer Fig. 4.2 in getch
() ;
which the control passes from the return 0;
Programming Tip: called function to the calling }
It is an error to use function when the return state- ame check xelation (int ia,
a return statement Programming Tip: int b)
ment is encountered.
ee ie | Aveturn statement may or may An error is // FUNCTION DEFINITION
has void as its ' generated when dq
/ not return a value to the calling
ee leg | function. The syntax of return
thefunctiondoes = if (a==b)
not return dataof i cae a
statement can be given as
the specified type rete
return <expression>;
else if (a<b)
Here expression is placed in between angular brackets return =
because specifying an expression is optional. The value of }
expression, if present, is returned to the calling function.
Output
However, in case expression 1s omitted, the return value
a is less than b
of the function is undefined.
The expression, if present, is converted to the type In the above program there are multiple return state-
returned by the function. A function that has void as ments, but only one of them will get executed depending
its return type cannot return any value to the calling upon the condition. The return statement, like the break
function. So a function that has been declared with return statement, is used to cause a premature termination of the
type void, a return statement containing an expression
function.
generates a warning and the expression 1s not evaluated.
An expression appearing in a return statement is
For functions that have no return statement, the
converted to the return type of the function in which
control automatically returns to the calling function after
the last statement of the called function is executed. In the statement appears. If no
other words an implicit return takes place upon completion Programming Tip: implicit conversion is possible,
A function that the return statement is invalid.
of the last statement of the called function, and control
does not return Since the return type of the
automatically returns to the calling function.
any value cannot
function check_relation() is
Notey |The programmer may or may not place be placed on ; :
the Ment side of _ int, so the result either 0, 1, or
the expression in a return statement the assignment _ -1 1s evaluated as an integer.
within parentheses angular brackets.
operator. We have mentioned earlier that
By default, the return type of a function
the variables declared inside
iS int.
Functions 121 |

the function cease to exist after the last statement of the If the called function is supposed to modify the value of
function is executed. So how can we return the value the parameters passed to it, then the change will be re-
of sum in the program that adds two integers using a flected only in the called func-
function? The answer to this question is that a copy of the tion. In the calling function no
value being returned is made automatically and this copy i es :'P: change will be made to the value
is available to the return point in the program. a - ae of the variables. This is because
U
: C |all the changes were made to the
statements in
copy of the variables and not on
4.6.1 Using Variable Number of Arguments
the actual variables.
Some functions have a variable number of arguments To understand this concept, consider the code given
and data types that cannot be known at the compile time. below. The function add() accepts an integer variable
Typical examples of such functions include the print () num and adds 10 to it. In the calling function, the value of
and scanf() functions. ANSI C offers a symbol called
num = 2. In add(), the value of num is modified to 20 but
ellipsis to handle such functions. The ellipsis consists of
in the calling function the change is not reflected.
three periods (...). It can be used as
Hm! funeecharwehiiv 2); #include <stdio.h>
void add(int n); // FUNCTION DECLARATION
The function declaration statement given above states
int main ()
that func is a function that has an arbitrary number and
type of argument. However, one must ensure that both the {
stale sale De
function declaration and function definition should use the
ellipsis symbol.
printf ("\n The value of num before
calling the function = %d", num);

4.7. PASSING PARAMETERS 10 THE add (num) ; // FUNCTION CALL

FUNCTION printf ("\n The value of num after calling


the function = %d", num);
When a function is called, the calling function may have
return 0;
to pass some values to the called function. We have been
doing this in the programming examples given so far.
We will now learn the technicalities involved in passing
void add(int n) // FUNCTION DEFINITION
arguments/parameters to the called function.
Basically, there are two ways in which arguments or {
parameters can be passed to the called function. They may E> ay es “al Oye

include: printf ("\n The value of num in the called


function! = sd) mn)
e Call by value in which values of the variables are
passed by the calling function to the called function. }
The programs that we have written so far all call
Output
the function using call by value method of passing
The value of num before calling the function = 2
parameters.
The value of num in the called function = 20
e Call by reference in which address of the variables
The value of num after calling the function = 2
are passed by the calling function to the called
function. Since the called function uses a copy of num, the value
of num in the calling function remains untouched. This
4.7.1 Call by Value concept can be more clearly understood from Fig. 4.5.
In the above program, the called function could not
Till now, we had been calling functions and passing
directly modify the value of the argument that was
arguments to them using call by value method. In the call-
passed to it. In case the value has to be changed, then the
by-value method, the called function creates new variables programmer may use the return statement. This is shown
to store the value of the arguments passed to it. Therefore, in the following code.
the called function uses a copy of the actual arguments to
#include <stdio.h>
perform its intended task. ime Tada (elateem)is; // FUNCTION DECLARATION
|122 [ Introduction to C Programming

int main() e When the called function does not modify the value
{ of the actual parameter. It simply uses the value of
He Ml SS By
the parameters to perform its task.
printf("\n The value of num before
calling the function = %d", num); e When you want that the called function should only
num = add(num); // FUNCTION CALL temporarily modify the value of the variables and
printf ("\n The value of num after calling not permanently. So although the called function
the function = %d", num); may modify the value of the variables, but these
reEWUEN OF,
variables remain unchanged in the calling program.
} \

int add(int n) // FUNCTION DEFINITION Pros and Cons


{ The pBeese ‘uak of using call by value technique
Ty Serie Ol
to pass arguments to the called
printf ("\n The value of num in the called
function) = sil ani)r
function is that arguments can be
variables (e.g., x), literals (e.g.,
return n;
ae ofpassing
} values must be 6), or expressions (e.g., x+1).

Output -preferredto The disadvantage is that copying

The value of num before calling the function = 2


_avoidinadvertent data consumes additional storage
The value of num in the called function = 12
_ changesto space. In addition, it can take
The value of num after calling the function = 12 variablesofthe = q_ lot of time to copy, thereby
_ calling function " 1 resulting in performance penalty,
the called functi
especially if the function is called
many times.

num in the calling function num in the calling function, 4.7.2 Call by Reference
is known as ninthe
called function When the calling function passes arguments to the called
function using call by value method, the only way to
return the modified value of the argument to the caller is
explicitly using the return statement. The better option
num in the calling function nis modified in the when a function wants to modify the value of the argument
remains unchanged called function is to pass arguments using call-by-reference technique.
Figure 4.5 /Call-by-value method ofargument passing - In call by reference, we declare the function parameters
as references rather than normal variables. When this is
done any changes made by the function to the arguments
The following points are to be noted while passing
arguments to a function using call-by-value method. it receives are visible to the calling program.
To indicate that an argument is passed using call by
e When arguments are passed by value, the called
reference, an ampersand sign (&) is placed after the
function creates new variables of the same data type
as the arguments passed to it. type in the parameter list. This way, changes made to the
e The values of the arguments passed by the function parameter in the called function body will then be reflected
are copied into the newly created variables. in its value in the calling program.
e Arguments are called by value when the function Hence, in call-by-reference method, a function receives
does not need to modify the values of the original an implicit reference to the argument, rather than a copy of
variables in the calling program. its value. Therefore, the function can modify the value of
e Values of the variables in the calling functions remain the variable and that change will be reflected in the calling
unaffected when the arguments are passed using call function as well. The following program uses this concept.
by value technique. To understand this concept, consider the code given below.
Therefore, call by value method of passing arguments #include <stdio.h>
to a function must be used only in two cases: void add (int *n);
Functions | 123 |
int main() swap_call
by ref (&c, &d) ;
{ // address of the variables is passed
int num = 2;
printf ("\n In main(), c = $d and d =
printf ("\n The value of num before
oll,
Gp Cl) p
calling the function = $d", num);
return 0;
add (&num) ;
printf ("\n The value of num after calling
}
void swap_call
by val(int a, int b)
the function = %d", num) ;
return 0;
{
int temp;
} temp = a;
void add( int *n) eh = JO 6

{ lo) & ieee


[sigh 3, waa Hs SL@)e printf ("\n In function (Call By Value
printf("\n The value of num in the called Method) a = %d and b = %d", a, b);
functaon = +d",
n) ; }
} void swap_call
by ref(int *c, int *d)

Output
{
int temp;
The value of num before calling the function = 2 Eempe=—aCr
The value o£ num in the called function = 20 // *operator used to refer to the value
The value of num after calling the function = 20
mae) => etehe
*d = temp;
Pros and Cons printf ("\n In function (Call By Reference
The advantages of using call-by-reference technique of Method) c = %d and d = %d",
*c, *d);
passing arguments are as follows: }
e Since arguments are not copied into new variables, it Output
provides greater time- and space-efficiency. in main ()), a = 1 and b= 92
e The function can change the value of the argument In function (Call By Value Method) a = 2
and the change is reflected in the caller. anGebi =e

e A function can return only one value. In case we InemaLrn (|, ta-= 1) and be= 92

need to return multiple values, pass those arguments


in main (eva s3 and id y= "4
by reference so that modified values are visible in
In function (Call By Reference Method) c
the calling function.
= vl eharel Gla 2)
However, the side-effect of using this technique is that tial iVeabon)), 2 = 2) siecl clio 2
when an argument is passed using call by address, it
becomes difficult to tell whether that argument is meant 4.3 Write a program to find biggest of three integers using
for input, output, or both. functions.
Now let us write a few programs that use the call-by- #include <stdio.h>
value and the call-by-reference mechanisms. int greater(int a, int b, int c);

4.2 Write a function to swap the value of two variables. int main()
#include <stdio.h> {
void swap_call by val (int, int) ; int numl1, num2, num3, large;

void swap call by ref (int *, int *);


main () printf ("\n Enter the first number: ") ;

{ scanf ("Sd", S&num1);

diate Ali, lo=e, Ces, Ce“ printf ("\n Enter the second number: ");
printf ("\n In main(), a = %d and b = %d", scanf("Sd", &num2) ;
printf("\n Enter the third number: ");
a,b);
swap _call by val(a, b); scanf("%$d", &num3);

printf ("\n In main(), a = %d and b = %d",


large = greater(num1,
num2, num3) ;
a, b)e¢
printf ("\n Largest number = %d", large);
printf ("\n\n In main(), c = *d and d =
BEEULhS OF
LIC,
Cy C))-5
|124 | Introduction to C Programming

} print£("\n Total minutes = %d", total_


mins) ;
intyqneakemnGnt al) satay ba ater) getch
() ;
{ return 0;
if(a>b && a>c)
return a;
if (b>a && b>c)
int convert _time_in_mins(int hrs, int minutes)
return b;
else
int mins;
1akebhaiay (ep
mins = hrs*60 + minutes; t
}
return mins;
Output }
Enter the first number : 45
Output
Enter the second number: 23
Enter the third number : 34 Enter the hours and minutes: 4 30
Largest number = 45 Total minutes = 270
.
4.4 Write a program to calculate area of a circle using 4.6 Write a program to calculate P(n/r).
function. #include <stdio.h>
#include <stdio.h> #include <conio.h>
float cal area(float r)j; int Fact (int) ;
main ()
int main()
{
{ nah 19 fee
float area, radius;
float result;
printf("\n Enter the radius of the
elrser();
CLECLe aU)
printf ("\n Enter the value of n: ");
scant ("S£", &radius) ;
area = Cal area (radius) ; scanf("%d", &n);
printf ("\n Area of the circle with radius printf ("\n Enter the value of r: ");
it ES ely radius, area); Scant (Usd Sx)
return 0; result = (float)
Fact (n) /Fact (nr) ;
} print£ ("\n Pi(n/r) > Psd) (<a) Set Aen,
float cal _area(float radius) Yr, result);
{ getch();
return (3.14 * radius * radius); return 0;
} }
Output int Fact (int num)

Enter the radius of the circle: 7 {


Area of the circle with radius 7 = 153.83 Int c=.

for (i=num; i>=1;i--)


4.5 Write a program to convert time to minutes.
#include <stdio.h> fcs fi.
#include <conio.h> return f;
int convert _time_in mins(int hrs, int
minutes) ;
}
main () Output
{ Enter the value of n: 4
int hrs, minutes,
total mins;
Enter the value of r: 2
printf("\n Enter hours and minutes: ");
Bi(n/ 3s) Pdi2)' 73) = 125.00
scanf("%d $d", &hrs, &minutes) ;
total_mins = convert _time_in mins(hrs, 4.7 Write a program to calculate C(n/r).
minutes) ;
#include <stdio.h>
Functions | 125 |
#include <conio.h> Output
int Fact (int) ;
See Enter the Gore Che ele 2
Th e sum 0 f th e€ series WAY M sy L/2)! 173!Voces eS
ke

ale: iq, 7c :
4.9 Write a program to sum the series—1/1!
/ ! + 4/2! ! +
float result; '
alee DS ae
printf ("\n Enter the value of n: "); #include <stdio.h>
scanf ("%d", &n); #include <conio.h>
printf ("\n Enter the value of r: "); #include <math.h>
scanf ("$d", &r); int Fact (int) ;
result = (float) Fact (n) / (Fact (r) *Fact (n-r)); main ()
joxcrtiqiese (Ter eGayse) 5 el(Eel/EXc)) S epee se ay {
GE, result) ; int n, i, NUM, DENO;
getch () ; float sum=0.0;
return 0; Gulsasyexe
(())
} printé ("\ni") 4
int Fact (int num) , scanf ("%d", &n) ;
{ for (1=1;i<=n;i++)
clighe és S17 {
for (i=num;i>=1;i--)
f = £*i; NUM = pow(i,1);
return f;
} DENO = Fact (i);

Output sum += (float) NUM/DENO;


Enter the value of n: 4 }
REE TOCnn laatoraa he prince (Nm W/W 45/2 e/a ee
C(n/r): C(12)/(3) = 6.00 sf", sum);
getch();
4.8 Write a program to sum the series—1/1! + 1/2! + 1/3! return 0;
Pi i/o! }
Tne ehacie (anateeen\)
#include <stdio.h> {
#include <conio.h> int f=1, i;
aahe, IeKele (Glial) p for (i=n;i>=1;i--)
main ()
{ (Spe ral
SOONG. cal) pecans ely return f;
float result=0.0; }
clrser();
printf("\n Enter the value of n: "); Output
scant (0sd", an) Enter the value of n: 2
for (i=1;i<=n;i++) Wits Cy ee genes ea
{
f=Fact (i);
result += 1/ (float) f; 4.8 7 SCOPE OF VARIABLES

princes necnessumof the series 17 li i+ In C, all constants and variables have a defined scope.
1/2! + 1/3!... = %£", result); By scope we mean the accessibility and visibility of the
getch(); variables at different points in the program. A variable or a
return 0; constant in C has four types of scope: block, function, file,

int Fact (int num) and program scope.


{
int f=1, 1; 4.8.1 Block Scope
for (i1=num;i>=1;i--)
We have studied that a statement block is a group of
2 para niet statements enclosed within opening and closing curly
} brackets ({ }). Ifa variable is declared within a statement
block then, as soon as the control exits that block, the
|126 |_Introduction to C Programming

variable will cease to exist. Such a variable also known as Hence, we can conclude two things:
a local variable is said to have a block scope. e Variables declared with same names as those in
So far we had been using local variables. For example, outer block mask the outer block variables while
Programming Tip: if we declare an integer x inside a executing the inner block.
tis an error to function, then that variable is e Innested blocks, variables declared outside the inner
use the name ofa unknown to the rest of the blocks are accessible to the nested blocks, provided
function argument program outside (i.e., outside these variables are not re-declared within the inner
as the name ofa ' that function). block.

=
local variable.
| Blocks of. statements may be
In order to avoid error, a programmer
placed one after the other in a must prefer to use different names for __
program; such blocks that are placed at the same level are variables not common to inner as well
as_-
known as parallel blocks. However, a program may also outer blocks. a
contain a nested block, like a while loop inside main().
If an integer x is declared and initialized in the main(),
and then re-declared and re-initialized in the while loop, 4.8.2 Function Scope :
then the integer variable x will occupy different memory Function scope indicates that a variable is active and
slots and will be considered as different variables. The visible from the beginning to the end of a function. In C,
following code reveals this concept. only the goto label has function scope. In other words
#include <stdio.h> function scope is applicable only with goto label names.
int main() This means that the programmer cannot have the same
{ label name inside a function.
Int =X =—10%
Using goto statements is not recommended as it is not
int i=0;
considered to be a good programming practice. We will
printf ("\n The value of x outside the
not discuss the goto statement in detail here but, we will
while loop is %d", x);
take a look at an example of code that demonstrates the
while (i<3) function scope.
{ int main()
inte.
sc ‘= 4.
printf("\n The value of x inside the
{
while loop is %d", x);
1++; loop: /* A goto label has function
} scope */

printf ("\n The value of x outside the


while loop is %d", x);
return 0; goto loop; /* the goto statement */
}
Output return 0;
The value of x outside the while loop is 10 }
The value of x inside the while loop is 0 In this example, the label loop is visible from the beginning
The value of x inside the while loop is 1 to the end of the main() function. Therefore, there should
The value of x inside the while loop is 2 not be more than one label having the same name within
The value of x outside the while loop is 10
the main() function.
, You may get an error message
Programming Tip: - d : : é
. . “ © while executing this code. This
Trytoavoid : 4.8.3 Program Scope
: __. is because some C compilers
variable names that _ :
: . ...___, make it mandatory to declare all Till now we have studied that variables declared within a
hide variablesin
the variables first before you do function are local variables. These local variables (also
outer scope. —
anything with i.e., they permit known as internal variables) are automatically created
declaration of variables right when they are declared in the function and are usable only
after the curly brackets of main () starts. within that function. The local variables are unknown to
Functions | 127 |

other functions in the program. Such variables cease to joneuliaiey(())p


exist after the last statement in the function in which they return 0;

are declared and are re-created each time the function is }


void print()
called.
{
However, if you want a function printf ("\n The value of x in the print()
| ramming Tip: to access some variables which = sell! o<)he
The value ofa are not passed to them as }
global variab! arguments, then declare those Output
variables outside any function The value of x in the main() = 10
from anywhere blocks. Such variables are The value of local variable x in the main()= 2
in the program commonly known as_ global The value of x in the print()= 10
variables and can be accessed From the code we see that local variables overwrite the
_ from any point in the program. value of global variables. In big programs use of global
it_| Lifetime Global variables are variables is not recommended until it is very important to
_creatéd at the beginning of use them because there is a big risk of confusing them with
program execution and remain in any local variables of the same name.
existence throughout the period
of execution of the program. These variables are known to
all the functions in the program and are accessible to them
“theyr
peed to be isolated from the rest 7
for usage. Global variables are not limited to a particular
+ code,but using alobatvariables ;
function so they exist even when a function calls another
function. These variables retain their value so that they can
be used from every function in the program.
4.8.4 File Scope
Place of Declaration The global variables are declared
outside all the functions including main (). Although there When a global variable is accessible until the end of the
is no specific rule that states where the global variables file, the variable is said to have file scope. To allow a
must be declared, it is always recommended to declare variable to have file scope, declare that variable with the
them on top of the program code. static keyword before specifying its data type, as shown:
Stats Cini c= Or
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
file in which it is declared but it is not accessible by any
the function will use the local variable declared within it
other files. Such variables are useful when the programmer
and ignore the global variable. However, the programmer
writes his own header files.
must not use names of global variables as the names of
local variables, as this may lead to confusion and lead to
erroneous result.
4.9 STORAGE CLASSES
rs
Note,~ ; Ifa global v eis not initialized The storage class of a variable defines the scope (visibility)
_ its initialization then it is automatical and lifetime of variables and/or functions declared within
a C program. In addition to this, the storage class gives the
_ initialized to zero by default.
following information about the variable or the function.
Consider the following program. e The storage class of a function or a variable
#include <stdio.h> determines the part of memory where storage
abiaiey Se = BLO space will be allocated for that variable or function
Void) print); (whether the variable/function will be stored in a
int main() register or in RAM).
{ e It specifies how long the storage allocation will
printf ("\n The value of x in the main() =
EXO)
UT okie continue to exist for that function or variable.
Ag) Oe e It specifies the scope of the variable or function, 1.e.,
printf ("\n The value of local variable x
the storage class indicates the part of the C program
Tmethe mali = od" sx)";
|128 | Introduction to C Programming

in which the variable name is visible or the part in The following code uses an auto integer that is local to the
which it is accessible. In other words, whether the function in which it is defined.
variable/function can be referenced throughout the #include <stdio.h>
program or only within the function, block, or source void funcl()
file where it has been defined. {
int a=10);
e It specifies whether the variable or function has
ishealiohene((
ial el see Golly, tel)
internal, external, or no linkage.
// auto integer local to funcl()
e Itspecifies whether the variable will be automatically
initialized to zero or to any indeterminate value.
}
void func2() t
C supports four storage classes: automatic, register, {
external, and static. The general syntax for specifying the Migle Q=HO)p
storage class of a variable can be given as jopaakianese
(MO\a, ey ss Sel,
ay) 5
// auto integer local to func2()
<storageclass specifier> <data type>
<variable name> }
void main()
{ :
4.9.1 auto Storage Class int a=30 // auto integer local to main()
TebhaKeul
(Q)
The auto storage class specifier is used to explicitly declare
func?
() ;
a variable with automatic storage. It is the default storage
joan gear (Way Cl = WexolW sel)
class for variables declared inside a block. For example,
if we write }
auto int x; Output
el = AL@)
then x is an integer that has automatic storage. It is deleted
El a 20)
when the block in which x was declared exits.
4 =) 30
The auto storage class can be used to declare variables
in a block or the names of function parameters. However,
since the variable names or names of function parameters 4.9.2 register Storage Class
by default have automatic storage, the auto storage class When a variable is declared using register as its storage
specifier is therefore treated as redundant while declaring class, it is stored in a CPU register instead of RAM. Since
data. the variable is stored in RAM, the maximum size of the
Important things to remember about variables declared variable is equal to the register size. One drawback of
with auto storage class include:
using a register variable is that they cannot be operated
e All local variables declared within a function belong using the unary ‘&’ operator because it does not have a
to automatic storage class by default. memory location associated with it. A register variable is
e They should be declared at the start of the program declared in the following manner:
block. (Right after the opening curly bracket { )
register int x;
e Memory for the variable is automatically allocated
upon entry to a block and freed automatically upon register variables are used when quick access to
exit from that block. the variable is needed. It is not always necessary that
e The scope of the variable is local to the block in the register variable will be stored in the register.
which it is declared. These variables may be declared Rather, the register variable might be stored in a
within a nested block. register depending on the hardware and implementation
restrictions.
e Every time the block (in which the automatic
variable is declared) is entered, the value of the Hence, programmers can only suggest the compiler
variable declared with initializers is initialized. to store those variables in the registers which are used
repeatedly or whose access times are critical. However,
e The auto variables are stored in the primary memory
of the computer. for the compiler, it is not an obligation to always accept
such requests. In case the compiler rejects the request to
e If auto variables are not initialized at the time of
store the variable in the register, the variable is treated as
declaration, then they contain some garbage value.
having the storage class specifier auto.
Functions | 129 |

Like auto variables, register variables also have usually external variables are declared and defined at the
automatic storage duration. That is, each time a block is beginning of a source file.
entered, the storage for register variables defined in that Memory is allocated for external variables when the
block are accessible and the moment that block is exited, program begins execution, and remains allocated until the
the variables becomes no longer accessible for use. program terminates. External variables may be initialized
Now let us have a look at the following code that uses a while they are declared. However, the initializer must be a
register variable. constant expression. The compiler will initialize its value
#include <stdio.h>
only once during the compiler time. In case the extern
int exp(int a, int b); // FUNCTION DECLARATION
variable is not initialized, it will be initialized to zero by
main ()
S
default.
{
int a=3, b=5, res;
External variables have global scope, i.e., these
res = exp(a, b);// FUNCTION CALL variables are visible and accessible from all the functions
printf ("\n %d to the power of %d = %d", in the program. However, if any function has a local
a, b, res); variable with the same name and types as that of the global
r
getch(); or extern variable, then references to the name will access
return 0;
the local variable rather than the extern variable. Hence
extern variables are overwritten by local variables.
} Let us now write a program in which we will use the
int exp(int a, int b) // FUNCTION DEFINITION
extern keyword.
{ fife VFaeIETR. ALIS
register int res=1;
soe abA
#include <stdio.h>
for (1=1 ;1<=b;
i++)
#include <FILE2.C>
res = res*b;
// Programmer’s own header file
return res;
AMINE Par
} WOnlel jorsslios (KezuGl)) F
int main()
Output
{
3 (eo vehe™power Of 5 "= 243 ae Oe
fopemotcas (Woy Se suey IIe, = Boll. Se)5
joreauake
()) 5

4.9.3 extern Storage Class return 0;

}
A large C program can be broken down into smaller
// END OF FILE1.C
programs. When these smaller programs are compiled,
they are joined together to form a large program. However, J jek GEE C
these smaller programs may need to share certain variables #include <stdio.h>
for processing. For such situations C language provides an
extern int x;
external storage class that is specified using the keyword void print()
exe Cian:
{
The storage class extern is used to give a reference fonantiohens (Q\iel Se Glial INGUIN D = keb>s, se)¢
of a global variable that is visible to all the program files. }
Such global variables are declared like any other variable main ()

in one of the program file. When there are multiple files {


// Statements
in a program and you need to use a particular function or
}
variable in a file apart from which it is declared, then use // END OF FILE2.C
the keyword extern. To declare a variable x as extern
write, Output
ee abel Ine = Aho)
extern int x; xi PRRE2 1 0

External variables may be declared outside any function In the program, we have used two files—File1 and
in a source code file as any other variable is declared. But File2. File1 has declared a global variable x. File1 also
|130 | Introduction to C Programming

includes File2 which has a print function that uses the


Note y
external variable x to Ain its value on the screen.

salto Bs
expression.

Look at the following code which clearly differentiates


be
between a static variable and a normal variable.
In a multi-file program, the global variable must #include <stdio.h> y
be declared only once (in any one of the files) without void print (void); // FUNCTION DECLARATION
using the extern keyword. This is because, otherwise the int main()
linker will have a conflict as to which variable to use and {
therefore in such a situation it raises a warning message. PEIntL(!Wn Rirst cally of print Ome,
jopentiate,
())f // FUNCTION CALL ~
DEInEE (@\n\n Secondicalll or pram Oi),
4.9.4 static Storage Class
print () ; // FUNCTION CALL
While auto is the default storage class for all local jouaalianere (UGA Gay Geswinec! Geli Gre Forestiais: (()))")) F
variables, static is the default storage class for all global jopeatiale.()9 // FUNCTION CALL

variables. Static variables have a lifetime over the entire return 0;

program, i.e., memory for the static variables is allocated


when the program begins running and is freed when the
program terminates. To declare an integer x as static, void print() // FUNCTION DEFINITION
write, {
Stare inte sc
State nts = Ol
ahiale
ff = (Oe
Here x isa local static variable. Static local variables printf ("\n Static integer variable, x =
209 y= Se))or
when defined within a function are initialized at the
printf("\n Integer variable, y = %d", y);
runtime. The difference between an auto variable and
X++;
a static variable is that the static variable when defined Yt+;
within a function is not re-initialized when the function is }
called again and again. It is initialized just once and further
Output
calls of the function share the value of the static variable.
First «calls of prant(®)
Hence, the static variable inside a function retains its value
Static integer variable,x i] ‘S}
during various calls. Integer variable, y = 0
When a static variable is not explicitly initialized by
the programmer then it is automatically initialized to Second call of print()
zero when memory is allocated for them. Although static Static integer variable, x ll hb

Integer variable, y = 0
automatic variables exist even after the block in which
they are defined terminates, their scope is local to the
Thoed callmoL onan()
block in which they are defined. Static integer variable, x = 2
Static storage class can be specified for auto as well Integer variable, y = 0
as extern variables. For example, we can write
static extern int x; 4.9.5 Comparison of Storage Classes
When we declare a variable as external static variable, Table 4.2 compares the key features of all the storage
then that variable is accessible from all the functions in classes.
this source file.
Functions 131 |

Table 4.2 Comparison of storage classes

_ STORAGE CLASS
Veeccic

Local: Accessible within


Accessible within the function or block in
Accessible within the Accessible within the
all program files which it is declared.
Accessibility function or block in which it function or block in
that are a part of Global: Accessible
is declared. which it is declared.
the program. within the program in
which it is declared.
Storage Main memory Main memory
Exists when the function Exists when the function
or block in which it is or block in which it is Local: Retains value
declared is entered. Ceases Exists throughout declared is entered. between function calls
to exist when the control the execution of Ceases to exist when the or block entries.
returns from the function the program. control returns from the Global: Preserves value
or the block in which it was function or the block in in program files.
declared. which it was declared.

Default value | Garbage

4.10 RECURSIVE FUNCTIONS This can be written as


Blea 52 4s aiwhene 4.= 4) xs 3)!
A recursive function is defined as a function that calls
itself to solve a smaller version of its task until a final Therefore,
call is made which does not require a call to itself. Every yc Sy oc ee er
recursive solution has two major cases, they are Similarly, we can also write,
e Base case, in which the problem is simple enough to Bice 5 Kae foe
be solved directly without making any further calls
Expanding further
to the same function.
e Recursive case, in which first the problem at hand is BY eX AO ea
divided into simpler sub-parts. Second the function We know, 1! = 1
calls itself but with sub parts of the problem obtained Therefore, the series of problem and solution can be
in the first step. Third, the result is obtained by given as shown in Fig. 4.6.
combining the solutions of simpler sub-parts.
Therefore, recursion is defining large and complex
problems in terms of a smaller and more easily solvable
_ SOLUTION
bx4xox2xil.
problem. In recursive function, a complex problem is de- -5 woxd
fined in terms of simpler problems and the simplest prob-
lem is given explicitly.
To understand recursive functions, let us take an example
of calculating factorial of a number. To calculate n!, what
we have to do is multiply the number with factorial of the Figure UH") Recursive factorial function
number that is 1 less than that number. In other words,
ig) is =; gh SK (Gamal)
Now if you look at the problem carefully, you can see
Let us say we need to find the value of 5!...
that we can write a recursive function to calculate the
Bill PSG 4 EX RD XK factorial of a number. Every recursive function must have
=120 a base case and a recursive case. For the factorial function,
|132 | Introduction to C Programming

e Base case is when n = 1, can find the GCD of two numbers recursively by using the
Programming Tip:
because ifn = 1, the result will Euclid’ algorithm that states
Every recursive
be aasai
function must have b,if b divides a
at least one base e Recursive case of the factorial GCD(a,b) =
GCD(b, a mod b), otherwise
case. Otherwise, the function will call itself but with
recursive function will - a smaller value of n, this case
GCD can be implemented as a recursive function be-
generate aninfinite can be given as
cause if b does not divide a, then we call the same function
sequence of calls factorial(n) = n x factorial (n—1) (GCD) with another set of parameters that are smaller and
thereby resulting in an
error condition known | Look at the following code simpler than the original ones. Here we‘assume that a >
as an infinite stack ' which calculates the factorial of b. However if a < b, then interchange a and b in the
au a number recursively. formula given above.
#include <stdio.h>
int Fact (int); // FUNCTION DECLARATION Working
main () Assume a = 62 and b = 8
{
int num;
GCD (62, 8)
printf ("\n Enter the number: ");
GeEME= OZ oO) — =o
scanf("%d", &num);
GCD(8, 6)
joreshiaicue (Wiel seKeiceraleul wie Excl SS ely asin,
rem = 8 OY I! Nh
Fact (num) );// FUNCTION CALL
GCD(6é, 2 oe
~
Ta\e\ohaay (09
gen = ey a BS 1)
} Return 2
Return 2
int Fact( int n) // FUNCTION DEFINITION
Return 2
{
abt, (Get=—=1l,)) 4.10. Write a program to calculate GCD using recursive
return 1;
functions.
return (n * Fact(n-1)); // FUNCTION CALL
} #include <stdio.h>
int GCD(int, int); // FUNCTION DECLARATION
From the above example, let us analyse the basic steps
main ()
of a recursive program.
{
Step 1: Specify the base case which will stop the function int numl, num2, res;
from making a call to itself. printf ("\n Enter the two numbers: ");
Step 2: Check to see whether the current value being scanf ("3d $d", &numl1, &num2) ;

processed matches with the value of the base res = GCD(numl1, num2); // FUNCTION CALL
case. If yes, process and return the value. printf("\n GCD of %d and %d = $d", num1,
num2, res) ;
Step 3: Divide the problem into a smaller or simpler sub-
igenebuaray (0)p
problem.
}
Step 4: Call the function from the sub-problem.
Step 5: Combine the results of the sub-problems. cian G CDI (iia teaesey int y) // FUNCTION DEFINITION

Step 6: Return the result of the entire problem. {


int rem;
CeMe =! Say,
The base case of a recursive function
if (rem==0)
acts as the terminating condition. So, in
BOCUER TY;
the absence of an explicitly-defined base
else
case, a recursive function would call itself return (GCD(y, rem)); // FUNCTION CALL
indefinitely.

4.10.1 Greatest Common Divisor 4.10.2 Finding Exponents

The greatest common divisor of two numbers (integers) We can find a solution to find exponent of a number using
is the largest integer that divides both the numbers. We recursion. To find x’, the base case would be when y=0,
Functions 4 133 |

as we know that any number raised to the power 0 is 1. else


Therefore, the general formula to find x” can be given as racieonain (>< 2 Kerqo) satsye( oi, Wy7=1))Ve

aly alae == 0
EXP\(x, y) = ae
x * EXP(x Y+), otherwise 4.10.3 Fibonacci Series
The Fibonacci series can be given as
Working Oded?
895 8 132d Saab bee
Sriqo) Bale), 2!) = Bai Coo) ae A, 2)))
That is, the third term of the series is the sum of the
249) 36582, S)) S AD qo mae( Bp A)
CXC Cl(2) me) ee exp ‘rec ( By lly) first and second terms. On similar grounds, fourth term
experec(27 l)ie= 2 Amexpm ced (§ 2775.0) is the sum of second and third terms, and so on. Now we
Geo
_WEE A, ©) Sa will design a recursive solution to find the n‘® term of
Smo ee( 2, i) = Ae is 2 the Fibonacci series. The general formula to do so can
Eq 2EG( 2, 2) 2a Fe Paw be given as
Sq0) saee'(( By 3) = 2 vgs e
Cxpereci Gi 74) =9 20% Sa a6 ih, mie fo)

4.11. Write a program to calculate exp(x,y) using FIB (n - 1) +FIB (n - 2), otherwise
recursive functions.
#include <stdio.h>
As per the formula, FIB(1) =1 and FIB(2) = 1. So
IMie experec (amt; aint); we have two base cases. This is necessary because every
main () problem is divided into two smaller problems (Fig. 4.7).
{ 4.12. Write a program to print the Fibonacci series using
int numl, num2, res;
printf ("\n Enter the two numbers: ");
recursion.
scanf ("$d @d", &numl, &num2); #include <stdio.h>
GES) = explneci(numiy,, num2)); int Fibonacci (int) ;
joraniovere (MWe iafsoneyr = Rll, res); main ()
return 0; {
} ahigie sale
printf ("\n Enter the number of terms in
int exp rec(int x, int y) the series: ");
{ scanf ("%d", &n);
Age Wa) for(int i=0;i<n;1i++)
return 1;

FIB(7)

FIB(3)

FIB(2) | FIB(1)

Figure 4.7 [it of £ib function


|134 | Introduction to C Programming

DEintee (\n) ba bonaccim (sd) ie—sc Our ac,


Fibonacci (i));
return 0;
}
int Fibonacci (int num)

{
Le (num <= 2)
return 1;
return (Fibonacci (num - 1) +
Fibonacci(num - 2));

Gree eee Indirect recursion =

Recursion is a technique that breaks a problem into one 4.11.3 Tail Recursion
or more sub-problems that are similar to the original A recursive function is said to be tail recursive if no
problem. Any recursive function can be characterized operations are pending to be performed when the recursive
based on: function returns to its caller (Fig. 4.10). When the called
e whether the function calls itself directly or indirectly function returns, the returned value is immediately returned
(direct or indirect recursion), from the calling function. Tail recursive functions are highly
desirable because they are much more efficient to use as the
e whether any operation is pending at each recursive
amount of information that has to be stored on the system
call (tail-recursive or not), and
stack is independent of the number of recursive calls.
e the structure of the calling pattern (/inear or tree-
recursive).
In this section, we will read about all these types of
recursions.

4.11.1 Direct Recursion

A function is said to be directly recursive if it explicitly


calls itself. For example, consider Fig. 4.8.

ete Tailrecursion

For example, the factorial function that we have written


is a non-tail-recursive function, because there is a pending
operation of multiplication to be performed on return from
each recursive call.
artice ew Direct recursion = Whenever there is a pending operation to be performed,
the function becomes non-tail recursive. In such a non-
Here, the function Func() calls itself for all positive tail recursive function, information about each pending
values of n, so it is said to be a directly recursive function. operation must be stored, so the amount of information
directly depends on the number of calls.
4.11.2 Indirect Recursion However, the same factorial function can be written in
A function is said to be indirectly recursive if it contains a tail-recursive manner as shown in Fig. 4.11.
a call to another function which ultimately calls it. Look In the code, Fact1 function preserves the syntax of
at the functions given in Fig. 4.9. These two functions are the Fact (n). Here the recursion occurs in the Fact1
indirectly recursive as they both call each other. function and not in Fact function. Carefully observe that
Functions | 135 |

Fact1 has no pending operation to be performed on return as we did in case of the Factorial function. The auxiliary
from recursive calls. The value computed by the recursive parameter is used to form the result. When we use such a
call is simply returned without any modification. So in parameter, the pending operation is incorporated into the
this case, the amount of information to be stored on the auxiliary parameter so that the recursive call no longer
system stack is constant (just the value of n and res needs has a pending operation. We generally use an auxiliary
to be stored) and is independent of the number of recursive function while using the auxiliary parameter. This is done
calls. to keep the syntax clean and to hide the fact that auxiliary
parameters are needed.

4.11.4 Linear and Tree Recursion


Recursive functions can also be characterized depending
on the way in which the recursion grows in a linear fashion
or forming a tree structure (Fig. 4.12).
In simple words, a recursive function is said to be /in-
early recursive when the pending operation (if any) does
not make another recursive call to the function. For ex-
ample, observe the last line of recursive factorial function.
The factorial function is linearly recursive as the pending
operation involves only multiplication to be performed and
does not involve another recursive call to Fact.
ae ee Tail-r
ail-recursive function On the contrary, a recursive function is said to be
tree recursive (or non-linearly recursive) if the pending
Converting Recursive Functions to Tail Recursive operation makes another recursive call to the function.
For example, the Fibonacci function Fib in which the
A non-tail recursive function can be converted into a
pending operations recursively calls the Fib function.
tail-recursive function by using an auxiliary parameter

Figure 4.12 ‘Tree rect


|136 | Introduction to C Programming

4.12 TOWER OF HANOI The final step is to move the n-1 rings from the spare
pole (B) to the destination pole (C). This is shown in
The tower of Hanoi is one of the main applications of a Fig. 4.16.
recursion. It says, ‘if you can solve n-1 cases, then you
can easily solve the n th case’;
Look at Fig. 4.13 which shows three rings mounted on pole
A. The problem is to move all these rings from pole A
to pole
C while maintaining the same order. The main issue is that the
smaller disk must always come above the larger disk.

Figure 4.16

To summarize, the solution to our problem of moving n


rings from A to C using B as spare can be given as:
Base case: if n=1 =

e Move the ring from A to C using B as spare


Figure 4.13 | Tower ofHanoi
Recursive case:

We will be doing this using a spare pole. In our case, A e Move n—1 rings from Ato B using C as spare
is the source pole, C is the destination pole, and B is the e Move the one ring left on A to C using B as spare
spare pole. To transfer all the three rings from A to C, we e Move n—1 rings from B to C using A as spare
will first shift the upper two rings (n-1 rings) from the The following code implements the solution of the
source pole to the spare pole. We move the first two rings Tower of Hanoi problem.
from pole A to B as shown in Fig. 4.14. #include <stdio.h>
int main()
{
aiaic: i9)p
printf("\n Enter the number of rings: ");
scanf("$d", &n);
none (Gat, WAP, SGP Wet)
return 0;

Figure 4.14 | Move ri from A to B [ void move(int n, char source, char dest, char
spare)

Now that n-1 rings have been removed from pole A, LE (n==1)
the source pole, the n‘" ring can be easily moved from printf ("\n Move from %c to
sc", source,dest) ;
the source pole (A) to the destination pole (C). Figure 4.15
else
shows this step. {
move (n-1, source, Spare, dest) ;
move (1,source,
dest, spare) ;
move (n-1,spare,dest,
source) ;

}
Let us look at the Tower of Hanoi problem in detail
using the program given:above. Figure 4.17 on the next
page explains the working of the program using one, then
Figure 4.15 [eons from A to C two, and finally three rings.
Functions | 137 |

ia ee
Gee

eo B

then simply move Uf


: there are two rings, then first move ring 1to
othe mee|
ing [Link] 9 the destination.) —_| a and pee move ring 2 irom source to the destination.

Whenever a recursive function is called, some amount


of overhead in the form of a runtime stack is always
Recursion is more of a top-down approach to problem involved. Before jumping to the function with a smaller
solving in which the original problem is divided into parameter, the original parameters, the local variables,
smaller sub-problems. On the contrary, iteration follows and the return address of the calling function are all stored
a bottom-up approach that begins with what is known and on the system stack. Therefore, while using recursion a lot
then constructing the solution step by step. of time is needed to first push all the information on the
Recursion is an excellent way of solving complex stack when the function is called and then time is again
problems especially when the problem can be defined in involved in retrieving the information stored on the stack
recursive terms. For such problems, a recursive code can once the control passes back to the calling function.
be written and modified in a much simpler and clearer To conclude, one must use recursion only to find
manner. solution to a problem for which no obvious iterative
However, recursive solutions are not always the best solution is known. To summarize the concept of recursion
solutions. In some cases, recursive programs may require let us briefly discuss the pros and cons of recursion.
substantial amount of run-time overhead. Therefore, The advantages of using a recursive program includes
when implementing a recursive solution, there is a trade- the following:
off involved between the time spent in constructing and
maintaining the program and the cost incurred in running- e Recursive solutions often tend to be shorter and
time and memory space required for the execution of the simpler than non-recursive ones.
program. e Code is clearer and easier to use.
|138 | Introduction to C Programming

e Recursion works similar to the original formula to stack space on the system is limited, recursion to a
solve a problem. deeper level will be difficult to implement.
Follows a divide and conquer technique to solve Aborting a recursive process in midstream is slow
problems. and sometimes nasty.
In some (limited) instances, recursion may be more Using a recursive function takes more memory and
efficient. time to execute as compared to its non-recursive
The drawbacks/disadvantages of using a recursive counterpart.
program includes the following: It is difficult to find bugs, particularly while using
e For some programmers and readers, recursion is a global variables.
difficult concept.
The advantages of recursion pays off for the extra overhead
e Recursion is implemented using system stack. If the involved in terms of time and space required.

e Every functionin the program is supposed to Call-by-value method passes —values _of : he
perform a well defined task. The moment the variables to the called function. ‘Therefore,
compiler encounters a function call, the control called function uses a copy of the actual arguments :
jumps to the statements that area part of the called to perform its intended task. This method is used —
function. After the called function is executed, the _ when the function does not need to modify the
control is returned back to the calling program. . values of the original variables _ in the calling
All the libraries in C contain a set of functions program.
that have been prewritten and pre-tested, so Incall-‘by reference method, Se. varacles
the programmers use them without worryingm _ are passed by the calling function to the called
This sos up progra
about the code details. function. Hence, in this method, a function receives
development. an implicit reference to the argument, rather thana _
While function declaration seatement identifies copy of its value. This allows the function'
to modify .
a function with its name, a list of arguments that the value of the variable and that change will :
it accepts and the type of data it returns, the reflected in the calling function as well.
_ function definition, on the other hand, consists Scope means the accessibility and visibility of the
of a function header that identifies the function, variables at different points in the program. A .
followed by the body of the function containing . variable. ora constant iin C has four ‘types of sce pe
the executable
code for that function. block, function, file, and program scope. _
main() is the function that is called by the The storage class of a variable defines Nieety
operating system and therefore, it is supposed to (visibility) and life time of variables and/or functions :
return the result of its processing to the operating declared within a C program.
system. The auto storage class is the default storage class -
* Placing the function declaration statement priorto for variables declared inside a block. The. scope
its use enables the compiler to make a check on of the variable is local to the block in which it —
the arguments
used while calling that function. is declared. When a variable isdeclared u: ing. [
A function having void as its return type cannot register as its storage class, it is stored|
‘ina CPU 7
return any value. Similarly, a function having void register instead of RAM. Extern is used to give a
as its parameter list cannot accept any value. reference of a global variable that is visible to all :
When a functionis defined, space is allocated for the program files. Staticis the default storage: ca :
_ that function in the memory. A function definition forgiebal variables. .
N

comprises of two parts: function header and


function body. —
Functions | 139 |

‘Argument A value passed to the called function by the Recursion termination The point at which base
calling function. condition is met and a recursive algorithm stops ee
Block A sequence of definitions, declarations, and itself and begins to return values.
statements, enclosed within curly brackets. Recursion tree Technique to analyse the complexity of ©
Divide and conquer Solving a problem by dividing it into an algorithm by diagramming the recursive function
GLOSSARY
_two or more smaller instances. Each of these smaller calls.
instances is recursively solved, and the solutions are Tail recursion A form of recursion in which the last _
- combined to produce a solution for the original problem. . operation of a function is a recursive call.
Iteration Solving a problem by repeatedly working on Tower of Hanoi Given three towers or poles and n
successive parts of the problem. oo of decreasing sizes, move the cee from one pole
_ Recursion An algorithmic technique where a functio
calls itself with a smaller of the task in order to solv
that task. .

Filliin the Blanks


i.e vides ann interface to use the function. 17. Variable declared inside a function is known as
2. After t ion is executed, the control passes

EXERCISES uses another function is known as Multiple Choice Questions —


1. The function that is es i
hat the function takes are known as (a) calling function
(c) called function _
2. Function declaration statemer identifiesa
A definition consists of and function with its _
(a) name
“method, address of the variable (b) arguments
3 passed by the calling function to the called (c) data type of return value ~
function.
(d) all of these
. Function scope is applicable only within _
3. Which return type cannot return any value to the
. Function that calls itselfisknown asa ____ _ caller?
(a) int (b) float
functions are implemented
~ (c) void (d) double :
. Memory is allocated for a function when the
function is defined as a function that .
function is
calls itself.
(a) declared (b) defined
] _The function int func();_ takes
(c) called (d) returned
arguments.
5. Which keyword allows a variable to have file
: _ variables can be accessed from all
scope?
: functions iin the program.
(a) auto (b) static
ecution of a program starts at
(c) register (d) extern
tee. return type of a function is
6. The default storage class of global variables is
(a) auto (b) static
sed in function call are called
(c) register (d) extern
|140 | Introduction to C Programming

7. Which variable retains its value in-between . Give the features of each storage class.
. function calls? . Explain the concept. of recursive functions with
2 (a) auto (b) static example.
ao (c) register (d) extern _ Differentiate between an iterative function and a
Sc 8. The default storage class of a local variable is recursive function. Which one will you prefer. to.
use and in what circumstances?
Liu (a) auto (b) static
. What will happen when the actual atametale are
a
(c) register (d) extern
less than formal parameters in a function?
State True or False 10. What will happen when data type of a variable in
the function declaration does not match with the
f The calling function must pass parameters to the corresponding variable in the function header?
called function. it, What will happen when a function returns a value
2. Function header is used to identify the function. that does not match with the return type ofue
3. The name ofa function is global. function?
. No function can be declared within the body of 12. Write a program to calculate factorial of anumber —
another function. using recursion. Also write a non-recursive
. The function call statement invokes the function. procedure to do the same job.
. Auto variables are stored inside CPU registers. is. Explain the Tower of Hanoi problem.
. Extern variables are initialized by default. 14. Write a program using function that calculates the —
hypotenuse of a right-angled triangle.
. The default storage class of local variables is
excerm. 45. Write a function that accepts a number n as input
and returns the average of numbers from 1 ton.
. Recursion follows a divide- and:-conquer technique
to solve problems. 16. Differentiate between call-by-value and call-by-
reference using suitable examples.
. Local variables: overwrite the value of global
variables. d/7. What do you understand by scope of a variable?
Explain in detail with suitable examples.
. AC function can return only one value.
18. Why function declaration statement is placed prior
1 . Afunction must have at least one argument.
to function definition?
JA function can be declared and defined before the
io. Write a function to reverse a string using
main ).
recursion.
.A function can be defined in the main().
20. Write a function is_prime that returns a 1 if the
_ Variable names in the function definition must argument passed to it is a prime — and a 0
match with those specified in the function decla- otherwise. _
ration.
Zn. Write a function that accepts an integer between
. Specifying variable names in the function declara- 1-12 to represent the month number and displays
tion is optional. the corresponding month of the year (e. 8) if
q/. The main () is a user-defined function. month= 1, then display JANUARY).
Ze Write a function is_leap_year which takes the year
Review Questions as its argument and checks whether the year is a
leap year or not and then displays an anes
1. Define a function. Why are they needed? message on the screen. _
2. Explain the concept of making function calls. 23, Write a program to concatenate two strings using
2 Differentiate between function declaration and recursion.
function definition. 24. Write a program to read an integer number. Print
4. Differentiate between formal parameters and the reverse of this number using recursion.
actual parameters. 25. Write a program to swap two variables that are
5. How many types of storage classes C language defined as global variables.
supports? Why do we need different types of such 26. Write a program to compute F(x, y) where ©
classes?
Functions | 141 |

Pix, y) = Blix-y, y) + 1 Lf vex 45. Write a program using functions to perform


And Bix, y) = 0 if xey calculator operations.
27. Write a program to compute F (n, xr) where 46. Write a function that converts temperature given
F(n, xr) can be recursively defined as in Celsius into Fahrenheit. —
Fin, x) =Fin-1, rc) + Fin-1,
- ’ 47. Write £-1)
afunction that prints th rsion tableof
EXERCISES
| 28. Write a program to compute Lambda(n) for all © Degrees Fahrenheit into Degre cols ranieine
positive values of n where Lambda(n) can be from 32-212 degrees Celsius.
recursively defined as 48. Write a function to draw the following pattern on
Lambda(n) = Lambda(nf2) + 1 if n>l the screen. ;
AND Lambda(n) = 0 if n = RRR RRR

) 29. Write a program to compute F (M, N) where


F (M, N) can be recursively defined as
B(IMN) = 2 if M=0 or M2N21
KEEKKKKK
AND F(M,N) = F (M-1,N) + F(M-1, N-1)
otherwise _ AY. Write a function to print a tableof binomial
30. Write an enu-driven program to add, subtract, _. coefficients which is given b ‘the.
1d divide two integers using function - B(m, x) _ (x! (m-x :.
31. Write a “program to find the smallest of three Hint: Bim, O) 41, B(0,0)
integers using functions. ‘Blm,x) = eae S41) 4 1 om 1) /x]
32. Write a program to calculate area of a triangle 50. Write a program to evaluate -
using function. + x°/5!1 -a +.
Pix) = x - oe.
. Write a program to find whether a number is
divisible by 2 or not using
Program Out. ut
. Write a program to © lustrate call-by-value
technique of passing arguments to a function. Find the output ofthe following codes: eS :
35. Write a program to illustrate call-by-reference 1. #include <stdio. h>
technique of passing arguments to a function.
int func’);
. Writeaprogram to swap two integers using call-
-by- main()
value oe of oe afeuteniis toa fun j
.
prince ("s0", func()
) wer ofy Onere y can be either negativ DEInlLe Lect, func()) ;
positive. : _ pYrintt ('20d", func) ;
. Write a program using function to calculate ‘printt (2d", func());
compound interest given the ee rate of return0;
interest and number of y
. Write a program to sw
by-reference method« passing arguments to a
function. int counter=0;
. Write a program to calculate factorial of a number relturn counter:
_ (a) using recursion (b) without using recursion.
}
. Write a program to convert the given string “hello
world” “dlrow olleh” without using recursion. 2. #include <stdio.h>
int funct) ;
Writ rogram to find HCF of two numbers (a»)
‘using recursion (b) without using recursion. main()

. Write a program to calculate x” (a) using recursion


(b) without using recursion.
44. Write a program to print the Fibonacci series
(a) using recursion (b) without using recursion.
|142 | Introduction to C Programming

return 0; : #include <stdio.h>


2)
li } THe func (int) ;
n Ist func
int ~

O
Gs { {
a
Lud static int counter=0; ant a=2;
ui return counter; printé ("sd", Eunc(a));
} return 0;

}
3. #include <stdio.h> int func (int a)
int func();
{
int counter 5. if (a>1)
main ()
return func (--a) + 10;
{
else
print (“td", func());
printt (‘¢d°, func); return 0;
print’ (“Sd", finc()); }
printf ("¢d", func()) ;
. #include <stdio.h>
retumm 0;
void func (int) ;
I main ()
aint func()
{
{ int a=l27>
return counter++;
printh("cd",
a);
} func (a) ;
return 0;
4. #include <[Link]
int: add (int, int); } :
void func(int a)
main()
{ {
Int a=2, b=-3:
at:
printf ("%d", a);
printf ("$d %a a", a, b, add(a, b));
return 0; a
} Sy #include <stdio.h>
int add(int a, int b) void func(int);
{ auto int a;
Ine Cc: main ()
Cc = atb {
return; int a=10;
} printt ('sd", a).
func (a);
5. #include <stdio.h>
return Q;
int add (ink, int);
main() }
void func(int a)
{
Tne a=2, bs=s> {
Att;
Print (§sd <d td", a,b, add(a, 6));
printf (“sd", a);
return QO;

} }
int add(int a, int b) #include <stdio.h>
{ static int add (int val)
int c¢;
c = ath static int sum;
sum += val;
Functions | 143|
return sum;
an20;
7
ain () _
{ 12. #include <stdio.h>
int a1, nal;
void func(char);
EXERCISES for 4-0; 1<10-i4+)
main ()
add (i);
{
print£("\n SUM = %d", func(0)); char ch=256;
veturn 0; func (ch) ;
3 < “ceturn 0;

10. #include <stdio.h> | }


» void func (char a)
ant func(int);
main() {
printt("sd", a);
}
Do)
int and;
13. #include <stdio.h>
int ap :
static int func()
(
return at+;

main ()
_
a=10;
printé("4d", fumc()) ;
a #2 10,
printl("2d", func());
return 0; _
}
14. #include <stdio.h>
int prod(int
x, int y)
{
_ weturn (x*y);
}
main()
a |
_ int X=2, y=3, 2]
z = prod(x,prod(x,y));
(Printi("sd",
2);
return 0;
ANNEXURE 3

A3.1 USER DEFINED HEADER FILES #include"fact.h"


main ()
At times the programmer may need a function that provides
{
additional processing capabilities and may want to create GME, Teh, IEF
a separate source code file to contain that function. This
lllbatcfeha(()) A
would help to segregate the function from rest of the main
printf ("\n Enter any number: ");
source code. In such a situation, the user may create a user
scant ("sd", &num) ; ‘
defined header file so that the compiler knows how to call
f = factorial (num) ;
this function.
prEanté£ (@\ne PACTORTALTOL cde —sesd.s mum mes ir
For example, if we want the factorial function to be
getch();
stored in a user defined header file, then write the code
return 0;
of the factorial function in a file and save it as "fact .h".
Then in the main program file, we will include the fact .h }
file and call the function in the same way as we call other In the above code, a user defined header file—fact .h
functions. Look at the code given below which illustrates has been used. The name of the header file has been
this concept. enclosed within quotes to tell the compiler not to look
int factorial (int num) along the standard library path, but to look in the same
path as the source file.
esate; atreae seals Note that you will compile the file that contains the
for(;num >= 1;num--) source code, that is the file contains the main(). The
im =e 28 4a) Gahbliie compiler will compile it into object code. As long as
return f;
the C program is syntactically correct, the object code will
} be created.
// Contents for the main file
The linker will combine the object code, library files,
#include <stdio.h> and create the executable. It is the header file that links the
#include <conio.h> definition of the function with the implementation.
CHAPTER

Arrays

Takeaways _
® Array Declaration e Array Operations eAraylength
e 2D Arrays e Using Arrays with Functions ¢ Multi-dimensional Arrays
_ © Sparse Matrices

5.1 INTRODUCTION for the user to follow this approach. But imagine, will it be
possible to follow this approach if we had to read and print
Take a situation in which we have 20 students in a class
marks of the students
and we are asked to write a program that reads and prints
e in the entire course (say 100 students)
the marks of all these 20 students. In this program, we will
e in the entire college (say 500 students)
need 20 integer variables with different names, as shown
e in the entire university (say 10000 students)
in Fig. 5].
The answer is no, definitely not. To process large
Marks1 Marks9 Marks13 Marks17
amount of data, we need a data structure known as array.
An array is a collection of
Programming Tip:
|. similar data elements. These
Marks2 Marks6 Marks10 Marks14 Marks18 eg aay el - _ data elements have the same data
n, the index ranges _
from Oto n—-1 _, type. The elements of the array
ne are stored in consecutive memory
Marks3 Marks7 Marks11 Marks15 Marks19 locations and are referenced by
an index (also known as the subscript). The subscript is
an ordinal number which is used to identify an element of
Marks4 Marks8 Marks12 Marks16 Marks20
the array. Some examples where the concept of an array
can be used include:

atatigeys |Twenty variables with different names e List of temperatures recorded on every day of the
month
e List of employees in a company
Now to read values for these 20 different variables, we
e List of students in a class
must have 20 read statements. Similarly, to print the value
of these variables, we need 20 write statements. If it is e List of products sold
just a matter of 20 variables, then it might be acceptable e List of customers
|146 | Introduction to C Programming

Therefore, the following array declarations are


5.2 DECLARATION OF ARRAYS
illegal in C.
We have already seen that every variable must be declared
aighe, clugia||
le
before it is used. The same concept is true in case of array Hale vale gchar lial) p
variables also. An array must be declared before being
used. Declaring an array means specifying three things: Generally it is a good programming practice to
define the size of an array as a symbolic constant as
e Data type—what kind of values it can store, for shown in the following code.
example int, char, float, double.
#include <stdio.h>
e Name—to identify the array. #define N 100
e Size—the maximum number of values that the array main()

can hold. {
int arr([N];
Arrays are declared using the following syntax:
type name [size] ;

Here the type can be either int, float, double, char The size of the array can be specified using an ex-
pression. However, the components of the expres-
or any other valid data type. The number within brackets
sion must be available for evaluation of the expres-
Programming Tip: indicates the size of the array, i.e.,
sion when the program is compiled. Therefore, the
Todeclareand © the maximum number of
following array declarations are valid in C language.
define an array, elements that can be stored in the
#include <stdio.h>
you must specify array. The size of the array is a
#define N 100
itsname, type, and — constant and must have a value at main ()
size.
/ compilation time. For example, if {
GONE abe IL{0)6
we write,
int arr [N+l0], my arr [ii-5*10)7;
int marks [10];

The above statement declares a marks variable to be an


array containing 10 elements. In C, the array index (also Netey C array indices start from 0. Sofor an array
known as subscripts) starts from zero. This means that jE with N elements, the index of the last.
element is N — 1.
the array marks will contain 10 elements in all. The first
element will be stored in marks [0], the second element in C never checks the validity of the array index—
marks [1], and so on. Therefore, the last element, 1.e., the neither at compile time nor at run time. So even if
10th element will be stored in marks [9]. Note that 0, 1, you declare an array as
2, 3 written within square brackets are subscripts/index. int arr[N];

In memory, the array will be stored as shown in Fig. 5.2. The C compiler will not raise any error but the result
of running such code is totally unpredictable. Even if
Points to Remember you declare an array of 10 elements and later on by
e Note that C does not allow declaring an array whose mistake try to access the 11th element, no error will
number of elements is not known at the compile be generated. But the results will be unpredictable
time. as the memory occupied by the (so-called) 11th
element may be storing data of another object.

ee

element element element element


Neenlernenti element |

aerkeiG] Taare mare) Wsckela] Panel markets] marks(6] mmacks(7] Pattie} markst9)

Figure 5.2 Memory representation of an array of 10 elements _


Arrays | 147 |

5.3.1 Calculating the Address of Array


For accessing an individual element of the array, the Elements
array subscript must be used. For example, to access You must be wondering, how C knows where an individual
the fourth element of the array, you must write arr [3]. element of the array is located in the memory? The answer
The subscript/index must be an integral value or an is that the array name is a symbolic reference for the address
expression that evaluates to an integral value. to the first byte of the array. When we use the array name,
_ Although storing the related data items in a single array we are actually referring to the first byte of the array.
. enables the programmers to The subscript or the index represents the offset from
develop concise and efficient the beginning of the array to the element being referenced.
programs there is no single With just the array name and the index, C can calculate the
operation that can operate on all address of any element in the array.
the elements of the array. To An array stores all its data elements in consecutive
access all the elements of the memory locations. So, storing just the base address, i.e.,
array, you must use a loop. That the address of the first element in the array is sufficient.
is, we can access all the elements
The address of other data elements can simply be
of the array by varying the value calculated using the base address. The formula for doing
of the subscript into the array. this calculation is,
But note that the subscript must be an integral value or an
Address of data element, A[k] = BA(A) + w(k
expression that evaluates to an integral value. As shown in
- lower bound)
Fig. 5.2, the first element of the array marks [10] can be
accessed by writing, marks [0]. Now to process all the Here, A is the array, k is the index of the element for
elements of the array, we will use a loop as shown in which we have to calculate the address, BA is the base
Fig. 5.3. address of the array A, w is the word size of one element in
memory (e.g., size of int is 2), and lower _bound is the
index of the first element in the array.

Given an array int marks [] = {99, 67, 78, 56, 88, 90, 34, 85}.
Calculate the address of marks [4] if base address = 1000.

Figure 5.3
Solution

The code accesses every individual element of the array


Marks [0] [1] [2] [3] [4] [5] [6] [7]
and sets its value to —1. In the for loop, first the value of 1000 1002 1004 1006 1008 1010 1012 1014
marks [0] is set to —1, then the value of the index (i) is
incremented and the next value, i.e., marks [1] is set to—l. We know that storing an integer value requires 2 bytes,
The procedure is continued until all the 10 elements of the therefore here, word size is 2 bytes.
array are set to —1. Marks [4] = 1000 + 2(4 - 0)
The name of the array is a symbolic reference for the = 1000 + 2(4) = 1008
address to the first byte of the array. Therefore, whenever
we use the array name, we are actually referring to the first
byte of that array. The index specifies an offset from the
beginning of the array to the element being referenced. Example 5.2 Given an array,

float avoll. = 499.0 ~ 67:.0;..7Sn0 e56eOy 850,


90.0, 34.0, 85.0}. Calculate the address of avg [4] if

to executethe base address = 1000.


We know that storing a floating point number requires 4
erent index values. bytes, therefore, word size is 4 bytes.
compiler error to specify more number of values than the
number of elements in the array, When we write,
avg [0] [1] 2]; «Bhoy ii ehsr ey” ei)
1000 1004 1008 1012 1016 1020 1024 1028
an array with name marks is declared that has space
Avg [4] = 1000 + 4(4 - 0)
= 1000 + 4(4) = 1016
that is enough to store 5 elements. The first element, i.e.,
marks [0] is assigned with the value 90. Similarly, the
second element of the array, i.e., marks[1] has been
assigned 82, and so on.
While initializing the array at the tinle of declaration,
the programmer may omit to mention the size of the array.
For example, ;
int marks[]= {98,
97, 90};
The above statement is absolutely legal. Here, the
compiler will allocate enough space for all initialized
elements. If the number of values provided is less than the
When we declare and define an array, we are just allocating number of elements in the array, the un-assigned elements
space for the elements; no values are stored in the array. are filled with zeros. Figure 5.5 illustrates initialization of
To store values in the array, there are three ways. First, to arrays.
initialize the array elements during declaration; second, to
input values for individual elements from the keyboard;
third, to assign values to individual elements. This is
shown in Fig. 5.4.

Rest of the
elements are
filled with Os

Tsugeae Storing values inanarray


5.4.1 Initialization of Arrays
Oo @ 2 B El
Elements of the array can also be initialized at the time of
declaration as in the case of every
Programming Tip: other variable. When an array is
By default, the ele-_
initialized, we need to provide a
_mentsof the array value for every element in the
are not initialized.
They may contain | array. «48
Arrays are initialized by
writing,
some garbage value,
so before using the — type array_name [size] ={list
See
array you must ini- of values};
tialize the array- 5.4.2 Inputting Values
The values are written with
read some meaning-
curly brackets and every value An array can be filled by inputting values from the
o as is separated by a comma. It is a keyboard. In this method, a while/do-while or a for
Arrays | 149 |

loop is executed to input the value for each element of the euese”) Ol] We chaseilOl Meuse |i eae rehcnethUy cuca, =
array. For example, look at the code shown in Fig. 5.6. arr1 [2], and so on.
We can also use a loop to assign a pattern of values to
the array elements. For example, if we want to fill an array
a alue of each element of the array with even integers starting (from 0), then we will write the
code as shown in Fig. 5.8.
or (i=0; 4107144)
i<:
"SA", &marks i):
// Bill an array with even numbers
Figure 5.6 [ecenieg inputting each efement of the array.
inti, acc(10);
for (i=0;1<10;i++) LL.
In the code, we start with the index i at 0 and input A@rrii) = 21%2;

the value for the first element of the array. Since the array
can have 10 elements, we must input values for elements Figure 5.8 :Code for filling an array with even numbers
whose index varies from 0 to 9. Therefore, in the for
loop, we test for condition (i<10) which means the number
of elements in the array. In the code, we assign to each element value equal to
twice of its index, where index starts from zero. So after

5.4.3 Assigning Values executing this code we will have, arr [0] =0, arr[1] = 2,
arr [2] = 4, and so on.
The third way to assign values to individual elements of
the array is by using the assignment operator. Any value
that evaluates to an appropriate data type as that of the 5.5 LENGTH OF AN ARRAY
array can be assigned to the individual array element. A
Length of the array is given by the number of elements
simple assignment statement can be written as,
stored in it. The general formula to calculate the length of
marks [3] = 100;
the array is,
Here, 100 is assigned to the fourth element of the array
Length = upper bound - lower bound + 1
which is specified as marks [3] .
We cannot assign one array to another array, even if the where upper _bound is the index of the last element and
two arrays have the same type and size. To copy an array, lower bound is the index of the first element in the array.
you must copy the value of every element of the first array Usually, lower_bound is zero but this is not a
into the element of the second array. Figure 5.7 illustrates compulsion as we can have an array whose index may
the code to copy an array. start from any non-zero value.

Example 5.3 Let Age be an array of integers such that

Age[0] = 2 Age[1] = 5 Age[2] = 3


Age[3] = 1 Age [4] =

Solution
Show the memory representation of the array and calculate
its length.
Memory representation of the array Age is as given

In Fig. 5.7, the code accesses each element of the


first array and simultaneously assigns its value to
Age[0] Age[1] Age[2] Age[3] Age[4]
the corresponding element of the second array. Finally,
the index value i is incremented to access the next ele-
Length = upper bound - lower_bound + 1
ment in succession. Therefore, when this code is executed,
|150 |_Introduction to C Programming

Here, lower_bound = 0, upper bound = 4 in Step 2 is executed until all the elements in the array
Therefore, length =4—0+1=5 are processed. In other words, the while loop will be
executed until i is less than or equal to the upper bound
of the array.

Assume that there is an array Marks[ ], such


There are a number of operations that can be performed on that the index of the array specifies the roll number of the
arrays. These operations include: student and the value of a particular element denotes the
marks obtained by the student. For example, if it is given
e Traversal
Marks[4] = 78, then the student whose roll number is 4
e Insertion
has obtained 78 marks in the examination. Now, write an
e Search algorithm to:
e Deletion
e Merging (a) Find the total number of students who have secured

e Sorting 80 or more marks.


(b) Print the roll number and marks of all the students
We will study all these operations in detail in this
who have got distinction.
section.
Solution
5.6.1 Traversal (a) Step 7: [Initialization] Set I =1I+1
Step 2: Repeat for I = lower_bound to upper_
Traversing the array element means accessing each and
bound
every element of the array for a specific purpose. We have
If Marks[I] >= 80, then: Set Count =
already seen this while reading about accessing array
Countia!
elements. This is just a re-visit of the topic.
End of Loop]
If A is an array of homogeneous data elements, then
Step 3: Exit
traversing the data elements can include printing every
(b) Step 1: [Initialization] Set I =I+1
element, counting the total number of elements, or
performing any processing on these elements. Since an Step2: Repeat for I = lower_bound to upper_
bound
array is a linear data structure (because all its elements
If Marks[I] >= 75, Write: I,
form a sequence), traversing its elements is very simple
and straightforward. The algorithm for array traversal is Marks [T]
given in Fig. 5.9. [End of Loop]
Step 3: Exit

5.1 Write a program to read and display n numbers using


an array.
#include <stdio.h>
#include <conio.h>
Figure 5.9 int main()

{
In Step 1, we initialize index to the lower bound of lia, sO), al, ease (2Ol|«

the array. In Step 2, a while loop is executed. Steps 3 and elxcsexr


()-

4 form a part of the loop. Step 3 processes the individual


printf ("\n Enter the number of elements:") ;
array element as specified by the array name and index
scanf("%d", &n);
value. Step 4 increments the index value so that the
next array element could be processed. The while loop for (2=0)- era)
Arrays | 151 |

{ #include <conio.h>

printf("\n Arr[%d] = ", i); nee gw


scanf("%d", &arr[il]);
} int i, n, arr[20], small =1234, pos = -1;
elimsea)-
printf("\n The array elements are ");
for (1=0;i<n;i++)
printf ("\n Enter the number of elements in

prints ("Arr [td] = saNel a, are fal); Be F


scanf ("$d", &n);
return 0; Pe
for (i=0;i<n; i++)
scanf ("%d",
&arr [i] );
Output for (1=0;i<n;i++)
Enter the number of elements: 5 {
Arr[0] = 1 j if (arr [i] <smal1)
Are elige=t2
{
Arr[3] = 3 small = arr[i];
Arailaie= 4 pos = i;

Arr[5] = 5 }

The array elements are }

Arr[0] = 1 Arr[1] = 2 Arr[3] = 3 printf("\n The smallest of element is


Arr [4] = 4 Arr [5] =i sq", small);

5.2 Write a program to read and display


n random numbers printf("\n The position of the smallest
using an array. number in the array is: %d", pos);
#include <stdio.h> return 0;
#include <conio.h> }
#include <stdlib.h>
#define MAX 10 Output
jl Enter the number of elements: 5

int arr [MAX], i,RandNo; 12345


for (i=0;i< MAX;1i++) The smallest number is: 1
{ The position of the smallest number in the
/* Scale the random number in the range
array is: 0
0 to MAX-1 */ Y

RandNo = rand() % MAX; 5.4 Write a program to interchange the largest and the
i) Pens teyeee, debinedstunciion smallest number in the array.
arr[i] = RandNo;
} #include <stdio.h>
ee alcceat Contents Ob the vanray ane: #indludek- chal oee

Poe ene i eax iss) int main ()


printt(!\t, 4a", ary (il); {
getch (); int i, n, arr[20], temp;
} EE ER 2° int small = 9999, smajl pos =0;
imt' large = —9999, large pos = 0;

Output elrscr();
The contents of the array are: printf ("\n Enter the number of elements in
So ENT Ty] is amen rea acai a phere ee
5.3 Write a program to print the position of the smallest scanf ("sd", &n);
of n numbers using arrays.
for (1=0;i<n; i++)
#include <stdio.h> {
|152 | Introduction to C Programming

printf("\n Enter the value of element 5,5 Write a program to find the second biggest number
sd: ",4); using an array of nnumbers.
scanf ("%d", &arr [i] );
} #include <stdio.h>
; ; j
for (i=0;ic<n;i++) H
#include iO) 5 ie
<conio.h>
{ int main ()

if (arr [i] <small) {


{ Tee al, ial, uae ||AO|), AesaeS, Saliba, SeXcomel
large = -1234;
small = arr[i];
Siieulil joer! = hy clrscr (); ‘

if (arr [i] >large) printf ("\n Enter the number of elements


{ in the array: ");
large = arr[il]l; scanf("%d", &n);

large pos = 1;
} for (i=0;i<n;1i++)

} { j
printf("\n The smallest of these numbers printf ("\n Enter the number: ");
is : $a", small); Seam (> Gui carats all)
printf("\n The position of the smallest }
number in the array is: %d",small_ for (i=0;i<n;i++)
pos); {
printf("\n The largest of these numbers if (arr [i] >large)
is: %d", large); large = arr[il;
printf£("\n The position of the largest }
number in the array is: %d",large_ for (1=0;i<n;i++)
pos); {
temp = arr[large_pos] ; if(arr[i] != large)
arr[large pos] =arr[small_pos] ; {
arr[small pos] = temp; if (arr [i] >second_large)
printf ("\n The new array is: "); siscoilel leiacts = elree || 5
for (i1=0;i<n;1i++) }
joxenine:e (Gar erate |ycll) eyelets oilgaerew are (isi]|
)) }
Leturn 07 printf ("\n The numbers you entered are: ");
} for (1=0;i<n;1i++)
peinwh (Sdn cara ieuly)y
Output
printf("\n The largest of these numbers
Enter the number of elements: 5 is: %d",large);

12345 printf("\n The second largest of these


Enter the value of elements 1:1 numbers is: %d",second_ large);
Enter the value of elements 2:2 return 0;
Enter the value of elements 3:3 }
Enter the value of elements 4:4 Output

Enter the value of elements 5:5 Enter the number of elements in the array: 5
The smallest of these numbers is : 1 Puterothe number ol
The position of the smallest number in the Racer chetmunben >
array is: 0 Enter the number: 3
The largest of these numbers is: 5 Enter the number: 4
The position of the largest number in the Enter the number: 5
array is: 4 The numbers you entered are in the array:
The new array is: le operetta 5
yy wo gs Be 1 The largest of these numbers is: 5
The second largest of these numbers is: 4
Arrays| 153 |
5.6 Write a program to enter n number of digits. Form a for (j= i+1;j<n;j++)
number using these digits. {
if (acrayl
[il == arrayi igi cari l=s)
#include <stdio.h>
#include <conio.h>
{
IEIEYS
Sib p
#include <math.h>
printf ("\n Duplicate number %d found
int main()
at location %d and %d", arrayl[i],
{
Deis Jig
int number=0,
digit [10], numofdigits,i;
Cllseeyehal(()\

printf ("\n Enter the number of digits: ");


scanf("%d", &numofdigits);
}
Lf (elag==()
printf ("\n No Duplicate");
for (1=0;i<numofdigits;
i++)
return 0;
{ ,

printf ("\n Enter the td th digit: , a1);


}
scant ("%d", &digit
[i] ); Output
} Enter the size of the array: 5
i=0;
1273-405
while (i<numofdigits)
No Duplicate
{
number = number + digit[i] * pow(10,i); 5.8 Write a program to read marks of 10 students in the
l++; range of 0-100. Then make 10 groups: 0-10, 10-20,
} 20-30, etc. Count the number of values that fall in
printf ("\n The number is: %d", number); each group and display the result.
return 0;
#include <stdio.h>
#include <conio.h>
main()
Output {
Enter the number of digits: 3 int marks[50],i;
Botem ehenOth digit: 3 int group[10]={0};
Enter the 1th digit: 4 printf ("\n Enter the marks of 10 students
Enter the 2th digit: 5
\n")7
The number is: 543
for (1=0;1<10;1i++)
5.7 Write a program to find whether the array of integers {
contain a duplicate number. jonanlauese (rey WNSaS) [Exell] = MW, at)
scanf("%d", &marks
[i] );
#include <stdio.h>
++group [ (int) (marks [i] )/10];
#include <conio.h>
int main() }
Prints
(1 \n\n ka
Rk a akk a IT);
{ printf ("\n GROUP \t\t FREQUENCY");
shakes fleraehyal [alll], aby tely ain eedkete—0)p
for (1=0;1<10;1++)
elrser();
jopantatens (Ue fxol Miea\ic, Gxellh, ab, Gpereisys) {fat} ))F
getch ();
printf ("\n Enter the size of the array:") ;
return 0;
scanf("%d", &n);
for (1=0;i<n;i++)
}
{ Output
scanf("%d", &arrayl
[i] );
Enter the marks of 10 students:
} MARKS [0] = 95
for (i=0;i<n;
i++)
MARKS [1] i] 88
{ MARKS [2] 67
|154 | Introduction to C Programming

MARKS [3] = 78 Output


MARKS [4] = 81
****%* THE FREQUENCY TABLE ******
MARKS [5] = 98
@)* jee) &
MARKS [6] = 55 HOmCOmLS
MARKS [7] = 45 ZiOme Ome 9
MARKS [8] = 72 230) jee) SIS)
MARKS [9] = 90 40 to 49
KKEKEKKKKEKRKEKKKEKKEKEKKKKKEKKKKEK
SOR tO 59.
GROUP FREQUENCY 60 to 69
0 0 LOMEOm So
at 0) PP
U1
SI750))
6)
©:
Te
WP 80 to 89
2 0 bh oS 90" ross NO
ND
WwW
FP
FN
WN

3 0
5.10 Modify the above program to display frequency
4 al
histograms of each group.
5 Al
6 1 #include <stdio.h>

i Z main ()

8 Zi {
Ss) 3 int marks[10], i;
int group [10]={0};
5.9 Write a program to enter the number of days a
printf("\n Enter the marks of 10 students
programmer takes to code a module. Then categorize
Nant);
it in different groups to analyse the data. for (i=0;1<10;1i++)
#include<stdio.h> {
#include<conio.h> pine
eC \neMARKS
sc ie Ui).
main () scanf("%d", &marks
[i] );
{ ++group [ (int) (marks [i] )/10];
Sholeiaa Mate: aisiegahals, end,arr [20] ; }
int Guoup lit = LO}; pilin & (o\n\ia FR RK RK RK KN):

CHieser()F; printf ("\n GROUP \t\t FRQUENCY");


printf(“\n Enter the number of for (1=0;1<10;i++)
programmers : “); jopaabahens (UN Excl We\ie xel, al,” fenetoysyes|
atl} "6
scant ('sd", &n) ; T=}
for (i=0;i<n;1i++) printf ("\n\n FREQUENCY HISTOGRAM");
{ printf£(“\n In how many days did for (index=0; index<10; index++)
programmer %d code the project? : %,
{
i+1); printf ("\n GROUP %d | ",index);
scant (“td", arr [2']) >
for (i1=0; i<group [index] ; i++)
++group[
(int) (arr[i]/10)];
print (ues):
} }
printf (“\n *******eeee** THE FREQUENCY
getch();
TABLE *** eke K KK KKK KKKK\ YN):
return 0;
for (i=0;i<10;1i++)
}
{
start = i*10; Output
alae (abil),
Enter the marks of 10 students:
end = start+9;
MARKS [0] = 95
else
MARKS [1] = 88
end = 100;
MARKS [2] = 67
Prince (SasGONe Ni sd Newto NewsdaNt
MARKS [3] = 78
d\n”, i+1, start, end, group[i]);
MARKS [4] = 81
} MARKS [5] = 98
Arrays | 155 |
MARKS [6] = 55 Enter the values:
MARKS[7] = 45 12 34 56 78 89
MARKS [8] = 72 MEDIAN = 56.00
MARKS [9] = 90 5.12 Write a program to feed a list of numbers and
KRKKKK KEK KKK KKKKKKKKK
KKK KK
calculate its mean, standard deviation, and variance.
GROUP FREQUENCY #include<[Link]
0
#include<conio.h>
#include<math.h>
main ()
{
alate SL, iste
float arr[20], std dev, sum=0, sum_sqr=0,
mean, variance, deviation;
liatsyese'() 5
Nr
£O
OO
tk
Seas
2) 4
printf (“\n Enter the number of values
oO
OLE
WwW
1B
On
SOV
»,OOF
XO

FREQUENCY HISTOGRAM
yee
scanf(“%d”, &n);
GROUP 0
for (1=0;1i<n;i++)
GROUP
GROUP {
scan£ (“38”,, -&arx [a].);
GROUP
sum += arr[il];
GROUP
GROUP | * }
mean = sum/(float)n;
GROUP
for (1=0;1i<n;1i++)
GROUP us) Tas

GROUP Ae kA {
deviation = arr[i] - mean;
GROUP STON
LOCOS
Goh
OS ek

sum_sqr += deviation * deviation;


5.11 Write a program to read a sorted list of floating point }
values and then calculate and display the median of varience = sum_sqr/(float)n;
the values. std_dev = sqrt (variance) ;
printf(“\n Mean : %.2£”, mean);
#include <stdio.h>
printf(“\n Standard Deviation : %.2f”,
#include <conio.h>
std_dev);
main ()
printf(“\n Variance : %.2£”, variance) ;
{
WME aL, Bl, Tals
}
float median, values[10]; Output
printf ("\n Enter the size of the array: ");
Enter the number of values : 10
scanf("%d", &n);
alps hehe eyed NS) Icy (oy)? Wish {sie (0) Si)
printf ("\n Enter the values: ");
Mean =52°90
for (1=0;1i<n;1i++)
Standard Deviation = 26.12
scanf ("S£", &values
[i] );
Variance = 682.49
if (n$2==0)
median = (values [n/2] + values [n/2+1] ) /2.0;
else 5.6.2 Insertion
median = values[n/2 + 1];
Inserting an element in the array means adding a new data
printf ("\n MEDIAN = %f£", median);
element in an already existing array. If the element has to
getch ();
be inserted at the end of the existing array, then the task
return 0
of inserting is quite simple. We just have to add | to the
}
upper_bound and assign the value. Here we assume that
Output the memory space allocated for the array is still available.
Enter the size of the array: 5 For example, if an array is declared to contain 10 elements,
156 | Introduction to C Programming

but currently it is having only 8 elements, then obviously (b) Write the upper bound and lower bound.
there is space to accommodate two more elements. But if (c) Give the memory representation of the array.
it already has 10 elements, then we will not be able to add (d) If anew data element with value 75 has to be inserted,
another element to it. find its position.
Figure 5.10 shows an algorithm to insert a new element
(e) Insert the new data element and then give the memory
to the end of the array.
representation of the array.
(f) length of the array = number of elements

-—-“Step 1: Set ound = upper_bo Therefore, length of the array = 10



pound] (g) By default, lower bound = 0, (it can be set to any
<2 3:: EXIT.
value) and upper bound = 9

Figure 5.10 “Algorithm to appen an


newwelement to an
existing array) — (OJ iltool2h adshen4)enh] (6h ZI" ie s{S
(h) Since the elements of the array are stored in ascending
In Step 1 of the array, we increment the value of the order, the new data element will be stored after 67,
upper bound. In Step 2, the new value is stored at the i.e., at the 6th location. So, all the array elements from
position pointed by upper bound. the 6th position will be moved one space towards the
For example, if we have an array that is declared as right to accommodate the new value.

int marks [60];

The array is declared to store marks of all the students


(a2[m3[34[a5[56[67[75|78[89|90300
(0) [1] [2] [3] [4] [5] (6) [7] [8] [9] [10]
in the class. Now suppose there are 54 students and a new
student comes and is asked to given the same test. The Algorithm to insert an element in the middle of the
marks of this new student would be stored in marks [55]. array
Assuming that the student secured 68 marks, we will The algorithm INSERT will be declared as INSERT (A, N,
assign the value as, POS, VAL). The arguments are
marks [55] = 68;
(a) A, the array in which the element has to be inserted
However, if we have to insert an element in the middle (b) N, the number of elements in the array
of the array, then this is not a trivial task. On an average, (c) POS, the position at which the element has to be
we might have to move as much as half of the elements inserted and
from its position in order to accommodate space for the
(d) VAL, the value that has to be inserted.
new element.
In the algorithm given in Fig. 5.11, in Step 1, we first
For example, consider an array whose elements are
initialize I with the total number of elements in the array.
arranged in ascending order. Now, if a new element has
to be added, it will have to be added probably somewhere
in the middle of the array. To do this, what we will have Step 1: [INITI
to do is, first find the location where the new element will Step <: Oe Ss

be inserted and then move all the elements (that have a


value greater than that of the new element) one space to
the right so that space can be created to store the new
value.

Example s.5 Data[] is an array that is declared as int arava eeAlgorithm to insert a new element at 3
Data [20]; and contains the following values: specified position

Data'[]’*= {127 23°/ 34)'45 ,-56; 67/78; 89,90, 100};


In Step 2, a while loop is executed which will move all
(a) Calculate the length of the array.
the elements that have index greater than POS one space
Arrays | 157 |

towards right to create space for the new element. In Step 5, printf ("\n Enter the position at which
Wwe increment the total number of elements in the array Epcguumber has’ to be added: ™);
by 1 and finally in Step 6, the new value is inserted at the scant hed" ie&pos);
desired position.
e 3 for (i=n;i>=pos; i--
Now, letay us visualize this algorithm by taking an Se es
euere|talemil||
ai
= yerese"| [al] ip
example. Initial Data[] is given as shown in Fig. 5.12. arr{pos] = num;
Calling INSERT (Data, 6, 3, 100) will lead to the n++;
following processing in the array: printf ("\n The array after insertion of
sa a3: =", Snum);

for (1=0;7<n+1
714+)
jousaiaieie (Misuse |[Holl) <= Sell, ay, aie [ak] ig
getch();
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6] shanre 2*0

Output
Data[0O] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6)
Enter the number of elements in the array: 5
Enter the values:
2, 3-455
Enter the number to be inserted: 7
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6]
Enter the position at which the number has
BO bemadded 5
The array after insertion of 7 is:

Data[O] Data[1] Data[2] Data[3] Data[4] Data[5] Data[6] a i


5.14 Write a program to insert a number in an array that
one is already sorted in ascending order.
#include <stdio.h>
5.13 Write a program to insert a number at a given #include <conio.h>
location in an array. int main()

1
#include io.h
<stdio.h>
{ ;
“ae :
Beg) 4 a, SE eer

#include <conio.h> clrscr ();


int main ()
printf ("\n Enter the number of elements
{ in the array: ");
aae, aby ial, ieloii, eS, Guere |aLOl| scanf ("$d", &n);

ellizteyerel()) :
printf ("\n Enter the array elements:");
for (1=0;i<n;i++)
printf ("\n Enter the number of elements scanf("$d", &arr[il);

in the array: "); printf ("\n Enter the number tobe inserted: ");
scanf("%d", &n); scanf("%d", &num);
for (1=0; i<n;1++)

for (i=0;1<n;1i++) {

{ if(arr[i] > num)


printf ("\n Arr[%d] =: ", i); {
scant ("$d", &arr[i]); for(g, = nely, G>=1e cen)
arr[j+1] = arr[j];

printf ("\n Enter the number to be arr[i] = num;


inserted: "); break;
scant ("%d", &num); }
158 | Introduction to C Programming

} do this, what we will have to do is, first find the location


n++; from where the element has to be deleted and then move
printf("\n The array after insertion of all the elements (that have a value greater than that of the
el Mushy WE Sahbiqi))
element) one space towards the left so that space vacated by
for (1=0; i<n+1;1++)
the deleted element be occupied by rest of the elements.
joneiniese (MONE Syelll, “eer [[at]|))e
getch ();
iaSiewbhaak (OF
Example 5.6 Data[] is an array that is declared as int
Data [10] ; and contains the following values:
}
Output Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};
Enter the number of elements in the array: 5 (a) Calculate the length of the array.
Teor ona 5
(b) Write the upper bound and lower bound.
Enter the number to be inserted: 6
The array after insertion of 6 is: (c) Give the memory representation of the array.
i Shon A By AS) (d) If a data element with value 56 has to be deleted, find
its position. z
5.6.3 Deletion Solution

Deleting an element from the array means removing a data (a) length of the array = number of elements

element from an already existing array. If the element has Therefore, length of the array = 10
to be deleted from the end of the existing array, then the
task of deletion is quite simple. We just have to subtract 1
from the upper_bound. Figure 5.13 shows an algorithm to (b) By default, lower bound = 0 (it can be set to any
delete an element from the end of the array. value) and upper_bound= 9.
(c) Data{O] Data[1] Data[2] Data[3] Data[4] Data[5]
Data[6] Data[7] Data[8] Data[9]
(d) Since the elements of the array are stored in ascending
order, we will compare the value that has to be deleted
from the value of every element in the array. As soon
Figure 5.13 ‘Algorithm to delete the last element of an
ce as VAL = Data[I], where Lis the index or subscript
atay _
of the array, we will get the position from which the
element has to be deleted. For example, if we see this
For example, if we have an array that is declared as array, here VAL = 56. Data[0] = 12 which is not
int marks []; equal to 56. Like this, we will compare and finally get
the value of POS = 4.
The array is declared to store marks of all the students
in the class. Now suppose there are 54 students and the
Algorithm to delete an element from the middle of the
student with roll number 54 leaves the course. The marks array
of this student were therefore stored in marks [54]. We The algorithm DELETE will be declared as DELETE(A, N,
just have to decrement the upper bound. Subtracting 1 POS). The arguments are as follows:
from the upper bound will indicate that there are 53 valid
(a) A, the array from which the element has to be deleted
data in the array.
(b) N, the number of elements in the array
However, if we have to delete the element from the
(c) POS, the position from which the element has to be
middle of the array, then this task is not trivial. On an
deleted.
average, we might have to move as much as half of the
Figure 5.14 shows the algorithm in which we first
elements from its position in order to occupy the space of
initialize I with the position from which the element has
the deleted element.
to be deleted. In Step 2, a while loop is executed which
For example, consider an array whose elements are
will move all the elements that have index greater than
arranged in ascending order. Now, if an element has to be
POS one space towards left to occupy the space vacated by
deleted probably from somewhere middle in the array. To
the deleted element. When we say that we are deleting an
Arrays | 159 |

element, actually we are overwriting the element with the #include <conio.h>
value of its successive element. In Step 5, we decrement int main()
the total number of elements in the array by 1. {
ame hyp pal, jeleksi,
eucra LO.
Gliese()-

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


scané ("Sd", &n);
printf ("\n Enter the elements of the
encweny 9 Ye
for (1=0;1i<n;
i++)
scant ("Sd", sar [2] );
printf ("\n Enter the position from which
F
the number has to be deleted: ");
scanf("%d", &pos);

Now, let us visualize this algorithm by taking an ex- for(i= pos; i<n;i++)
ample and having a look at Fig. 5.14. eke N oc tiakWiaeh iy
Initial Data [] is given as shown in Fig. 5.15. Fee
printf ("\n The
array after deletion is:");
Calling DELETE (Data, 6, 2) will lead to the following
for (i=0;i<n;
i++)
processing in the array: jotestiahewe
(UWNici, uae |/zfoll| == kyel, ah, ~elero (41) ))p
getch ();
return 0;

}
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5]
Output
Enter the size of the array: 5
Enter the elements of the array:
LZ ese 45
Enter the position from which the number has
(b) LO, be Geleved|: 33
The array after deletion is:
Nae ||O}l| =a
Nae (dl) tt 2
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] Arr [2] ll 3}

(c) Arr [3] 5

5.16. Write a program to delete a number from an array


that is already sorted in ascending order.
Data[0] Data[1] Data[2] Data[3] Data[4] Data[5] 43 ne tade Séatidvoens

(d) #include <conio.h>


int main()

‘ {
Data[0] Data[1] Data[2] Data[3] Data[4] int i, n, j, num, arr[10];
(e) clrscr();

in the array :
= . , printf ("\n Enter the number of elements

ng elements scanf("$d", &n);

5.15. Write a program to delete a number from a given Perea tae)


location in an array. ea aeacr

#include <stdio.h> printf ("\n Enter the number to be deleted : ");


|160 | Introduction to C Programming

scanf("%d", &num); #include <conio.h>

for (i=0;i<n;
j++) main ()

{
alates stereo)
2 chare2s (abOyl|e. stetes} [2 (0)i]
thghe ob, sells) ta, aul, atgkelebie=t0)7
for (j=i; jJ<n;i++) clrscr ();
arr[j] = arr h+1); printf ("\n Enter the number of elements
} sgh Teneigeyye alg —)\)-
} secant ("Sd", Sn): t
printf("\n The array after deletion is:
printf("\n\n Enter the Elements of the
Ws
first array");
for (i=0;1i<n-1;i++)
opeauanese (Oa FRI RK KKK RK KK KKK KI)
ousdiaisin(')
Wisco cle, ragst= [eins
for (i=0;i<n1;i++)
getch ();
scanf("%d", sSarri1[i]);
return 0;

}
printf ("\n Enter the number of elements
Output in Ansa ys Zone yy
Enter the number of elements in the array: scanf ("%d", &n2);
5
printf ("\n\n Enter the Elements of the
eas: 740-5
second array");
Rnvemetne mumberm to) be deleted: 3
PLANtE ("re RKKR KIN);
The array after deletion is: 1245
for (1=0;i<n2;1i++)

scant ("S$d", -“S&arr2


[1] );
5.6.4 Merging
m = ni+n2;

Merging two arrays in a third array means first copying for (1=0;i<n1;1++)
the contents of the first array into the third array and {
then copying the contents of the second array into the arrs fandex] = arni[i],-
third array. Hence, the merged array contains contents index++;
of the first array followed by the contents of the second
}
array.
for (i=0;i<n2;i++)
If the arrays are unsorted then merging the arrays is
very simple as one just needs to copy the contents of {
arr3 [index] = arr2[i];
one array into another. But merging is not a trivial task
index++;
when the two arrays are sorted and the merged array
also needs to be sorted. Let us first discuss the merge }
operation on unsorted arrays. This operation is shown in printf ("\n\n The merged array is");
printf ("\n RRR KKK K KK KK KK KK KK KM)
Fig. 5.16.
for (i=0;i<m;i++)
jomanetese (MS ies lexcll| SS welll Si. uae) (aL) jp

pissy 1 getch ();


retum “0s

Array 3
EnEee ES EEE Output
Enter the number of elements in array 1: 3
Merging of two unsorted arrays Enter the Elements of the first array
10 20 30 KHEKKKKKKKEKKKKKEKK

Enter the number of elements in array 2: 3


5.17 Write a program to merge two unsorted arrays. Enter the Elements of the second array
15 25 35 KKKKKKKKKKKK

#include <stdio.h>
Arrays | 161 |

The merged array is printf ("\n Enter the number of elements


KKKKKKEKKKK
dja eviarsaly2 a ')))e
MAOIs Le iNveie (ak I 20 Arr [3] i 30 scanf ("%d", &n2);
Nera |) aS) Arr [5] 25 Neral) = SNS printf ("\n\n Enter the elements of the
second array");
If we have two sorted arrays and the resultant merged
PLANE
("\ mR ek kk RK RK KM)»
array also needs to be a sorted one, then the task of merging
for (1=0; 1<n2;i++)
the arrays becomes a little difficult. The task of merging
scanf("%d", &S&arr2[i]);
can be explained using Fig. 5.17. m = nil+n2;
while (index first <nl && index _second < n2)

Array
1-
{
if (arr1 [index _first] <arr2 [index_second] )

Array
2- {
ans fandexl|) = arial landex fansite

Array 3-
i]z0 so]as50]5]co]ea]70) }
index first++;

else
arieeews | Merging oftwo sorted arrays -
{
arr3 [index] = arr2 [index second] ;
The figure shows how the merged array is formed using index second++;
two sorted arrays. Here, we first compare the Ist element of }
Array | with the Ist element of Array 2, put the smaller index++;

element in the merged array. Since 20 > 15, we put 15 as


the first element in the merged array. We then compare the
/* if elements of the first array is over
2nd element of the second array with the 1st element of the
and the second array has some elements */
first array. Since 20 < 22,now 20 is stored as the second
element of the merged array. Next, 2nd element of the
Lf Gindex rims ==—nil)
first array is compared with the 2nd element of the second
{
array. Since 30 > 22, we store 22 as the third element of while (index_second<n2)
the merged array. Now, we will compare the 2nd element
{
of the first array with 3rd element of the second array. As arr3 [index] = arr2[index_second];
30 < 31, we store 30 as the 4th element of the merged array. index second++;
This procedure will be repeated until elements of both the index++;
arrays are placed in the right location in the merged array.
5.18 Write a program to merge two sorted arrays.
}
if elements of the second array is over
#include <stdio.h> and the first array has some elements */
#include <conio.h>
main () elise if (imdex second)'==7n2)

{
intrans. [Molar
iL0lG, arsc3l201; while (index first<n1)
pages why gh, il 2 7 jie abalolo>e—0),
int index first = 0, index second = 0; arr3 [index] = arrl[{index first];
culbeeyete())s index first++;
printf ("\n Enter the number of elements index++;
ine akrayluc 2)
scanf("%d", &n1); }
print£("\n\n Enter the elements of the printf ("\n\n The contents of the merged
first array"); array are");
printf ("\n KK KK kk kK KKK KK KM) printf (Xn KKK KK KK RK KKK KKK KKK KK KK KKM) ,

for (i=0;i<n1;1++) for (1=0;1i<m;


i++)
scanf ("$d", &S&arri1[i]); joiner ("wnayAnar [Sil Sach let aracsileinli
|162 | Introduction to C Programming

getch
() ;
return 0;

}
Output
Enter the number of elements in arrayl: 3
Enter the Elements of the first array A[O] A[1] A[2] A[3] A[4] A[5] Ale] A[7] AL8] ALI]
KAEKKEKKKEK

LON2Z0 730
Enter the number of elements in array2: 3
Enter the Elements of the second array
KREKKEKKKKEKK

U5 -2555)5
The contents of the merged array is
KEKKKKKKKKK

Arr[0]= 10 Arr [1] dks) Arr [3] 20


Abela) = 925 iNere |(5)] 30 Arr [6] S5

5.6.5 Searching
Searching means to find whether a particular value A[O] A[1] A[2] A[3] A[4] A[5] Af6] A[7] A[8] A[9]
is present in the array or not. If the value is present in
the array then searching is said to be successful and the
searching process gives the location of that value in the
array. Otherwise, if the value is not present in the array, the
searching process displays the appropriate message and in
this case searching is said to be unsuccessful. Ao} A(1] Al2] A[3] Al4] Als] A[6] A[7] A[8] Ato]
There are two popular methods for searching the array
Figure 5.18
elements. One is /inear search and the second is binary
search. The algorithm that should be used depends entirely
on how the values are organized in the array. For example, Thus, we see that linear search executes in O(n) time
if the elements of the array are arranged in ascending order, where n is the number of elements in the array. Obviously,
then binary search should be used as it is more efficient for the best case of linear search is when VAL is equal to the
sorted list in terms of complexity. We will discuss these first element of the array. In this case, only one comparison
two methods in detail in this section. will be made.
Likewise, the worst case will happen when either VAL is
Linear Search not present in the array or it is equal to the last element of the
Linear search, also called sequential search is a very simple array. In both the cases, n comparisons will have to be made.
method used for searching an array for a particular value. However, the performance of the linear search algorithm
It works by comparing every element of the array one by (Fig. 5.19) can be improved by using a sorted array.
one in sequence until a match is found. Linear search is In Step 1 and Step 2 of the algorithm, we initialize the
mostly used to search an unordered list of elements (array value of Pos and I. In Step 3, a while loop is executed
in which data elements are not sorted). For example, if an that would be executed until I is less than N (total number
array A[] is declared and initialized as, of elements in the array). In Step 4, a check is made to
see if a match is found between the current array element
Trt Al oe BOs ne 24 eo ee
and the VAL. If a match is found, then the position of the
and VAL = 7, then searching means to find out whether array element is printed else the value of I is incremented
the value ‘7’ is present in the array or not. If yes, then to match the next element with VAL. However, if all the
the search is successful and it returns the position of arrays elements have been compared with VAL, and no
occurrence of VAL. Here, the POS = 3 (index starting from match is found then it means that the VAL is not present in
0). Figure 5.18 illustrates this concept. the array.
Arrays | 163 |

Output
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

Binary Search

[ENDOFIF We have seen that the linear search algorithm is very slow.
OF while I
ENDane If we have an array with 1 million entries then to search
a value from that array, we would need to make | million
comparisons in the worst case. However, if the array is
sorted, we have a better and efficient alternative, known
attic Algorithm forlinear search as binary search.
o

Binary search is a searching algorithm that works


efficiently with a sorted list. The algorithm finds out the
5.19 Write a program to implement linear search.
position ofa particular element in the array. The mechanism
#include <stdio.h> of binary search can be better understood by using the
#include <conio.h>
analogy of a telephone directory. When we are searching
main ()
for a particular name in the directory, we will first open
{
ikate, Eas ALO ,,sein,
aly, sel akeyeralel =x Oy joes! a aly
the directory from the middle and then decide whether to
elzesex); look for the name in the first part of the directory or in
the second part of the directory. Again we will open some
printf ("\n Enter the number of elements page in the middle and the whole process will be repeated
im thesarray= <= '); until we finally find the name.
scanf("%d", &n); Take another analogy. How do we find words in a
dictionary? We first open the dictionary somewhere in the
printf ("\n Enter the elements -");
middle. Then we compare the first word on that page with
for (i=0;i<n;i++)
scant ("sda", Sarr [i] );
the desired word whose meaning has to be found. If the
word comes before the word that appear on the page we
printf ("\n Enter the number that has to will look in the first half of the dictionary else we will
be searched : "); look in the second half. Again, we will open up some page
scant ("%d", &num); in the first half of the dictionary pages. Compare the first
word on that page with the desired word and repeat the
for (i=0;i<n;
i++)
same procedure until we finally get the word. The same
{ mechanism is applied in binary search.
skie(lano|[a|) SS sakbiei))
Now let us consider how this mechanism will be applied
{
found =i; to search for a value in a sorted array. Given an array that
pos=i; is declared and initialized as,
printf ("\n %d is found in the array int ws (Oi 2 tay 64S aeen 7 7 By PD, MLOYy
Ale jOOenenein = Zell, imibit, al)
break; and VAL = 9, the algorithm (Fig. 5.20) will proceed in
the following manner.
} He SO, iN) = ah), NEEDS (© ss LO) ye = &
alse (Greyeratcl == (0)
printf ("\n %d DOES NOT EXIST in the Now, VAL = 9 and A[MID] = A[5] = 5
array", num); A[5] 1s less than VAL, therefore, we will now search for
getch (); the value in the later half of the array. So, we change the
return 0;
values of BEG and MID.
|164 | Introduction to C Programming

Now, BEG = MID + 1 = 6, END = 10, MID = (6 + the algorithm should terminate as it will indicate that the
10)./2.=16/2.= 8 element is not present in the array and the search will be
Now, VAL = 9 and A[MID] = A[8] = 8 unsuccessful.
A[8] is less than VAL, therefore, we will now search for Let us consider another example.
the value in the later half of the array. So, again we change inteaLh =A00, 0; Soieay: 2, <5 Ope rrereuos
the values of BEG and MID. 10}; and VAL = 2
Now, BEG = MID + 1 = 9, END = 10, MID = (9 +
Step 1: BEG = 0, END i] 10, MID = 5
A[MID] > VAL
LO aae 9
Step 2: BEG = 0, END = MID - 1 = 4, MID = 2
Now VAL = 9 and A[MID] 9.
A[MID] = VAL
Now VAL = 9 and A[MID] 9.
Figure 5.20 shows an algorithm for binary search.
In this algorithm we see that BEG and END are the
In Step 1, we initialize the value of variables—BEG,
beginning and ending positions of the segment that we
END, and Pos. In Step 2, a while loop is executed until
are looking to search for the element. MID is calculated
BEG is less than or equal to END. In Step 3, value of MID
as (BEG + END) /2. Initially, BEG = lower bound and
is calculated. In Step 4, we check if the value of MID is
END = upper bound. The algorithm will terminate when
equal to VAL (item to be searched in the array). Ifa match
A[MID] = VAL. When the algorithm ends, we will set Pos
is found then value of the POS is printed and the algorithm
= MID. POS is the position at which the value is present in
exits. However, if a match is not found then if the value
the array.
of A[MID] is greater than VAL, then the value of END is
However, if VAL is not equal to A [MID], then the values
modified otherwise if A[MID] is less than VAL, then value
of BEG, END, and MID will be changed depending on
of BEG is altered. In Step 5, if the value of POS = -1, then
whether VAL is smaller or greater than A[MID] .
it means VAL is not present in the array and an appropriate
(a) If VAL <A[MID], then VAL will be present in the left message is printed on the screen before the algorithm
segment of the array. So, the value of END will be exits.
changed as, END = MID - 1 The complexity of the binary search algorithm can be
(b) If VAL > A[MID], then VAL will be present in the expressed as f (n), where n is the number of elements in
right segment of the array. So, the value of BEG will the array. The complexity of the algorithm is calculated
be changed as, BEG = MID + 1 depending on the number of comparisons that are made. In
Finally, if that VAL is not present in the array, then binary search algorithm, we see that with each comparison,
eventually, END will be less than BEG. When this happens, the size of the segment where search has to be made is

BINARY _SEARCH(A, lower bound, upper bound, VAL, POS)


=X

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


Step 2: Repeat Step 3 and Step 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
IF A[MID] > VAL then;
SET END = MID - 1
ELSE
SET BEG = MID +1
"TREND OF TF).
[END OF while LOOP]
Step 5: IF POS = -1, then
PRINTF “VAL IS NOT PRESENT IN THE ARRAY”
[END OF IF]
Step 6: EXIT

arVi¢-eery40a Algorithm for binary search


Arrays _| 165 |

reduced to half. Thus, we can say that, in order to locate Enter the elements: 123 45
a particular VAL in the array, total number of comparisons Enter the number that has to be searched: 7

that will be made is given by, 7 DOES NOT EXIST in the array

Dee nor c(h) = loon

5.20 Write a program to implement binary search.


#include <stdio.h>
#include <conio.h> Like variables of other data types, we can also pass an
main ()
array to a function. While in some situations, you may
{ Pe
want to pass individual elements of the array, and in other
int arr[10],
num, i, n, pos =-1, beg, end,
situations you may want to pass the entire array. In this
mid, found =0;
section, we will discuss both these cases. Look at Fig. 5.21
elirserei();
which will make the concept easier to understand.

printf("\n Enter thé number of elements


in the array: ");
scanf("%d", &n);
printf ("\n Enter the elements: ");
for (1=0;i<n;1i++)

{
scant ("%d", &arr[i]);

}
printf ("\n Enter the number that has to
be searched: ");
scanf("%d", &num);

begp=0), cende—an— 15,


while (beg <end) Figure 5.21 (lel
{
mid = (beg + end) /2;
if (arr[mid] == num)
Passing Individual Elements
{
printf("\n %d is present in the array The individual elements of an array can be passed to a
at position = %d", num, mid); function either by passing their addresses or their data
found=1; values.
break;

} Passing Data Values


if (arr [mid] >num) The individual elements can be passed in the same manner
end = mid-1; as we pass variables of any other data type. The condition
else if (arr[mid] < num) is just that the data type of the array element must match
beg = mid+1; the type of the function parameter. Figure 5.22 shows the
} code to pass an individual array element by passing data
if ( beg > end && found == 0)
value.
printf ("\n %d DOES NOT EXIST IN THE
In the above example, only one element of the array
ARRAY", num);
is passed to the called function. This is done by using the
getch ();
index expression. So arr [3] actually evaluates to a single
return 0;
integer value. The called function hardly bothers whether
}
a normal integer variable is passed to it or an array value
Output is passed.
Enter the number of elements inthe array: 5
|166 | Introduction to C Programming

the elements in the array can be calculated using the array


Calling name and the index value of the element. Therefore,
when we need to pass an entire array to a function,
we can simply pass the name of the array. Figure 5.24
illustrates the code which passes the entire array to the
called function.

Calling
function

Figure 5.22

Passing Addresses
Now again like ordinary variables, we can pass the
address of an individual array element by preceding the
address operator (&) to the element’s indexed reference.
Therefore, to pass the address of the fourth element of the Figure 5.24 | Passing entire array to function —
array to the called function, we will write carr [3] .
However, in the called function the value of the array In cases where we do not want the called function to make
element must be accessed using the indirection (*) any changes to the array, the
operator (Figure 5.23). We will read more about this array must be received as a
technique later in this chapter. arrayistobe constant array by the called
_sent to the callec function. This prevents any type
function, the calling of un-intentional modifications
function just needs — of the array elements. To declare
“to 1e name of | the array as a constant array,
/ simply add the keyword const
before the data type of the array.
5.21 Write a program to read and print an array of n
Called — numbers.
~Cefunction #include <stdio.h>
#include <[Link]
void Teadvarray( anteater []) ints);
void display array( int arr[], int);

int main()

Figure 5.23 Passin individual ar {


atime AMWUGILILO)|| , sai
function — :
@lliaisyeue
(())5
printf ("\n Enter the size of the array: —s ~

Passing the Entire Array scanf("%d", &n);°


read_array(num, n);
We have studied that in C, the array name refers to the
display array(num, n);
first byte of the array in memory. The address of rest of
getch ();
Arrays _| 167 |

return 0; reverse array(arr3, t);


} getch();
void read_array( int arr[10], int n) return 0;
{ }
aban, als void read_array(int my_array[10], int n)
£or (a=0 -2<n-1++)
{
{ aligie aks
print£ ("\n array [td] = ", i); for (i=0;i<n;
i++)
scanf("%d", &arr[i]); scanf("%d", &my array
[i] );

} e
}
void merge _array(int my _array3[], int t, int
void display array( int arr[10], int n) my arrayl[], int m, int my _array2[], int n)
{
£or (ant 1=05
ten 21+) shale ab, 3 =0)5
pistaiet (U\neancay
isdli=—sal sine Vamr [1] ); for(i=0; i<m; i++)
} ’ {
my_array3[j] = my_arrayl1[i];
Output
ibrar
Enter the size of the array: 5
gh 293) 45 for(i=0; i<n; i++)
253) 45

my _array3[j] = my_array2[i];
5.22 Write a program to merge two integer arrays. Also J++;

display the merged array in reverse order.


}
#include <stdio.h>
void display _array(int my _array[], int n)
#include <conio.h>
{
void read_array(int my _array[], int);
bake Gbe
void display array(int my_array[], int);
for (i=0;i<n;i++)
void merge_array(int my_array3[], int, int
joseaborea((W
Ga ~aee|iGxoll) x6 p eat,
my_arrayl[], int, int my _array2[], int);
my_array
[i] );
void reverse _array(int my_array[], int);
}
int main()
void reverse array(int my_array[], int m)
{ {
IntrariwalLOlemarce lle arrsi2o@ls, nem, t;
ee al, SIs
else()); £O%s (Gm a = Ole
=Ol eeaitat)
jorbo (In Enea lize eel, a),
printf ("\n Enter the number of elements
my_array
[i] );
in the first array: ");
}
scanf("%Sd", &m);
read_array(arrl, m); Output
printf ("\n Enter the number of elements Enter the number of elements in the first
in the second array: "); euaigehye =
scanf("%d", &n); ILO) 230) Sy)
read_array(arr2, n); Enter the number of elements in the second
= eee avray: 3
merge_array(arr3, fe, wae, mile eur sal)
is) As) S}5)
The merged array is:
printf ("\n The merged array is : "); Arr[0]= 10 aesejlall| aS AO iver |(2)| Eas 2h)
display _array(arr3, t); mMecre||3l) = AUS Neel) EBS INE |S) ee BS
The merged array in reverse order is:
printf("\n The merged array in reverse ere (Ol) S Sis. Aree [lp ea Bey eee) SS
order is: "); NSE (S| = BO acai) SS ZO sXe |('5)| = Ako)
|168 | Introduction to C Programming

5.23 Write a program to interchange the biggest and the for (i=0;i<n;1i++)

smallest number in the array. {


if (my_array[i] > large)
#include <stdio.h>
{
#include <conio.h> large = my_array[il];
pos=i;
void read_array(int my array[], int);
void display array(int my_array[], int);
}
void interchange(int arr[], int); return pos;
int find biggest _pos(int my array[10], intn);
} '
int find_smallest_pos(int
my array[10], intn); int find_smallest_pos(int my_array[10], int
n)
int main()

{ int 1, smalie= 123456, pos=—15,


ies clare [@l) , rp for (i=0;i<n;i++)
elesen();
{
if (my_array[i] < small) “
printf ("\n Enter the size of the array:") ; {
scanf ("%d", &n); small = my_array[i];
read _array(arr, n); pos=i;
display array(arr, n);
interchange (arr, n); }
display array(arr, n); return pos;
getch (); }
return 0;
Output
}
void read_array(int my_array[10], int n) Enter the size of the array: 5
{ IM 2i 3 aes
alighe ale Mente |1O)]/ eal ocr lilt |= 92 Nera
||2. = 3!
for (1=0;i<n;i++) Nga |[Ssl| es 4 Navara [24]) 1s
scanf("%d", &my_ array [1] ); PNeeie
|0)\ eS jNverae| (AL) es De Arnis 3
} MNarel(sy| =e Arirha jar i
void display array(int my_array[10], int n)
{ ie function receives
an array that does
stials, abs
popaabal
cre (War)
for (i=0;i<n;1i++)
jopaniene (U\ie cuagety7|lixcll| = Syelll, sy, iy? 0 sistedoe To declare an
array
[i] ); ay as constant, prefix its type with the
}
void interchange
(int my _array[10], int n) ny sum (const int
{
int temp, big pos, small pos;
big pos = find biggest_pos(my
arr, n); 5.8 TWO-DIMENSIONAL ARRAYS | .

small pos = find smallest


_pos (my arr,n);
temp = my_array
[big pos]; Till now we have read only about one-dimensional arrays.
my_array[big pos] = my_array[small_
pos] ; A one-dimensional array is organized linearly and only in
my_array[small_
pos] = temp; one direction. But at times, we need to store data in the form
} of matrices or tables. Here the concept of one-dimensional
int find _biggest_pos(int my _array[10], int n) array is extended to incorporate two-dimensional data
{ structures. A two-dimensional array is specified using two
int i, large = -123456, pos=-1;
subscripts where one subscript denotes row and the other
Arrays | 169 |

denotes column. C considers the two-dimensional array marks [1] [0] stores the marks obtained by the second
as an array of a one-dimensional array. Figure 5.25 shows student in the first subject, and so on.
a two-dimensional array which can be viewed as an array
of arrays. Note g Each dimension of th
ray is indexed from |
size minus one. The first
_ fow and the second selects th
The pictorial form of a two-dimensional array is given
First
dimension in Fig. 5.26:
Hence, we see that a 2D array is treated as a collection
of 1D arrays. The elements of the 2D array comprises 1D
array (the rows). To understand this, we can also see the
Second dimension representation of a two-dimensional array as shown in
Figure 5.25 Two-dimensional array Fig. O27.

5.8.1 Declaration of Two-dimensional Arrays


Similar to one-dimensional arrays, two-dimensional
arrays must be declared before being used. The declaration
statement tells the compiler the name of the array, the data marks [2]
type of each element in the array, and the size of each
dimension. A two-dimensional array is declared as: Figure 5.27

data_type array _name[row_size] [column_size] ;

Therefore, a two-dimensional m X n array is an array that


Although Fig. 5.27 shows a rectangular picture of a
contains mn data elements and each element is accessed
two-dimensional array, these elements will be actually
using two subscripts, i and j where i<= m and j<= n.
stored sequentially in memory. Since computer memory
For example, if we want to store the marks obtained by
is basically one-dimensional, a multidimensional array
3 students in 5 different subjects, then we can declare a
cannot be stored in memory as a grid.
two-dimensional array as
Basically, there are two ways of storing a two-
int marks
[3] [5] dimensional array in memory. The first way is row major
A two-dimensional array called marks is declared that order and the second is column major order. Let us see
has m(3) rows and n(5) columns. The first element of the how the elements of a 2D array are stored in a row major
array is denoted by marks [0] [0], the second element as order. Here, the elements of the first row are stored before
marks [0] [1], and so forth. Here, marks [0] [0] stores the elements of the second and third row, i.e., the elements
the marks obtained by the first student in the first subject, of the array are stored row by row where n elements of

ai4¥ig-yeyvacys Two-dimensional array


|170 | Introduction to C Programming

the first row will occupy the first nth locations. This is OO Om toms So)
illustrated in Fig. 5.28. i] 1000 + 176 = 1176

(0,0) (0,1) (0,2) (0,3) (1,0) (1,


My CON
2) (1,TeyOVNZ, 1)1(2,2):(2, 3) 5.8.2 Initialization of Two-dimensional Arrays
Sethe y Elements of 2Darray in row major order Like in case of other variables, declaring a two-
dimensional array only reserves space for the array in the
When we store the elements in a column major order, the memory. No values are stored in it. A’ two-dimensional
elements of the first column are stored before the elements array is initialized in the same way as a one-dimensional
of the second and third column, i.e., the elements of the
array. For example, :
array are stored column by column where n elements of
the first column will occupy the first nth locations. This is int: marks [2ieiaiv= 908287; 78,°68, 62, 71};
illustrated in Fig. 5.29. The initialization of a two-dimensional array is done
row by row. The above statement can also be written as

int marks [2] [3] ={{90,87,78},{68, 62, .71}};


(0,0)(1,0) (2,0) (3,0) (0,1) (1,1) (2,1) (3,1) (0,2) (1,2) (2, 2)(3, 2)
The given two-dimensional array has 2 rows and 3 col-
Elements of 2D array in column major order umns. Here, the elements in the first row are initialized
first and then the elements of the second row are initial-
In one-dimensional arrays, we have seen that computer
ized. Therefore,
does not keep track of the address of every element in the
marks
[0] [0] = 90 marks
[0] [1] 87
array. It stores only the address of the first element and
marks
[0] [2] = 78 Marks
|L (Ol =.68
calculates the addresses of other elements from the base
address (address of the first element). Same is the case with mesks [ale =n62 marks [1] [2] 7

a two-dimensional array. Here also, the computer stores Therefore, in the above example, each row is defined as a
the base address and the address of the other elements is one-dimensional array of three elements that are enclosed
calculated using the following formula. in braces. Commas are used to separate the elements in
Address (A[I] [J] =B A+w{M(J-1) + (I-1)}, if
the row as well as to separate the elements of two rows.
the array elements are stored in column major order, and
In case of one-dimensional array, if the array is
Address (A[I] [J] =B A+w{N (I-1) + (J-1)},if
completely initialized, we may omit the size of the array.
the array elements are stored in row major order.
Same concept can be applied to a two-dimensional array,
where, w is the number of words stored per memory
except that only the size of the first dimension can be
location, N is the number of columns, M is the number of
omitted. Therefore, the declaration statement given below
rows, I and J are the subscripts of the array element, and
is valid.
B_Ais the base address.
int marks
[] [3]={{90,87,78},{68, 62, 71}};
Example 5.7 Consider a 20 x 5 two-dimensional array In order to initialize the entire two-dimensional array
Marks which has base address = 1000 and number of words
to zero, simply specify the first value as zero, i.e., simply
per memory location of the array = 2. Now compute the
write
address of the element Marks [18, 4] assuming that the
elements are stored in row major order. int marks[2]
[3] = {0};

If some values are missing in the initializer then it


Address (A[I] [J]
= Base Address + w{N (I - 1) + (J - 1)} is automatically set to zero. For example, the statement
Address (Marks [18,4] ) given below will initialize the values in the first row but
= 1000 + 2{5(18 - 1) + (4-1) } the elements of the second row will be initialized to zero.
= 1000 + 2 { 5(17) + 3} int marks[2]
[3] ={ {50, 70}};
a Dor at
#include <stdio.h>
#include <conio.h>
main ()

{
int arr[7]
[7] ={0};
5.8.3 Accessing the Elements He THOS) Coll, ab, S)e
The elements in a multidimensional array are stored eae |(Ol| Ol) = ehkere lal) [LOl) = ereelali} lial) cS abe
in contiguous memory locations. While accessing the while (row <= 7)
elements, remember that the last subscript varies most {
rapidly whereas the first varies least rapidly. ariirow
lslO was;
In case of one-dimensional arrays we used a single for for (col = 1;col <= row;col++)
loop to vary the index i in every pass, so that all the elements arr [row] [col] = arr[row-1] [col-1] +
could be scanned. Similarly, since a two-dimensional array arr [row-1] [col];
contains two subscripts, we will use two for loops to scan LOW++;
the elements. The first for loop will loop for each row in
}
the 2D array and the second for loop will scan individual for (1=0;i<7;1++)
columns for every row in the array.
{
However, individual elements of a two-dimensional
jonettrayere((U Gal)
array can be initialized using the assignment operator as
for (j=0;j<=1;3++)
shown below.
PrAnte (UNE say wari laylelailp):
marks
[1] [2] 79 Or }
marks
[1] [2] = marks[1]
[1] + 10; getch ();

In order to input the values from the keyboard, you return 0;

must use the following code. }


for (i=0;1<2;1i++) Output
for (j=0;j3<2;
j++)
scanf ("$d", &arr[i]
[3] ); Al
dk
Look at the code given below which prints the elements
Sago acl:
of a 2D array on the screen.
4° 6 4 2
5.24 Write a program to print the elements of a 2D array. ey alo ala) sy al
Sy illsy XO alisy yal
#include <stdio.h>
#include <conio.h> In a small company there are 5 salesmen. Each
main () salesman is supposed to sell 3 products. Write
{ a program using two-dimensional array to print
ermtearrieri2) = (12, 34, 56,32); (i) the total sales by each salesman and (ii) total
int. 2,. ds sales of each item.
for (i=0;i<2;i++)
#include <stdio.h>
{ #include <conio.h>
prince @\n").;
main ()
for (j=0;j<2;
j++)
print’ ("sd\e", arr (i) (41); {
int sales[5] [3], i, j, total_sales=0;
} //INPUT DATA
return 0;
printf ("\n ENTER THE DATA");
} printf ("\n kK RR RRR RR RHI):

Output for (i=0;i<5;i++)

12 34
{
printf ("\n Enter the sales of 3 items
56 32 sold by salesman %d: ", i);
5.25 Write a program to generate Pascal’s triangle. for (j=0;4<3;
j++)
|172 | Introduction to C Programming

scanf("%d", &sales[i] [j]); (iii) store the average of each student in a separate
} 1D array so that it can be used to calculate the
// PRINT TOTAL SALES BY EACH SALESMAN class average.
for (1=0;1<5;1++4) #include <stdio.h>

{ #include <conio.h>
totaly sales j= 0); main ()
for (j=0;
3<3; j++)
total sales += sales[il] [j]; Mighe natal
ts}(AKO) LAI aby Shs
printf("\n Total Sales By Salesman %d int total_marks[10]={0};;
= Cll ee Otalesenes)) float class avg=0.0, total_avg = 0.0;
} float avg[10];
// TOTAL SALES OF EACH ITEM
for (i=0;1<3;1++)// for each item //INPUT DATA

{ printf ("\n ENTER THE DATA");


PLintE ("\n KeK KKK RR RK KR KAKI):
total sales=0;
for (j=0;3<5;3++)// for each salesman for (1=0;i<10;1++)
total sales += sales[j] [i]; { .

printf ("\n Total sales of item %d printf("\n Enter the marks of student %d
=o ste cOralusales); in 3,subjects Solbh) vi);
for (j=0;3<3;
++)
}
scanf("%d", &marks
[i] [j]);
getch ();
ae bheay (Oy

}
// CALCULATE TOTAL MARKS OF EACH STUDENT

Output for (1=0;1<10;


i++)

ENTER THE DATA {


KREKKKKKKKKKKKKEKKK for (j=0;4<3;3++)
total _marks[i] += marks[i] [3];
Enter the sales of 3 items sold by saleman
QO: Dass PX ORS }
// CALCULATE AVERAGE OF EACH STUDENT
Enter the sales of 3 items sold by salesman
for (1=0;1<10;
i++)
dhs 34 45 63
Enter the sales of 3 items sold by salesman {
Bor ssns
for (j=0;j3<3;
j++)
2s
avg[i] = (float) total_marks [i] /3.0;
Enter the sales of 3 items sold by salesman
Be 3352635 }
// CALCULATE CLASS AVERAGE
Enter the sales of 3 items sold by salesman
for (i1=0;1<10;
i++)
4: 32 45 64
total avg += avg[i];
Total Sales By Salesman 0 seo:
class avg = (float)total_avg/10;
Total Sales By Salesman 1 = 142
// DISPLAY RESULTS
Total Sales By Salesman 2 = 112
printf ("\n\n STUD NO. MARKS OBTAINED IN
Total Sales By Salesman 3 = 120
THREE SUBJECTS TOTAL MARKS \t AVERAGE");
Total Sales By Salesman 4 = 141
jexgaliaheae
(1
Total sales of item 0 = 158
\ TR KI III RII eT );
Total sales of item 1 = 198
for (1=0;i<10;1i++)
Total sales of item 2 = 250
{ printf("\n %4d", i);
5.27 In a class there are 10 students. Each student is for (j=0;4<3;
j++)
supposed to appear in 3 tests. Write a program using joneaiahend (( sa", marks
[i] [j]);
two-dimensional arrays to print printf ("4d \t%2.2£", total_marks[il,
avg [i] );
(i) the marks obtained by each student in different ‘

subjects }
printf("\n\n CLASS AVERAGE = $f", class_
(ii) total marks and average obtained by each avg);
student getch ();
Arrays | 173 |

Hevurin OK; {
} PLINneE (\n mark
[3d lois
s lle eh):
scanf("%d", &mar
[i]
ks[j]);
Output }
ENTER THE DATA }
KRKEKKEKEKKKKKKKKKKK ORS (Op 7e3 7 ales)

Enter the marks of student 0 in 3 subjects: {


78 89 90 Max markse ———-999);
Enter the marks of student 1 in 3 subjects: for (i=0;1<5;i++)
Se Si VS {
Enter the marks of student 2 in 3 subjects: meyer ks [Ao ee
2 max marks = marks[i] [j];
Oy He By) } =
Enter the marks of student 3 in 3 subjects: printf("\n The highest marks obtained
90 87 65 in the subject %d= %d", j,
Enter the marks of student 4 in 3 subjects: max marks);
56 87 97 , } a
Enter the marks of student 5 in 3 subjects: getch ();
45 67 89 saQaEbhaial (0)5

Enter the marks of student 6 in 3 subjects: }


66m 7. SS | . Output
Enter the marks of student 7 in 3 subjects:
76 87 98 Enter the marks obtained by student 0

Enter the marks of student 8 in 3 subjects: See eT gee


Lee Ree marks[0] [1] = 76
mark [0]s[2] = 100
Enter the marks of student 9 in 3 subjects: Enter the marks obtained by student 1
56 7/5 173 marks[1]
[0] = 99
STUD NO. MARKS OBTAINED IN THREE SUBJECTS marks[1] [1] = 90
TOTAL MARKS AVERAGE mark
[1]s[2] = 89
FOR ROKK Enter the marks obtained by student 2
0 78" = 894%) (90) 26257) © 185167 marks [2] [0] = 67
1 Bet = SS7PPEi Gems 261b4'S7:.00 ae i = a
2 e7 is 8? ee Enter the marks obtained by student 3
3 30 87 65 242 80.67 mark e[01 =
[3] .88
4 56 87 97 240 80.00 Waree lott ogy
5 45 67 89 AOU 7/100) marks [3] [2] = 66
6 66 Td. 88 AS Wi OO Enter the marks obtained by student 4
7 76 87 98 261 87.00 [4]s[0]
mark = 67
8 ejmmmace. 665 2221 73.67 marks [4] [1] = 78
9 Ging WTS) (e171Sane 22.00 n73200 (4) 12 le=3e?
marks .
CLASS AVERAGE = 78.90 fe marks obtained in the subject 0

5.28 Write a program to read a two-dimensional array The highest marks obtained in the subject 1
marks which stores marks of 5 students in 3 SE trie
, : ; : The highest marks obtained in the subject 2
subjects. Write a program to display the highest ee:
marks in each subject.
#include <stdio.h>
#include <conio.h>
main ()
{
int marks[5] [3], i, 3, max_marks; Two-dimensional arrays can be used to implement the
for (i=0;i<5;1i++) mathematical concept of matrices. In mathematics, a
{ matrix is a grid of numbers, arranged in rows and columns.
printf ("\n Enter the marks obtained by Thus, using two-dimensional arrays, we can perform the
student %d",1i);
following operations on an m x n matrix:
for (j=0;4<3;j++)
|174 | Introduction to C Programming

Transpose: Transpose of a m x n matrix A is given as a return 0;

nXm matrix B where, }


Bij = Aji Output
Enter the elements of the matrix
Sum: Two matrices that are compatible with each other
KK KKK KEK KEKE KEK KKK KEK KKK KEEKK
can be added together thereby storing the result in,the third
25 sas St 617 (8° 29)
matrix. Two matrices are said to be compatible when they
The elements of the matrix are
have the same number of rows and columns. Elements of KKK KKK KEKE KK KKK KKK KKK KEK KEKE

the matrices can be added by writing: 15-253 t


i SEG
78:8 9
Difference: Two matrices that are compatible with each
other can be subtracted thereby storing the result in the 5.30 Write a program to transpose a 3 x 3 matrix.
third matrix. Two matrices are said to be compatible when #include <stdio.h>
they have the same number of rows and columns. Elements #include <conio.h>
of the matrices can be subtracted by writing: int main() :
{
Ca Pig Ba int i, j, mat[3] [3], transposed_mat
[3] [3];

Product: Two matrices can be multiplied with each other clrscr


();

if the number of columns in the first matrix is equal to the printf ("\n Enter the elements of the
number of rows in the second matrix. Therefore, m x n matrix");
matrix A can be multiplied witha p x qmatrixifn = q. printf ("\n FOR RR OR Oe eI)»

Elements of the matrices can be multiplied by


for (i1=0;1<3;1++)
writing:
{
Ci j = » Ai «By x for k=[Link]<in for (j=0;j}<3;
j++)
{
5.29 Write a program to read and display a 3 x 3 matrix. print£("\ne mat [$d] [ta]h= "Pi, 3);
#include <stdio.h> scanf ("%d", &mat
[i] [5]);
#include <conio.h> }
int main() }
{ printf ("\n The elements of the matrix are ");
ita yr eemat
Ls Ler: Print ("rn i ki ie):
elrser();
for (i1=0;1i<3;i++)
printf("\n Enter the elements of the {
matrix "); pEINtee
(iu\n)s
print ("\n KKK KKK KKK KKK KKK KKK KEKEKKEEEEKN ); for (j=0;3<3;j3++)
Drintée (W\G mat [td] [td] = Sd a) aa,
for (i=0;i<3;1++) mat
[i] [3] );
{ }
for (j=0;4<3;
j++) for (1=0;1<3;1i++)
scanf ("%d", &mat [1] [5] );
{
} for (j=0;4<3;
j++)
printf ("\n The elements of the matrix are");
transposed
mat [i] [3] = mat([j] [i];
jonephavese (W\Gat Hk KR OR RR RM)

}
printf ("\n The elements of the transposed
for (i=0;i<3;i++)
matrix are ");
{ printf ("\n OR kk ok kok kok kok ok ok ok kok kk kkk ek I );
printer (wn);
for (j=0;4<3;j++)
printl("\t tdtdtad",1, 3, mat
[1] [j)); for (1=0;1<3;1i++)
{
Arrays | 175 |

printf ("\n"); printf ("\n Enter the numbers of columns


for (j=0;3<3;j3++) in the second matrix:");
printf ("\t transposed_mat
[%d] [%d] scanf ("%d", &cols2);
= sd",i, j, transposed_ mat [i]
(31); if (rows1 != rows2 || colsl != cols2)
}
return 0; printf("\n The number of rows and
} columns of both the matrices must
Output be equal");
Enter the elements of the matrix getch ();
KR KKK KKK KKK KEKE KKK KKK EKKEEEK exit ();

ies 95.627, 89 }
The elements of the matrix are
rows sum = rows1;

KEKE KKKEKKEKKEKEKKEKKEKKKKEKKEKE cols sum = colsl;


és

i A 2)
printf("\n Enter the elements of the
45 6
first matrix");
USS,
printf ("\n RAK KKK KK RK KKK KK KKK KKK KK KKM)

The elements of the transposd matrix are


ttt fee eee ee ee ee ee
for (i=0;i<rows1;i++)
4 ey)
{
2S for (j=0;j<cols1;j++)
Timken’) scanf ("$d", &mat1 [i] [5] );

}
5.31 Write a program to input two m x n matrices and printf ("\n Enter the elements of the
then calculate the sum of their corresponding second matrix");

elements and store it in a third m X n matrix. picint fa(v\n KRKKKKKKKEKKKKEKEKKEKKEKKEKEEEKEN );

#include <stdio.h>
for (i=0;1i<rows2;1i++)
#include <conio.h>
{
int main() for (j=0;j<cols2;j++)
{ scanf ("%d", &mat2 [i] [4] );
abayen chy it }
int rows1, colsl1, rows2, cols2, rows_sum, for (1=0;i<rows_sum;
i++)

cols sum; {
int mat1[5] [5], mat2[5] [5], sum[5] [5]; for (j=0;j<cols
sum, j++)
sum [Dee li=smataihn sig] + mat2ita) [i
elxrser
();

printf ("\n The elements of the resultant


printf ("\n Enter the numbers of rows in
matrix are");
the farst matrix: ©");
jopaabayere (Gai KKK KKK KKK KK KK KKK KK KKK KK KK I)
/

scanf ("%d", &rows1);

for (i=0;i<rows sum;i++)


printf ("\n Enter the numbers of columns
{
sie) (elavey serine iweheralier 1))r joiealiaiere
(MU\ial)jp
scanf ("%d", &cols1); for (j=0;j<cols
sum; j++)
Piredmie (NE. sai sumilaeleiaie

printf("\n Enter the numbers of rows in }


the second matrix: "); return 0;

scanf ("%d", &rows2); }


|176 | Introduction to C Programming

Output send a single row of a two-dimensional array, then the


Enter the numbers of rows in the first called function receives a one-dimensional array. Figure
ieheieslda
2 5.31 illustrates how a single row of a two-dimensional
Enter the numbers of columns in the first array is passed to the called function.
Maisie?
Enter the numbers of rows in the second
Matix 2
Enter the numbers of columns in the second
matrix: 2
Enter the elements of the first matrix
KKK KKK KKK KKK KKK KEKE KKK KKK

ee?
eS 4
Enter the elements of the second matrix
KKK KKK KEKE KK KEKE KEK KKK KKK KEKEK

5 6 a/e8
The elements of the resultant matrix are
KKK KKK KKK KKK KKK KEK KKK KKK KEK

6 8 Sink ees
AQ) IE

There are three ways of passing parts of the two-


dimensional array to a function (process). First, we can Figure 5.31 Passing two-dimensional arrays foriinte
pass individual elements of the array. This is exactly ) communication

same as we passed element of a one-dimensional


array. Second, we can pass a single row of the two-
5.10.2 Passing an Entire 2D Array
dimensional array. This is equivalent to passing the
entire one-dimensional array to a function. This has To pass a two-dimensional ar-
Programming Tip:
already been discussed in the previous section. Third, -Acompilererror ray to a function, we use the
we can pass the entire two-dimensional array to the willbe generated array name as the actual pa-
function. Refer Fig. 5.30 which shows the three ways 4 ‘you omit the rameter. (The same we did in
of using two-dimensional arrays for inter-function, array size in case of a 1D array). However,
interprocess communication. the parameter — the parameter in the called
declaration for a function must indicate that the
array dime nsio _ array has two dimensions.
5.32 Write a menu-driven
jon commun
program to read and display an
m Xn matrix. Also find the sum,
transpose, and product of two m Xx n matrices.
Passing an #include <stdio.h>
entire 2D array #include <conio.h>
void read matrix(int mat [2] [2], int, int);
void sum _matrix(int mat1[2]
[2], int mat2[2]
[2 enaitey anit)
void mul_matrix(int mat1[2] [2], int mat2[2]
iy stake, skate,A
5.10.1 Passing a Row void transpose matrix(int mat2[2] [2], int,
int);
A row of a two-dimensional array can be passed by void display amatiisn(int mak i2 iy,
indexing the array name with the row number. When we bac, Ce
Arrays | 177 |

int main() }
{ VOLdpucadsmatirix
(int matii2) [2iyaantaaeatcec)
shale, (ojoiestoral, sey, Clot {
THicematir2) (2, mat2
(2) [217 siiale Sl, She
clrscr (); iene (Gi = Oa < seenitess)
{ “peants ("\n");
do
£or(qj =80% j=) Crate)
{ {
pesner ("\t mat [sd] (td) “= "209s
printé ("\n kkk KKK MATIN MENU ** eM)
scanf("%d", &mat
[i] [3] );
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"); }
void sum _matrix(int mat1[2] [2], int mat2[2]
Pusat (Va Be 1p, Ge ya
Aly aeale Ge, auiaye yex)

printf ("\n\n Enter your option: ");


scanf ("%$d", &option); ale al, Jp, Shoal 2)(l2i)p
switch (option) for (i=0;i<r;i++)
{ {
casei: for (j=0;3<c;j++)
printf ("\n Enter the number of summit) [ji = matii) [yl ee mat2
ie Phas;
rows and columns of }
the matrix: "); display matrix(sum, r, C);
scant ("%d %d", &row, &col);
}
jperkee (Wim IMahesie ielete) aealsalsic void mul_matrix(int mat1[2] [2], int mat2[2]
Matrix: "); (All_» aliste ze, sWate e))
read_matrix(mat1, row, col);
printf ("\n Enter the second
aac, I, yn Ys, jonsorel
iil Zl. 4
Matrix: )-
for (i1=0; i<r;1++)
read_matrix(mat2,
row, col);
break;
{
for (j=0;j<c;
j++)
case 2:
sum_matrix(matl,
mat2, row,
{
jonqexel
{Isai} [ia|l| = Wp
col);
for (k=0;k<c;k++)
break;
prod[i]
[j] += mati[i]
[k] * mat2[k] [3];
cCasezs:
tk(COle=—— GOW) }
mul_matrix(matl, mat2, row, }
eo) Cbigiollena tmeterauinel((onsotcl; ae, G)))p
else }
printf ("\n To multiply two void transpose matrix(int mat[2][2], int r,
matrices, number of alias (el)
columns in the first
matrix must be equal to int ar vis tp mat (2) [215
number of rows in the for (i=0;i<r;i++)
second matrix"); {
break; for (j=0;j<c;
j++)
case 4: tp_mat[j]
[i] = mati] [3];
transpose_matrix(mat1, row, col); }
break; diuspillayamatiasc
(pe mate. a4,) -C));

}
}while (option != 5);
getch (); void display _matrix(int mat[2][2], int r,
return 0; sige. ))
|178 | Introduction to C Programming

{ display_matrix(mat1,
row);
sh@tee aly, Shp getch ();
for (i=0;i<r;i++) return) 0);
{ }
oredr (ia) =
for (j=0;j<c;
j++) void read_matrix(int mat [5] [5], int r)
printé ("\temat [sail [sdii =) sd", i; 7),
{
mat
[i] [3] ); alinte. Gh, 3)f
} for(i = O;1 < r;1++)
} { t

Output LOM(Ge —aO} ali ce)


KKKKKKK MAIN MENU KEKKKKEKK {
1. Read the two matrices L£(1==9)
2. Add the matrices Thats ible}
3. Multiply the matrices alge ((als=5))
4. Transpose the matrix macy aaa, 7
Sis) EL else if [i > j]
Enter your option: 1 mat [a] [gp] = 1;
Enter the number of rows and columns of the
}
[Wetercubey A)
}
Enter the first matrix:
mat [0] [0] = 1 mat [0] [1] ul NS)
}
void display matrix(int mat[5] [5], int r)
Mate Oss mat[1] [0] = 4
Enter the second matrix : {
ioe ah, ps
Mata
tO) elOUm 2 mat [0] [0] = 3
mat [0] [0] = 4 mato][0] = 5 for (i=0;i<r;i++)
kkk*K*K*E*K MAIN MENU ******** {
Read the two matrices jonasiiohene (Ua! ))
. Add the matrices for (j=0;j4<r;j++)
. Multiply the matrices piEint
GU \ temate Sail sai) tat ee es
Transpose the matrix mat [i] [3] );
EXIT
PF
OM
BP
WD
}
Enter your option: 2
}
mat [0] [0] = 3 mat O!MO]m a5
Output
mat [0] [0] = 7 mat [0] [0] ! \o
Enter the number of :rows and columns of
Oo da
the matrix: 2
5.33 Write a program to fill a square matrix with value 0 Al

zero on the diagonals, | on the upper right triangle, all 0


and —1 on the lower left triangle.
#include
#include
<stdio.h>
<conio.h>
5.11 MULTIDIMENSIONAL ARRAYS _
void read _matrix(int mat[5]
[5], int); A multidimensional array in simple terms is an array of
void display matrix(int mat[5]
[5], int); arrays. Like we have one index in a one-dimensional
int main () array, two indices in a two-dimensional array, in the
{ same way we have n indices in a, n-dimensional array or
int row; multi-dimensional array. Conversely, an n-dimensional
intematl ES) (Sly matztsi
isis array is specified using n indices. An n-dimensional
clrscr
();
m; XM, X m; X .. m, array is a collection m,*m,*m;*
printf("\n Enter the number of rows and
*m, elements. In a multi-dimensional array, a particular
columns of the matrix ");
element is specified by using n subscripts as A[I,] [I,]
scanf("%d", &row);
(i, ] bial epwhere,
read_matrix(mat1,
row);
Arrays 179 |

I, <= M, In< = M 5.34 Write a program to read and display a 2 x 2 x 2


A multi-dimensional array can contain as many indices array.
as needed and the requirement of the memory increases #include <stdio.h>
with the number of indices used. However, practically #include <conio.h>
speaking we will hardly use more than three indices in int main ()
any program. Figure 5.32 shows a three-dimensional {
array. The array has three pages, four rows, and two alias epecenyal
(All [Bil TAllip abeTie bee
columns. eluser
():

a
printf("\n Enter the elements of the
mea taguexa)\
printf ("\n KR KKK KKK KKK KKK KKK KKK KKK KK KKK KKM) ;
Second
dimension * for(i = O;i < 2;1++4)
(Columns)
First - {
dimension for(j = 0;3 < 2;34++)
(Rows) {
for(k = 0;k < 2;k++)
{
printf ("\n array[%d] [ %d] [ %d]
Page 1
= vi ly Ie; k);
Third dimension
scanf ("$d", &arrayl [i] [3] [k]);
Figure 5.32 Muiceecian
A multi-dimensional array is declared and initialized
similar to one- and two-dimensional arrays.
}
printf£("\n The matrix is: ");
jsranlioyese((W\war KKK KKK KEKE KKK KEK KK KKK KK KKK KKK KKM)»

Example 5.8 Consider a three-dimensional array defined


mera(Gh = Ops q pals)
as int ARI2I[3]. Calculate the number of elements in the
{
array. Also give the memory representation of the array in prante (@\n\n");
row major order and column major order. for(j = 0;3 < 2;3++)
{
jaguars (U\aill!))
for(k = 0;k < 2;k++)
printf ("\tarray[%d] [sd] %d] = Say ee
Ke, ewarereyyal
(iatl)[fyi] (si) )p

ee eee ee
[o)
oO
al
=)
N
(em)
(2)
a
Sa
a
NX
a
o.
(=)
a
(=)
N
o.
oO
Gal
at
Tall
NX
Gal
}
CO
CON ©:
Or OFC (CO
OS worm
eS Cuwdistdi
SUSI StesaciRS od getch ();

(a) Row major order Keturn 0;


}
Output
ee) Ee SS ee ee Enter the elements of the matrix
KKK KKK KKK KKK KKK KE KKK KEKE KEKE KEKKEKEE

ue est bt Se ie St
a
One So
© e OO © OCSOf eS) RS SS LS al By, Bh AN IES WG. Ys

(b) Column major order arr [0] [0] [0] 1 arr [0] [0] [1]

The three-dimensional array will contain 2 x 2 x 3 = 12 arr [0] [1] [0] i 3 evare
LO (akl] lak) ii]

arr [1] [0] [0] 5 ewes


|fal,))) [K@l) [fal
elements .
axr iy (1) (0) 7 eltetoy
La) [eal te AE
NS
AO
On
|180 | Introduction to C Programming

5.12 SPARSE MATRICES


1 2 4 5
Sparse matrix is a matrix that has many elements witha value
3 7 8
zero. In order to efficiently utilize the memory, specialized
Al 9 1
algorithms and data structures that take advantage of the
sparse structure of the matrix should be used. If we apply 9 3

operations using standard matrix structures and algorithms 7

to sparse matrices, then execution will slow down and the


matrix will consume large amounts of memory. Sparse data Upper tri ngular matrix —
can be easily compressed which in turn can significantly In the second variant of a sparse matrix, elements
reduce memory usage. with a non-zero value can appear only on the diagonal
Basically, there are two types of sparse matrices. In the or immediately above or below the diagonal. This type
first type of sparse matrix, all elements above the main of matrix is also called a tridiagonal matrix. Hence in a
diagonal have a value zero. This type of sparse matrix is tridiagonal matrix, A; ;= 0 where |i - j|>1. Mathemat-
also called a /ower triangular matrix because if you see it ically, in a tridiagonal matrix, if elements are present on
pictorially, all the elements with a non-zero value appear the main diagonal, then it contains non-zero elements for
below the diagonal. In a lower triangular matrix, A; ; = 0 i=. In all there will be n elements diagonal by below
where i >= }. Ann x nlower triangular matrix A has one the main diagonal, it contains non-zero elements for i =
non zero element in the first row, two non-zero element, 3 +1. In all there will be n - 1 elements diagonal above
in the second row and likewise, n non-zero elements in the the main diagonal, it contains non zero elements for i =
n‘" row. Figure 5.33 shows a lower triangular matrix. 3 -1. In all there will be n - 1 elements.
Figure 5.35 shows a tridiagonal matrix.

il
5 3
4 1
2 vi 1
5 1
3 1 4 2
g il
g 2 8 1 i
2 2

Figure 5.33 BEig triangular matrix i) 1 $


8 7,
To store the lower triangular matrix efficiently in
memory, we can use a one-dimensional array which stores Figure 5.35
only the non-zero elements. The mapping between a two-
dimensional matrix and a one-dimensional array can be
To store the tridiagonal matrix efficiently in memory,
done in any one of the following ways:
we can use a one-dimensional array which stores only
(a) Row wise mapping—here the contents of array A[] the non-zero elements. The mapping between a two-
WihOE1, 57 8) ey ines S50 1 eee = 9, dimensional matrix and a one-dimensional array can be
eres: rnc Pia done in any one of the following ways:
(b) Column wise mapping—here the contents of array (a) Row wise mapping—here the contents of array A[]
Aud [Link]) Son oy Se op ieee ew, will be (4) 25 1S, Ljy2s A9nee ciekyat4 ems co oe
Ah vG, 25 ey Le Ope Opie
Like a lower triangular matrix, we also have an upper (b) Column wise mapping—here the contents of array
triangular matrix in which A;; = 0 where i<=j. An Ah) willbe4 ,¥5i/a:,) 1psiee, 8) See
n X nupper triangular matrix A has n non zero element in 2, Wee Sl
the first row, n-1 non zero element in the second row and
(c) Diagonal wise mapping—here the contents of array
likewise, 1 non zero elements in the nth row. Figure 5.34
Af) willbe{S; 9, 4,°5,°8, 47 2, 3, 2anaenoe
shows an upper triangular matrix.
Pe ad habe al he
Arrays | 181 |

Li An array is a collection of similar data elements of dimensional array as an array of a one-dimensional


ad the same data type. array.
oo The elements of the array are stored in consecutive © A multi- dimensional array in simple terms is an
memory locations and are referenced by an index array of arrays. Like we have one index in a one-
= (also known asthe subscript). Subscript indicates an dimensional array, two indices in a two-dimensional
WY g

bo ordinal number of the elements counted from the array, in the same way we have n indices in an n-
= beginning of the array. dimensional or multi-dimensional array. Conversely,
Oo Declaring an array means specifying three things: an n-dimensional array is specified using n indices.
o.
data type, name, and its siZe. e Sparse matrix is a matrix that has many elements
The name of the array is a symbolic reference for with a value zero. Basically, there are two types of
the address of the first byte of the array. Therefore, sparse matrices. In the first type of sparse matrix,
whenever we use the array name, we are actually all elements above the main diagonal have a value
referring to the first byte of that array. The index — zero. This type of sparse matrix is Called a lower
specifies an offset from the beginning of the array triangular matrix.
to the element being referenced. e In the second variant of a sparse matrix, elements
A two-dimensional array is specified using two with a non-zero value can appear only on the diago-
subscripts where one subscript denotes row and nal or immediately above or below the diagonal. This
the other denotes column. C considers the two- type of sparse matrix is called a tri-diagonal matrix.

Array An array is a collection of similar data elements. Matrix A two- dimensional array in which the first index
Array index Location of an item in an array. is the row and the second index is the column.
Binary search Search a sorted array by repeatedly One-dimensional array An array with one dimension
dividing the search interval in half. Begin with an or one subscript/index.
interval covering the whole array. If the value of Rectangular matrix An n x m matrix whose size may

| RY the search key is less than the item in the middle of not be the same in both dimensions.
the interval, narrow the interval to the lower half. Sparse matrix A matrix that has relatively few non-zero
Otherwise narrow it to the upper half. Repeatedly elements.
check until the value is found or the interval is empty. Three-dimensional array An array with three
k-dimensional array An array with exactly k orinogonal dimensions or three subscripts/indices.
axes or k dimensions. Two-dimensional array An array with two dimensions _
_ Linear search Search an array by checking elements or two subscripts/indices.
one ata time. Upper triangular matrix A matrix Aj forms an upper
Lower triangular matrix A matrix A; forms a lower triangular when i <j.
triangular wheni 2 j.

Fill in the Blanks


1. An array isa __ 5. An n-dimensional array contains
2 Every element isaccessed using a subscripts.
3. An expression that evaluates to an 6. Name of the array acts as a
EXERCISES
| value may be used as an index. 7. Declaring an array means. specifying the
4. The elements of an array are stored in ; and
memory locations.
|182 | Introduction to C Programming

8. The subsea or the index represents the offset (a) 5


from the beginning of the array to (c) 10
9. ___ is used to access an element in the 6. The worst case complexit an compared .
array. with the average cas
i. ___ is the address of the first element in search algorithm.
the array. (a) equal be
' greater :
11. Length of the array is given by the number of (c) less (dj ‘none of these
7. The complexity of binary search algorithm iis
i2. _means accessing each element of the (a) O(n) -(b) O(n?)
array for a specific purpose.
(c) O(n log n) (a) Oflog n)
. Performance of
the linear search algorithm c
can»be: 3 In linear search, when VAL is equal to the fi
improved by using a : element of the array, which case is it?
14. The complexity of linear a algorithm (a) worst case _ (b) average case
_ (c) best case _ (d) amortized cas
15. An array occupies
memory locations. 9. Given an integer array, arr[]; the ith element cannbe
16. An array name is often known to be a accessed by writing
pointer. (a) fareei)> (hy) Fr)
17. A multi-dimensional array in simple terms is an (c) arr{i] (d) all of these

18. arr[3] = 10; initializes the element of State True or False -


. _ the 3 with value 10.
1. An array is used to refer to. multiple memory _
| 19 The _ search locates the value by locations having the ==
13 starting a the beginning of the array and
2. An array need not e being used. -
:towards: its
send.
3. Anarray contain f
the same data type.
4. A loop is used to access all the elements of the
Muttiple-Choice Questions
array.
. If an array is declared as arr[] = {1,3,5,7, 9); 5. All the elements of thearray are automatically
then what is the value of sizeof(arr[])2 initialized to zero when the array is defined.
(a) 10 (b) 20 6. An array stores all its data elements in non- :
(c) 30 (d) 40 consecutive memory location.
2. If an array is declared as arr[] = {1,3,5,79h‘then _ 7. To copy an array, you must copy the value of eve
what is the value of arr[3]? element of the first array into the epics: a th
(a) 4 (b) 7 second array. |
(c) 9 (d) 5 8. Lower bound is the index of the last eh
3. If an array is declared as double arr[50], how many array.
bytes will be allocated to it? 9. Merged array contains contents of the first array :
(a) 50 (b) 100 followed by the contents of the second array. -

(c) 200 (d) 400 10. Binary search is also called sequential search.
11. Linear search is performed on a sorted array..
4. \f an array isdeclared as int arr[50], how many
elements can it hold? 12. Binary search is the best searching algorithm for
all types of arrays. _
(a) 49 (b) 50
(c) 54. (d) 0 13. | is possible to [Link]
argument. | .
5. If an array isdeclared as int arr{5][5], how many
elements can it store? 14. arr[i] is equivalen
Arrays | 183 |

. Array name is equivalent to the address of its last 17 Given an array, int arr[]= (9, 18, 27, 36, 45, 54, 63,
element. 72, 81, 90, 99}; Trace the steps of binary search
When an array is paced to a function, C passes the algorithm to find value 90 and 17 from the array.
value for each element. 13, Which technique of searching an element in the
. When an array is passed to a function, it is always array
do you prefer to use and in which situation?
passed by call--by-reference method. 14. Write a program which deletes all duplicate
EXERCISES.
. Linear search can be see to search a ous in any elements from the array.
array. _ 15. Write a program that tests ie equality of two
. Linear search is ecu méides for small arrays. one-dimensional arrays.
. Atwo-dimensional array is nothing but an arrayof 16. Write a program that reads an array of 100
one-dimensional arrays. integers. Display all pairs of elements whose sum |
. A two- dimensional array contains data of two | 650.
different types. Write a program to input an array of 10 numbers:
. When an array is declared, all its elements are and swap the value of the largest and eines:
automatically initialized to zero.
. Achar type variable can be used as a subscriptin 18. Write a program to interchange second element
an array. withthe second last element. |
. By default, the frst subscript of the array is zero. 19. Write a program that calculates the sum of squares
. Along int value can be ceeas an pole ee of the elements.
20. Write a program to calcilete the ‘number of
duplicate entries in the array.
21. Write a program
to arrange the values of an array
_ in such a way that even numbers precede the odd
numbers.

. What does |name signi 22, Given a‘sorted array of eer calcubte the sum,
mean, variance and standard deviation of the
. Howis an array is ee aa in memory?
numbers iin thearray.
23. Write a program to compute thessum and mean of
the elements of a two- dimensional array.
s be ee inter-function
24. Write a‘program to read and display a 3X3 matrix.
25. Write a program to transpose a 3X3 matrix.
26. Write a program that computes the sum of
~ elements that are stored on the main Mldeo02 ofa
: (a) fewer initializers as ‘compared to its size?
matrix using pointers.
initializers as compared to its size? so
Write a program to count the total number of non-
8. Explain sparse matrix. :
zero elementsin a two-dimensional array.
es storing otsparse matrices need extra >3
Write a program to read and display an array of 10
_ floating point numbers.
— 29. Write aprogram to read and display an array of 10
y | located as int art{50l,¢calculate the
floating point numbers using functions.
address of arr(35], if Base(arr) =1000 and w=2 a
Write a program to read an array of 10 floating
al0Oxs Ae aks array Marks [
~ point numbers. Display the mean
of these numbers
till two decimal places.
Si, Write a program to read an array of 10 floating
point numbers. Display the position of the largest
5] assuming ‘that the lence: are stored in row
number.
major order.
|184 [ Introduction toC Programming

32. Write a program to read an array of 10 floating 46. Write a program to find a pesa er {
point numbers. Display the smallest number and sorted array. _
' its position in the array. 47. Write a program to read z
an arrayfof 10
33. Write a program to input the elements of a two- point numbers. Display the position of the se
dimensional array. Then from this array make two largest number. -
arrays—one that stores all odd elements of the 48. Write a program to enter five single digit num
two-dimensional array and the other stores all in an array. Form a number using ee
even elements of the array. elements. _.
34. Write a program to merge two integer arrays. Also 49. Write a program to find whether number 3
display the merged array in reverse order. present in the array arr[]= {1,2,3,4,5,6,7,8}. :
35. Write a program to transpose a 3X3X3 matrix. 50. Write a program to read a floating point array. —
36. Write a program to multiply two mXn matrices. Update the array to insert a new number at the —
37. Write a menu driven program to add, subtract, specified location.
and transpose two matrices. sae Write a program to read a sorted floating point _
38. Write a program that reads a matrix and displays array. Update the array to insert a new number. :
the sum of its diagonal elements. 52. Write a program to read a floating point array.
39. Write a program that reads a matrix and displays Update the array to delete the number from the ©
the sum of the elements above the main diagonal. specified location.

Hint: Calculate sum of elements a oo A,where 53. Write a program to read a sorted floating point
Aj and i<j ___ array. Update the array to delete the given number.
40. Write a program that reads 4 matrix and displays 24 Modify the linear search program so that it
the sum of the elements below the main diagonal. operateson a sorted array.
Hint: Calculate sum of elements ofarray A,where 5s. Write aprogram to build an array of 100 random
numbers in the range 1 to 100. Perform the
Aj and i>j
following operations on the array:
Hint: Calculate sum of elements ararray Awhere
Aj and i>j (a) Count the number of elements that are
completely divisible by 3.
41. Write a program that reads a square |
matrixcofsize
(b) Display the elements of the array by displaying
nxn. Write a function
a maximum of 10 elements in one line.
int is Upper Triangular(int al][], int
(c) Display only the even elements of the array by
n) that returns 1 if the matrix is upper triangular.
displaying a maximum of 10 elements in one
Hint: Array A is upper triangular ifA,= 0 for i>j
line.
42. Write a program that reads a square matrix of size
(d) Count the number of odd elements.
nxn. Write a function
(e) Find the smallest element in the array.
int is Lower Triangular(int ali [|], int
(f) Find the position of the largest value in the
n) that returns 1 if the matrix is lower triangular.
array.
Hint: ArrayA is lower triangular ifA,= 0 for i<j
56. Write a program to read two floating point arrays.
43. Write a program that reads a square matrix of size
Merge these arrays and display the resultant array.
nxn. Write a function int isSymmetric(int
57. Write a program to read two sorted floating
al] [], int n) that returns 1 if the matrix is
point arrays. Merge these arrays and display the
upper triangular.
resultant array. _
Hint: Array A is symmetric ifAj= A; for all values of
ijandj 58. How can one-dimensional array be used for inter-
process communication?
44. Write a program to calculate XA + YB where A and
B are matrices and X = 2 and Y= 3. oo. Write a program to read and display a p*q*r array.
45. Write a program to find a given number from an 60. Write a program to initialize all diagonal elements
unsorted array. of a two-dimensional array to zero.
Arrays | 185 |

. 61 Consider a 10 X 10 two-dimensional array which (e) int marks[ ];


has base address= 1000 nd the number of (f). intmarks[10] ek
words per memory locat f the array= 2. (g) int| é rks[9+1][6- 1);
ow compute the address of 1 1e element arr[8]
Identify errors, if any, in re foe initialization
[5] assuming that the elements are stored in row
eae statements.
major order. Then calculate the same assuming
[ the elements are stored in column major order. — (a) int marks[ ] = {0, 0,0,0};_

3 Consider. -— (b) int marks[2][3]=(10,20,3040};


rray MARKS[20][5] which stores the _
marks obtained by 20 students in 5 Shae Now (c) int marks[2,3]= {10,20,30},140, 50,60};
write a program to. (d) int Cs {0};
find the average a obtained in each Find out the output of the following code
subject . :
1 #incl de <stdio. be
find the average mark tained by every _ . main ()
student /
find the number of dents who have scored int1, arr[iol;
below 50 in their average for(1=0;4<10;1+4)
display the scores obtained by every student arr[i*2] = 1;
given below: for (i=0;i<10; {
Charles Dicken Esha Georgia _ _are(it2s1)= -1;
Hillary Mishael - £or(i=0;i<10;i++)

Name[0] Name[1] Name[2] Name[3] Name[4] _ printh(*\t 2d”, aria);


-weturn 0; <. -
Name(5] Name[6] el
a) How many elements would 9 moved if the
name Andrew has to be added iin it?
2. #include <stdio.h>
main®)
7 (ii) 4
{
(iii) 5 (iv) 6 int arr[]={0,1,2,0, 12,042),
(b) How many elements would be moved ifthe printé(“\\n 9d” arr
name Esha has to be deleted from it? _ Peince(”\\n sd”, arr [arr [3]]);
32. (ii) 4 print£("\\n 3d”, arr [arr [3] +arr[1]]);
(iii) 5 - - . WG - printf ( \\n fay
arr arr [arr (arr [1111] );
(c) How many comparisons need to be made to
return oi
search for the name Hillary?
() 3 (i)4
tee <stdio.h>
(ii) 5 7 “(iv) 6
main ()

{
Program Output int avril (]=(0,1,2,0,1,2,0;1,2,0},
ivt i, aryv2,i0|- —C
Identify errors, ifany, in the following decerston
for (4=0;1<10-133)
statements.
arr2(i] = arri i9-i];
“G) int marks(10); for (i=0;1<10;i++) :
int marks[10, 5]; -printi(“\t %d”, arr2{i)); .
int marks[10],[5]; return 0; —_
(d) ‘intmarks[10];
‘A4.1 INTRODUCTIONTO SORTING (b) Compare 52 and 29. Since 52 > 29, swapping is
done. 30, 29, 52, 87, 63, 27, 19, 54
The term sorting means arranging the elements of the array
(c) Compare 52 and 87. Since 52 < 87, no swapping is
in some relevant order which may either be ascending or
done.
descending, i.e., if A is an array, then the elements of A are
(d) Compare, 87 and 63. Since, 87 > 83, swapping is
arranged in sorted order (ascending order) in such a way
that. All <All) -~ Alelee ... <-A Ns
done. 30, 29, 52, 63, 87, 27, 19, 54
For example, if we have an array that is declared and (e) Compare 87 and 27. Since 87 > 27, swapping is
initialized as, done.30, 29; 52, 63, 27,87,19554)
SEAT) eho dw ose le Oy. Oe LO 2a) 5 (f) Compare 87 and 19. Since 87 > 19, swapping is
Then the sorted array (ascending order) can be given as, done? 30529. 52, 0552 7,19 Ste 54
Rien Ov. en Opel lad paa, Sach. (g) Compare 87 and 54. Since 87 > 54, swapping is
A sorting algorithm is defined as an algorithm that done. 30, 29, $2,63,.27, 19, 54,87
puts elements of a list in a certain order (that can either be Observe that after the end of the first pass, the largest
numerical, lexicographical, or any user-defined order). element is placed at the highest index of the array. All the
other elements are still unsorted.

A4.2 BUBBLES Pass 2:

Bubble sort is a very Sale method that sorts the array (a) Compare 30 and 29. Since 30 > 29, swapping is done.
elements by repeatedly moving the largest element to the 29,.30,,52,:63,.274195:545 87
highest index position of the array (case of arranging el- (b) Compare 30 and 52. Since 30 < 52, no swapping is
ements in ascending order). In bubble sorting, consecu- done.
tive adjacent pairs of elements in the array are compared (c) Compare 52 and 63. Since 52 < 63, no swapping is
with each other. If the element at the lower index is greater done.
than the element at the higher index, the two elements are
(d) Compare 63 and 27. Since 63 > 27, swapping is done.
interchanged so that the smaller element is placed before
29, 30, 52, 27,63, 19, 54, 87
the bigger one. This process is continued till the list of
unsorted elements gets exhausted. (e) Compare 63 and 19. Since 63 > 19, swapping is done.
This procedure of sorting is called bubble sorting 29, 30, 52, 27, 19, 63, 54, 87
because the smaller elements ‘bubble’ to the top ofthe list. (f) Compare 63 and 54. Since 63 > 54, swapping is done.
At the end of the first pass, the largest element in the list 29, 30, 52, 27, 19, 54, 63, 87
will be placed at the end of the list. Bubble sort is also
Observe that after the end of the second pass, the second
referred to as sinking sort.
largest element is placed at the second highest index of the
| Netey lf the elements are to be sorted in array. All the other elements are still unsorted.
descending order, then with each pass the
Pass 3:
smallest element is moved to the lowest
index of the array. (a) Compare 29 and 30. Since 29 < 30, no swapping is
done.
(b) Compare 30 and 52. Since 30 < 52, no swapping is
Bubble Sort Example
done.
To discuss the bubble sort let us consider an array that has (c) Compare 52 and 27. Since 52 > 27, swapping is done.
the following elements:
29; 30; 273,52; 19°54; 63,37,
Pi Were 30, 52,229, S%res 27; 18.54)
(d) Compare 52 and 19. Since 52 > 19, swapping is done.
Pass 1: 29. 30,275 19, S2..540032. 87,
(a) Compare 30 and 52. Since 30 < 52, then no swapping (e) Compare 52 and 54. Since 52 < 54, no swapping is
is done. done.
Arrays 187 |

Observe that after the end of the third pass, the third
largest element is placed at the third highest index of the Sole “aly idle Weeuieype
ap, encre |LIUG)I|r

array. All the other elements are still unsorted. Gilbaisrena


(i
printf ("\n Enter the number of elements
Pass 4: shim, Wea) ekeceyeg UW)
scanf("%d", &n);
(a) Compare 29 and 30. Since 29 < 30, no swapping is
printf ("\n Enter the elements ");
done.
fon (=) Oak midi)
(b) Compare 30 and 27. Since 30 > 27, swapping is done. scantisdNy camnr tau).
2 7p aN, SU, 1),02, J+, 03, 8) iene (SNS Opa = Seip sites)
(c) Compare 30 and 19. Since 30 > 19, swapping is done. {
for(j =0;3 < n-i;9++)
29927519, 30, 52, 54, 63, 87
{
(d) Compare 30 and 52. Since 30 < 52, no swapping is nhien(Ghere Hell 23 eussa) [fyfeaab ll)
done. {
temp = arr [j];
Observe that after the end of the fourth pass, the fourth
enere (ig) =: eres [ise 5
largest element is placed at the fourth highest index of the
arr [j+1] = temp;
array. All the other elements are still unsorted.
}
Pass 5: }
}
(a) Compare 29 and 27. Since 29 > 27, swapping is done. printf("\n The array sorted in ascending
Zi, 29, 19,30, 52, 54) 63, $7 order is: \n");
EON 3 W)psh = salpalehs4)
(b) Compare 29 and 19. Since 29 > 19, swapping is done.
joueahighera (U\ey eel, at) evesa |ishIl )\g
21 19,2930, 52, 54, 63,87
getch ();
(c) Compare 29 and 30. Since 29 < 30, no swapping is done. return 0;

Observe that after the end of the fifth pass, the fifth }
largest element is placed at the fifth highest index of the Output
array. All the other elements are still unsorted.
Enter the number of elements in the
Pass 6: eneicelye
Enter the elements 27 72 36 63 45 54
(a) Compare 27 and 19. Since 27 > 19, swapping is done. The array sorted in ascending order is:
195 27,.29,50, 52..94; 63, 8/ 2 S6n4 5a 54 6S a2

(b) Compare 27 and 29. Since 27 < 29, no swapping is


done.
Observe that after the end of the sixth pass, the sixth
Insertion sort is a very simple sorting algorithm, in which
largest element is placed at the sixth largest index of the
the sorted array (or list) is built one element at a time.
array. All the other elements are still unsorted.
We all are familiar with this technique of sorting as we
Pass 7: usually use it for ordering a deck of cards while playing
bridge.
(a) Compare 19 and 27. Since 19 < 27, no swapping is
The main idea behind insertion sort is that it inserts
done.
each item into its proper place in the final list. To save
Observe that the entire list is sorted now.
memory, most implementations of the insertion sort
A4.1 Write a program to enter n numbers in an array. algorithm work by moving the current data element past
Redisplay the array with elements being sorted in the already sorted values and repeatedly interchanging
ascending order. it with the preceding value until it is in its correct
#include <stdio.h> place.
#include <conio.h> Although insertion sort is less efficient when
int main ()
compared with other more advanced algorithms such
|188 [ Introduction to C Programming

as quick sort, heap sort, and merge sort, we will still In Pass 1, A[0] is the only element in the sorted set. In
read about its technique to gain an understanding of the Pass 2, A[1] will be placed either before or after A[0],
subject. so that the array A is sorted. In Pass 3, A[2] will be placed
either before A[0], in-between A[0] and A[1] or after
The Technique A[1], so that the array is sorted. In Pass 4, A[4] will be
placed in its proper place so that the array A is sorted. In
Insertion sort works as follows: Pass N, A[N—1] will be placed in its proper place so that
e The array of values to be sorted is divided into two the array A is sorted.
sets. One that stores sorted values and the other Therefore, to insert the element A[K] in the sorted list
contains unsorted values. Aol, Ate .., A[K-1], we need to compare A[K]
e The sorting algorithm will proceed until there are with A[K-1], then with A[K-2], then with A[K-3] until
elements in the unsorted set. we meet an element A[J] such that A[J] <=A[K] .
e Suppose there are n elements in the array. Initially In order to insert A[K] in its correct position, we need
the element with index 0 (assuming LB, Lower to move each element A[K-1], A[K-2],...., A[J] by one
Bound = 0) is in the sorted set, rest of the elements position and then A[K] is inserted at the (J+1) “® location.
are in the unsorted set. The algorithm for insertion sort is given in Fig. A 4.1.
e The first element of the unsorted partition has array
index 1 Gf LB = 0).
e During each iteration of the algorithm, the first
element in the unsorted set is picked up and inserted
into the correct position in the sorted set.

mee Oe Consider an array of integers given below.


Sort the values in the array using insertion sort.

Pass 1: |

Pass 2:
In the algorithm, Step 1 executes a for loop which will
be repeated for each element in the array. In Step 2, we
store the value of kK‘ element in TEMP. In Step 3, we set
Pass 3: the o“” index in array. In Step 4, a for loop is executed that
will create space for the new element from the unsorted
Pass 4: | list to be stored in the list of sorted elements. Finally, in
Step 5, the element is stored at the J‘? location.
Pass 5: |
Advantages of Insertion Sort
Pass 6:
The advantages of this sorting algorithm are as follows:
e Easy to implement.
Pass 7: |
e Efficient to use on small sets of data.
Pass 8: | e Efficient implementation on data sets that are already
substantially sorted.
Pass 9: | e Performs better than algorithms such as selection
sort and bubble sort. Insertion sort algorithm is much
Pass 10: simpler than the shell sort, with only a small trade-
off in efficiency. While, the insertion sort is twice as
Arrays | 189 |

fast as the bubble sort, it is almost 40% faster than A4.4 SELECTION SORT
the selection sort.
Selection sort is a sorting algorithm that has quadratic
e Requires less memory space. running time complexity given as O(n’) thereby making
e Considered to be online as it can sort a list as and it inefficient to be used on large lists. Although, selection
when it receives new elements. sort performs worse than insertion sort algorithm it is noted
for its simplicity, and also has performance advantages
A4.2 Write a program to sort an array ARR using
over more complicated algorithms in certain situations.
insertion sort algorithm.
Selection sort is generally the preferred choice for sorting
#include <stdio.h>
#include <conio.h> a4
files with very large objects (records) and small keys.
void insertion
sort (int arr[],int n);
void main() The Technique
{
SLs, EhaellWOl|
, aby Idesasian
Consider an array ARR with N elements. The selection
eileaciene (5 , sort takes N—1 passes to sort the entire array and works as
printf ("\n Enter the number of elements follows. First find the smallest value in the array and place
in the array: "); it in the first position. Then find the second smallest value
scanf ("%$d", &n); in the array and place it in the second position. Repeat this
printf ("\n Enter the elements of the procedure until the entire array is sorted. Therefore,
array"); In Pass 1, find the position Pos of the smallest value
ise (al = yah ce taresiees) in the array and then swap ARR[POS] and ARR[0].
{ Thus, ARR [0] is sorted.
jorerioere (ON Eraeliexell] = ©, a))p In Pass 2, find the position Pos of the smallest value
scanf ("%d", &arr[i]); in sub-array of N-1 elements. Swap ARR[POS] with
} ARR [1]. Now, A[0] and A[1] 1s sorted.
insertion_sort (arr,n);
In Pass 3, find the position Pos of the smallest value
printf ("\n The sorted array is: \n");
in sub-array of N—2 elements. Swap ARR[POS] with
Oia (Ge s Oj- dee Osa tte)
ARR [2]. Now ARR[0], ARR[1], and ARR[2] 1s sorted.
fonqabayene (Mole) Givers |[at}))-
In Pass N-1, find the position POS of the smaller of
getch ();
the elements ARR [N-2] and ARR [N-1]. Swap ARR [POS]
}
void insertion
sort (int arr[], int n)
and ARR [N-2] so that ARR[0], ARR[1],..., ARR[N-1]
is sorted.
{
shale ah, af, 1eeuiop The algorithm for selection sort is shown in Fig. A 4.2.
for(i = O;i < n;i++) In the algorithm, during the Kt" pass we need to find
{ the position POS of the smallest elements from ARR[K] ,
eels = ekare lla] 5 ARR[K+1], ..., ARRIN]. To find the smallest element
Bie Dow ees we will use a variable SMALL to hold the smallest value in
while((temp < arr[j]) && (j>=0)) the sub-array ranging from ARR [K] to ARR[N] . Then swap
{ ARR [K] with ARR[POS] . This procedure is repeated until
arr [j+1] arr[j]; all the elements in the array are sorted.
Je>F
}
arr[j+1] = temp;

}
Output
Enter the number of elements in the array: 6
Enter the elements of the array 27 72 36 63
45 54
The sorted array is:
236) 45854 06S 2
190 | Introduction to C Programming

scané ("$d", &arr [il] );


}
selection_sort
(arr, n);
printf("\n The sorted array is: \n");
For(i *="0 enya +)
prance ("SdNereicr
| lh) >
getch ();

FEL Algorithm for selection sort }


TAG Sita Lest (erates cust [ally clita mataaiomaa))
{ i

The advantages of the selection sort algorithm are as slieie jokes = Ve, Ete lileweia
ied) a!
follows: for(i = k+1;1i < n;i++)

¢ simple and easy to implement {


if (arr[i]l< small)
* can be used for small data sets
{
* 60% more efficient than bubble sort algorithm small = arr[il];

The disadvantage is that it is inefficient for large data sets. POs=— ai;

Insertion sort is considered to be better than selection sort }


and bubble sort. }
return pos;
A4.3 Write a program to sort an array using selection sort }
algorithm. void selection
_sort (int arr[],int n)

#include <stdio.h>
{
int k, pos, temp;
#include <conio.h>
for(k = 0;k < n;k++)
int smallest (int arr[], int k, int ’n);
void selection
‘sort (int arr[], int n);
{
pos = smallest (arr, k, n);
void main()
temp = arr([k];
{ arr[k] = arr[pos];
abahemcware [aMOy |i Mneeecols ec)anes
arr[pos] = temp;
cirser();
printf ("\n Enter the number of elements
in the array: ");
}
scanf ("Sd", &n); Output
printf ("\n Enter the elements of the
Enter the number of elements in the array: 6
array");
Enter the elements of the array 27 72 36 63
fForn(G==. Osas an a++)
45 54
{ The sorted array is:
roparamuene (uNGny ebene bevelll =) We aby)
29 3:6) 25 4 2688 2

Example A4.2 Sort the array given below using selection sort

sls [als [= [ale [a


CHAPTER

a
Strings

T akeaways
ie Reading and Writing Strings Upprescing Input . « String Operations _
© Array of Strings [7+ ne ane Character Functions. -

char) sts [5] = sUhEELONM-

Then the null character will not be appended automatically


Nowadays, computers are widely used for word processing
to the character array. This is because, str can hold only 5
applications such as creating, inserting, updating, and
characters and the characters in HELLO have already filled
modifying textual data. Besides this we need to search for
the space allocated to it.
a particular pattern within a text, delete it, or replace it .
with another pattern. So there are actually a lot we as users
do to manipulate the textual data.
In C language, a string is
nothing but a_ null-terminated
character array. This means that
after the last character, a null characters inthestring plus one. =
character (‘\0’) is stored to
signify the end of the character Like we use subscripts (also known as index) to access
array. For example, if we write, the elements of an array, the

Programming Tip:
same subscripts are also used to
Charestr|]! = “HELLO,
access the elements of the
We are declaring a character array that has five usable character array. The subscript
characters namely,H, E, L, L, and o. Apart from these starts with a zero (0). All the
characters, a null character (‘\0’) is stored at the end characters of a string array are
of the string. So, the internal representation of the string stored in successive memory
becomes HELLO’ \0’. To store a string of length 5, we locations. Figure 6.2 shows how
need 5 + 1 locations (1 extra for the null character). The str[] is stored in memory.
name of the character array (or the string) is a pointer to Thus we see that in simple terms a string is a sequence
the beginning of the string. Figure 6.1 shows the difference of characters. In Fig. 6.2, 1000, 1001, 1002, and soon
between character storage and string storage. are the memory addresses of individual characters. From
If we had declared str as, the figure, we see that H is stored at memory location 1000
|192 |_Introduction to C Programming

. “charstr{] ="HE
8 a
End of
string
{ Beginning )
ofstring

Here Hisa rine not aa character. The ‘


string H requires two m mory locations,
{Kk One
_ to store the characte
_ the null characte

but in reality the ASCII codes of characters are stored in of the string (or the character array). Here, the compiler
memory and not the character itself, i.e., at address 1000, will automatically calculate the size based on the number
72 will be stored the ASCII code for His 72. of elements initialized. So, in this example 6 memory slots
Ginnie Giere|| S Uglies will be reserved to store the string variable, str.
We can also declare a string with size much larger than
the number of elements that are initialized. For example,
str[0] consider the statement below.
str[1] Glens Sexe |il@]|, SH. MelawiLOM

str[2] In such cases, the compiler creates a character array of


size 10; stores the value "HELLO" in it and finally terminates
str[3]
the value with a null character. Rest of the elements in the
str[4] array are automatically initialized to NULL. Figure 6.3
str[5] shows the memory representation of such a string.

Figure 6.2 Memory representation of a character array :

The above statement declares a constant string as we have


assigned value to it while declaring the string. However,
the general form of declaring a string is, Beginning Beginning End of
of string of string character array
char str[size];

When we declare the string in this way, we can store size


-1 characters in the array because the last character would
be the null character. For example, char mesg[100]; can
store maximum 99 usable characters.
However, the following declaration is illegal in C and
Till now we have seen one way of initializing strings.
would generate a compile time error because of two
The other way to initialize a string is to initialize it as an
reasons. First, the array is initialized with more elements
array of characters, like
than it can store. Second, initialization cannot be separated
char str[] = {SE y wa, Sane EY NO-; \ \O ! } ;
from declaration.
In this example, we have explicitly added the null char str [elk
character. Also observe that we have not mentioned the size Seige VIShWIL{O).) 5
Strings | 193 |

The next method of reading a string is by using gets ()


function. The string can be read by writing
gets (str) ;

gets () isa simple function that overcomes the drawbacks


Shar str?, ae
of the scanf () . The gets() takes the starting address of
> ste2 = stri;
the string which will hold the input. The string inputted
using gets() is automatically terminated with a null
character.
6.1.1 Reading Strings
Last but not the least, the string can also be read by
If we declare a string by writing calling the getchar() repeatedly to read a sequence
char str[100];
of single characters (unless a terminating character is
entered) and simultaneously storing it in a character array
Then str can be read from the user by using three ways: as shown below.
1. using scanf function
’ L=Olg
2. using gets() function ch=getchar();// Get a character
3. using getchar(), getch(), or getche ()function while(ch != ‘*’)

repeatedly {
str[i] = ch;
The string can be read using scanf () by writing // Store the read character in str
i++;
SCan miscues.) ch=getchar();// Get another character

Although the syntax of scanf() function is well }


Siene|(sh|| So OO! s
known and easy to use, the main pitfall with this function // terminate str with null character
is that the function terminates as soon as it finds a blank Stee fail) oa SOX ¢
space. For example, if the user enters Hello World, then
: Note that in this method, you have
str will contain only Hello. This is because the moment
r to deliberately append the char-
a blank space is encountered, the string is terminated by
will begene ited ifa acters with a null character. The
the scanf () function. You may also specify a field width
String is assigned to _ other two functions automatically
to indicate the maximum number of characters that can be
i character variable. | do this.
read in. Remember that extra
_ characters are left unconsumed in
6.1.2 Writing Strings
the input buffer.
Unlike integer, float, and The string can be displayed on screen using three ways:
_ characters, %s format does not 1. using printf() function
require the ampersand before the 2. using puts() function
variable str.
3. using putchar () function repeatedly
The string can be displayed using printf () by writing
print’ (este);
We use the conversion character ‘s’ to output a string.
Observe carefully that there is no & character used with
the string variable. We may also use width and precision
specifications along with %s (as discussed in Chapter 1).
The width specifies the minimum output field width. If
the string is short, extra space is either left padded or right
padded. The precision specifies the maximum number of
characters to be displayed. A negative width left pads short
string rather than the default right justification. If the string
‘e2icen |(stdin);. is long, the extra characters are truncated. For example,
|194 | Introduction to C Programming

jouaabalera (CASS Seyouy Chena)!&

The above statement would print only the first three


characters in a total field of five characters. Also these
three characters are right justified in the allocated width. getchar() sea! aeae aTee from the
keyboard; waits for carriage return (enter
To make the string left justified, we must use a minus sign.
key). It returns an integer, in which the
For example,
low-order byte contains the character. The
PLIneE ("s-Secsus Stn) getchar() can be used to input any key,
including RETURN, TAB, and ESC.

|
Note,
getch() Getch() is an alternative for the getchar().
Unlike getchar(), the getch() waits
- will be brinted for a keypress, after which it returns
[ characters t be pecified immediately.
_ as zero, the printed
on the
getche() Similar to getch(). The only difference is that
getche() echoes the character on screen.
putchar() Used to write a character to the screen.
The next method of writing a string is by using puts ()
It accepts an integer parameter of which
- function. The string can be displayed by writing
only the low-order byte is output to the
puts (str) ; screen. Putchar() returns the character
written, or EOF (—1) if an error occurs.
puts () is a simple function that overcomes the drawbacks
of the printf (). The function puts() writes a line of 6.1 Write a program to display a string using printf ().
output on the screen. It terminates the line with a newline #include <stdio.h>
character (‘\n’). It returns an EOF (-1) if an error #include <conio.h>
occurs and returns a positive number on success. main ()
Last but not the least, the string can also be written by {
calling the putchar() repeatedly to print a sequence of chacestnilim=. wintroductlonytonGly,:
single characters. elsesexr
() ;
DESOeL nea)
ee le
1=0)>
Prince\e ees" str).
Wintinlael(S
ters fs Y—) a NOs)
Drantr(®\n (a-o0e
|! ati);
{
Printe ("NE |s.4e
|" Sscrn,
jowleelnene
(ies fat] ))5
// Print the character on the screen
printer ("\nw| 320-48", Str);

1++; printh((nr |*-20 74s |) eer


getch() ;
}
rasywbhainl {0)r

"Note one interesting point from the given” }


at gment. —
Output
char str sO
“print (“\n $s”, ; // prints Hello |Introduction to C|
printf (“\n %s”, ee : // prints Hello | Introduction to C|
print£("\n
#s”, str[2]); / |Introduction to C |
|Intr|
array of character | intr
| Intr |

6.2 Write a program to read and display a string.


6.1.3 Summary of Functions Used to Read and
#include <stdio.h>
Write Characters #include <conio.h>
main ()
Table 6.1 contains a list of functions that are used to read
characters from the keyboard and write characters to the {
char str[50];
screen.
Strings | 195 |

printf ("\n Enter the string: his }


scanf("%s", str); jonsaiiaters
(0 Nini)
elisser ())7; for (1=5;i>=0;1--)
Drintt ("\nw|ts.|"50 stas)t {
Pil
Be Ld! \als |,S208" StL) 5 jy & deste
Plante\n, |$-20e8|%, str); jonesaotens
(CUWel ee, jo. Giese)
Print O\n, |e .45|"5. str); }
Pradce (Nn le20.48 |") Ser); getch();
PLiIntE (*"\n"|'S-2074s|", Str) return 0;
getch() ; }
ase bhaial (05
6.4 Write a program to print the following pattern.
}
H
Output Her:
Enter the string: Te Th
Heyy Ts
| Introduction |
(at 1 Ik) 1, ©)
| Introduction |
leh (ah thy iy XC
| Introduction |
tal eh Jy ll
|Intr|
HEL
| Intr|
H E
|Intr | H
The printf function in UNIX supports specification #include <stdio.h>
of variable field width or precision, i.e., if we write, #include <conio.h>
main ()
joraaonenel(D\isl Bere eee a i, 1p Sieve)s
{
the printf statement will print first p characters of str in SHANE al, Wp 1D
the field width of w. char stalls = .YHRLEOW-
jongabayene
((U Nai)
6.3 Write a program to print the following pattern.
for(i = O;i <= 5;i++)
H
{
HE jo = Algille
Hi Ey & jenaaliaiene
(U Wal EAS) jet")
Voy, thee)!p
Hab aie is }
HAE ely ho joueakiahers
(OUNGal) 5
leh ay JE) aly x) for (i, ==5)d9)5=.0,4--)
HOB {
Hees Diesel,
HE jonenligheie (Win BIS SI", jd), Siete) p
H }
getch();
#include <stdio.h>
return 0;
#include <conio.h>
main()
}
{ sprintf () Function
SMe, BG, Wp 194
The library function sprintf () is similar to printf ().
chan stmije= UHELEO!
joer
(O Wat),
The only difference is that the formatted output is written
for (i=0;i<=5;
i++) to a memory area rather than directly to a standard output
{ (screen). The sprintf()is useful in situation when
p = 1+1; formatted strings in memory has to be transmitted over a
print£("\n 3-5.*s",
°
Pp, str); communication channel or to a special device.
|196 | Introduction to C Programming

The syntax of sprintf () can be given as return 0;

}
int sprintf( char * buffer, const char *
The code will stop accepting a character as soon as the
e@natere ll 4 Cuecbineine,- 4 .J]|
user enters a character that is not a vowel.
Here, buf fer is the place to store the resulting string from However, if the first character in the set is a * (caret
using the function. The argument command is an ellipsis symbol), then scanf() will accept any character that is
sO you can put as many types of arguments as you want. not defined by the scanset. For example, if you write
Finally, the format is the string that contains the text to be scanf ("%[*“aeiou]", str);
printed. The string may contain format tags.
Then, str can contain characters other than those specified
#include < stdio.h> in the scanset, 1.e., it will accept any non-vowel character.
main () However, the caret and the closing bracket can be included
{ in the scanset anywhere. They have a predefined meaning
char buf [100]; only when they are included as the first character of the
Tate ial = ILO} scanset. So if you want to accept a text from the user that
Gjorgatiquese (joke, Nabi ap Geyel sakbiny)F contain caret and opening bracket then make sure that they
are not the first characters in the scanset. This is shown in
the following example:

6.2 SUPPRESSING INPUT scanf ("%[0123456789.*[] ()_+-$%&*]", str);

In the given example, str can accept any character


The function scanf () can be used to read a field without
enclosed in the opening and closing square brackets
assigning it to any variable. This is done by preceding that
(including * and [).
field’s format code with a *. For example, given:
The user can also specify a range of acceptable
scanf ("Sd*c%d",
&hr, &min) ; characters using a hyphen. This is shown in the statement
The time can be read as 9:05 as a pair. Here the colon given below.
would be read but not assigned to anything. Therefore, Scant
ala— zi eeesteeln ie
assignment suppression is particularly useful when part of Here, str will accept any character from small a to small
what is input needs to be suppressed. z. Always remember that scansets are case sensitive.
However, if you want to accept a hyphen then it must ei-
6.2.1 Using a Scanset ther be the first or the last character in the set.

The ANSI standard added the new scanset feature to the


Example 6.1 To better understand the scanset try the
C language. A scanset is used to define a set of characters
following code with different inputs:
which may be read and assigned to the corresponding
#include <stdio.h>
string. A scanset is defined by placing the characters int main()
inside square brackets prefixed with a %, as shown in the {
example: elatene (Shere |PalO)|=.
%["aeiou"] printf ("\n Enter string: " );
scant ("%[A-Z]", str );
When we use the above scanset, scanf () will continue // Reads only upper case characters
to read characters and put them into the string until it printf( "The string is: ss",
2° wt
Si)
encounters a character that is not specified in the scanset. igejeibheig, Os
For example, consider the code given below.
#include <stdio.h>
int main()
{ A major difference between the scanset and the string
Chamusiers (0 1%; conversion codes is that scanset does not skip leading
pPEincke
i \nebneerrstrimgeys y))y
white spaces. If the white space is a part of the scanset,
scant ("%[aeiou]", str );
then scanset accepts any white space character otherwise,
jononligeic(( Wanlays fehenenare; wuss: "a, Chere)6
it terminates if a white space character is entered without
being specified in the scanset.
The scanset may also terminate if a field width
specification 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 statement will terminate if 10 characters has
been read or if a non-vowel character is entered.
scanf("%10[aeiou]", str );

sscanf () Function
The sscanf function accepts a string from which to read
Figure 6.4
input. It accepts a template string and a series of related
arguments. The sscanf function is similar to scanf
function except that the first argument of sscanf specifies Variable-length string A better option is to use a variable
a string from which to read, whereas scanf can only read length format in which the string can be expanded or
from standard input. Its syntax is given as contracted to accommodate the elements in it. For example,
if you declare a string variable to store the name of a student.
sscanf (const char *str, const char *format, [p1, p2, ...]);
If a student has a long name of say 20 characters, then
Here the sscanf () reads data from str and stores them the string can be expanded to accommodate 20 characters.
according to the parameter format into the locations given On the other hand, a student name has only 5 characters,
by the additional arguments. Locations pointed by each then the string variable can be contracted to store only 5
additional argument are filled with their corresponding characters. However, to use a variable length string format
type of value specified in the format string. you need a technique to indicate the end of elements that
Consider the sscanf example given below. are a part of the string. This can be done either by using
sscanf (str, "%d", &num);
length-controlled string or a delimiter.

Here, sscanf takes three arguments. The first is str Length-controlled string In length-controlled string,
that contains data to be converted. The second is a string you need to specify the number of characters in the string.
containing a format specifier that determines how the This count is used by string manipulation functions to
string is converted. Finally, the third is a memory location determine the actual length of the string variable.
to place the result of the conversion. When the sscanf Delimited string In this format, the string is ended
function completes successfully it returns the number of with a delimiter. The delimiter is then used to identify
items successfully read. the end of the string. For example, in English language
Similar scanf () , the sscanf () will terminate as soon every sentence is ended with a full-stop (.). Similarly,
as it encounters a space, i.e., if data continues till it comes in C we can use any character such as comma, semicolon,
across a blank space. colon, dash, null character, etc. as the delimiter of a string.
However, null character is the most commonly used string
delimiter in the C language.

You must be having some confusion when we use the term


In C, we can store a string either in fixed-length format or
string and character array. Basically a string is stored in an
in variable-length format as shown in Fig. 6.4.
array of characters. If we are using the null character as
Fixed-length string When storing a string in a fixed the string delimiting character then we treat the part of the
length format, you need to specify an appropriate size for array from the beginning to the null character as the string
the string variable. If the size is too small, then you will and ignore the rest. Figure 6.5 illustrates this concept.
not be able to store all the elements in the string. On the
Notey InC,astringisa variable length array of
other hand, if the string size is large, then unnecessarily
~ _ characters that is delimited by the null
memory space will be wasted.
|198 | Introduction to C Programming

FUN") will return 20. Note that even blank spaces are
counted as characters in the string.
char str[10];
gets (str); LENGTH (‘0’) = 0 and LENGTH(*’) = 0 because both
the strings do not contain any character and the ASCII
5 hen array of characters code of ‘\0’ is zero. Therefore, both the strings are
can begivenas J Part
of the array) empty and of zero length. Figure 6.6 shows an algorithm
not of thestring | that calculates the length of a string.
“Although he y has 10 locations, !
first 6 locations will be treated asa string.
1 enna SE
tant pey| Delimited st
‘ : (END OFLOOP]
Step4:‘SET LENGTH=I
6.4 STRING OPERATIONS _ Step 5: END

In this section, we will learn about different operations BRT Algorithm to calculate the length ofastring
that are performed on character arrays. But before we
start with these operations, we must understand the way In this algorithm, I is used as an index of the string STR.
arithmetic operators can be applied to characters. To traverse each and every character of STR we increment
In C, characters can be manipulated in the same way as the value of I. Once the null character is encountered,
we do with numbers. When we use a character constant or the control jumps out of the while loop and initialize
a character variable in an expression, it is automatically length with the value of I. This is because the number of
converted into an integer value, where the value depends characters in the string constitutes its length.
on the local character set of the system. For example, if we
write,
egos ake
that returns the mere. si. Itis defined
ee h.
Chargche— SAG:
Tees Ging
6.5 Write a program to find the length of a string.
jorealaaiee (WRC sk)
#include <stdio.h>
// Prints 65, ASCII value of ch that is ‘A’
#include <conio.h>
C also enables programmers to perform arithmetic int main ()
operations on character variables and character constants.
{
So, if we write,
Chaz str (LOOl ie = 0), lengthy
TEIOe |lye @illiarsrengn())
Chakechs=—NA4-
printf ("\n Enter the string :");
dee Chin ta, 0)
gets(str) ;
Piaget (50%)
while(str[i] != ‘\0’)
// Prints 75, ASCII value of ch that is ‘A’. + 10 l++;
Character variables and character constants can be used length = i;
with relational operators as shown in the example, printff("\n The length of the string is:
Ghamech) =uitCuy $a", length) ;
E(chy s=) NAVE && ch! <= ‘Z’) getch();
printf("The character is in upper case") ;
}
Output
6.4.1 Length
Enter the string: HELLO
The number of characters in the string constitutes the length The length of the string is: 5
of the string. For example, LENGTH ("C PROGRAMMING IS
Strings | 199 |
6.4.2 Converting Characters of a String into gets (str) ;
while(str[i] != '\0')
Upper Case
{
We have already seen that in memory the ASCII codes are mie (here
|All SSE Gas here |[SL]| eal ya" ))

stored instead of the real value. The ASCII code for a-z Ujoere
sie |[sl]) = Bells) =a,
else
varies from 65 to 91 and the ASCII code for a-z ranges
Wexere Steve labl = tse [lakil p
from 97 to 123. So if we have to convert a lower case
L++; J++;
character to upper case, then we just need to subtract 32
}
from the ASCII value of the character. Figure 6.7 shows WpperES tie — NOW
an algorithm that converts characters of a string into upper printf ("\n The string converted into
case. upper case ig: ");
puts (upper
str) ;
rereisa library fi retSiewuea, 0)5
ceconverts a characte! }
defined i
in ctype. ho/
Output
Enter the string: hello
The string converted into upper case is:
HELLO

6.4.3 Converting Characters of a String Into


Lower Case
The ASCII code for A-z varies from 65 to 91 and the
ASCII code for a-z ranges from 97 to 123. So if we have
to convert an upper case character into lower case, then we
just need to add 32 to its ASCII value. Figure 6.8 shows
Figure 6.7 Algori thm to) convert‘characters of aString an algorithm that converts characters of a string into lower
into. U case.

Note, In C, there is a library function


In the algorithm, we initialize I to zero. Using I as the
tolower () that converts a character into
index of STR, we traverse each character from step 2 to 3. _ lower case. It is defined in ctype. he
If the character is already in upper case, then it is copied
in the Upperstr string else the lower case character is
converted into upper case by subtracting 32 from its : alize] SETI=0
ASCII value. The upper case character is then stored in Step 2: Rep Step 3 while STR[I] t=" \o
Upperstr. Finally, when all the characters have been chee IF STRAT = AU AND STRIT) = ‘2’
. . SET Lowerstnl Ls=- STR[T] >32|
traversed a null character is appended to the Upperstr (as
done in Step 4). a y srstr (1 = -STR(T)
SEND OR IF, — :
6.6 Write a program to convert characters of a string to . : [END OF while Li
step 4: SEY ie =a
upper case. ee EXIT _
#include <stdio.h>
#include <conio.h>
Figure 6.8 Algorithm to convert Bena ota
a string
int main ()
: into lower case. :
{
Ghar str (200) F*upper str -[100)7
taht ah8) Oe In the algorithm, we initialize I to zero. Using I as the
cirscen index of STR, we traverse each character from Steps 2 to 3.
printf£("\n Enter the string:"); If the character is already in lower case, then it is copied
|200 | Introduction to C Programming

in the Lowerstr string else the upper case character is


converted into lower case by adding 32 to its ASCII value.
The lower case character is then stored in Lowerstr.
Finally, when all the characters have been traversed a null
character is appended to the Lowerstr (as done in Step 4).
6.7 Write a program to convert characters of a string into
lower case.
#include <stdio.h>
#include <conio.h>
int main()
{
char str[200), lowertstr [100];
Figure 6.9 @NIeldiag
shine 2 c= Oy, 3) = Op
lliraexene(())
print: ("\n Enter the string =");
gets (str) ;
6.8 Write a program to concatenate two strings.
while(str[i] != '\0"') #include <stdio.h>
{ #include <conio.h>
ae (Stee
[SL SSA Ge ies [areal
yA? )) int main()
ewes
sic |[g)]]) = Steels] w Sa¢
{
else Chars stat 00le stro [100] sts: OO
LORIEies |[Sh]) SeSieig lakl|ip oye t=O, WHO
l++; J++;
Guleseue(()) ¢
} printf ("\n Enter=the first strings =);
ieyeke Fee afl) SS" (NOM
gets (str1);
printf ("\n The string converted into
printf ("\n Enter the second string : ");
lower case is : ");
gets(str2) ;
puts (lower
str) ;
while(stri[i] != *\0’)
LeEUEHO ;
} {
Serotype —es toi al
Output 1++;

Enter the string: HeLLo


The string converted into lower case is:
hello
while(str2[i] != '\0"')
{
6.4.4 Concatenating Two Strings to form a Heres
|5) |S eSeie |tsules
New String 1++;
47
IF $1 and S2 are two strings, then concatenation operation
}
produces a string which contains characters of S1 followed Sere (ai| s TNO" >
by the characters of S2. Figure 6.9 shows an algorithm printf ("\n The concatenated string is:");
that concatenates two strings. puts (str3) ;
In this algorithm, we first initialize the two counters I getch();

and J to zero. To concatenate the strings, we have to copy return 0;

the contents of the first string followed by the contents of }


the second string in a third string, new_str. Steps 2 to Output
4 copies the contents of the first string in the new_str.
Enter the first string: Hello,
Likewise, Steps 6 to 8 copy the contents of the second Enter the second string: How are you?
string in the new_str. After the contents have been copied The concatenated string is: Hello, How are
a null character is appended at the end of the new str. you?
Strings | 201 |

6.4.5 Appending
Dest_Str[i] = Source Str[j];
Appending one string to another string involves copying 1++;
the contents of the source string at the end of the destination FF;
string. For example, if S1 and S2 are two strings, then }
appending S1 to S2 means we have to add the contents Dest Strili] = \0';
of S1 to S2. Here S1 is the source string and S2 is the printf ("\n After appending, the
destination string. The appending operation would leave destination string is: ");

the source string S1 unchanged and destination string s2 puts (Dest_Str);


getch();
= $2 + S1. Figure 6.10 shows an algorithm that appends
ieeebuain Op
two strings.
}
Output
Enter the source string: How are you?
Enter the destination string: Hi,
After appending,
the destination string is:
Hi, How are you?

6.4.6 Comparing Two Strings

ile Source If S1 and S2 are two strings then comparing two strings
str will give either of these results:
(a) S1 and S2 are equal
(b) S1 >S2, when in dictionary order S1 will come after S2
(c) Sl < S2, when in dictionary order S1 precedes S2

To compare the two strings, each and every character


Figure 6.10 PAY is compared from both the strings. If all the characters are
same then the two strings are said to be equal. Figure 6.11
In this algorithm, we first traverse through the shows an algorithm that compares two strings.
destination string to reach its end, 1.e., reach the position
where a null character is encountered. The characters
of the source string are then copied into the destination
string starting from that position. Finally, a nu11 character
is added to terminate the destination string.
In this algorithm, we first check whether the two strings
6.9 Write a program to append a string to another string. are of same length. If not, then there is no point in moving
#include <stdio.h> ahead as it straightaway means that the two strings are not
#include <conio.h> same. However, if the two strings are of the same length,
main () then we compare character by character to check if all the
{ characters are same. If yes, then variable SAME is set to 1
char Dest _Str[100],
Source _Str[50]; else if SAME = 0, then we check which string precedes
Ie a) SOR) S\eaOr the other in dictionary order and print the corresponding
elirser();
message.
print£ ("\n Enter the source string: (");
gets (Source
Str) ; 6.10 Write a program to compare two strings.
printf ("\n Enter the destination string:"); #include <stdio.h>
gets (Dest _Str) ; #include <conio.h>
while(Dest_ Str[i] != ‘\0’) #include <string.h>
i++; main ()
while(Source Str[j] != ‘\0’) {
|202 fiIntroduction to C Programming

char Stri50) 7, str2itsod-


int 1=0); tend = 0,en26=.0rs same) 0;
eGlrser())>
printf("\n Enter the first string: ");
gets (str1) ;
printf ("\n Enter the second string : ");
gets(str2);
lenil = strlen(stri) ;
len2 = strlen(str2);
if(lenl == len2)
{
while (i<len1)
{
age (Giesewl
(i) SS Sieie2|[s0))))
1++;
else break;
}
if (1==len1)

same=1;
printf ("\n The two strings are equal");
}
}
if (len1!=len2)
printf("\n The two strings are not
equal");
if (same == 0)
{
shied(Seiaila[lal existe? |[s.]|9)
printf("\n Stringl is greater than
SemiImg Zi);
else if (str1[i] <str2 [i] )
printf ("\n String2 is greater than
Shereuligromlllye
}
getch();
return 0;

}
Output In Step 1, I is initialized to zero and J is initialized
Enter the first string: Hello to the length of the string STR. In Step 2, a while loop is
Enter the second string: Hello executed until all the characters of the string are accessed.
The two strings are equal In Step 3, we swap the ithcharacter of STR with its jth
character. (As a result, the first character of STR will be
6.4.7 Reversing a String replaced with the last character, the second character will
be replaced with the second last character of STR, and so
If Si=. "HELLO", then,reverse of S1 = "OLLEH". To
on). In Step 4, the value of I is incremented and J is
reverse a string we Just need to swap the first character with
decremented to traverse STR in the forward and backward
the last, second character with the second last character,
direction, respectively.
so on and so forth. Figure 6.12 shows an algorithm that
reverses a string. 6.11 Write a program to reverse the given string.
#include <stdio.h>
Note There is a library function strrev (sl).
i
#include <conio.h>
‘Se _ that reverses all the characters in the string #include <string.h>
except the null character. It is defined in int main()
string. _ {
Strings | 203 |

char str[100],
reverse str[100], temp; access the next character in STR. In Step 5, the Substr is
sgh ay On9 = Of appended with a nu11 character.
culsaeere
()) 5
printf("\n Enter the string: ");
6.12 Write a program to extract the first N characters of a
gets (str) ; string.
j=strlen(str)-1; #include <stdio.h>
while (i<j) #include <conio.h>

{ int main()
ESI S See (5p) 3 {
Sieve 5) -S Sieialiahl)< 2 char str[100], substr[100];
HMC: t=O. gays
ste [i] = temp;
@ulaaexvere
()) &
1++;
printf("\n Enter the string: ");
jn; gets(str) ;
} printf ("\n Enter the number of characters
printf£("\n The revérsed string is: "); to be copied: ");
puts(str); scanf ("%d", &n);
Seen ib = Os
wmeleibkwag Og while(str[i] != ‘\0’ && i< n)
} {
Silostese [ali] = Sieia|[ai
|9
Output 1++;
Enter the string: Hi there }
The reversed string is: ereht iH Sielosiere |[al| = S\Oe s
printf ("\n The substring is: ");
puts (substr) ;
6.4.8 Extracting a Substring from Left getch();
ise Cuianim OF;
In order to extract a substring from the main string we
}
need to copy the content of the string starting from the
first position to the nth position where n is the number of Output
characters to be extracted. For example, if S1 = "Hello Enter the string: Hi there
World", Enter the number of characters to be copied: 2
The substring is: Hi
cen Sulosicw
Wee (Sil, 7) = Ietealiley Whi
Figure 6.13 shows an algorithm that extracts the first n
characters from a string. 6.4.9 Extracting a Substring from Right of the
String
In order to extract a substring from the right side of the
main string we need to first calculate the position. For
example, if S1 = "Hello World" and we have to copy 7
characters starting from the right, then we have to actually
start extracting characters from the 5th position. This is
calculated by, total number of characters ~ n.
For example, ifS1 = "Hello World", then Substr_
Figure 6.13 RuLeime (Sil, 7) = © VWrorellel
Figure 6.14 shows an algorithm that extracts n
characters from the right of a string.
In Step 1, we initialize the index variable I to zero
In Step 1, we initialize the index variable I with zero. and J to Length(STR) — N + 1, so that J points to the
In Step 2, a while loop is executed until all the characters character from which the string has to be copied in the
of STR have been accessed and I is less than N. In Step substring. In Step 2, a while loop is executed until the null
3, the 1*® character of STR is copied in the I‘? character character in STR is accessed. In Step 3, the o** character
of Substr. In Step 4, the value of I is incremented to of STR is copied in the 1‘ character of Substr. In Step
|204 | Introduction to C Programming

4, the value of I and J is incremented. In Step 5, the substring. For example, if we have a string,
Substr is appended with a null character. str[] = "Welcome to the world of
programming" ;

then,
SUBSTRING (str, 15, 5) = world

Figure 6.15 shows an algorithm that extracts the


substring from a middle of a string.

extractn characters from the

6.13 Write a program to extract the last N characters of a


string.
#include <stdio.h>
#include <conio.h>
int main()
Figure 6.15 ‘Algorithm to extract a substring f
middle of astring
{
Glaewe Sjera||AKOO
||. rlosiere | MOOI
Mas TO, 3SOp inp In this algorithm, we initialize a loop counter I to M,
@uluseyena (up
e., the position from which the characters have to be
printf ("\n Enter the string: ");
copied. Steps 3 to 6 are repeated until N characters have
gets (str) ;
printf ("\n Enter the number of characters been copied. With every character copied, we decrement
to be copied: "); the value of N. The characters of the string are copied into
Scant (Usd ci) another string called substr. At the end a null character
j = Seclea(SEee) = ireily is appended to the substr to terminate the string.
Witile(sitar
[ial l= eNO)
{ 6.14 Write a program to extract the substring from a given
Sulo itera fa) = esitere lala, string.
1++, J++;
#include <stdio.h>
} #include <conio.h>
Substre fu) = SVO7-
int main ()
joreasaeic (Nay AUerSy fjloysiiesasiiatep ales 1)
puts (substr) ;
{
Glee ers LALO), substr[100] ;
getch();
ate TO, WSO; nN, Mm;
metcuion Or
Eulliacyehe
() 5
} printf("\n Enter the main string: ");
Output gets(str) ;
printf ("\n Enter the position from which
Enter the string Hi there
to start the substring: ");
Enter the number of characters to be
scanf("%d", &m);
COpled a>
The substring is there printf ("\n Enter the length of the
Subsitaeime-iay)
Scank Ucar asm)r
6.4.10 Extracting a Substring from the Middle
1=m;
of a String while(str[i] !=*‘\0’ && n>=0)
{ ‘
To extract a substring from a given string requires
substr[j] = str[il];
information about three things. The main string, the i++;
position of the first character of the substring in the given j++;
string, and maximum number of characters/length of the Wie
Strings | 205 |
} 6.15 Write a program to insert a string in the main text.
eibleshese
[Sj] = “\O"s
#include <stdio.h>
printf("\n The substring is: ");
puts (str) ; #include <conio.h>
getch() ; main ()
return 0; {
} char text[100], str[20], ins _text[100];
Me =O, FEO, les, iso 5
Output clrscer();
Enter the main string : Hi there print£("\n Enter the main text : ");
Enter the position from whi¢h to start the gets (text) ;
substring: 1 printf ("\n Enter the string to be
Enter the length of the substring: 7 inserted: ");
The substring is i there gets(str) ;
printf ("\n Enter the position at which
the string has to be inserted: ");
6.4.11 Insertion , scanf("%d", &pos) ;
The insertion operation inserts a string S, in the main text while (text [1] !=’\0’)

T, at the kth position. The general syntax of this operation


ifi(G==pos)
is INSERT(text, position, string). For example,
{
NSERC
Zoey 7S WANA) - UV
7RAR KYA while (str [k] ! ='\0’)
Figure 6.16 shows an algorithm to insert a string in a {
given text at the specified position. ins text ij]=str[k] ;
j++;
k++;
}
}
else
{
new, strfj] =sted. se TNSmtextellaill
=cess (ali,
SET dade - o
I+;
}
1++;
}
dinate esta La — aN OMe;
printf ( fe The new string is: ");
puts (ins text) ;
getch();
meebuaa, Op

}
Figure 6.16 PA -eu sert a string in a given text at
Output
Enter the main text: How you?
Programming Tip: _ This algorithm first initializes Enter the string to be inserted: are
Aprogrammust _the indexes in the string to zero. Enter the position at which the string has
include stdio.h From Steps 3 to 6, the contents of to be inserted: 6
The new string is: How are you?
for standard /0 new_str are built. If 1 is exactly
Pade ece | equal to the position at which the
eae ae substring has to be inserted into 6.4.12 Indexing
ene: ;
the text, then the inner loop copies Index operation returns the position in the string where the
_ the contents of the substring into string pattern first occurs. For example,
stxing.b . >
stringfunctions, the new str. Otherwise, the INDEX ("Welcome to the worldof programming",
and stdlib. h for | contents of the text are copied UW O tallCiel) Mame
other general utility into it. However, if the pattern does not exist in the string, the
INDEX function returns 0. Figure 6.17 shows an algorithm
|206 | Introduction to C Programming

to find the index of the first occurrence of a string within a


given text.
Step 1: (intr: 0 and J=0 — -
Step 2: Rep ile text [I] fe 0"
Step 3: IF
— N>=0
[Initialize]
SET I=0
ENGTH (st) +1

Pipe chine tog Step 5:SET J= coe 1


Step 5: S . Goto step 8 _ Step 6: SEriscis i
- -[ END of outer loop]
. Step 7: SET new_str[J] = ‘0

AR eG Algorithm to delete a substring from a text


area Algorithm to find the index of the first
occurrence of a string within a given text
In this algorithm, we first initialize indexes to zero.
The Steps 3 to 6 are repeated until all the characters of the
text are scanned. If I is exactly equal to M, the position
In this algorithm, MAX is initialized to LENGTH (text) —
from which deletion has to be done, then the index of the
Length(str) + 1. Take for example, if a text contains
text is incremented and Nis decremented. N is the number
"Welcome To Programming" and the string contains
of characters that have to be deleted starting from position
"World". In the main text we will look for at the most
M. However, if I is not equal to M, then the characters of
22 - 5 + 1 = 18 characters because after that there is the text are simply copied into the new_str.
no scope left for the string to be present in the text. Delete operation can also be used to delete a string from
Steps 3 to 6 are repeated until each and every character a given text. To do this, we first find out the first index
of the text has been checked for the occurrence of the at which the string occurs in the text. Then we delete n
string within it. In the inner loop, in Step 3, we check n number of characters from the text, where n is the number
characters of string with n characters of text to find if the of characters in the string.
characters are same. If it is not the case, then we move to
6.16 Write a program to delete a substring from a text.
Step 6, where I is incremented. If the string is found,
#include <stdio.h>
index is initialized with I else set to -1. For example, if
#include <conio.h>s
PE — aWeltelinC JOeMoE ORs oH Hes. Onk LiiD main ()
STRING = COME {
char text[200], str[20], new text[200] ;
In the first pass of the inner loop, we will compare int i=0, j=0, found=0, k, n=0, copy_
WORLD with WELC character by character. As soon as E and loop=0;
O do not match, the control will move to Step 6 and then (oulstsychat()}s

ELCO will be compared with WORLD. In the next pass, COME printf("\n Enter the main text: ");
gets (text) ;
will be compared with COME. fflush(stdin) ;
We will write the programming code of indexing printf ("\n Enter the string to be deleted: ");
operation in the operations that follows. gets(str) ;
fflush(stdin) ;
while (text [i] !=’\0’)
6.4.13 Deletion
{
=O OUnG—s0 c=
The deletion operation deletes a substring from a given
while (text [k] ==str[j] && str[j]!='’\0’)
text. We write it as, DELETE (text, position, length) .
{
For example, k++;
DELETE ("ABCDXXXABCD", 5, 3) = "ABCDABCD" ay
Figure 6.18 shows an algorithm to delete a substring from
£(str[j]=='\0')
a given text.
Strings | 207 |

copy _loop=k; index=0;


new _text[n] = text [copy loop]; eilnetsyehe
(())p
1++; 7 printf ("\n Enter the string: ");
copy_loop++; gets(str) ;
n++; fflush(stdin) ;
} printf("\n Enter the pattern: ");
new str[n]='’\0'; gets (pat) ;
printf("\n The new string is: ");
fflush (stdin) ;
puts (new_ text) ;
printf ("\n Enter the replace pattern: ");
getch();
Gers (cepmpat));
IAS
EW RAIA, 9(0),9
while(str[i] !='\0’)
} ‘
{
Output j=0,k=i;
Enter the main text: Hello, how are you? while (str [k]==pat[j] && pat[j]!='’\0’)
Enter the string to be deleted: , how are you? {
The new string is: Hello k++;
j++;

6.4.14 Replacement }
if (patilj)=='\02)
Replacement operation is used to replace the pattern {
P1 by another pattern P2. This is done by writing, copy_loop=k;
REPLACE (text, patternl, pattern2) while (rep pat [rep index] !=’\0’)
For example, ("AAABBBCCC", "BBB", "X") = {
AAAXCCC ("AAABBBCCC", "X", "YYY")= AAABBBCC. new_str[n] = rep pat [rep index] ;
In the second example, there is no change as ‘x’ does rep_index++;
not appear in the text. Figure 6.19 shows an algorithm to LA ars

replace a pattern P1 with another pattern P2 in the text.


}
new _str[n] = str[copy loop] ;
i++;
copy _loop++;
Tasty

}
new str [n] =’\07;
Figure 6.19 | Algorithm to reple printf ("\n The new string is: ");
_another patter puts (new_str) ;
getch();
ngtsrebaial (0)
The algorithm is very simple, where we first find the }
position Pos, at which the pattern occurs in the text, then
Output
delete the existing pattern from that position, and insert
a new pattern there. String matching refers to finding Enter the string: How ARE you?
Enter the pattern: ARE
occurrences of a pattern string within another string.
Enter the pattern: are
6.17 Write a program to replace a pattern with another The new string is : How are you?
pattern in the text.
#include
#include
<stdio.h>
<conio.h>
6.5 MISCELLANEOUS STRING AND.
main() . CHARACTER FUNCTIONS —”
{
char str[200], pat[20], new _str[200],
In this section, we will discuss some character and
rep pat [100]; string manipulation functions that are part of ctype.h,
eee = 01] =O) ero el =O CODYa
ltOOp—O),, ep string.h, and stdlib.h-
|208 | Introduction to C Programming

6.5.1 Character Manipulation Functions 6.5.2 String Manipulation Functions


Table 6.2 illustrates some character functions contained in In this section we will look at some commonly used string
CeyPe al functions present in the string. h header file.

strcat Function
Syntax:
Ghar *strcat(char *strl, Conse Charetstr2)r,
isalnum(int c) Checks whether isalpha(‘A’);
character cis an
The strcat function appends
alphanumeric character
the string pointed to by str2 to
isalpha(int c) Checks whether isalpha(‘z’); the end of the string pointed to
character c is an
by str1. The terminating null
alphabetic character
character of str1 is overwritten.
iscntrl(int c) Checks whether scanf("%d",
The process stops when the
character c is a control &c);
terminating null character of
character iscntrl(c);
T str2 is copied. The argument
isdigit(int c) Checks whether isdigit(3);
str1 is returned. Note that str1
character c is a digit
should be big enough to store
isgraph() Checks whether isgraph(‘!’);
the contents of str2.
character c is a graphic
#include <stdio.h>
or printing character.
#include <string.h>
The function excludes
int main ()
the white space
{
character
char sErL [50] .= 'Programmng;
isprint(int c) Checks whether isprint(“@’); Claeue eis?|) = Vinay Gus
character c is a printing slemecic (GteisiL, Sieis2))6
character. The function joneatiojene (Mil terse Get. fejereal))s
includes the white return 0;

space character }
islower(int c) Checks whether the islower(‘k’); Output
character c is in lower
strl: Programming In C
case
isupper(int c) Checks whether the isupper(‘K’); strncat Function
character c is in upper
case Syntax:
eS S|
ispunct(int c) Checks whether ispunct(‘?’); Ghar *Stirmcat (char—*Sstril, const char *sts2)
the character cis a size t nm);
punctuation mark
Appends the string pointed to by str2 to the end of
isspace(int c) Checks whether the isspace( ‘); the string pointed to by str1 up ton characters long. The
character cis a white
terminating null character of str1 is overwritten. Copying
space character
stops when n characters are copied or the terminating null
isxdigit(int c) Checks whether isxdigit(‘F’); character of str2 is copied. A terminating null character is
the character cis a
appended to str1 before returning to the calling function.
hexadecimal digit
#include <stdio.h>
tolower(int c) |Converts the character tolower(‘K’) #include <string.h>
c to lower case returns k int main()
toupper(int c) |Converts the character tolower(‘k’) {
c to upper case returns K char str1[50] = "Programming";
Strings | 209 |

changst E22 i je=) “ain-Cl--


Sitmmca tists ersites2y) char str[50] = "Programming In) C";
jorenbahens (Nay hoses Ey fejeucil)) char *pos;
qeibhaig (0)5 jos Ss Siecle (sites, Yin” )) 5
} if (pos)
print£("\n The last position of mm 1s:
Output
$d", pos-str) ;
strl: Programming In else
printf("\n n is not present in the
strchr Function Sieierere/!))5
return 0;
Syntax: 6
}
char *strchr(const char *str, int c);
Output
The strchr ( ) function searches for the first oc-
currence of the character c (an unsigned char) in the string The last position of n is: 13

pointed to by the argument str. The function returns a


strcmp Function
pointer pointing to the first matching character, or null if
no match was found. Syntax:
#include <stdio.h> int strcemp(const char *strl1, const char
#include <string.h> *str2);

int main()
The strcmp compares the string pointed to by str1 to
{ the string pointed to by str2. The function returns zero if
char str[50] = Wieraecpastiiiuige) Ile) Cie
the strings are equal. Otherwise, it returns a value less than
char *pos;
zero or greater than zero if str1 is less than or greater
DOSm=—Cl rehire (Stsa pula )e-
if (pos)
than str2, respectively.
jorsatiniene
(UY Nia got alisy Aeeybievel alia ies Elite #include <stdio.h>
position %d", pos);
#include <string.h>
int main ()
else
printf("\n n is not present in the {
Serinau)y,
char str1[10] "HELLO" ;
Char str2 (0) =" Evan
return 0;
i (Stremp(striy str2)—==0)
} printf ("\n The two strings are
Output identical") ;
elise
n is found in str at position 9
printf ("\n The two strings are not
identical") ;
strrchr Function
return 0;
Syntax:
chane*strechs (const char *Sstr, ant ic);

The strchr ( ) function searches for the first occur- Output


rence of the character c (an unsigned char) beginning at The two strings are not identical
the rear end and working towards the front in the string
pointed to by the argument str, 1.e., the function search- strncmp Function
es for the last occurrence of the character c and returns a
Syntax:
pointer pointing to the last matching character, or null if
no match was found. int strncemp(const char *strl1, const char
A Steieae) Sea Cetan in)
#include <stdio.h>
#include <string.h> This function compares at most the first n bytes of str1
int main() and str2. The process stops comparing after the null
|210 | Introduction to C Programming

character is encountered. The function returns zero if the str2 is reached then the null
first n bytes of the strings are equal. Otherwise, it returns a characters are continually copied
value less than zero or greater than zero if str1 is less _ to str1 until n characters have
than or greater than str2, respectively. acter array that is been copied. Finally, a null
#include <stdio.h> not terminated with 4 character must be appended to
#include <string.h> anull character. Z
str1. However, if nis zero or
int main()
negative then nothing is copied.
{
char strl(10]* = "HELLO" > #include <stdio.h>

char str2 (20) = “HEY"- #include <string.h>


{
ie (Gerqevenyo
(fsiersil ,Stee , 2) ==0))) int main()
printf ("\n The two strings are {
identical") ; chanestril iol, str2 [10], = "HELLO" ;
else Strmncpy(stri,Str2, 2);
printf ("\n The two strings are not jSuerlighere (W\iny Sleeps Vp, ySiensil)nc
identical") ;
igelewnag, (0)F
return 0; } =

}
Output
Output
HE
The two strings are identical
Notes To copy the string str2 in stri, a better
strcpy Function way is to write _ _
Syntax: strncpy(stri, stra,
char *strcpy(char *st rl, const char *str2); / Sizeof(strl)-1);

This function copies the string pointed to by str2 to


str1 including the null character of str2. It returns the __much characters for which s
argument str1. Here str1 should be big enough to store to accommodate. We have writte of
the contents of str2. str1 minus 1 to store the null character. -
#include <stdio.h>
#include <string.h>
strlen Function
int main()
{ Syntax:
Glatne Shessillfaloll, SiereH alo = "HELLO"; SA ZembEStrnlen(cConsts Chan tse);
Bicictejony (Sheil, SieicA)) 5
DEinee (Uae stil sol stile This function calculates the length of the string str up
return 0; to but not including the null character, i.e., the function
} returns the number of characters in the string.
#include <stdio.h>
Output #include <string.h>
HELLO int main ()

{
strncpy Function char str[] = “HELLO”;
printf ("\n Length of str iis: %d",
Syntax:
strlen(str)
);
char *strncpy(char *st rl, const char *str2, return 0;
fsjaly4= ysl)
}
This function copies up to n characters from the string Output
pointed to by str2 to str1. Copying stops when n
lafevatejiclal, pe (here see
characters are copied. However, if the null character in
Strings | 211 |

strstr Function strcspn Function


Syntax: Syntax:
char *strstr(const char *strl1, const char size t strcspn(const
char *strl1, const char *str2);
*str2);
The function returns the index of the first character in
The function is used to find the first occurrence of string str1 that matches any of the characters in st r2.
str2 (not including the terminating null character) in the #include <stdio.h>
string str1. It returns a pointer to the first occurrence of #include <string.h>
str2 in str1. If no match is found, then a null pointer int main()
is returned. a {
#include <stdio.h> char stri[] = "PROGRAMMING IN C";
#include <string.h>
char str2[]-= "IN":
int main ()
printf("\n The position of first
{ character in str2 that matches with that
Clothe fsieredl
|i NHAPPY BIRTHDAY TO) YOUN; in str1l is %d", strcespn(strl1,str2));
char str2[] i] "DAY" ;
return 0;
char *ptx;
}
DEERE =SerSER (sited, str2) ;
a EN(tea) Output
printf ("\n Substring Found"); The position of first character in str2
else that matches with that in strl is 8
printf ("\n Substring Not Found");
return 0; strpbrk Function
} Syntax:

Output char *strpbrk (const char *str1, const char *str2) ;

Substring Found The function strpbrk() returns a pointer to the first


occurrence in str1 of any character in str2, or NULL if
strspn Function none are present. The only difference between st rpbrk ()
Syntax: and strcspn is that strcspn() returns the index of the
size t strspn(const
char *str1, const char *str2) ; character and strpbrk() returns a pointer to the first
occurrence of a character in str2.
The function returns the index of the first character in
#include <stdio.h>
str1 that doesn’t match any character in str2. #include <string.h>
#include <stdio.h>
int main()
#include <string.h>
{
int main () char stri[] "PROGRAMMING IN C";
chiara sit2) ie —— WABI
char stri([] = "HAPPY BIRTHDAY TO YOU"; Gloves Asjowies = sheagelopale((sherail, ieie2)))))
char str2[] = "HAPPY BIRTHDAY JOE"; if (ptr==NULL)
printf ("\n The position of first printf("\n No character matches in the
character in str2 that does not two strings") ;
match with that in strl is %d", elise
strspn (striyist12)))) ; printf ("\n Character in str2 matches
return 0; with that ane stiri"):

} return 0;

}
Output
The position of first character in str2 Output
that does not match with that in strl is 15 No character matches in the two strings
|212 | Introduction to C Programming

strtok Function all, then the strtol function will store the original value
of str in *end. You may pass NULL instead of *end if
Syntax:
you do not want to store the invalid characters anywhere.
char *strtok( char *strl, const char
Finally, the third argument base specifies whether
*delimiter );
the number
is in hexa-decimal, octal, binary, or
The strtok() function is used to isolate sequential tokens decimal representation.
in anull-terminated string, str. These tokens are separated #include <stdio.h>
in the string using delimiters. The first time that st rtok is #include <stdlib.h>
called, str should be specified; subsequent calls, wishing main ()
to obtain further tokens from the same string, should pass { ‘

a NULL pointer instead. However, the delimiter must be long num;


supplied each time, though it may change between calls. num = strtol ("12345 Decimal Value", NULL, 10);
The strtok() function returns a pointer to the printf ("%ld", num);
beginning of each subsequent token in the string, after num = strtol ("65432 Octal Value", NULL, 8);
replacing the token itself with a NULL character. When all jovealvaenn
(WE SLCRU. aalbtin))5
tokens are left, a null pointer is returned. num = strtol ("10110101 Binary Value"., NULL, 2) ;
#include <stdio.h> jovenhalene (USLCl aaybiin)6
#include <string.h> num = strtol("A7CB4 Hexadecimal Value",
main () NULL, 16);
{ pine (Usa emum)s
chan str] =, "Hello; to, the, «world .of,
getch();
programming" ;
return 0;
eleec Ceulyill < Ws
char result [20]; }
result = strtok(str, delim);
Output
while (result ! =NULL)
12345
{ 27418
Didier ues Se meresuilss)i
Algesal
result = strtok(NULL, delim) ;
687284
}
getch();
strtod Function
return 0;
Syntax:
}
double strtod(const char *str, char **end);
Output
The function accepts a string str that has an optional plus
Hello
(‘+’) orminus sign (‘-’) followed by either:
to
the e a decimal number containing a sequence of decimal
world of digits optionally consisting of a decimal point, or
programming
e a hexadecimal number consisting of a "0X" or
"0x" followed by a sequence of hexadecimal digits
strtol Function
optionally containing a decimal point.
Syntax:
In both cases, the number may be optionally followed
long strtol(const char *str, char **end, int
by an exponent (‘E’ or ‘e’ for decimal constants or a
base); |
‘P’ or ‘p’ for hexadecimal constants), followed by an
The strtol function converts the string pointed by str optional plus or minus sign, followed by a sequence of
to a long value. The function skips leading white space decimal digits. For decimal constants and hexadecimal
characters and stops when it encounters the first non-
constants, the exponent indicates the power of 10 and 2,
numeric character. strtol stores the address of the first
respectively, by which the number should be scaled.
invalid character in str in *end. If there were no digits at
Strings | 213 |

#include <stdio.h>
atol() Function
#include <stdlib.h>
main () The function atol() converts the string into a long int
{ value. The atol function returns the converted long value
double num; to the calling function. Like atoi, the atol() will read
num = strtod("123.345abcdefg", NULL) ; from a string until it finds any character that should not be
print£ ("Slf", num); in a long. Its syntax can be given as,
getch();
longratol @constcharexcitiam) rk,
wecurny 0);

} Example =x = atol( "12345.6789" );


RESULAL exe = s 4 Sine
Output :
123 .345000 Notey e : functions ato atofi),and atol()
art of stdlib.h F
atoi() Function
Till now you must have understood that the value | is an

6.6 ARRAY OF STRINGS —


integer and ‘1’ is a character. So there is a huge difference
when we write the two statements given below as

Till now we have seen that a string is an array of characters.


siete, ak=ake // here i =1
For example if we say, char name[] = "Mohan", then
Iutn= s // here i =49, the ASCII
name is a string (character array) that has five characters.
value of character 1
Now suppose that there are 20 students in a class and
Similarly, 123 is an integer number but ‘123’ isa string of we need a string that stores names of all the 20 students.
digits. What if you want to operate some integer operations How can this be done? Here, we need a string of strings
on the string ‘123’? For this, C provides a function atoi or an array of strings. Such an array of strings would store
that converts a given string into its corresponding integer. 20 individual strings. An array of string is declared as,
The atoi() function converts a given string passed to it char names
[20] [30];

as an argument into an integer. The atoi () function returns Here, the first index will specify how many strings are
that integer to the calling function. However, the string needed and the second index specifies the length of every
should start with a number. The atoi() will stop reading individual string. So here, we allocate space for 20 names
from the string as soon as it encounters a non-numerical where each name can be a maximum of 30 characters long.
character. The atoi () is included in the stdlib.h file. So Hence, the general syntax for declaring a two-dimensional
before using this function in your program, you must include array of strings can be given as,
this header file. The syntax of atoi () can be given as, <data type> <array_name> [<row_size]

int atoi( const char *str ); [<column_size>] ;

Let us see the memory representation of an array of strings.


ig=satOi(eUI23545 6
If we have an array declared as,
PEHSUMLYM ak aS ye
char name[5] [10] = {"Ram", "Mohan", "Shyam",
atof () Function "Hari" , "Gopal " };

The function atof () converts the string that it accepts as


then in memory the array is stored as shown in Fig. 6.20.
an argument into a double value and then return that value
to the calling function. However, the string must start with
a valid number. One point to remember is that the string Name [0] ee
Name [1]
can be terminated with any non-numerical character, other
than "E" or "e". The syntax of atof () can be given as,
double atof( const char *str );

x = atof( "12.39 is the answer" );


RE SUL =) le e3'9
|214 | Introduction to C Programming

By declaring the array names, we allocate 50 bytes. Enter the name of student: Aditya
But the actual memory occupied is 27 bytes. Thus we Enter the name of student: Goransh
see, more than half of the memory allocated lies wasted. Enter the name of student: Sarthak
Figure 6.21 shows an algorithm to process an individual Names of the students are: Aditya Goransh
string from an array of strings. Sarthak
6.19 Write a program to sort names of students.
#include <stdio.h>
#include <conio.h>
main () i

{
char names [5] [10], temp[10] ;
sane lb, |lek aly
Figure 6.21 ealnaeyene
(())4
es printf ("\n Enter the number of students: ");
scant ("Sd", &m) ;

In Step 1, we initialize the index LAE EIS RRS


variable I to zero. In Step {
printf ("\n Enter the name of the
2, a while loop is executed
student @d: ", i+1);
until all the strings in the array
Flush (stdin);
_ are accessed. In Step 3, each
gets (names [i]) ;
| individual string is processed.
}
ree (al, = ES ee alpelees)
6.18 Write a program to read and print the names of n {
students of a class. ford = 054 contol jas)
#include <stdio.h> {
#include <conio.h> 1£ (strcmp (names [j] , names [j+1] ) >0)
main () {
{ strcpy (temp, names[j]);
char names[5] [10]; strcpy (names[j], names[j+1]);
alate Ghe tal strcpy (names [j+1], temp);
S@llsaexena(O)¢
printf ("\n Enter the number of students:") ;
scanf("%d", &n);
for (1=0;i<n;i++) printf("\n Names of the
{ students are: ");
printf ("\n Enter the name of for (1=0;
i<n; i++)
student *d: ", i+1); puts (names [i] ) ;
gets (names [i] ) ; getch
() ;
} return 0;
printf ("\n Names of the students are:\n") ; }
imona (al, =) (pak ce inlsants5))
puts (names [i]) ; Output
getch() ; Enter the number of students: 3
return 0; Enter the name of student: Sarthak
} Enter the name of student: Goransh
Enter the name of student: Aditya
Output Names of the students are: Aditya Goransh
Enter the number of students: 3 Sarthak
Strings | 215 |

BOACDARARAIAIC CV: >


PROGRAMMING
SSS a
EXAMPLES_.
—os| aets
while(str[i]
(str) ;
| !=
ee*\0’)
6.20 Write a program to read and print the text until a * is ,
. se (Shere|(ab]| aa YOY te Chere |[steil]) ea ©”)
encountered. Also count the number of characters in
count++;
the text entered.
1++;
#include <stdio.h> }
#include <conio.h> printf ("\n The total count of words is:
int main() $a", count) ;
{ return 0;

char str[1000]; 4 }
int 1=0;
ae Output
eillaetstenal@))s
printf ("\n Enter * to end"); Enter the sentence: How are you
Printé ("\n #eeke
ke REE EN) The ScOtalE Count Or aWwOLGS s1cimES

printf("\n Enter the text: "); 6.22 Write a program to read multiple lines of text until
SGania Gus Cul mcs cialkialW is a * is entered. Then count the number of characters,
while(str[i].!= \**) words, and lines in the text.
{
ote #include <stdio.h>
‘ ’ #include <conio.h>
scank(“te", Setrla)5 :
int main()

See fall es NO s
2 ! \ : char str[1000] ;
jouculigyene
(U\ inl “Mba ieee, akg 0) p ;
: int 1=0, word count = 1, line count =1,
nee!: gyi, edt char a count = 1;
while(str[i] ! Or) curser

{ printf ("\n Enter a * to end");


joreuim@ese (UNM. fsherel
abl) ))§ printf ("\n *** eee RR RIT)
a printf ("\n Enter the text: ");
} fxeehghe (eye. tesshene |[Sil| ))
printf ("\n The count of characters is: while(str[i] != ‘*")
$d",i-1); {
igaieueay (0) Laer

} scank("se", Sst [a>

Output
}
p
Sere |[sil| = ONO p
Enter * to end i=0;
KKK KK KK KKK KEKE while(str{i] != ‘\0’)

Enter the sentence: Hi there* {


The text is: Hi there if(str[i] == ‘\n’ || is=79)
The count of characters is: 7 line count++;

6.21 Write a program to read a sentence. Then count the if(str[i] == ‘ ' &&str[i+l] != * ')
number of words in the sentence. word_count++;
char_count++;
#include <stdio.h> 1++;
#include <conio.h> }

int main () printf ("\n The total count of words is:


{ 3a", word count) ;
char str[1000]; prints (Wn The total count ofmilanestas.
int i=0, count=0; $d", line count) ;
clrser(); printf ("\n The total count of characters
printf ("\n Enter the ‘sentence: "); is: $d", char count);
|216 | Introduction to C Programming

return 0; elmsen()y;
} printf ("\n Enter the text: ");
gets (str);
Output while(str[i] != ‘\0’)
Enter the text: Hi there* {
The total count of words is: 2 alse (Siew
[atl] Ss? ,”)
ihe eOtalsCount Ob wiamesmts sa: COpyesieis [al =sey kar
The total count of characters is: 7 else

6.23 Write a program to copy n characters of a string from Ni i aN


the mth position in another string. ; sla ;
#include <stdio.h> Copyustr[il = “\07;
#include <conio.h> print (Nn Thescopiledstext ssa. "));
int main() i=0;
{ while(copy_str[i] != ‘\0’)
Eine See lOO] , Cejsy7_
siee |LOOOK ; {
ite =O =O Te PrAner (“clre Copy
isi ails |p;
iincteyeng (()) 5 ees .
printf("\n Enter the text: "); }
gets (Str) ; return 0;
printf("\n Enter the position from which }
tO) Gieekceg )) 5
scanf("%Sd", &m); Output
printf ("\n Enter the number of characters Enter the text: Hello, How are you
to be copied: "); The copied text is: Hello; How are you
scanf("%d", &n); : 2 :
6.25 Write a program to enter a text that contains multiple
sh eS ity ‘ é ; schioke '
es Steere tor ee ee) lines. Rewrite this text by printing line numbers
{ before the text of the line starts.
COp
Yas ters lelpligeeasteta ley) a, #include <stdio.h>
i++; #include <conio.h>
J++; int main ()
n--; {
} char str[1000];
Sein Seal(al) = Y\O? p mae TO), dishmerctewisie = als
print£("\n The copied text is: "); elzsser());
puts (copy str); printf ("\n Enter a * to end");
Beturn 0; printf ("\n FORO IG doa In):

} printf ("\n Enter the text: ");


Scant Cuca eSt rid,
Output yall lley(henas
list) Wey a7)
Enter the text: How are you? {
Enter the position from which to start: 2 i++;
Enter the number of characters to be copied: scant ("se", &str([i]);
5 }
The copied text is: w are Serial eS YO";
i=0;
6.24 Write a program to enter a text that has commas.
while(str[i] != ‘\0’)
Replace all the commas with semicolons and then
display the text. {
if (linecount == 1 && i == )
#include <stdio.h>
printf ("\n %d\t", linecount);
#include <conio.h>
TE ¢Str
pt] ==" \n")
int main () { :
{ linecount++;
char str[1000], copy_str[1000];
printf ("\n %d\t", linecount);
Int =O)
Strings | 217 |

} linecount++;
joreubaese (UE, Sheae|fall|))2 printf ("sd \t", linecount) ;
i++; }
} }
gebhagh (la }
} else

Output Satins

Enter a * to end ole (here


[al] es Sal)}
KEK KKEKKEKK KEKE linecount++;

Enter the text: }


Hello ¢ }
how getch();
are You? return 0;
1 Hello }
2 how
3 are you? , Output
Enter the text : Hello
6.26 Write a program to enter a text that contains multiple
how
lines. Display the n lines of text starting from the
mth line. are you?
*

include <stdio.h
: FS = Enter the line number from which to copy: 1
#include <conio.h>
Enter the line number till which to copy: 2
int main ()
Hello 1
{ how 2
char str[1000];
site ak = O, (al, in, lakaeeoybinie = Os
6.27 Write a program to enter a text. Then enter a pattern
eulueeyene(() 5 and count the number of times the pattern is repeated
:
printf ("\n Enter the text: "); in the text.
scanf("%c", &str[i]); #include <stdio.h>
We wLIles (here |[5h]) Weer) #include <conio.h>
{ i++; main ()
Scant (cl estas) yy {
} char str[200], pat[20];
Jain) SP cate, SO, =O), stowinceO), Jk, Coiniea@ y

printf ("\n Enter the line number from clrecr yi .


Een seo copy... n\e printf("\n Enter the string: ");
gets (str) ;
scant
W &
("¢d", &m);
W .
printf("\n

Enter the pattern: ");
printf ("\n Enter the line number till
gets (pat) ;
which to copy: ")j while (str [i] !=’\0’)
scanf("%d", &n); {
d=; j=0, k=i;
whistles ts) l= \0) while (str[k]==pat[j] && pat[j]!=’\0’)
{ {
Te (sinecounts==i ms) k++;
{ j++;
se ne,
while (n>0) Uf (paeiia
==" NO!)
{ {
jonealinese (ORI, hese Way found=1;
j++; count++;
if(str[j] == ‘\n’) }
L++;
{
no=3 }
|218 | Introduction to C Programming

if (Eound==1) #include <string.h>


printf ("\n PATTERN FOUND %d TIMES", #include <conio.h>
count); main ()
else {
printf ("\n PATTERN NOT FOUND") ; char quest
[5] [100];
return 0; char option1 [3] [20] ,option2 [3] [20],
} option3 [3] [20] ,option4 [3] [20],
options
[3] [20];
Output
int response[5], correct_ans[5], option,
Enter the string: She sells sea shells on i, marks;
the sea shore ellagsere())7 LY

Enter the pattern: sea strcpy


(quest [0] , "Name the capital of
PATTERN FOUND 2 TIMES
India") ;
6.28 Write a program to find whether a given string is a Siiacjon (Gjoeakoraul |LO)]| , Wale Mumbai") ;
Strepy (optren li]; V2. New Delhi");
palindrome or not.
Geneon
(jor aeraul || , Sh Chennai") ;
#include <stdio.h> Coiaigecic
Ens ((@)| = a6
#include <conio.h> strepy(quest [1] , "Name the national bird
int main() of India") ;
{ Strcpy (CpEron2 10)5 1. Peacock") ;
Chara Sit [OOF Stxrepy (optron2) [1] "2. Sparrow") ;

Pte =. 0), ea hence =O) Sstrcpy (cprE1on2[ 2) 73. Parrot") ;

Gulbasere (ng correct


ans [1]=0;
joretiatere (Vin isieee jel) Ghereriareye ™))5 strcpy (quest [2] , "Name the first prime
minister of India") ;
gets (str) ;
strcepy (option3[0],"1. M D Gandhi") ;
whidel(stx
[1] e= a Vom)
strepy (opttons [17 "2: S D Sharma") ;
length++;
Stccpy(optvonsii2Z
ease J L Nehru");
1++;
correct
‘ans [2] =2;
1=0;
strcepy
(quest [3] , "Name the first female
i) = dletaeiclt = ale
president of India") ;
while(i <= length/2) strcepy (option4[0],"1. Pratibha Patil");
{ strcpy (option4 [1] ,"2. Sonia Gandhi") ;
abe (Siete [fall] a here (5/1) Stucpy (Optezon4 12 y's. Indira Gandhi") ;
COmnectransis lm —m Or
strcpy (quest [4] , "Name the youngest prime
minister of India");
SEncpya(OprevenS [Ole vie Rajiv Gandhi") ;
SEuepy(Oprlens [lye Sanjay Gandhi") ;
strcepy (options [2] ,"3. Rahul Gandhi") ;
correct _ans[4i| = 0;
}
do
ses (S91)
joneatiae te (Y \iok PALINDROME") ; {
else
printf ( ("\n\n\n\n QUIZ PROGRAM");
PLANCE (1
( \ mk * ke IN)
printf ("\n NOT A PALINDROME") ;
return 0;
printf("\n ( 1. Display Questions") ;
joResnayesic ( "\n 2. Display Correct Answers") ;
}
printf ( "\n 3. Display Result") ;
Output ( (Nm Zh iapcical)y
jonenbahenc
Enter the string: madam PLANE ( (TIT)
PALINDROME printf ( ("\n\n\n Enter your option: ");
scanf ("%d", &option) ;
6.29 Write a program to implement a quiz program. switch (option)
#include <stdio.h> {
Strings _| 219 |

case’ 1: CGascmer
print£("\n %s \n" quest (0]); printf ("\n\n CHECK THE CORRECT ANSWERS");
PLANE ("\m KKK RHR RRR KERR KKK KA AM)
1B@pe (SLO) Pal) ols 5))
organise (Wiad BS, @youeaivejaual
(fst) ))¢ jsncaigiene (Va Se} Wal
printf ("\n\n Enter your answer number:
$s",quest [0] ,optionl[correct_ans[0]]);
printf ("\n\n %s \n
scanf("%d", &response[0]) ;
$s",quest [1] ,option2 [correct _ans[1]])j;
printf ("\n %s \n", quest[1]);
jonaalimtese (Uae Se}. Winn
for (1=0;1<3;1++)
$s",quest [2] ,option3 [correct_ans[2]]);
orale (T\iey BY, CSjokeaeya
|i] ))5 printf ("\n\n %s \n
printf ("\n\n Enter your answer number: $s", quest [3] ,option4 [correct_ans[3]]);
scant (adr &response [1]) ; joneabintene
(UM\Wal\iay eye} iat
jorezbiayete (Un Sis) ral quest [2]) ; $s",quest [4] ,option5 [correct _ans[4]])j;
for (1=0;1<3;i++) break;
jai (WN SY, wjpoieateras}
|i )))¢ CASE Be

printf ("\n\n Enter your answer number: marks 0;


for(i O;i <= 4;1i++)
scanf ("%d", &response
[2] ) ;
printf ("\n %s \r", quest [3]); {
if (correct_ans[i]+1 == response
[i] )
for (1=0;1<3;1++)
marks++;
jonestiohese (War Sse, jojeakonave
lian ))p
}
printf ("\n\n Enter your answer number: pint Cine OubLmoh > youNscoLremsaur,
scanf ("%d", &response
[3] ) ; marks) ;
picinter (Nn aoss \ntequest (41) )k break;
for (1=0;1<3;1++) }
joraaimeie
(UO\el Be, Cejyoieatexals) |fali))) p }while (option! =4) ;
printf ("\n\n Enter your answer number: getch();
return 0;
scanf("%d", &response
[4] ) ;
break;

id
-
O
=
O
Be
—)
-
=
O
a.
|220 | Introduction to C Programming

_ O<

SZ
no
SZS

oa yyZe
E77
.
LK

GLOSSARY WS
s LINED
Li SRE

ZX Li
Gy YE

©
S

ao
Z,
7

EXERCISES SHES 7

jonS S -
YY LUI
aN
iN
WR Le <
acte
AS Me
&

27
QZLOR Se
7 SS
LUO. EN
2
Se Ce 7 SZ
SZ A
LZ 7 N
TOES
— Co
ZN
SZ SSG

dir
CWS
RO
ZS <
Z
<7 yy WA
EG UNO NONU
S24
nath.h
ae
2 NZ -; : Strin. NG, a NS

hCrr—“—sOC—OCS 2 C < NS
-
7. As ingcan be re
\ 7 ee ONO NT
GY
SZ Ju
2
Cw NS Dd
2 NY NY
as 1D<7
ae as
QZ
77 7Ce
SYSG
- OZ
O Nv

< 7 a/ Ceo
7 WN NZ,
UN
Th
Lo oa
DOC.
Lcome Z
aS
C
Lo
plac
ZY O : V3
Ss
ZU
roar Loy - yo eS
SY G7777S V3 S20 &
A
7 Z _eY
De Sa x
7 LUT
A NZ 7 < 7
Oe
ZZ -
yy
yt 77 7
oo
The
:
iS Y SY, Lo we Y Wy
ES
. aN7
Ti. 0
Fe
LERSUE. SUES WS aN
LZ Ze SZ QZ
Z
< < DUN a
CZ Oe Yi
YY
ZY aT SS
SS ZN

Yi I 7 SS
ee es SN
) return
UE SOE Upp Ups
AL
EX

~~ Ch
SZ,
Yy
CO

aN NN
Ly
WY Rens
OO
OU>

eS
Zo
ey OR. 7

7. 7),
y WS

Co
OS
Le

Le oo
: Ce Oe
SINS
NG
eS

BNE SES
PAU
NZNZS Ce
ENTS

pO OS x
OO e S
Strings | 221 |

State True or False device? Explain the different functions used to


n
Lu perform string input operation.
1. A string Hello World can be read using scanf ()
pe 2 Initializing a string as, char str[]=”HELLO”;
. Explain how strings can be displayed on the screen.
O . Explain the syntax of printf () and scanf ().
ac is incorrect as a null character has not been
Lid . Write a short note on string operations.
x explicitly added.
. Differentiate between gets() and scanf().
Lid . Astring when read using scanf () needs an
ampersand character. wv
aD
On
© . Give the drawbacks of getchar() and scanf ().
Which function can be used to overcome the
. The gets () takes the starting address of the
shortcomings of getchar() and scanf ()?
string which will hold the input.
. The gets() and seane automatically
10. How can putchar () be used to print a string?
appends a null character at the end of the string ve Differentiate between a character and a string.
read from the keyboard. 12 Differentiate between a enarent! array and a
string. /
. The function scanf () can be used to read a line
of text that includes white space characters. 13, List all the substrings that can
¢ be formed from the -
string “ABCD”. /
. The function tolower () isdefined in ctype -h
header file. 14. What do you Hees ane bypatter matching?
Give an algorithm for it.
. Arithmetic operators can be applied to string
variables.
15. Write a short note on aay of strings.
(416. How is an array of strings represented in the
. String variables can be present either on the left
memory?
_ oron the right side of the assignment operator.
17. Explain with an example how an array of strings isis
10. lf S1 and S2 are two strings, then concatenation
stored in main memory.
Operation produces a string which contains
characters of S2 followed by the characters of
18, If Substring function is given as-
SUBSTRING (string, position, length)
S1. / _ _
then, finds (5,9) ifs = “Welcome to world
aa. Appending one string to another string involves Of C Programming”.
copying the contents of the source string at the
19. If Index function is given as INDEX (text,
end of the destination string.
pattern), then find the index(T, P) where T=
12, $1<s2, when in dictionary order $1 precedes s2. “Welcome to world of C Programming” and P=
a3. If S1 = “GOOD MORNING”, then Substr_ ‘or. Co
Right ($1, 5) =MORNING. 20. Write a program in which a oak is paced as an
“ Replace (“ARABBBCCC” , NY | UN” )=
argument to a function. /
BAABBBCC. Zi. Write a program in C to concatenate first n
6. When a String Is initialized during its declaration, characters of a string to another string.
the string must be explicitly terminated with a 24. Write a program in C that compares first n
acter. characters of one string with first n characters of
null char
16. A re another string.
a positive value. — 23. Write a program that reads your name and then
a. Assignment operator can be used to copy the displays the ASCII value 7 each character in your
name on a separate line. _
contents of one string into another.
24. Write a program in C that removes leading and
trailing spaces from a string.
Review Questions
29. Write a program to read a word and re-write its
‘What are strings? Discuss some operations that characters in alphabetical order.
_can be performed on strings.
26. Write a program that accepts an integer value
. Explain how strings are represented in main from 0 to 999. Display the value of the number
_memory. read in words. That is, if the user enters 753, then
. Explain operations that can be performed on print Seven Hundred Fifty Three.
strings. 27. Write a program to insert a word before a given
How are strings read from the standard input word in the text.
|D2), | Introduction to C Programming

28. Write a program to (a) read a name and then . 45. (a)
| Write aprogram to convert the given string
display it in abbreviated form, (b) Janak Raj Thareja “GOOD MORNING” to “good morning”.
should be displayed as JRT; (c) Janak Raj eee (b) Write a program to convert the given ae
should be displayed as J.R. Thareja. “hello world” to “HELLO WORLD”. a
29. Write a program in C that replaces a given character 46. Write a program to concatenate two. given
with another character in the string. strings “Good Morning” and “World”. Diepley hs ]
). Write a program to display the word Hello in the resultant string. - -
following format: 47. Write a program to append tw ) iN en strings’
“Good Morning” and
resultant string. © >
48. Write a program to check vd
strings “Good pas oe
a :oO. are same.
: _\Write a program to display the given string array in 49. Write a program to convertt th :
reverse order. world” to “dirow olleh”.
. Write a program to count the number of characters, 50. Write a menu-driven program ‘that demonstrates
words, and lines in the given text. the use of string functions presentint
thestring. h
33. Write a program to count the number of digits, header file. _.
upper case characters, lower case characters, ae
special characters in a given string. ©
oe Write a menu-driven program that denonniee
the use of character handling functions present ine
34. Write a program to count the total number of : the ctype .h header file.
occurrences of a given character in the string. | 52. Write a program to extract the string “Good” froma
35. Write a program to accept a text. Count and| displ _ the given string “Good Morning”. .
the number of times the word “the”
"appears | Write a program to extract the string “od Mo”
text. from the given string “Good Morning”.
36. Write a program to count the total | . Write a program to insert “University” in the given
occurrences ofawordinthetext. string “Oxford Press” so that the string should read .
37. Write a program to find the last instance as “Oxford University Press”. :
occurrence of a sub-string within a string. _
55. Write a program to delete “University” from the
38. Write a program to insert a sub-string inthemiddle given string “Oxford University Press” so that eg
of a given string. string should read as “Oxford Press”. oo
39. Write a program to input an array of strings. Then 56. Write a menu-driven program to read a tine. :
reverse the string in the format shown below. display the string, merge two strings, copy A
“HAPPY BIRTHDAY TO YOU” should be displayed as characters from the mth pe calculateathe
_ “YOU TO BIRTHDAY HAPPY”. length of the string. / —
Vritea program to append a given string in the of. Write a program to copy the lastncharacters of
llowing format. a character array inanother |
GOOD MORNING MORNING GOOD” convert the lower case lett
rogram to trim a string. letters while copying.
Write a program to input a text of at least two 58. Write a program to. copy
paragraphs. Interchange the first and second string “Oxford University |Pre
paragraphs and then re-display the text on screen. 59. Write a program to simulate the str pyfunction. -
. Write a program to input a text of at least two 60. Write a program to program to rewrite the string :
paragraphs. Construct an array PAR such that “Good Morning” to “Good Evening”. =
PAR[I] contains the location of the I paragraph in 61. Write a program to read and display. names of
TEXT. employees in a department. - -
44. Write a program to find the length of “GOOD 62. Write a program to:sort the names of employees
MORNING”. alphabetically.
Strings | 223

. Write a program to read a


short story and count Char str{i5]="HELLO';
the number of characters, words, lines in the story. Orinvi(
\n str = ce', ctr);
. Write a program to entera text that has both }
4. main()
lower case as well as uppercase characters.
eplace all the lower case characters with upper
char str[10];
case characters and then display the text.
Strncpy(strl, "HELLO", 32);
EXERCISES
— . Write a program to read a short story. Display the printf ("\n str = ss", stc);
n lines of story starting from the mth line. } ‘ :

. Write a program to read a short story. Rewrite 5. main()


the story by printing the line number before the of
arting of each line. char ste liol:
strepy(str, "Hello there");
. Write a program to display a list oF candidates.
printt("\n str = ss", str);
Prompt. 100 users to cast their vote. Finally display } . _
the winner in the elections.
6. main()
Write a program to delete the last ch racter ofa
- G : oo
char str[]= "Hello there";
: Write a program to delete the fe character of a if(strstr(str, "Uni") ==0)
string. _ printf ("\n Substring Found");
} _ CO <
. Write a program to count the number of vimes a
7. Wain’)
given character appears in the string.
. Write a program to insert a new namein the string char stri[/10]|, str2[10],;
|
‘array STUD [] [1, assuming that names are sorted gets (strl, str2).
alphabetically. printf ("\n strl = %s and str2 = 5s",
program to delete a name in the string Strl, str2); _ —
array STUD(i 1], assuming that names are sorted }
alphabetically.
|class there are 20 students. Each student is _Find the outputof the following codes.
supposed to appear in three tests and two quizzes 1. maing)
throughout the year. Make anarray that stores the {
all these 20 students. Make five arrays char stri[]= {/H',’1’}; _
that stores marks of three subjects as well as scores char str2(] = {‘H’, ‘1', 0):

- ot two quizzes for a ~ students. aot the if (stromp (str1, str2) ==0)
printf ("\n The strings are equal");
else :
printt ("\n a are not
el
}
2. main()
_
har str1[]="Programming"; Ghar strij]= "Programming in C';
Char str2{] = "in C"; int i;
while (str[i] !=’\0’)
{
"\n strl = $s", str);
1£(1%2=-0)
printfi("sc", strli]);
itt;
hae erli=|'H' 'e'./1','1','0'); }
print ("\n str = %s", str);
faah
3. Main’)
{
char str[]="GGOD MORNING";
|224 Introduction to C Programming

7)
uw
ed,
O
[aa
Ww
x<
fr

char str [l= "Oxford University


£("“es", st 7 aie;
We

CHAPTER

Pointers

Takeaways
e Pointer Expressions 7 . e Pointer Arithmetic - ‘Null and Generic Pointers
e Pointers with Functions —s_—~ e Pointers with Arrays — © Pointers with Strings
© Function Pointers e Dynamic Memory Allocation

©
INDERSTANDING OTHREY
When the program has used the variables or data stored

COMPUTER’S MEM
in the stack, it can be discarded to enable the stack to be
used for other programs to store its data. We have already
Every computer has a primary memory. All data and read a little bit on the system stack in Functions when we
programs need to be placed in the primary memory for discussed Recursion. We will read more about them in the
execution. The primary memory or RAM (Random chapter on Stacks.
Access Memory which is a part of the primary memory)
Note g - Stackis sectionon ofof memory that is
is a collection of memory locations (often known as cells)
jutomatic variables within
and each location has a specific address. Each memory
location is capable of storing | byte of data (though new
computers are able to store 2 bytes of data but in this book Heap It is acontiguous block of memory that is available
we have been talking about locations storing 1 byte of for use by the program when the need arises. A fixed size
data). Therefore, a char type data needs just 1 memory heap is allocated by the system and is used by the system
location, an int type data needs 2 memory locations. in a random fashion.
Similarly, float and double type data need 4 and 8 The addresses of the memory locations in heap that are
memory locations, respectively. not currently allocated to the program for use are stored in
Generally, the computer has three areas of memory a free list. When the program requests a block of memory,
each of which is used for a specific task. These areas of the dynamic allocation technique (discussed at the end
memory include—stack, heap, and global memory. of this Chapter) takes a block from the heap and assigns
it to the program. When the program has finished using
Stack A fixed size of stack is allocated by the system
the block, it returns the memory block to the heap and the
and is filled as needed from the bottom to the top, one
location of the memory locations in that block is added to
element at a time. These elements can be removed from
the free list.
the top to the bottom by removing one element at a time,
Compared to heaps, a stack is faster but smaller and
i.e., the last element added to the stack is removed first.
expensive. When a program begins execution with
|226 | Introduction to C Programming

the main(), all variables declared within main() are printf ("\n The size of long integer is:
allocated space on the stack. Moreover, all the parametres oll, fslulvacyone (AKerate) Siiake))
))§

passed to the called function will be stored on the stack.


printf("\n The size of character is: fd",
Global memory The block of code that is the main() sizeof (char) ) ;

program (along with other functions in the program) is printf("\n The size of unsigned character
is: %d", sizeof (unsigned char) );
stored in the global memory. The memory in the global
printf("\n The size of signed character
area is allocated randomly to store the code of different is: %d", sizeof (signed char) );
functions in the program in such a way that one function is
not contiguous to another function. Besides, the function printf("\n The size of floating point
number is: %d", sizeof (float) );
code, all global variables declared in the program are
printf("\n The size of double number is:
stored in the global memory area.
$a", sizeof (double) );
return 0;
Other memory layouts C provides some more memory
areas such as text segment, BSS, and shared library
Output
segment. .
The size of short integer is: 2
e The text segment is used to store the machine The size of unsigned integer is: 2
instructions corresponding to the compiled program. The size of signed integer is: 2
The size of integer is: 2
This is generally a read-only memory segment.
The size of long integer is: 4
e BSS (Block Started by Symbol) is used to store un- The size of character is: 1
initialized global variables. The size of unsigned character is: 1
e Shared library segment contains the executable The size of signed character is: 1
The size of floating point number is: 4
image of shared libraries that are being used by the
The size of double number is: 8
program.
Consider the statement below.

7.2 INTRODUCTION TO POINTERS int x = 10;

When this statement executes, the compiler sets aside


Every variable in C language has a name and a value 2 bytes of memory to hold the value 10. It also sets up
associated with it. When a variable is declared, a specific a symbol table in which it adds the symbol x and the
block of memory within the computer is allocated to hold relative address in memory where those 2 bytes were set
the value of that variable. The size of the allocated block aside.
depends on the type of the data. Let us write a program Thus, every variable in C has a value and a memory
to find the size of the various data types on your system. location (commonly known as address) associated with it.
(Note the size of integer may vary from one system to Some texts use the term rvalue and /value for the value
another. In 32 bit systems, integer variable is allocated 4 and the address of the variable, respectively.
bytes while on 16 bit systems it is allocated 2 bytes). The rvalue appears on the right side of the assignment
statement (10 in the above statement) and cannot be used
7.1 Write a program to find the size of various data types
on the left side of the assignment statement. Therefore,
on your system.
writing 10 = k; is illegal. If we write,
#include <stdio.h>
int main() niialies og) War
{ 53S oe AND}.
printf ("\n The size of short integer is: Yo = 925i)
$d", sizeof (short int));
printf ("\n The size of unsigned integer Then in this code we have two integer variables x and
is: %d", sizeof (unsigned int)); y. Compiler reserves memory for integer variable x
printf("\n The size of signed integer is: and stores rvalue 10 in it. When we say y = x, then x is
$d", sizeof (signed int)); interpreted as its rvalue (since it is on the right-hand side
printf("\n The size of integer is: %d", of the assignment operator 69‘=’). Here x refers to the value
sizeof (int) );
Pointers | 227 |

stored at the memory location set aside for x, in this case going to run. To verify this, execute the following code
10. After this statement is executed, the rvalue of y is also and observe the result:
TOR #include <stdio.h>
You must be wondering why we are discussing main ()
addresses and lvalues? Actually pointers are nothing but {
int *pnum;
memory addresses. A pointer is a variable that contains
char *pch;
the memory location of another variable. Therefore, a
float *pfinum;
pointer is a variable that represents the location of a data double *pdnum;
item, such as a variable or an array element. Pointers are long *plnum;
frequently used in C language as they have a number of printf ("\n Size of integer pointer =
useful applications. These applications include: $a", sizeof (pnum) ) ;
printf("\n Size of character pointer =
© to pass information back and forth between a function $a", sizeof
(pch) ) ;
and its reference point jopaubiatess
(U ig) Sialeqey ope aeillejaje joloplinieare = Gyel,
e enable the programmers to return multiple data items sizeof (pfnum) ) ;

from a function via function arguments printf ("\n Size of double pointer = %d",
sizeof (pdnum) ) ;
e provide an alternate way to access individual
printi (Nn Siz eotmelongmpomniter—ssciue
elements of the array sizeof (plnum) ) ;
e to pass arrays and strings as function arguments }
e enable references to functions. So with pointers, the
Output
programmer can even pass functions as argument to
another function Size of integer pointer = 2
Size of character pointer = 2
e to create complex data structures such as trees, Size of float pointer = 2
linked list, linked stack, linked queue, and graphs Size of double pointer = 2
e for dynamic memory allocation of a variable Size of long pointer = 2

Now let us declare an integer pointer variable and start


7.3 DECLARING POINTER VARIABLES using it in our program code.
Slime Sie iL0)9
A pointer provides access to a variable by using the address HUME, SO\eIE
of that variable. A pointer variable is therefore a variable ptr = &Xx;
that stores the address of another variable. The general
In the above statement, ptr is the name of pointer
syntax of declaring pointer variables can be given as
variable. The ‘*’ informs
below.
Programming Tip: the compiler that ptr is a
dodeamr
Oem Demmaaney pointer variable and the int
oe can store only -
Here, data_type is the data specifies that it will store the
th address of a
type of the value that the pointer address of an integer variable.
will point to. For example, An integer pointer variable,
therefore, point to an integer
int *pnum; variable. In the last statement, ptr is assigned the address
char *pch; of x. The & operator retrieves the lvalue (address) of x, and
float *pfnum; copies that to the contents of the pointer ptr.
In each of the above statements, a pointer variable is Consider the memory cells given in Fig. 7.1.
declared to point to a variable of the specified data type.
Although all these pointers, pnum, pch, and pfnum
point to different data types but they will occupy the same
1000 1001 1002 1003 1004 1005 1006 10071008 1009
amount of space in memory. But how much space they
occupy will depend on the platform where the code is Figure 71 ‘Memory representatior
|228 | Introduction to C Programming

Now, since x is an integer variable, it will be allocated We can also assign values to variables using pointer
2 bytes. Assuming that the compiler assigns it memory variables and modify its value. The code given below
locations 1003 and 1004, we say the value of x = 10 and shows this.
the address ofx (written as &x) is equal to 1003, i.e., the #include <stdio.h>
starting address of x in the memory. When we write, ptr int main()
= &x, then ptr = 1003. {
int num, *pnum;
Note In C, pointers are not allowed to store pnum = &num;
ev memory addresses, but they can store *pnum.= 10;
only the addresses of variables of a given printf ("\n *pnum = %d", *pnum) ;
type. Therefore writing a statement like joxentreuenz(U
Web aaibinl = <xolll aebinn). 5
“ant *per = 1000; is absolutely illegal *pnum =" *pnum +" 1;
nc
// increments the value of num
printf ("\nAfter increment *pnum=%d", *pnum) ;
We can dereference a pointer, i.e., refer to the value of the
variable to which it points, by printf ("\n After increment
num = $d", num);
Programming Tip: using unary ‘*’ operator (also return 0;

The address of a known as indirection operator) }


memory location as in *ptr, i.e., *ptr = 10, since
10 is value of x. Therefore, * is Output
is a constant,
therefore, it cannot equivalent to writing value at *pnum = 10

be changed in the address .Look at the code below num? ="L0

program code. j which shows the use of pointer After increment *pnum = 11
variable. After increment num = 11
#include <stdio.h>
Now can you predict the output of the following code?
int main()

{ #include <stdio.h>
int num, *pnum; int main()

pnum = &num; {
printf ("\n Enter the number: "); int num, *pnuml, *pnum2;
scané ("td" , &num); pnuml = &num;
printf("\n The number that was entered *pnuml = 10;
is: *d", *pnum) ; pnum2 = pnuml;
printf ("\n The address of number in printf("\n Value of num using all three
memory is: %p", &num); variables (num, *pnuml, *pnum2) = %d %d
mecuUrne OF sa", num, *pnuml, *pnum2);
} printf("\n Address of num using all three
variables (&num, pnuml, pnum2) = %x %x
Output
$x", num, pnuml, pnum2);
Enter the number: 10
return 0;
The number that was entered is: 10
The address of number in memory is: FFDC
}
While the first printf statement will print the value
Notes %p control string prints the argument as a of num, the second printf statement will print address
memory address in hexadecimal form. su of num. These are just three different ways to refer to the
prints memory address in decimal form. value and address of the same variable.

Programming Tip:
‘Can you tell what will be the Any number of pointers can point to es
value of *(&num)? Yes it is same address.
A pointer variable
equivalent to num. The indirection
cannot be assigned
and the address operators are
value of the variable The address of a variable is the address of the first byte
| inverse of each other, so when
to which it points. occupied by that variable. Basically, address of the variable
/ combined in an expression, they
cancel each other. is the relative location of the variable with respect to the
Pointers | 229 |

program’s memory space. We cannot change the address of then the following statements are valid:
a variable, we can only use them. Although the address of a
Inte numd=2 num2= 3, Ssum=07, mul=O; div=1;
Programming Tip: _ variable cannot be changed, the sHOe, “Heyercll, “ENED
It is an error to variable’s address may change
ptrl = &numl;
assign address _ during different program runs,
ptr2 = &num2;
of a variable to _ 1.e., if you try to print the address
another variable of num today, it may print 4010.
SUne=) *DErIaeaspeEn2;
of the same type. Next time when you run the TMU =erSUm! esto rae;
The variable to _ program, it may print the address * DOIS2 ete
which the adddress- as FA12. _ div = 9 + *ptrl1/*ptr2 - 30;
is being assigned One thing to remember always
must be declared as || 1s that the data type of the pointer In C, the programmer may add or
Programming
Tip:
_a pointer variable. | variable and the variable whose subtract integers from pointers.
A pointer variable
address it will store must both We can also subtract one pointer
that is declared
be of the same type. Therefore, the following code is not but not initialized
from the other. We can also use
valid. contains garbage © short hand operators with the
Thee oe SS alie)s value. Hence, such pointer variables as we use with
EIMORE 3 SS BS OF a pointer variable other variables.
int *px; must not be used C also allows to compare
float *py; before itis assigned pointers by using relational
px = &y; //INVALID any variables =| operators in the expressions. For
py = &x;//INVALID address example, p1 > p2, pl == p2, and
Also note that it is not necessary that the pointer variable pl! = p2 are all valid inc.
will point to the same variable throughout the program. It When using pointers, unary increment (++) and decre-
can point to any variable as long as the data type of the ment (--) operators have greater precedence than the
pointer variable is same as that of the variable it points to. dereference operator (*). But both these operators have
The following code illustrates this concept. a special behaviour when used as suffix. In that case the
#include <stdio.h> expression is evaluated with the value it had before being
main () increased. Therefore, the expression
{ ADELE
Imta=3)t b=5i;
int *pnum; is equivalent to *(ptr++) as ++ has greater operator
pnum = &a; precedence than *. Therefore, the expression will increase
jepeeibahere
(CUA ay gl $a", *pnum) ;
the value of ptr so that it now points to the next element.
pnum = &b;
This means the statement *ptr++ does not perform the
joneatianene (Day joy = Axel, “jorelbiin) 5
return 0;
intended task. Therefore, to increment the value of
} the variable whose address is stored in ptr, you should
write
Output
(*ptr)
++
ci
lo = § Now, let us consider another C statement

Notes Using an un-initialized pointer can cause Int numi=2, mum2=3)-

unpredictable results. int *p = &numl, *q=&num2;


Oamap &) eRe y

What will *p++ = *q++ do? Because ++ has a higher

POINTER EXPRESSIONS AND


precedence than *, both p and

"POINTER ARITHMETIC.
74 Programming Tip:
It is an error to g are increased, but because the
subtract two increment operators (++) are
Like other variables, pointer variables can also be used in pointer variables. _ used as postfix and not prefix, the
expressions. For example, if ptr1 and ptr2 are pointers, SABLE
AER EEO SEY aad value assigned to *p is *q before
|230 | Introduction to C Programming

both p and q are increased. Then both are increased. So the // pnuml = &numil;

statement is equivalent to writing: *psum = *pnuml + *pnum2;


PHIneh(! \nste ei" e2 Ue *pnuml,
ra) = LACS [F

*pnum2, *psum) ;
++P; +4;
return 0;
Let us now summarize the rules for pointer operations: }
e A pointer variable can be assigned the address of Output
another variable (of the same type).
Enter the two numbers: 2.5 3.4
e A pointer variable can be assigned the value of 2 Ses 4i= 5.90 i
another pointer variable (of the same type).
7.4 Write a program to calculate the area of a circle.
e A pointer variable can be initialized with a NULL
#include <stdio.h> :
(or 0) value.
#include <conio.h>
e Prefix or postfix increment and decrement operators int main()
can be applied on a pointer variable. {
e An integer value can be added or subtracted from a double radius, area = 0.0; .
pointer variable. double *pradius = &radius, *parea = &area;

e A pointer variable can be compared with another printf ("\n Enter the radius of the circle: ");

pointer variable of the same type using relational scanf ("%1f", pradius);

operators. *parea = 3.14 * (*pradius) * (*pradius) ;


printf ("\n The area of the circle with
e A pointer variable cannot be multiplied by a constant.
HAdWUS St. 21h = 3.226" *pradius), *pacea)/;
e A pointer variable cannot be added to another pointer return 0;
variable.
}
Output
AMS USING POINTERS Enter the radius of the circle: 7.0
The area of the circle with radius 7.0 =
7.2 Write a program to print “Hello World’ using pointers. 153.83
#include <stdio.h>
int main() 7.5 Write a program to convert a floating point number
{ into an integer.
char *ch = "Hello World"; #include <stdio.h>
jShenkiagens (Were) lal) 2 int main()
return 0;
{
} float fnum, *pfnum = &fnum;
int num, *pnum = &nun;
Output
printf ("\n Enter the floating point no.: ");
Hello World
scant ("%S£", &fnum) ;
7.3 Write a program to add two floating point numbers. *pnum = (int) *pfnum;
The result should contain only two digits after the printf ("\n The integer equivalent of %f =
decimal. Oly *pfnum, *pnum);
#include <stdio.h> return 0;
int main() }
{ Output
float nuni, num2 [Link] = 0).0);
Enter tehe, floating pointe nos-er4
float *pnum1l = &numl, *pnum2 = &num2,
The integer equivalent of 3.4000 = 3
*psum = &sum;
printf ("\n Enter the two numbers: ");
7.6 Write a program to find the biggest of three numbers.
#include <stdio.h>
Scant("si sf", pnumil, pnum2)
int main()
Pointers | 231 |

#include <stdio.h>
int num1l, num2, num3; #include <conio.h>
int *pnuml = &num1, *ponum2 = &num2,
int main()
*pnum3= &num3;

printf ("\n Enter the first number:


{
%)3
chanach)y atpch =_cchr
scanf ("%da", pnum1) ;
ClESer (r-
printf("\n Enter the second number: ") ;
scant ("td", pnum2); printf("\n Enter any character: ");

printf ("\n Enter the third number: excehabe (URE, jorelal))5


ny
scanf("Sd", pnum3) ; nine ((rajeYelal SWAY tet kujeyel aes 74" ))
if (*pnuml > *pnum2 && *pfhium1
> *pnum3) printf ("\n Upper case char was entered");
printf ("\n %dis the largest number", *pnum1); ale ((3jeyelah Sete {S403 whoyelarea’
v2" )
if (*pnum2 > *pnum1 && *pnum2 > *pnum3) printf ("\n Lower case char was entered") ;
printf ("\n%dis
the largest number", *pnum2); else if (*pch>='0' && *pch<=’9")
else printf ("\n You entered a number") ;
printf ("\n%dis the largest number", *pnum3) ; getch();
return 0;
return 0;
} }
Output Output
Enter the first number: 5
Enter any character: 7
Enter the second number: 7
You entered a number
Enter the third number: 3
7
is the largest number 79 Write a program using pointer variables to read
a character until * is entered. If the character is in
7.7 Write a program to print a character. Also print its
upper case, print it in lower case and vice versa. Also
ASCII value and rewrite the character in upper case.
count the number of upper and lower case characters
#include <stdio.h>
entered.
#include <conio.h>
#include <stdio.h>
int main ()
#include <conio.h>
{
shove lal, “oyelal = txelaly int main()

eulizetsyera(())o3 {
the character: "); inee Gla, “sjo%elol =) fxelaic
printf("\n Enter
Scank("sceN, &ch); int upper = 0, lower = 0;
printf ("\n The char entered is: %c", *pch); elms
er O)i
printf ("\nASCII
value of the char is: %d", *pch); printf ("\n Enter the character: ");
printf ("\n The char inupper case is: sc", *pch - 32) ; scanfi("%c", pch);
getch() ; while (*pch != ‘*”)
return 0; {
} ae (goyelel Ses YAY && *pch <= SWAY)
{
Output Aolelay tk Be
Enter the character: Zz upper++;
The char entered is: Zz }
ASCII value of the char is: 22. ise (josloy Se Ney && *pch <= ‘z’)
The char in upper case is: Z {
wolel@ =) e245
7.8 Write a program which takes an input from the user lower++;
and then checks whether it is a number or a character. }
If it is a character, determine whether it is in upper joreslaee (USSU Ssjoyela))A
case or lower case. fflush (stdin) ;
|232 | Introduction to C Programming

printf("\n Enter the character: "); int m, *pm = &m;


seein (MeN, joelal)) Sime. ia, yore! <a sale
} int sum = 0, *psum = &sum;
printf ("\n Total number of upper case float avg, *pavg = &avg;
characters = 4d", upper); printf ("\n Enter the starting and ending
printf ("\n Total number of lower case limit of the numbers to be summed:") ;
characters = %d", lower) ; scanf ("sd sd",
pm, pn) ;
getch () ; range =n-m™ ;
while(*pm <= *pn)
return 0;
} {
*psum = *psum + *pm;
Output *pm = *pm + 1;
Enter the character: A }
aR printf("\n Sum of numbers = %d , *psum);
character: b *pavg = — *
*psum / range; .
Enter the
B printf ("\n Average of numbers = %f",

Enter the character: c *pavg);


C return 0; :

Enter the character: * }


Total number of upper case characters = 1 Output
Total number of lower case characters = 2
Enter the starting and ending limit of the
7.10 Write a program to test whether a number is positive, numbers to be summed: 0 10
negative, or equal to zero. Sum of numbers = 55
#include <stdio.h> Average of numbers = 5.5
int main ()
7.12 Write a program to print all even numbers from m-n.
#include <stdio.h>
eg haea es #include <conio.h>
printf("\n
7 "
Enter any number: .
")
W
;. emai)
Scank (izdues pnum)s; {
if (*pnum>0) int m, *pme= &m;
printf ("\n The number is positive"); int n, *pn = &n;

else printf("\n Enter the starting and ending


{ limit of the numbers: ");
if (*pnum<0) scanf("%d $d", pm, pn);
printf ("\n The number is negative") ; while(*pm <= *pn)
else {
printf("\n The number is equal to if (*pm %2 == 0)
Zero") ; printf("\n %d is even", *pm) ;
} else
return 0; joreaiqhere (War Excl auc! Gretel, Eso)
} (*pm) ++;

}
Output return 0;
Enter any number: -1 }
The number is negative
Output
7.11 Write a program to display the sum and average of miter the starting sand endiuar liq elor iene
numbers from m to n. sumbers ghOn
#include <stdio.h> 0 is even
int main() 2 is even
{ 4 is even
int num, *pnum = &num, range; 6 is even
Pointers | 233 |

8 is even pointer value that does not point anywhere. This means
10 is even
that a NULL pointer does not point to any valid memory
7.13 Write a program to read numbers until —1 is entered. address.
Also display whether the number is prime or To declare a null pointer you may use the predefined
composite. constant NULL, which is defined in several standard header
#include <stdio.h> files including <stdio.h>, <stdlib.h>, and <string.h>.
int main() After including any of these files in your program just write,
{ nae, esojcse = INULIN
int num, *pnum = &num;
inte Llagr— 20) P
You can always check whether a given pointer variable
printf ("\n ***** ENTER -1 TO EXIT stores address of some variable or contains a NULL by
kk KR KN) ; writing,
printf ("\n Enter any number: "); if (ptr == NULL)
scanf ("%d", pnum);
{
while(*pnum != -1), Statement block;
{ }
alse (yore ea il)
printf ("\n %d is neither prime nor
You may also initialize a pointer as a null pointer by
composite", *pnum) ; using a constant 0, as shown below.
else if (*pnum == 2) sige, [Oe
printf ("\n %d is prime", *pnum) ;
ptr = 0;
else
{ This is a valid statement in
for(i=2; i<*pnum/2; i++) C, as even NULL which is a
{ preprocessor macro typically has
ie(spmum/ ae=—, 10) the value, or replacement text, 0.
iplleve; mils
to dereference a
Null pointer. _ However, to avoid ambiguity it
} is always better to use NULL to
LTi(flag == 0)
declare a null pointer.
printf ("\n %*d is prime", *pnum) ;
else A function that returns pointer values can return a null
printf ("\n %d is composite", *pnum); pointer when it is unable to perform its task.
} Null pointers are used in situations where one of the
printf ("\n Enter any number: "); pointers in the program points to different locations at
scanf ("$d", pnum) ; different times. In such situations it is always better to set
} it toa Null pointer when it doesn’t point anywhere valid,
return 0;
and to test to see if it’s a Null pointer before using it.
}
Arun time error is generated if you try to
Output
dereference a Null pointer.
KkKKKK ENTER -1 TO EXIT KKKKKK

Enter any number: 3


3 is prime
Enter any number:
I is neither prime
1
nor composite
7.6 GENERIC POINTERS
Enter any number: -1 A generic pointer is a pointer
Programming Tip: _
variable that has void as its data
Acompilererror
will be generated if type. The void pointer, or the
7.5 NULLPOINTERS _ you assign a pointer generic pointer, is a special type
We have seen that the pointer variable is a pointer to some of one type toa of pointer that can be used to point
other variable of the same data type. However, in some pointer of another _ to variables of any data type. It
cases we may prefer to have null pointer which is a special type without a cast is declared like a normal pointer
234 | Introduction to C Programming

variable but using the void keyword as the pointer’s data Pointers provide a mechanism to modify data declared
type. For example, in one function using code written in another function. In
ViOnGle xp EG.
other words: If data is declared in funcl1 () and we want to
write code in func2 () that modifies the data in funcl(),
In C, since you cannot have a variable of type void, the then we must pass the addresses of the variables we want
void pointer will therefore not to change.
Programming Tip:
point to any data and thus, The calling function sends the
_Apointer variable of Programming Tip:
cannot be dereferenced. You addresses of the variables and
_ type void * cannot While using pointers
_ be dereferenced. _ heed to type cast a void pointer the called function must declare
to pass arguments
/ (generic pointer) to another kind those incoming’ arguments as
to a function, the
of pointer before using it. pointers. In order to modify the
calling func ion
Generic pointers are often used when you want a must pass addresses variables sent by the caller, the
pointer to point to data of different types at different times. of the va riables called function must dereference
For example, look at the code given below. as arguments and the pointers that were passed to
Here is some code using a void pointer: the called function it. Thus, passing pointers to a
#include <stdio.h>
_ must dereference function avoids [Link] of
int main()
the arguments to copying data from one function
_ use them in the to another. Hence, to use pointers
{
nia: S=IlO)¢
function body for for passing arguments to a
seewsedeseonesseawimnnsodicsS
processing
Giiene Gin = WAYS function, the programmer must
void *gp; do the following:
gp = &X; e Declare the function parametres as pointers.
printf ("\n Generic pointer points to the
integer value = %d", *(int*)gp) ;
e Use the dereferenced pointers in the function body.
(joy =) (elaip e Pass the addresses as the actual argument when the
printf("\n Generic pointer now points to function is called.
the character %c", *(char*)
gp) ;
returns 0); Note, _ It is an error to return a pointer
to a local
} re _ variable in the called function, because
_when the function terminates , its
Output
Generic pointer points to the integer value
=Pal'®
Generic pointer now points to the character

PROGRAMMING EXAMPLES
=A

It is always recommended to avoid using void pointers


unless absolutely necessary, as they effectively allow you Let us write some programs that pass pointer variables as
to avoid type checking. parametres to functions.

7.14 Write a program to add two integers using functions

NG ARGUMENTS TO. #include


#include
<stdio.h>
<conio.h>
void sum (int *a, int *b, int *t);

We have already seen call by value method of passing int main ()

parametres to a function. Using call by value method, it is {


impossible to modify the actual parametres in the call when Ines numa num2ytOba ls

you pass them to a function. Furthermore, the incoming printf("\n Enter the first number: ");

arguments to a function are treated as local variables in the scanf ("$d", &numl) ;
function and those local variables get a copy of the values printf ("\n Enter the second number: ") ;
passed from their caller. scanf ("%d", &num2) ;
Pointers al 235 |

sum(&numl, &num2, &total) ; void read(float *b, float *h);

printf ("\n Total = %d", total) ; void calculate area (float *b, float *h,
getch() ; float *a);

return 0; int main()

} {
float base, height, area;
void sum (int *a, int *b, int *t)
read (&base, &height);
{
*t = *a + *b; calculate _area(&base,
&height, &area) ;
printf ("\n Area of the triangle with base
}
s£andheight tf =%f", base, height, area) ;
»
Output Iejevham, (0)p

Enter the first number: 2 }


Enter the first number: 3 void read(float *b, float *h)

Totale=_5 {
printf("\n Enter the base of the
7.15 Write a program, using functions, to find the biggest triangles "i;
of three integers. scant Wiceiy, tb)
#include <stdio.h> printf ("\n Enter the height of the
int greater (int *a, int *b, int *c, int *large); triangle: ");
int main () yee (Wael. Ts)5
{ }
int num1, num2, num3, large; void calculate area (float *b, float *h,
printf ("\n Enter the first number: "); float *a)
scanf ("%d", &numl1);
printf ("\n Enter the second number: ") ; weal = O58 12 (lo) 2 (cad)yp
scanf("%$d", &num2) ; }
printf ("\n Enter the third number: ");
Output
scanf ("$d", &num3) ;
greater (&num1, &num2, &num3, &large) ; Enter the base of the triangle: 10
Enter the height of the triangle: 5
return 0;
Area of the triangle with base 10.0 and
height 5.0 = 25.00
int greater
(int *a, int *b,
int *c, int *large) Hence, we see that functions usually return only one
value. Pointers can be used to return more than one
if(*a > *b && *a > *c) value to the calling function. This is done by allowing
*large = *a; the arguments to be passed by address which enables the
if (*b > *a && *b > *c) function to alter the values pointed to and thus helps to
*large = *b; return more than one value.
else
*large = *¢;
printf ("\n Largest number = %d", *large) ;

The concept of array is very much bound to the one of


} pointer. An array occupies consecutive memory locations.
Output Consider Fig. 7.2. For example, if we have an array
Enter the first number: 1 declared as,
Enter the second number: 7 int anrtl, =lee2na3 a4rebie
Enter the third number: 9 then in memory it would be stored as shown in Fig. 7.2.
Largest number = 9 Array notation is a form of pointer notation. The name
of the array is the starting address of the array in memory.
7.16 Write a program to calculate the area of a triangle.
It is also known as the base address. In other words, base
#include <stdio.h>
|236 | Introduction to C Programming

address is the address of the first element in the array or - x++, adds 1 to the value of x. But
Programming Tip:
the address of arr [0] . Now let us use a pointer variable An error sc ptr is a pointer variable, so when
as given in the statement below. we write ptr + i, then adding i
AME,“ GOLENE gives a pointer that points i
oles = Sebae Oils change the address _ elements further along an array
of the array. | than the original pointer.
Since ++ptr and ptr++ are both
equivalent to ptr + 1, incrementing a pointer using the
unary ++ operator, increments the address. it stores by the
arr(O] arr[1] arr[2] arr[3] arr[4]
amount given by sizeof (type) where type is the data
1000 1002 1004 1006 1008
type of the variable it points to (i.e., 2 for an integer). For
Figure 7.2 ‘Memory representation of arr[] example, consider Fig. 7.4.
If ptr originally points to arr[2], then ptr++ will
Here, ptr is made to point to the first element of the make it to point to the next element, i.e., arr [3] . This is
array. Execute the code given shown in Fig. 7.4.
below and observe the output
gramming Tip:
‘name ofthe — which will make the concept
array is actually a clear to you.
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
pointer that points — main ()
arr[0] arr[1] arr[2] arr[3] arr[4]
tothe first element _ {
imntiarri}={l,2,3,475};
printf ("\n Address of
array = Sp sp sp", arr,
Figure 7.4 The pointer (ptr)
| pointing to the: fourth
&arr[0], &arr);
_. |element ofthe array. :
}
Similarly, writing ptr = &arr[2], makes ptr to point
Had this been a character array, every byte in the
to the third element of the array, that has index 2. Figure
memory would have been used to store an individual
7.3 shows ptr pointing to the third element of the array.
character. ptr++ would then add only | byte to the address
Of Drie
When using pointers, an expression like arr[i] is
equivalent to writing * (arr4+1) . If arr is the array name,
arr[O] arr(1] arr[2] arr[3] ey then the compiler implicitly takes
arr = ég&arr[0]

To print the value of the third


Figure 7.3 Pointer pointing to the third ert of the
Programming
Tip: element of the array, we can
array — :
Whenanarray straightaway use the expression
is passed Pu(eairatar2)ae Note that arr[i] =
If pointer variable ptr holds the address of the first function, we are” *(arr + 1)
element in the array, then the address of successive actually passing Many beginners get confused
elements can be calculated by writing ptr++. a pointer to the by thinking of array name as a
function. Therefore, pointer. For example, while we
int *ptr = Sarr [0] §
’ _inthe function can write
DERE,
declaration you
printf("\n The value of the second element
must declare a per = arr, f/ .pen =
of the array is %d", *ptr);
pointer to rec &arr [0]
The printf () function will print the value 2 because We cannot write
after being incremented ptr points to the next location.
Eligng KV joenae
One point to note here is that if x is an integer variable, then
Pointers | 237 |

This is because while ptr is a variable, arr is a is 2 because there are two elements between ptr1 and
constant. The location at which the first element of arr ptr2 in the array arr. Both the pointers must point to the
will be stored cannot be changed once arr[] has been same array or one past the end of the array, otherwise this
declared. Therefore, an array name is often known to be a behaviour cannot be defined.
constant pointer. Moreover, C also allows pointer variables to be com-
To summarize, the name of an array is equivalent to the pared with each other. Obviously, if two pointers are
address of its first element, as a pointer is equivalent to the equal, then they point to the same location in the array.
address of the element that it points to. Therefore, arrays However, if one pointer is less than the other, it means that
and pointers use the same concept. the pointer points to some element nearer to the beginning
of the array. Like with other variables, relational operators
arr(il, ifarr], *(arrti), “(arn givesthe (>, >, =, etc.) can also be applied to pointer variables.
same value. .
7.17 Write a program to display an array of given
Look at the following code and understand the result of numbers.
#include <stdio.h>
executing them:
main ()
main ()
{
int “arr [l= (,2;3,475,6,7
7 oN:
int arya;
2.0, 4,5;
shale wyejesedl, =/oee® 6
sige, oer, als
ptr=&arr [2]; (REA = eka
jee ss Cewee |[s}) 9
weg =] Saks
(DET SOF
while (ptrl<=ptr2)

=i(Gojeeaal)y" as as {
jonartialese (USI, esOEneIL))6
joneakiavena (H\iay pweseehye “alteye M1)p
je ae F
for (1=0;1<5;i++)
jopeabanere
(UN Vexell a(eueieesal
|)5

} }
Output Output

Array is: hoa ae Oe 273


aS 6 71 89

In C we can add or subtract an integer from a pointer


Netey anAn obj ect is anamed region of storage; .
to get a new pointer, pointing somewhere other than the lvalue i isan se hor referr g to
original position. C also permits addition and subtraction
of two pointer variables. For example, look at the code
given below. Table 7.1 summarizes pointer arithmetic.
main () 7.18 Write a program to read and display an array of n
{ integers.
int war, [iS {1 7253747 57:67 7785 o}7 #include <stdio.h>
eae, Ejeet “solare
ay int main ()
Denil = "arr,
{
ptr2 = ptr+2;
Sige 41, tay
PLIntE-(_sa;-ptr2-—ptr.) +
imi vases io ys parnyse= sada;
}
printf ("\n Enter the number of elements: ");
Output Scant (Usd cin)i
2 printf ("\n Enter the elements: ");

In the code, ptr1 and ptr2 are pointers pointing to the fon (Ge=0)-ers< 1. i++)

elements of the same array. We may subtract two pointers scanf ("$d", parr+i) ;
as long as they point to the same array. Here, the output printf ("\n The elements entered are: ");
|238 |_Introduction to C Programming

for (i=0; 2° < nj; i++) printf("\n The sum is: %d", *psum) ;
printf ("\t %d", *(parr+i)); printf ("\n The mean is: %f£", *pmean) ;
return 0; return 0;

} }
Output Output
Enter the number of elements: 5
Enter the number of elements: 5
Enter the number: 1
Enter the elements: 12 3 4 5
Enter the number: 2
The elements entered are: 12345 Enter the number: 3 t

7.19 Write a program to find mean of n numbers using Enter the number: 4
Enter the number: 5
arrays.
#include <stdio.h> The numbers you entered are:

int main() D2) 3745


The sum is: 15
{
shige, aby tal, chara fX0)l| , Soin) =0).e The mean is: 3.00

int *pn = &n, *parr = arr, *psum = &sum; 7.20 Write a program to find the largest of n numbers
float mean = 0.0, *pmean = &mean; using arrays. Also display its position.
printf("\n Enter the number of elements #include <stdio.h>
aligl ela: Bhaceyyg UW) int main()
scanf ("%d", pn); {
fom = 0; i) < *pn; i++) shite, aly, gal, Evers ||A0)|| ,, enact ae Sibililily joes; = 0p
{ int *pni= Gn, “pare = ane, ~plerge:=
printf ("\n Enter the number: "); &large, *ppos = &pos;
scanf("$d", (parr + i)); eliesex());
} printf ("\n Enter the number of elements
for(i=0; i < *pn; i++) atial Nelavs) ~hagehiag W))
*psum += *(arr + i); scant ("$d", pn);
*pmean = *psum / *pn; £orm(Gs— Oliess <ax pny tt)
printf("\n The numbers you entered are: "); ‘
for (i=07 2-< *pn; i++) printf ("\n Enter the number: ");
printl Csdwon*larre+ 1); scanf ("%Sd", parr+i);

Rear leginters must


t Be of int ptr, *ptr2; ify
we write *ptr1= *ptr?, then both ‘he pointers
same type point to the same location
Addition of an integer int i, *ptr; If we write, ptr +i, then ptr will point to ith object
after its initial position
Subtraction of an int i, *ptr; If we write, ptr —i, then ptr will point to ith object
integer before its initial position
Comparison of Pointers should point to Jint *ptr1, *ptr2; If we write, ptr1 < ptr2, then it would return 1
pointers elements of the same if ptr1 points to an element that is near to the
array beginning of the array, i.e., the element comes
before the element pointed by ptr2
Subtraction of Pointers should point to jint *ptr1, *ptr2; If we write ptr1 — ptr2, then it returns the number
pointers elements of the same of elements between ptr1 and ptr2 (provided ptr1
array > ptr2)
Addition of pointers is illegal in C. Therefore, ptr1+ptr2 is not valid in C.
Pointers | 239 |

} expression, array_name + index. To find out how many


for(i=0; i < *pn; i++) elements are there in the array, you must pass the size of
{ the array as another parameter to the function. So for a
if(*(parr+i) > *plarge)
function that accepts an array as parameter, the declaration
{ should be as follows:
*plarge = * (parr+i);
mbIMe (Sue elae|ill, slale tal)p OR
*ppos = i;
} rebuaKeN(Glighe ttchicia—- atighe jay)«

} Look at the following program which illustrates the use


printf ("\n The numbers you entered are:
of pointers to pass an array to a function.
HN 4
£O tia Of ee pin) 7.21 Write a program to read and print an array of n
print£ ("sd ", * (parr+i)); numbers, then find out the smallest number. Also
printf ("\n The largest of these numbers print the position of the smallest number.
is: %d", *plarge) ; #include <stdio.h>
joneulgiene (May Gdares position of the largest void read_array(int *arr, int n);
number in the array is: %d", *ppos) ; void print array (int *arr, int n);

raebhargt (0)F void find_small(int *arr, int n, int *small,


int *pos);
}
int main()
Output {
int num[10],n, small, pos;
Enter the number of elements: 5
printf ("\n Enter the size of the array:
") ;
Enter the number: 1
Enter the number: 2 scanf ("%d", &n);
Enter the number: 3
read_array
(num, n) ;
print_array
(num, n)
Enter the number: 4
find small(num, n, &small, &pos) ;
Enter the number: 5
printf ("\n The smallest number in the
The numbers you entered are:
array is at position %d", small pos);
Ec ee a
return 0;
The largest of these numbers is: 5
The position of the largest number in the }
VGld= read vanray, (ini ater Lilies 10)
array is: 4
{
elirates well=
printf ("\n Enter the array elements: ");
for (i1=0;i<n;i++)
scant ("Sd", sarri[a])-;

An array can be passed to a function using pointers. For }


WKOELCl, yonealinye cwareey/(igle, WEWaig sale. ta)
this, a function that expects an array can declare the formal
{
parameter in either of the two following ways: Soho, yah

func(int arr[]);
OR func(int *arr); printf("\n The array elements are: ");
for (1=0;i<n;i++)
When we pass the name of the array to a function, joneatiqnere (I\e Sel, aera [atl yg
the address of the zeroth element of the array is copied }
to the local pointer variable in the function. Observe void find ismelii(ante *ann, inten, inte somes,

the difference; unlike ordinary variables the values of int *pos)

the elements are not copied, only the address of the first
for (i=0;i<n;1i++)
element is copied.
When a formal parameter is declared in a function
{
1f£ (* (arr+i])< *small)
header as an array, it is interpreted as a pointer to a
{
variable and not as an array. With this pointer variable *small = *(arr+i);
you can access all the elements of the array by using the *DOS =a,
|240 | Introduction to C Programming

}
Output
Enter the size of the array: 5
Enter the array elements: 123 45 oe : ane
The array elements: are: iL A ey aE 1S
The smallest number in the array is = 1 at
position 0

It is not necessary to pass the whole array to a function.


We can also pass a part of the array known as a sub-array. A
pointer to a sub-array is also an array pointer. For example,
if we want to send the array starting from the third element
then we can pass the address of the third element and the
size of the sub-array, i.e., if there were 10 elements in the
0:;1i<5; i
array, and we want to pass the array starting from the third ££ ("\n $d”, are);
element, then only eight elements would be a part of the
sub-array. So the function call can be written as
func (&arr[2],
8); a ut-iegees Array and pointer

Therefore, the following statements are valid in C:


7. 10 DIFFERENCE BETWEEN ARRAY — int arri (J={172,3,4,5};

NAME AND POINTER © : HME, VAoVeTeIL,. “Lois f


joreaedl easels
When memory is allocated for an array, its base address is DES2Z =p erds;
fixed and it cannot be changed during program execution.
In other words, an array name is an address constant. When we write ptr2 = ptrl, we are not copying the
Therefore, its value cannot be changed. To ensure that data pointed to. Rather, we are just making two pointers
the address of the array does not get changed even point to the same location. This is shown in Fig. 7.6.
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.
However, you may declare a pointer variable of
appropriate type that points to the first element of the array 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
and use it as lvalue. Figure 7.5 shows two sets of codes. arr[0O] arr[1] arr[2] arr[3] arr[4]
The first code gives an error as the array name is being
used as an lvalue for the ++ operator. The second code
shows the correct way of doing the same thing.
Second thing to remember is that an array cannot be area) Pointers pointing to the same location
assigned to another array. This is because an array name
cannot be used as the lvalue. Third point of difference lies with the return value of
int avril []={1,25354,5); the address operator. The address operator returns the
int arr2[5]; address of the operand. But when an address operator is
arr2 =arrl1; // ERROR applied to an array name, it gives the same value as the
array reference without the operator. Therefore, arr and
But, one pointer variable can be assigned to another
&arr gives the same value. However, this is not true for a
pointer variable of the same type.
pointer variable.
Pointers | 241 |

Last but not the least, the sizeof operator when applied pstr = str;
to an array name returns the number of bytes allocated for jovealgatere (WNiay MBavey Yenereatinyey alisjo Wh)c

the array. But in case of a pointer variable, the sizeof while(*pstr != ‘\0’)

operator returns the number of bytes used for the pointer {


joreiiaidie
(“SY i, tee) 5
variable (machine dependent). Look at the following code
pstr++;
which illustrates this concept.
main () }
return 0;
{
intsarnci)=(152,3,4,;5}; }
gale, “Esjolenar Output
ptr=arr;
The string is: Hello
printf("\n Size of array = %d", sizeof (arr) );
printf ("\n Size of pointer variable = %d", In this program, we declare a character pointer *pstr
sizeof (ptr) ); to show the string on the screen. We then point the pointer
} ‘
pstr at str. Then we print each character of the string in
the while loop. Instead of using the while loop, we could
Output (On Turbo C) have straightaway used the function puts () as shown.
Size of array = 10
puts (pstr) ;
Size of pointer variable = 2
The function prototype for puts () is as follows:

7.11 POINTERS AND STRINGS


int puts(const char *s);

Here the const modifier is used to assure the user that


In C, strings are treated as arrays of characters that are
the function will not modify the contents pointed to by the
terminated with a binary zero character (written as ‘\0’).
source pointer. The address of the string is passed to the
Consider, for example,
function as an argument.
char str[10]; The parameter passed to puts() is a pointer which is
stel0] = YH” = nothing but the address to which it points to, or, simply, an
Sere| fall) Sp address. Thus by writing puts (str) ; means passing the
See (Al) S ee address of str[0].
Heels = “NOs Similarly, when we write puts (pstr) ; we are passing
the same address, because we have written pstr = str;
C language provides two alternate ways of declaring and
Now consider the code which displays a string using
initializing a string. First, you may write:
pointers.
char etr[10) saad “Homebase, 00
aghyh #include <stdio.h>

But this also takes more typing than is convenient. So, C int main (void)

permits: {
char *str = "Welcome to the world of
Gineie Sere (TO) SS Mel
programming" ;
When the double quotes are used, null character char *pstr; // pointer to character
(*\0") is automatically appended to the end of the string. josivie = Cie,
When a string is declared like this, the compiler sets while (*pstr! ='\0’)
aside a contiguous block of memory 10 bytes long to {
hold characters and initializes its first four characters joreiiaiers (Weel, ejosiens) 4

Hi!\0. pstr++;

Now, consider the following program that prints a text: }


#include <stdio.h> ig=Seichaial (0)y

int main() }
{ Output
Givens sieve(fj) = “rill,
Welcome to the world of programming
Chara pstL;
|242 | Introduction to C Programming

PSELsthy
In the above code, pstr is assigned the address of the
string, str. The pointer pstr can then be used to point to }
jovesimnens (MMe, Giavey hegealatey alsie "))5
successive characters until the null character is reached.
jowiers) (Gere) 5
Consider another program which reads a string and
printf ("\n Number of characters
=%d", chars);
then scans each character to count the number of upper
printf("\n Number of lines = %d", lines) ;
and lower case characters entered.
#include <stdio.h> printf ("\n Number of words = %d", words) ;
int main() pacienbe
gel Or
{ }
char str[100], *pstr;
int upper = 0, lower = 0;
Output
printf("\n Enter the string: "); Enter the string: How are you
gets(str) ; Number of characters = 11
pstrv= str; Number of lines = 1
Number of words = 3
while(*pstr != ‘\0’)
7.23 Write a program to copy a character array in another
{ character array. ‘
nae (foie ens MUAY setsa egovarian, WA)
upper++; #include <stdio.h>
elisesi i (Gpsta == Sal ee *pstiai<= 2977) #include <conio.h>
lower++; int main ()
pstr++; {
} char str[100],
copy _str[100];
printf ("\n Total number of upper case char *pstr, *pcopy str;
characters = %d", upper) ; int 1 = 0;
printf("\n Total number of lower case ellbacyena
Glee

characters = %d", lower) ; jORNEIS ES hetae


iaeeuaial (8p pCcoOpy str = Copy str;
Dinter (Nn Enter the string am ye
}
gets (str) ;
Output Vober (ejeyeicie We S\ol ))

Enter the string: How are you {


*DCOpy StL = *PStis;
Total number of upper case characters = 1
pstr++, pcopy str++;
Total number of lower case characters = 8
}
7.22 Write a program to read and print a text. Also count Helctojoye See S| Y\O¢
the number of characters, words, and lines in the printf ("\n The copied text is: ");
text. pcopy str = copy str;

#include <stdio.h> while (*peopy str = \\07)

int main() {
jeveubahers (Viel, “olelolowy,
Sheu) 5
{ pcopy_ str++;
char str[100], *pstr;
}
tntechanre =slebines = sy wordse=sl-
getch();
pstr=str; imal hagd (OE
jokeminhese
(UWNey Igueee (eles feheveniiatesg «Wer
}
gets(str) ;
Output
joetens a Flere,
Enter the string: C Programming
while(*pstr != ‘\0’)
The copied text is: C Programming
{
spe (Gujoysiere) aes Sa?) 7.24 Write a program to copy n characters of a character
lines++; array from the mth position in another character
sues aa SN fie eos seh) le YS) array.
words++; #include <stdio.h>
chars++j; int main()
Pointers | 243 |

pstr = pstr + strlen(str) - nj;


char str[100],
copy _str[100] ; while(*pstr != ‘\0’)
char *pstr, *pcopy str; {
MOE Tay, 10h, th 9 Oe WN) here = Twiosieie = 36
pstr = str; PSEA, DCOD
Veo eit ty,
pcopy_str = copy str; }
printf ("\n Enter the string: "); wij See = VO" p
gets (pstr) ; printf ("\n The copied text is: Ls
printf ("\n Enter the position from which puts (copy str);
c® Sicekace |) ew Usk On
scanf ("$d", &m) ; - }
printf ("\n Enter the number of characters
to be copied: "); Output
Scant (G’sds Sia)> Enter the string: Hi there
psStn = pstr +m = 1; Enter the number of characters to be copied
t=O) 9 (from the end): 5
while(*pstr != ‘\0” && i <n) The copied text is: there
{
ZOCOR Vas Ela s—— SP Sieisy
7.26 Write a program to read a text, delete all the semi-
pcopy_ str++; colons it has, and finally replace all °.’ with a ‘,’.
pstr++; #include <stdio.h>
1++; int main()

} {
oso, Sere = “NOY char str[100],
copy _str[100] /

printf ("\n The copied text is: "); OGMehe Woysiers, woxXSesyy_Sheis 7
puts (copy str); jowieIe = Seis

Iau RY Og pcopy str = copy str;


printf ("\n Enter the string: Pe
}
gets (str) ;
Output josicie = ERs
while(*pstr != ‘\0’)
Enter the string: How are you
Enter the position from which to start: 2 {
aie (ogee fe: Ye?)
Enter the number of characters to be
(|) // doencthing,
copied: 5
He (Soest as “ 5%)
The copied text is: w are
cDCOD YES Sg = sa

7.25 Write a program to copy the last n characters of else


OSS Shere — tjorshiere
a character array in another character array. Also
DSi COD ycietatan,
convert the lower case letters into upper case letters
while copying.
}
*pcopy_ str = ‘\0’;
#include <stdio.h>
printf ("\n The new text is:
#include <string.h> pcopy_ str = copy str;
int main () while(*pcopy
str != *\0’)
{ {
char str[100], copy_str[100]; joucauineie (“Gell 7 ejaKcw@joye
Sie) j
Glavene <Aoysjese,, “ioclojone ee pcopy str++;
ani oe = Oy. seve }
josie = Stee, return 0;

pcopy str = Copy Seay }


printf ("\n Enter the string:");
gets(str);
Output
printf ("\n Enter the number of characters Enter the string: IbglengorclurenCial Yeo)

to be copied (from the end): "); Programming; is a book written by; Reema
scant ("3d", &n); Thareja.
|244 | Introduction to C Programming

The new text is: Introduction to C pstr2 = str2;


Programming is a book written by Reema pcopy_ str = copy str;
printf("\n Enter the first string: ");
Thareja,
gets (str1) ;
7.27 Write a program to reverse a string. printf("\n Enter the second string: ");
#include <stdio.h> gets (str2) ;
int main() DSELL=stink,
{ while(*pstr1 != ‘\0’)
char str[100], copy_str[100]; {
char *pstr, *pcopy str; EAoKclejey~ Shee = ssjoysheilp
pstr = str; pcopy_str++, pstrl++; :
pcopy str = copy str; }
printf ("\n Enter * to end"); pstr2
= str2;
printf ("\n ***k eK RRR RRR RRM) | while(*pstr2 != ‘\0’)
printf ("\n Enter the string: "); {
Scant (utc sp Stia)y: *pcopy str = *pstr2;
while (*pstr != \44) pceopy_str++, pstr2++;
{ } :
pstr++; xDCOpY stl =) \Oke7
scant ("%e", pstr) ; printf ("\n The new text is: ");
} pcopy_str = copy str;
*petrre, Y\0"; while (*pcopy_ str != ‘\0’)
Petr-=; {
while |(pstris=" Str) print a(" tele pcopy rset);
{ pcopy_str++;
xDCOpya Sth = *pstxy; }
pcopy_str++; return 0;
pStu=—; }
}
*pcopy str = ‘\0'; Output
printf("\n The new text is: "); Enter the first string: Introduction to C
pcopy_str = copy str; Programming by
while (*pcopy_str != ‘\0’) Enter the first string: Reema Thareja
{ The new text is: Introduction to C
print£ ("te", *pcopy ‘str)’; Programming by Reema Thareja
pcopy_str++;

ow a One VCD owe


earere) 0 TAS RR SRY OF OINTERS. See
} An array of pointers can be declared as
Output int *ptr[10]
Enter * to end
KKKKKKKKKKKKEKEK
The above statement declares an array of 10 pointers
Enter the string: Learning C++
where each of the pointer points
4
to an integer variable. For
The new text is: ++ C gninraeL
example, look at the code given below.
f 4 iene, “syoneua)||AL(0)]|¢
7.28 Write a program to concatenate two strings. i
uate, Je) GH 2, as = Se Sea ee Sees
#include <stdio.h> ptr[0] = &p;
int main() ptr[1] = &q;
{ jee |All = Gaas
char str1[100], str2[100], copy_str[2000] ; ptr[3] = &s;
char *pstrl,. “pstr2, *pcopy str; ptr[4] = &t
eAleatexehiat(())an
Can you tell what will be the output of the following
eeucilky cy yeheiailie
P statement?
Pointers =| 245 |

printf ("\n %d", *ptr[3]); However, char str[3] [10] = {"Janak", "Raj " P

The output will be 4 because ptr [3] stores the address "Paul"}; will behave in the same way as an array of
of integer variable and *ptr[3] will therefore print the characters. The only difference is the memory layout
value of s that is 4. Now look at another code in which we (Fig. 7.8). While the array of pointers needs only 15 bytes
store the address of three individual arrays in the array of of storage, str will reserve 30 bytes in memory, despite
pointers. the fact that some memory locations will be reserved but
not utilized.
main ()
{
ine arriba
ds 2; 3,4%5 bine
int arr2[]={0,2,4,6,8};-
int-arrs []/={1,3,5,:7;9}3 Here, the grey locations represent the
int *parr[3] = (anrl, arr2, ‘arr3); uninitialized memory cells
whee, 1s
Figure 7.8 Memory | jor
for(i = 0;1<3;i++)
prints ("Sa") *parmr fa);
} Look at the following program that uses an array of
characters to display the name of the day corresponding to
Output the number.
leas leg: #include <stdio.h>
char *day of week (int) ;
Surprised with this output? Try to understand the main ()
concept. In the for loop, parr [0] stores the base address
{
of arr1 (or, &arr1 [0] ). So writing *parr [0] will print the int day _num;
value stored at &arr1 [0]. Same is the case with *parr [1] char *day;
and *parr[2] . peintl ("\n Enter ‘the day rom letOn 7s)
Now consider an array of character pointers that is scanf ("%d", &day_num) ;

pointed to the strings. day = day of week(day


num) ;
if (day)
char *ptr[3];
jonerbionese (MEG Gleby)¢
In the ptr array, each element is a character pointer. else

Therefore, we can assign character pointers to the elements josebahese


(U Nin, aekieulaiel iDyeyiA!)5

of the array. For example, }


char *day_of week(int d)
jOREa LO) =e Shee
{
Another way to initialize an array of characters with char *week day[7] = { "SUNDA ", "MONDAY",
"TUESDAY", "WEDNESDAY", "THURSDAY",
three strings can be given as,
"FPRIDAY", "SATURDAY" } ;
char *ptr[3] = {"Janak","Raj","Paul"};
if (day>=1 || day<=7)
Here, ptr[0] is Janak, ptr[1] is Raj, and ptr[2]is return week day[d-1];

Paul. elise
return NULL;
The memory layout of ptr can be given as shown in
Fig. 7.7. It requires only 15 bytes to store the three strings. }
Output
Enter the day from 1 to 7: 3
TUESDAY
An array of pointers whose elements point to arrays of
varying sizes is called a ragged array. Therefore, array
of pointers week _day and ptr in the above discussion are
better known as ragged arrays.
246 | Introduction to C Programming

which would make ptr the name of an array of 10 pointers


7.13 POINTERS AND 2-D ARRAYS © to type int. You must be thinking how pointer arithmetic
Elements of a two-dimensional array are stored in works if you have an array of pointers. For example:
contiguous memory locations. A two-dimensional array is
ime rar Oder
not the same as an array of pointers to one-dimensional inky eee PERe=sor iad:
arrays. To declare a pointer to a two-dimensional array,
you may write In this case, arr has type int **. Since all pointers
have the same size, the address of ptr + i can be calculated
int **ptr
as:
Here int **ptr is an array of pointers (to one-dimensional addr (ptr +i) =addr(ptr)
+ [sizeof (int *) * i]
arrays), while int mat [5] [5] is a 2D array. They are not = addr (ptr) + \[2)*si)
the same type and are not interchangeable. Since arr has type int **,
Consider a two-dimensional array declared as
arr fol) =< arr
lol iol;
int mat[5] [5];
arr[1] = & arr[1] [0], and in general,
Individual elements of the array mat can be accessed using abe [|= "er ane EEO
.
either: According to pointer arithmetic, arr + i = & arr[il],
mare
[as Rilp sor yet this skips an entire row of 5 elements, i.e., it skips
*(*(mat + i) + 3) or complete 10 bytes (5 elements each of 2 bytes size).
* (mat [i] +j); Therefore, if arr is address 1000, then arr + 2 is
To understand more fully what is going on, let us address 1010. To summarize, sarr[0] [0], arr[0], arr,
replace and &arr [0] point to the base address.

* (multi + row) with X so the expression &arr[0]


[0] + 1 points to arr[0] [1]

*(*(mat + i) + j) becomes *(X + col) arr[0] + 1 points to arr[0] [1]

arr + 1 points to arr[1] [0]


Using pointer arithmetic, we know that the address
pointed to by (i.e., value of) X + col + 1 must be greater than &arr[0] + 1 points to arr[1] [0]

the address X + col by an amount equal to sizeof (int) . To conclude, a two-dimensional array is not the same
Since mat 1s a two-dimensional array, we know that in as an array of pointers to 1D arrays. Actually a two-
the expression multi + row as used above, multi + row + dimensional array is declared as:
1 must increase in value by an amount equal to that needed
sqies ((“Asiena) etl Ul F
to point to the next row, which in this case would be an
amount equal to COLS * sizeof (int) . Here ptr is a pointer to an array of 10 elements. The
Thus, in case of a two-dimensional array, in order to parentheses are not optional. In the absence of these
evaluate expression (for a row major 2D array), we must parentheses, ptr becomes an array of 10 pointers, not a
know a total of 4 values: pointer to an array of 10 ints.

1. The address of the first element of the array, which is


Notey Pointer to a one-dimensional array can be
given by the name of the array, i.e., mat in our case ee declaredas, |<
2. The size of the type of the elements of the array, i.e., Ant arr[}=(1,2,3,4,5)>
sizeof integers in our case int *parr;

3. The specific index value for the row parr = arr; .


Similarly, pointer to a two-dimensional _
4. The specific index value for the column
array can be declared as,
Note that int arrl2] (2)=({1,2},(3,4))
int (*ptr) [10];
“| ine (parr) 2), |
parr=arr;
declares ptr to be a pointer to an array of 10 integers. This
is different from Look at the code given below which illustrates the use
salle,
esonce [AMON
of a pointer to a two-dimensional array.
Pointers | 247 |

#include <stdio.h> printf ("\n Elements of the matrix are");


main () PLANCE
(1 \rk RRR RR RR KN) 5

{ for (1=0;1<3;1++)
int aArEi22) =(i1,
2) (34) ).,
{
aliaie, ck, (ioeweie))
(12i)5 jonestiayeie
(UW Nail) ¢
parr = arr; Pog] = OF a << Bp als)
rene Cy (pak <e ilp aL-S)) printf ("\t mat [%d] [
{ *(* (mat +1)+j));
‘eoa(s) = We 3) 2 2 poss)
}
Drinte ("sd") (* (parr
2) ia 1);
Bec Uisne Oly
ow

}
Output OR

ime2ro 4 #include <stdio.h>


int main()
The golden rule to access an element of a two-
{
dimensional array can be given as
shige shy,
a), mene (23) (12) 2
arr[i] [j] = (*(arr+i))[j] = *((*arr+i))
+3) ilaasyene(())<
= £5 (ware) ishiler))) printf ("\n Enter elements of the matrix") ;
printf ("\n FOR I IO kk kkk kk kK KK KK KK I) P

Therefore,
for (i=0;1<3;1++)
aang |\0)]| fi) = seekRelaera)),
|0))) = eo(((ssenaig))
2(0)))
{
= *(arr[0]
+0)
for (j=0;3<3;3++)
arr [1] [2] = (* (arr+1))
[2] = *((* (arr+1) )+2)
{
= *(arr[1]
+2) DIInee
("!\nemat [SP Esdl a—e ead a
scant (Usd; (*(mat + 1)+)j));
}
}
printf ("\n The elements of the matrixare ");
printf ("na
akek IT) 5

for (i=0;1<3;i++)
{
joncabaneia
GUM WalY)) F
for (j=0;4<3;j++)
jonas arene (Ue, jiene llesel [icoll| = Sxol!
ak a7,
*(* (mat + 1)4+3);

7.29 Write a program to read and display a 3 x 3 matrix. }


return 0;
#include <stdio.h>
int main() }
{ OR
wae Gly, aj, unene lll rest
#include <stdio.h>
Ghiseereral
Oe
void display(int (*) [3]);
printf ("\nEnter elements of the matisisc"))
int main()
printf ("\n KKK RK KR RK RR KK RR KK KK KK KKM)
{
for (i=0;i<3;i++)
HNS Sh hy weedy) |e
{ Gilsesxere(())
for (j=0;4<3;j++)
printf ("\n Enterelements of the matrix") ;
{ foneabonere (OI\Gal Kk RR KK KK KK KR KK KK KK KA KKM)
printf ("\n mat [%d] [sd] = ",1,j);
for (i=0;1<3;1++)
scanf ("$d", &mat [i] [3]);
} {
Ga (Gq) = Ope a) Sesheo sia)
248 | Introduction to C Programming

{
pminte (\nematiisdle(sdl" a0 2G
scanf("Sd", &mat
[i] [j]); In this section, we will see how pointers can be used to
} access a three-dimensional array. We have seen that
pointer to a one-dimensional array can be declared as,
display (mat) ;
int arr([]={1,2,3,455};
} int *parr;
void display(int (*mat) [3])
parr = arr;
{
sholes th, She
Similarly, pointer to a two-dimensional array can be
printf ("\n elements of the matrix are");
declared as,
PLANtE ("\n * RR kKoe IN) tnt ary (2) [2j=i{1,2))
13,4) 3
naena (al eNO) pe ay ee ep caleree) atime, ((Sjoyeb252))
(2)

{ Daue ga mcliata,
joreniaiese
(UW \ia” )
A pointer to a three-dimensional array can be declared
for (j=0;3<3;j++)
as, ‘
printf("\t mat [% d] [sd] = oe East aly

*(* (mat + 1)+3)); int arr [21 [2] [2%=(132;3;455,


6; 7784
aval (CHo~waie))
(2 Lili
}
return 0; parr = arr;

} We can access an element of a three-dimensional array


Output by writing,

Enter the elements of the matrix arr [i] [j] [k] = * (* (* (arr+i)
+3) +k)
KREKKKKKKKKKKEKR
KEK KKK KKK KKKKEKEKEKKEKEK
Look at the code given below which illustrates the use
12s 74 5 FG e7 28a9)
of a pointer to a three-dimensional array.
The elements of the matrix
#include <stdio.h>
KKK KK KKK KKK KKK KR KKK KKK KKEKKEKKKKKEKK
#include <conio.h>
iy 22 main ()
456
{
DSS int i,j,k;
Ine arr t2) [2ii2i
eae, ((fjeyebare))
[Al Ail chases
elrser
() ;
printf("\n Enter the elements of a 2 x
DR >< Ph eumgeny 3) WW)2
EOINGis = Olah Ore BE)
{
money] = Op aj < AP sles)
{
for(k = 0; k <= 2) k++)
sxeevane (Megolls iewere
fall] [sill {ivell))-s
}
}
printf("\n The elements of the 2 x 2 x 2
AGLAY ace) E.

~When a double pointe thatee to for(i = 0; i < 2; i++)


the first element of an array is ied we ' {
Oa) = Op Ge Be gies)
{
for(i t=) OF ekg kee)
print£ ("Sd", *(*(* (parr+i)
+3) +k) );
value a the firstelement ofthearray.:
Pointers |249 |

} pointer to the function, then that pointer can be assigned


getch
() ; the address of the correct function just by using its name.
return 0;
Like in the case of an array, a function name is changed
}
into an address when it’s used in an expression. It is
Output optional to use the address operator (&) in front of the
Enter, the: elements of a 2 «x 2°x 2°array: 1 function name.
2 8 5 6 8 For example, if fp is a function pointer and we have a
The elements of the 2 x 2 x 2 array are: 1 function add() with prototype given as,
BS) Ay GT {8 highs Exslsh(auale, See),

Then writing fp = add; initializes the function pointer fp


with the address of add() .

7.15.2 Calling a Function Using a Function


Pointer
When a pointer to a function is declared, it can be called
C allows operations with pointers to functions. We have using one of two forms:
seen earlier in this chapter that every function code along
(Siuney RG 2);
with its variables is allocated some space in the memory.
or
Thus, every function has an address. Function pointers are imObaVe!
(aly A) A
pointer variables that point to the address of a function.
Like other pointer variables, function pointers can be Look at the program given below which makes use of a
declared, assigned values, and used to access the functions pointer to a function.
they point to. #include <stdio.h>
This is a useful technique for passing a function as an ydouKel, jorsuigaie (uae ia),
argument to another function. In order to declare a pointer void (*£p) (int) ;
to a function we have to declare it like the prototype of the main ()
function except that the name of the function is enclosed {
1gj0) =I Jonealiahe
between parentheses () and an asterisk (*) is inserted
(Exiga) (CLO) 5
before the name. The syntax of declaring a function
‘mek WAC) ie
pointer can be given as,
ieee (0)F
return _type(*function_
pointer name) }
(argument list) ; void print (int value)

Look at the declaration below in which we declare a pointer


{
printf ("\n %d", value) ;
to a function that returns an integer value and accepts two
}
arguments—one of type int and the other of type float.
Output
int (*func) (int a, float b);
10
Because of precedence, if you do not put the function 20
name within parenthesis, you will end up declaring a
Now let us write another code that illustrates how the
function returning a pointer as shown:
contents of fp can be changed at run time to point to two
/* function returning pointer to int */ different functions during program execution.
int *Lune (intTa, tlloat b)!;
#include <stdio.h>
float (*func) (float, float) ;//Define a
7.15.1 Initializing a Function Pointer function pointer
float add(float, float) ;
As in case of other pointer variables, a function pointer
float sub(float, float) ;
must be initialized prior to use. If we have declared a
main ()
|250 | Introduction to C Programming

{ result = (*operate
fp) (num1, num2) ;

func = add; #include <stdio.h>


// function pointer points to add sets Geveleh(Shate, Sliac))5
PEMmeEL ("\nwAddi ion = ir Eune(oms; SEU); sha, Cwloe(Ghmepwalew)is
func = sub; int operate(int (*operate
fp) (int, int),
// function pointer points to sub HME, Bane)ec
princes ("Yn Subtraction
= sf", func (95,321); main ()

} {
float add(float x, float y) int result; 5

{ result = operate(add,9, 7);

return (x+y); printf ("\n Addition = %d", result);

} result = operate(sub, 9, 7);

float sub(float x, float y) printé ("\n Subtraction = td", result);

{ return 0;

return (x-y); }
} Int paddes (unt sa aia)

{
Output return (a + b);
Addition = 12.80000
}
Subtraction = 8.40000 int subtract (int a, int b)

A function pointer can be declared and initialize to NULL {


return (a - b);
as shown below:
}
int (*fp) (int) = NULL; int operate(int (*operate
fp) (int, int),
antwaye Tne)

7.15.3 Comparing Function Pointers int result;

Comparison operators such as == and != can be used the result’ = (*operate


fp) (a,b);
same way as usual. Consider the code given below which return result;

checks if fp actually contains the address of the function }


print (int) .
Output
if(fp >0){ // check if initialized
Addition = 1/6
if(fp == print)
Subtraction = 2
BPENEE
(= \n PPOLDECE Porntes GO print!) ;
else
printf ("\n Pointer not initialized!");

When an array of function pointers is made, the appropriate


function is selected using an index. The code given below
7.15.4 Passing a Function Pointer as an
shows the way to define and use an array of function
Argument to a Function
pointers in Cc.
A function pointer can be passed as the calling argument
Step 1: Use typedef keyword so that ‘fp’ can be used
of a function. This is in fact necessary if you want to pass
as type
a pointer to a callback function. The following code shows
how to pass a pointer to a function which returns an int typedef int (*fp) (int, int);

and accepts two int values. Step 2: Define the array and initialize each element to
Note that in the program below, the function operate NULL. This can be done in two ways:
calls the functions add and subtract with the following // with 10 pointers to functions which return an int and
line: take two ints
Pointers | 251 |

1. fp funcArr[10] = {NULL}; return a - b;

[Link] (*funcArr[10]) (int, int) = {NULL}; }


abohe, inibUll (aime ely, ashe 10)
Step 3: Assign the function’s address—‘Add’ and
{
‘Subtract’ EuncArr?
[0] ="fLuncArr2
[1] =" Add; return a * b;

funcArr[0] = &Add; }
alighe, liniA(akioie Gl aliehe, 1s)
funcArr[1] =-&Subtract;
{
Step 4: Call the function using an index to address the if (b)
function pointer return a / b;
else
Peintin*ed\n", funcArryrin2, os)
return 0;
(4 SHOrte £onm
}
princes (™Sd\n = (*tuncArr
[0] 12) 3)))r-
// correct way Output
Enter the numbers: 2 3
7.30 Write a program to add} that uses an array of function 0: Add
pointers, subtract, multiply, or divide two given iS Suberace
numbers. 2: Multiply
#include <stdio.h>
3: Divide
IME, BUA (AME fey, Sale doy)-A
4. EXIT
int subtract (int a, int b)-;
Enter the operation: 0
SANE, piqiwid
ln(ain aie ere aatal Beeo)))ep
Result = 5
init "iva ant Valine b)s
Enter the operation: 4
INEM CHE IP4]) PH Ginthay. amt) s

int main(void)

In C language you are also allowed to use pointers that


int result;
point to pointers. The pointers in turn, point to data (or
int num1, num2, op;
iZO@|) ee eqns
even to other pointers). To declare pointers to pointers,
LO — Subtract, just add an asterisk (*) for each level of reference.
12OVA), es sulbs For example, if we have:
SOs pe—ndanva:
aoe S46 — iNOe
printf ("\n Enter the numbers: ");
int *px;//pointer to an integer
scanf ("$d $d", &numl, &num2);
int **ppx; // pointer to a pointer to an
do integer
1s = SOF
prantte(@\nrOkeAdd \neiisy Subtract \n ppx = &px;
2: Multiply \n 3: Divide \n 4. EXIT\n");
Assume, that the memory location of these variables is as
printf ("\n\n Enter the operation: "); shown in Fig. 7.9.
scanf ("$d", &op);
result = (*fp[op] ) (numl, num2) ;
printé ("\n Result = %d", result) ;
} while (op!=4) ;
return 0;
1002 2004
}
THeEesSUMMAIMeED ay anit) aralicwec Pointer to pointer
{
return a + b;
Now if we write,
}
int subtract (ant a, int b) pieamtE (Wn sd", ss pps)i;

{ then it will print 10, the value of x.


|252 |_Introduction to C Programming

dynamic memory data. The way in which C handles the


7.18 MEMORY ALLOCATION INCc
memory requirements is a function of the operating system
PROGRAMS | | and the compiler.
C supports three kinds of memory allocation through the When a program is being executed, its main() and all
variables in C programs: other functions are always kept in the memory. However,
the local variables of the function are available in the
Static allocation When we declare a static or global
memory only when they are active. When we studied
variable, static allocation is done for the variable. Each
recursive functions, we have seen that the system stack
static or global variable is allocated a fixed size of memory
is used to store a single copy of the function and multiple
space. The number of bytes reserved for the variable
copies of the local variables.
cannot change during execution of the program. Till now
Apart from the stack, we also have a memory allocation
we have been using this technique to define variables,
known as heap. Heap memory is unused memory allocated
arrays, and pointers.
to the program and available to be assigned during its
Automatic allocation When we declare an automatic execution. When we dynamically allocate memory for
variable, such as a function argument or a local variable, variables, heap acts as a memory pool from which memory
automatic memory allocation is done. The space for is allocated to those variables. :
an automatic variable is allocated when the compound However, this is just a conceptual view of memory and
statement containing the declaration is entered, and is implementation of the memory is entirely in the hands of
freed when it exits from a compound statement. system designers.
Dynamic allocation A third important kind of memory
allocation is known as dynamic allocation. In the following
sections we will read about dynamic memory allocation 7.20 DYNAMIC MEMORY ALLOCATION
using pointers. The process of allocating memory to the variables during
execution of the program or at run time is known as
dynamic memory allocation. C language has four library
routines which allow this function.
Before jumping into dynamic memory allocation, let Till now whenever we needed an array we had declared
us first understand how memory is used. Conceptually, a static array of fixed size, say
memory is divided into two—program memory and data
int arr[100];
memory (Fig. 7.10).
When this statement is executed, consecutive space for
100 integers is allocated. It is not uncommon that we may
be using only 10% or 20% of the allocated space thereby
Memory
wasting rest of the space. To overcome this problem and
to utilize the memory efficiently c language provides a
mechanism of dynamically allocating memory so that only
Program memory : Data memory the amount of memory that is actually required is reserved.
We reserve space only at the run time for the variables that
are actually required. Dynamic memory allocation gives
best performance in situations in which we do not know
Global | Stack |
memory requirements in advance.
C provides four library routines to automatically allocate
Figure 7.10 BVeustelay usage memory at the run time. These routines are shown in Table 7.2.
When we have to dynamically allocate memory for
variables in our programs then pointers are the only way
The program memory consists of memory used for the
to go. When we use malloc() for dynamic memory
main () and other called functions in the program, whereas
allocation, then you need to manage the memory allocated
data memory consists of memory needed for permanent
for variables yourself.
definitions such as global data, local data, constants, and
Pointers | 253 |

request multiple blocks of storage


Programming Tip: each of the same size and then
Function _| Task Touse dynamic
sets all bytes to zero. Calloc()
malloc() | Allocates memory and returns a pointer to the stands for contiguous memory
first byte of allocated space _ allocation and is primarily used to
calloc() Allocates space for an array of elements and allocate memory for arrays. The
initializes them to zero. Like malloc(), calloc() syntax of calloc() can be given
also returns a pointer to the memory as:
Frees previously allocated memory ptr=(cast-type*) calloc(n,elem-size);

realloc() | Alters the size of previously allocated memory The above statement allocates contiguous space for n
blocks each size of elements size bytes. The only difference
between malloc() and calloc() is that when we use
7.20.1 Memory Allocations Process
calloc(), all bytes are initialized to zero. Calloc()
In computer science, the free memory region is called the returns a pointer to the first byte of the allocated region.
heap. The size of heap is not constant as it keeps changing When we allocate memory using malloc() or
when the program is executed. In the course of program calloc(), a null pointer will be returned if there is not
execution, some new variables are created and some enough space in the system to allocate. A null pointer,
variables cease to exist when the block in which they were points definitely nowhere. It is a not a pointer marker;
declared is exited. For this reason it is not uncommon to therefore, it is not a pointer you can use. Thus, whenever
you allocate memory using malloc() or calloc(), you
encounter memory overflow problems during dynamic
must check the returned pointer before using it. If the
allocation process. When an overflow condition occurs, the
program receives a null pointer, it should at the very least
memory allocation functions mentioned above will return a
print an error message and exit, or perhaps figure out some
null pointer. way of proceeding without the memory it asked for. But in
any case, the program cannot go on to use the null pointer
7.20.2 Allocating a Block of Memory it got back from malloc ()/calloc().
A call to malloc, with an error check, typically looks
Let us see how memory is allocated using the malloc().
something like this:
malloc is declared in <stdlib.h>, so we include this
header file in any program that calls malloc. The malloc int *ipe=umalwloce G00 Skisizeor (iat)))e
aie (aij) = INTEL)
function reserves a block of memory of specified size and
returns a pointer of type void. This means that we can {
printf ("\n Memory could not be
assign it to any type of pointer. The general syntax of the allocated");
malloc() is return;

ptr =(cast-type*)
malloc (byte-size) ;

where ptr is a pointer of type cast - type. The malloc () 7.31 Write a program to read and display values of an
returns a pointer (of cast type) to an area of memory with integer array. Allocate space dynamically for the
size byte-size. array.
For example, #include <stdio.h>
#include <conio.h>
arr=(int*)malloc(10*sizeof
(int) ) ;
#include <stdlib.h>
This statement is used to dynamically allocate memory main ()

equivalent to 10 times the area of int bytes. On successful {


‘limcy ab, Gave
execution of the statement the space is reserved and the
int *arr;
address of the first byte of memory allocated is assigned to
Gliese erei(\r
the pointer arr of type int. printf ("\n Enter the number of elements ") ;
The function Calloc() is another function that scan£ ("%d", &n);
reserves memory at the run time. It is normally used to arr = (int*)malloc(n * sizeof (int) ) ;
|254 | Introduction to C Programming

if(arr == NULL) This is even more important when the storage space is
{ limited. Therefore, if we no longer need the data stored
printf ("\n Memory Allocation Failed"); in a particular block of memory and we do not intend to
exit (0);
use that block for storing any other information, then as
} a good programming practice we must release that block
for (i=0;i<n;i++)
of memory for future use, using the free function. The
{
general syntax of the free () is
printf("\n Enter the value %d of the
ehovehyan WES si))e free (ptr) ;
scanki(isdly
Gamer [idle
where ptr is a pointer that has been created by using
} malloc() or calloc(). When memory is de-allocated
printf("\n The array contains \n");
using the free (), it is returned back to the free list within
for (i1=0;i<n;i++)
printi("tda"; arr) ))
the heap.
// another way is to write *(arr+i)
return 0; 7.20.4 To Alter the Size of Allocated Memory
}
At times the memory allocated by using calloc() or
Now let us also see how we can allocate memory using
malloc() might be insufficient or in excess. In both
the calloc function. The calloc() function accepts two
the situations we can always use realloc() to change
parametres—num and size, where num is the number of
the memory size already allocated by calloc() and
elements to be allocated and size is the size of elements.
malloc (). This process is called reallocation of memory.
The following program demonstrates the use of calloc ()
The general syntax for realloc() can be given as,
to dynamically allocate space for an integer array.
#include <stdio.h> ptr = realloc(ptr,newsize) ;

#include <stdlib.h> The function realloc() allocates new memory space of


main ()
size specified by newsize to the pointer variable ptr. It
{ returns a pointer to the first byte of the memory block.
age BlyJair
The allocated new block may be or may not be at the same
int *arr;
region. Thus, we see that realloc() takes two arguments.
printf ("\n Enter the number of elements: ");
The first is the pointer referencing the memory and the
scanf ("%d", &n) ;
second is the total number of bytes you want to reallocate.
arr = (int*) calloc(n,sizeof
(int) );
If you pass zero as the second argument, it will be
if (arr==NULL)
equivalent to calling free(). Like malloc() and calloc(),
Sscaitege(ln)iee
printf("\n Enter the %d values to be
realloc returns a void pointer if successful, else a NULL
stored in the array", n);
pointer is returned.
for (1=0; i<n; i++)
If realloc() was able to make the old block of memory
(SHAME ae(Wiel pfeegie’ lau) yr
bigger, it returns the same pointer. Otherwise, if realloc ()
printf ("\n You have entered: ");
has to go elsewhere to get enough contiguous memory then
for(i=0; i<n; i++) it returns a pointer to the new memory, after copying your
PLAMCE (UeA",
ai [biees old data there. However, if realloc() can’t find enough
free (arr) ; memory to satisfy the new request at all, it returns a null
return 0; pointer. So again you must check before using, that the
pointer returned by the realloc() is not a null pointer.
/*Example program for reallocation*/
7.20.3 Releasing the Used Space #include < stdio.h>
#include < stdlib.h>
When a variable is allocated space during the compile time,
#define NULL 0
then the memory used by that variable is automatically main ()
released by the system in accordance with its storage class.
{
But when we dynamically allocate memory then it is our char *Str;
responsibility to release the space when it is not required. /*Allocating memory*/
Pointers 255 |
str = (char *)malloc(10); allocated") ;
if (str==NULL) exit (-1);
{ }
printf ("\n Memory could not be allocated") ; for (i=0; i<ROWS; i++)
exit (1);
{
} arr [i] = (int *)malloc(COLS * sizeof (int) ) ;
stxcpy (str, VHi") >
af (ars
(ale =—s NUL)
printf ("\n STR = $s", str);
/*Reallocation* / {
Siiae=— (cheats *)xealloc(str, 20); printf ("\n Memory Allocation Failed") ;
if (str==NULL) : exit (-1);

{
printf ("\n Memory could not be }
reallocated") ; printf ("\n Enter the values of the array: ");
exit (1);
for(i = 0; 2 < ROWS? 1++)
}
printf ("\n STR size modified.\n");
{
OIA) 2 OF 3 & COWS Geese)
joperiness (UN YEU eS Sail. feheia))sp
strcpy(str,"Hi there") ; scanf ("%d", sarr[i]
[j]);

johenlsaters
(WU \Wel Stns) as yc |iene) 5 }
/*freeing memory*/ printf("\n The array is as follows: ");
free (str) ; for(i = 0; i < ROWS; i++)
return 0;
{
imena(gh cs 0)9 a} xe GOS}. a)4is))
jopenkiqyepe
(Meek, Sweie|ati| {13).| 9
}
fora = 0;) f= ROWS a+)

free(arr[i]);
free (arr) ;
Dynamically Allocating a 2-D Array return 0;

We have seen how malloc() can be used to allocate a }


block of memory which can simulate an array. Now we
Here, arr is a pointer-to-pointer-to-int: at the first level
can extend our understanding further to do the same to
as it points to a block of pointers, one for each row. We first
simulate multi-dimensional arrays.
allocate space for rows in the array. The space allocated to
If we are not sure of the number of columns that the
each row is big enough to hold a pointer-to-int, or
array will have, then we will first allocate memory for each
int *. If we successfully allocate it, then this space will
row by calling malloc. Each row will then be represented
be filled with pointers to columns (number of ints). This
by a pointer. Look at the code below which illustrates this
can be better understood from Fig. 7.11.
concept.
#include <stdlib.h>
#include <stdio.h>
main ()

{
int **arr,i,j,
ROWS, COLS;
printf ("\n Enter the number of rows and
columns in the array: ");
scanf ("$d %d", ROWS, COLS) ; Column
arr
= (int **)malloc(ROWS * sizeof(int *))j;
Lf (arr == NULL) Figure 7.11 ) ory alloca
{
printf ("\n Memory could not be
256 | Introduction to C Programming

Once the memory is allocated for the two-dimensional To dynamically allocatespace for a
array, we can use subscripts to access its elements. When _3-D array, arr[10][20][30], perform
the
we write, arr[i] [j], it means we are looking for the _ - following steps
ith pointer pointed to by arr, and then for the jth int
_ int eeearr;
pointed to by that inner pointer.
When we have to pass such an array to a function, then
the prototype of the function will be written as . for (i=0; au i++) arr[i] =
xx) malloc (20*sizeof (int *));
rmbhgvel(Ghalic = ele, shale IRONS. shehes (GOIN), 4. for(i=0;i<10;i++) (for (j=
=O;
In the above declaration, func accepts a pointer- 3<20; j++) arrlil[j] = (int. *
malloc (30 * sizeof (int)) ;
to-pointer-to-int and the dimensions of the arrays
as parametres, so that it will know how many rows and
columns there are.
Look at the code given below which illustrates another 7.21 DRAWBA
OF CK
POINTS
ERS
way of dynamically allocating space for a two-dimensional Although pointers are very useful in C they are not free
array. from limitations. If used incorrectly, pointers can lead
#include <stdlib.h> to bugs that are difficult to unearth. For example, if you
#include <stdio.h> use a pointer to read a memory location but that pointer
main () is pointing to an incorrect location then you may end up
{ reading a wrong value. An erroneous input always leads
inte <a, 9 ROWS), (COhS; to an erroneous output, therefore however efficient your
printf("\n Enter the number of rows and program code may be, the output will always be disastrous.
columns in the array: ");
Same is the case when writing a value to a particular
scanf ("%d %d", ROWS, COLS) ;
memory location.
arg = (int *)imalloc(ROWS * COLS *
Consider a scenario in which the program code is
sizeof (int) );
supposed to read the account balance of a customer, add
pate (Quiate == NU Els))
new amount to it, and then re-write the modified value
{
printf ("\n Memory could not be to that location. If the pointer is pointing to the account
allocated") ; balance of some other customer then the account balance
exit (-1) ; of the wrong customer will be updated.
} Let us try to find some common errors encountered
printf ("\n Enter the values of the array: "); when using pointers.
for(i = 0; i < ROWS; i++)
shige od). Ssiepico
{
fOr (i= Ol j < COLS; j++)
scanf (eo PIs otMB) a *px = 20;
}
printf("\n The array is as follows: "); Error un-initialized pointer px is pointing to an un-
for(i = 0; i < ROWS; i++) known memory location. Hence it will overwrite that loca-
{ tion’s contents and store 20 in it. Such a pointer is called
fomGin=mOranim< CObSi. ) ++) a wild pointer. A pointer which is not initialized with any
printf ("sd", arr[i] [j]); address is called a wild pointer. It may contain any gar-
} bage address and thus dereferencing a wild pointer can be
for(i = 0; i < ROWS; i++)
dangerous.
free(arr[i]);
free (arr) ; amis er, “Sores

return 0;
joe S ep
ERROR: it should be px = &x;
Pointers | 257 |

PHC ONS MO yy = (20,9 *pxpaspy: pointer, unpredictable behaviour may result, as the
px = &X, py = &y; memory may now contain completely different data.
Te (Gop ce Feni7) // it should be *px and *py This problem can become worse when the program
printf ("\n px is less than py");
writes data to memory pointed by a dangling pointer causing
elise
a silent corruption of unrelated data, leading to subtle bugs
printf ("\n py is less than px");
that can be extremely difficult to find. Moreover, if the
Look at another code given below. overwritten data is bookkeeping data used by the system’s
#include <stdio.h> memory allocator, the corruption can even cause system
main () instabilities.
{ Z Hence, dangling pointer problem occurs when the
Ghart*serl yy *str2> pointer still points to the same location in memory even
printf ("\n Enter the string: "); though the reference has been deleted and may now be
gets (str1) ; used for other purposes.
while (*str1!='\0’)
A common mistake that we often do in C program is
{ to return address of a stack-allocated local variable. We
Seis a wisheiaihs
know that once a called function returns, the space for
str2++, strl++;
these variables gets de-allocated and technically they have
}
garbage values. Look at the code below which illustrates
*str2='\0';
jovenuintere (U\aer Siesestae; skeig” W)) how we get a dangling pointer when a called function
while (*str2!='\0‘) returns.
{ char *func (void)
Prince
(user wStr2)s-
{
str2++; Ghetech=_ A
} Ga OI Sid
} return &ch;

Error str2 will not be printed because str2 has moved }


ahead of its starting location and before displaying the The above program returns the address of ch. So the
string, it has not been initialized with its starting address. calling function may access its value. Any functions called
thereafter will overwrite the stack storage allocated for ch
Memory leak Memory leakage occurs when memory is
with other values and the pointer would no longer work
allocated but not released when it is no longer required.
correctly. Therefore, if a pointer to ch must be returned it
This causes an application to unnecessarily consume
must be declared as static.
memory thereby reducing the memory available for other
Consider the code below which illustrates another
applications. Although in small programs it is not a big
dangling pointer problem.
concern but when dealing with large projects, memory
leakage may result in slowing down the application or Chars *peri;
crashing the application when the computer memory char *ptr2 = (char *)malloc(sizeof
(char) ) ;
PER Spin? ;
resource limits are reached.
free (ptr2) ;
For example, ifa function dynamically allocates memory
for 100 double values and forgets to free the memory and Now ptr1 becomes a dangling pointer. A solution to the
in worst case if that function is called several times within above is to assign 0(null) to ptr1l immediately before
the code then ultimately the system may crash. exiting the block in which it is declared. An alternative
solution would be to somehow guarantee that ptr! will not
Dangling pointer Dangling pointers arise when an
be used again without further initialization.
object is deleted or de-allocated, without modifying the
value of the pointer. As a result, the pointer still points to Memory corruption Memory corruption often occurs
the memory location of the de-allocated memory. when due to programming errors, the contents of amemory
Once the memory is de-allocated, the system may location gets modified unintentionally. When the program
reallocate that block of freed memory to another process. uses the contents of the corrupted memory, it either results
In case the program then dereferences the (now) dangling in program crash or in strange and bizarre behaviour.
|258 leIntroduction to C Programming

Memory corruption is one of the most difficult memory that is not owned by the program. This
programming errors to trace mainly because of two situation may arise when the pointer happens to be
reasons: a null pointer or a dangling pointer. Using such
e The source of the memory corruption and _ its a pointer to write to a memory location is a serious
manifestation may be far apart. Therefore, it may programming flaw as it may lead to crash another
become hard to correlate the cause and the effect of program or even the operating system.
the problem. Using beyond allocated memory (buffer overflow): \f
Symptoms of memory corruption problem may the elements of the array are accessed in a loop, with
appear under unusual conditions thereby making it incorrect terminating condition, memory beyond the
even harder to consistently reproduce the error. array bounds may be manipulated. Buffer overflow is
a common programming flaw exploited by computer
Memory corruption errors can be broadly classified
viruses causing serious threat to computer security.
into following categories:
4. Faulty de-allocation of memory: Memory leaks
1. Using un-initialized memory: An _ un-initialized and freeing un-allocated memory can also result in
memory contains garbage value. Hence, using the
memory corruption.
contents of an un-initialized memory can lead to
unpredictable program behaviour. These days, memory debuggers like Purify, Valgrind,
Using un-owned memory. A common programming Insure++ are widely used for detecting memory corruption
mistake is to use pointers for accessing and modifying errors.

All data and programs need to Ne placed in the constant NULL, You may also ini alize a pointer asa _
primary memory for execution. null pointer by using a constant 0.
Pointers are nothing but memory addresses. A A generic pointer|isa pointer variable that has void
pointer is a variable that contains | the memory _as its data type. Th generic pointer can be us d to :
address of another point to variable ny data type.
-e The‘s’ operator retrievessthe lvalue (address) ofhe When the memory for an array is allocated, its
bare
variable. We can dereference a pointer, i.e., refer to address is fixed and it cannot be
5 Senses during
the value of the variable to leg it ¢ joints by using program execution.
POINTS
TO
NOTE unary cae
“ operator. Vhe e dynamically allocate m smory
V Ores
The address of a memory location isa pointer heap acts as a memory pool from which memory
constant, therefore it cannot be changed itin He is allocated to those variables. The process - of -
program code. allocating memory to the variables during executi -
Unary increment and ecrement operators have of the program or at runtime is [Link] dyi
greater precedence than the dereference operator memoryallocation. =
{*). malloc(), pic and realloc toe
Null pointer is a special pointer value that is known a void pointer if successful, else a NULL pointer is
not to point anywhere. This means that a NULL returned. |
pointer does not point to any valid memory address. Memory leakage occurs hes‘me Y ory issallocd
To declareanull pointer you may use the predefined but not released when it is no longer required.

Alias A reference (usually in the form of a pointer) to points to. InC, a pointer i
is derirenced either using the
an object which is also known via other references that unary * operator or the array subscripting operator {].
may include its own name or other pointers.
Function pointer A pointer to any fi
f
ence To look up a value referred
to. Usually, the
Lvalue An expression that appears on the lefchand: sign
‘value referred
to’ is the value pointed to by a pointer.
GLOSSARY of an assignment epetator hence, something that can :
_ Therefore, ‘dereference a pointer’ means to see what it
Pointers | 259 |

_perha s be assigned to. An lvalue specifies something represents a null pointer.


that h s a location, as opposed to a transient value.
Pointer Variable that stores addresses.
| Null pointer A pointer value which is not the address of
Rvalue An expression that appears on the right-hand sign
ny object or function. A null pointer points to nothing.
ofan assignment operator. Generally, rvalue can participate
stealull pointer constant An integral constant expression
with value 0 (or such an expression cast to void *), that
in an expression or be assigned to some other variable.

| Fill in the Blanks


. Size of character pointer is 22. The only integer value that can be assigned toa
: Allocating memory at run time is: known as _ pointer variable is
23. can be used as parameter declaration to

EXERCISES of another declare


an array of integers passed to a function.
24. Dynamically allocated memory can as referred
not point to ay ald __using
ory address. 25. function returns memory [Link] heap.
. The size of memory allocated 1 a variable 26. Ragged array is eyeteietis using an array of
pointers to
tems, integer verabie ie aloceted —
bytes. Multiple Choice Questions
appears onthe right side ofthe 1. The operator signifies a
(a) referencing operator
(b) dereferencing operator —
‘sto return multiple _
: values from a function via function arguments. (c) address operator

+ »perator informs the compiler that : (d) none of these


variable is a pointer variable. 2. (snum) is equivalent to writing
: Data and programs need to be placed in the (a) &num (b) *num
__ for execution. (c) num _(d) none of these
. When compared with heaps, ao is faster but _ 3. Pointers are used to create con data
maller and ee structures like
— (a) trees (b) linked list
space on the_ (c) stack (d) queue
14. Shared libr (e) all ofthese
4, While declaring pointer variables, which operator
do we use?
(a) address (b) arrow
(c) indirection (d) dot
alloc(), calloc(), and
5. Which operator retrieves the lvalue of a variable?
if successful, else
(a) & (b) *
© 2 (d) none ofthese
6. The code of the main () program is stored in
memory in
(a) stack (b) heap
260 | Introduction to C Programming

(c) global (d) bss 18, Dangling point is when


: an object iiscle
. For dynamically allocated variables, memory is or de-allocated, hout modifying the valu
allocated from which memory area? the pointer.
(a) Stack (b) Heap 1. It is possible to add twocone .
(c) Global (d) BSS 20. Pointer constants cannot be che
_ The function malloc () is declared in which 21. The value of a pointer isalways
header file Poa *otr++ will add 1 to the value poi d by
(a) stdio.h (b) stdlib.h 2. Pointers of different types can be assigned toea
(c) conio.h (d) iostream.h other without a cast.
. Which function is used to request memory and (4. Adding 1 to a po variable will-make it poi
set all aloocated bytes to zero? byte ahead of the memory location to —
(a) malloc() (b) calloc() currently pointing. -
(c) realloc() (d) free () 29. Any arithmetic operator can be used : ae the
value of a pointer. ©
State True or False 26. Only one call to front) isi enoug release the —
. Apointer is a variable. entire array allocated using calloc().
. The & operator retrieves the lvalue of the variable. af, Ragged arrays censure less memory space.
. Array name can be used as a pointer.
. Unary increment and decrement operators have Review Questions
greater precedence than the dereference operator.
i Explain the difference ceieen a null pointer and
. The generic pointer can be pointed at variables of
a void pointer.
any data type.
: Define pointers.
. Afunction pointer cannot be pasred as a function’s
calling argument. _ Write asshort note on pointers.
. On 32-bit systems, integer ibe is allocated 4 . Compare pointer and array name.
bytes. . Explain
WN
mf the result of the following code-
. Lvalue cannot be used on the left side of the int numl = 2, num2 = 3.
assignment statement. dnt *o = Spun | 7a = &num2;
. Pointers provide an alternate way to access *ptp = at

individual elements of the array. 6. What do you understand by a null sotntee!


10. Pointer is a variable that represents the contents 7. What is an array of pointers? Hew) is it different
of a data item. from a pointer to an array?
an. Unary increment and decrement operators have 8. Write a short note on pointer arith etic.
greater precedence than the dereference operator.
9. How are generic pointers different. from other ©
AZ: A fixed size of stack is allocated by the system and pointer variables?
is filled as needed from the top to bottom.
10. What do you understand by the termn pointerte
) 2
£3. All the parametres passed to the called function function?
will be stored on the stack.
sae Differentiate beweer otra and yore
14. When the memory for an array is allocated, its
12, How are arrays related to pointers?
base address is fixed and it cannot be changed
13. Briefly explain array of pointers.
during program execution.
14. Write a program to sort 10 integers
ao. An array can be assigned to another array.
pointers.
16. Memory leakage occurs when memory is allocated
15, Write a program to illustrate the use
eof a pointer
but not released when it is no longer required.
that points to a 2D array. _
a7. mat [i] [j] is equivalent to *(*(mat + i)
16. Give the advantages of using pointers.
+ 4).
Pointers | 261 |

e an array of function pointers? If yes, 43. Differentiate between a variable address and a
vith the help of a suitable example. variable’s value. How can we access a variable’s
address and its value using pointers?
ate between malloc(), calloc, and 44. Givea brief of different memory areas available to
the programmer.
EXERCISES 45. What do you understand by dereferencing a
pointer variable?
. Write a short note on pointer expressions and
pointer arithmetic.
. What will *p++ = *q++ do?
Write a program to add two integers using
functions. Use call by address technique of passing
_ parameters.
. Write a short note on pointer and a three
dimensional array.
. How can a pointer be used to access individual
elements of an array? Illustrate with an example.
. Can we assign a pointer variable to another pointer
_ variable? Justify your answer with the help of an
example.
. What will happen if we add or subtract an integer
to or from a pointer variable?
. Is it possible to compare two pointer variables?
lllustrate using an example.
. Can we subtract two pointer variables?
. With the help of an exampie explain how an array
can be passed to a function? Is it possible to send
just a single element of the array to a function?
. Can array names appear on the left side of the
assignment operator? Why?
. Differentiate between an array name and an array
pointer.
. Using a program, explain how pointer variables
- can be used to access strings.
Write. a program. to input a character. If it is in
. Write a program to print “Good Morning” using
percase print in lowercase and vice versa.
_ pointers.
. Write a program to display the sum and average of :
ae ee : . Write a program to print the lowercase characters
nur bers from 100-200. : : : ;
into uppercase and vice versa in the given string
Write a program to print all odd numbers from “gOOd mORninG’.
0-200.
61. Write a program to copy “University” from the
rite a program to input 10 values in an array. given string “Oxford University Press” in another
_ Categorize each value as prime or composite. string.
. Write a program to subtract two floating point =, . Write a program to copy last five characters from
numbers using functions. the given string “Oxford University Press” in
. Write a program to calculate the area of a circle. another string.
. How can you declare a pointer variable?
|262 | Introduction to C Programming

tu
an
2
Lid
St
Lil
Pointers _ | 263 |

2 char Str ll ="ABCDEFGH", *pstr=str;


net ("a <a" Parr-1, 1+*-p: =: pstr+t;
while (*pstr!='H’)
Prince ("5c" , “Petre
s) =

EXERCISES
eS
{
Shor str [] ="ABCDEFGH ;
printi("s Sd", (estr[3)- -astr (01) ;

‘eqn < 8", str)

<a.

i. &k ksptr) pe

oy fooae

= *perssnum; -
a 3d", a mee. (*ptr) -

printf ("Hello World"+3) ;

19 wmaing)
7
,4,5,6,7.8,9 1;
int arr (] [2)=(1,2,3
*(arr+l+i
* (arr+* (arr+1) L sprintf ("$a", sizeof (arr));
* (arrsi)+* (erry);
}
* (arr+j}));

“20 ming
{
int arc(2) (3]2{1,2,3,4,5,6,7.8,9);
|264 | Introduction to C Programming

printf ("$d", sizeof (arr[1]));

ai main
4 .
Ant arr(5), *parrearr;
EXERCISES
_ while(parr < éarr[5])

*parr = parr-arr;
printt("2a", *parr),
parr++;
g

22. main()
.
ar *str = “Hello
ex(S]=!1"; |

*str1 = "Hello World";

m, “#ptr=num;
yee

, epED.
ANNEXURE 5
IPHERING POINTER ptr is array of pointer to

Step 4: Continue moving left. Here, you find int. So say,


LARATIONS
ptr is array of pointer to int.
The right—left rule is a widely used rule for creating as
well as deciphering C declarations. Before starting, let us Now decipher the following declaration:
first understand the meaning of different symbols and the apo, tai aabhave:
(Oy Ohr
way in which they are read. Step 1: Find the identifier. Here, the identifier is func. So
a
say,
- Read As :. . :.Location EUG wes

Step 2: Identify the symbols on the right side of the


identifier until you run out of symbols or encounter a left
parenthesis. Here, the symbol is (). So say
() function placed on the right side func is function returning
returning
Step 3: Move to left of the identifier until you run out of
Following are the steps to decipher the declaration: symbols or encounter a left parenthesis. Here, the symbol
is *. So say,
Step 1: Find the identifier and read as ‘identifier is’.
func is function returning pointer to
Step 2: Read the symbols on the right of the identifier.
For example, if you find ‘( )’, then you know that it is Step 4: Can’t move left anymore because of the left
a function declaration. So you can now say, ‘identifier is parenthesis, so now move to right. Here, you will encounter
function returning’. Or if you encounter a ‘[ ]’, then read a symbol (). So say,
it as ‘identifier is array of’. func is function returning pointer to

Continue moving right until you either run out of symbols function returning

or you encounter a right parenthesis. Step 5: Can’t move right anymore as all symbols have
Step 3: Now, check the symbols to the left of the identifier. exhausted so move to left. Here you will encounter a ‘*’.
If it is not a symbol given in the table, then just say it. So say,
For example if you encounter int, then just say it as it is. func is function returning pointer to
Otherwise, translate it into English using the above table. function returning pointer to

Continue going left until you either run out of symbols or Step 6: Continue moving left. Here you will find int. So say,
you encounter a left parenthesis. func is function returning pointer to
Step 4: Repeat Steps 2 and 3 until the entire declaration is function returning pointer to int.

completely deciphered. Consider some examples: Some declarations also contain array size and function
shay. teste
Ml 9 parametres. So if you encounter a symbol as ‘[10]’, then
Step 1: Find the identifier. Here, the identifier is ptr. So read it as ‘array (size 10)’. If you encounter, something
say, like ‘(int *, char)’, then read it as ‘function expecting
\ptaaaas4
(int *, char) and returning...’. Now consider such an
example and decipher the following decalaration:
Step 2: Identify the symbols on the right side of the
identifier until you run out of symbols or encounter a left Dit) (H(REune) Mammy Fl char)
) 13) 15] 5

parenthesis. Here, the symbol is []. So say Use the steps illustrated below and check your answer.
‘Piigaucs abnay; OL! func is pointer to function expecting (int

Step 3: Move to left of the identifier until you run out of * char) and
returning pointer to array (size 3) of array
symbols or encounter a left parenthesis. Here, the symbol
(si zey5) "of “met.
is *. So say,
|266 | Introduction to C Programming

Some Illegal Declarations in C notice that a function cannot return an array, but only a
pointer to an array. Therefore, this declaration is illegal.
It is quite possible that you end up with some illegal
Let us look as some more illegal combinations in C
declarations using this rule. So, you must be very clear
language:
about what is legal in C and what is not allowed in the
F : — t Lt array of functions
language. For example, consider a declaration as shown: UR er ae oN CTRSecm v
() ()—A function cannot return a function
int *((*£une)s@ shy, :
() []—A function cannot return an array
This can be deciphered as, ‘func is pointer to function
é ; ; he table gi below lists the declaration, meaning, and
returning array of array of pointer to int’. But did you The table Smee Oyenet ‘ s
its remarks as valid or invalid.

Declaration — Meaning . _. oo

func is a function returning float

ptr is a pointer to pointer to int

char (*ptr)[]; ptr is a pointer to array of char

char (*ptr)(); ptr is a pointer to function returning char

float *ptr[]; ptr is array of pointers to float

int mat(][]; mat is an array of array of int


int func[]() func is an array of function returning int

func is a function returning pointer to float

func is a function returning array offloat

float func()(); func is a function returning function returning float


ptr is a pointer to pointer to pointer to int

int (**ptr)[]; ptr is a pointer to pointer to array of int

float (**func)(); func is a pointer to pointer to a function returning float


char *(*ptr)[]; ptr is a pointer to array of pointer to char

float (*ptr) [JU]; ptr is a pointer to array of array of float

float (*ptr)[](); ptr is a pointer to array of function returning float

char *(*(ptr)); ptr is a pointer to function returning a pointer to char

char (*ptr)(){]; ptr is a pointer to function returning an array of char

ptr is an array of pointer to pointer to int

char (*ptr[])[]; ' | ptr is array of pointer to array of char Valid

char (*ptr[])(); ptr is array of pointer to function returning char Valid

float *ptr[][]; ptr is array of array of pointer to float

int arr[]()[]; arr is array of array of array of int

(Contd)
Pointers | 267 |

(Contd)

. Meaning /

int arr{][](); arr is array of array of function returning int .


float *arr[](); arr is array of function returining pointer to float

int arr{]()(]; arr is array of function returning array of int


float **func(); func is a function returning pointer to float pointer (or pointer to float)
char *func()[]; func is a function returning array of char pointer

float (*func())[]; func is a function returning pointer to array of float


float (*func())\); func is a function returning pointer to function returning float

char func()(][]; func is a function returning array of array of char

char func()[](); func is a function returning array of array of function returning char

char *func()(); func is a function returning function returning char pointer


Case Study
forChapters6and7

In C language, a string is nothing but a null-terminated int option,m, n, length=0;


character array and a pointer is a variable that contains olllnacrerad
)) 5

the memory location of another variable. Therefore, a do

pointer is a variable that represents the location of a data {


item such as a variable or an array element. printf("\n 1.
it Enter the string");

Pointers provide an alternate way to access individual jonesuoteie (WUNiel A,


Zz 1DApoileyy tela) e\ereinate
(|!) +

elements of the array and they are used to pass arrays printf("\n [Link] two strings") ;

and strings as function arguments. Now utilize all these printf("\n 44. Copy n characters from m* h
position") ;
concepts to write a program that performs various
printf("\n 5. Calculate length of the
operations on a string (using pointers).
Gieiartares!)s
1. Write a menu-driven program to read the following
printf ("\n 6. Count the number of upper
Operations: 1. a string, 2. display the string,
case, lower case, numbers, and special
3. merge two strings, 4. copy n characters from
characters") ;
the mth position, 5. calculate the length of the
printf ("\n 7. Count the number of words,
string, 6. count the number of upper case, lower lines, and characters") ;
case, numbers and special characters, 7. count the printf("\n 8. Replace, with ;");
number of words, lines and characters, 8. replace, jonenuinyene (UNGal GS)5 inpciga
hl) 2
with; 9. exit.
#include <stdio.h> printf ("\n\n Enter your option: ");
#include <string.h> scané ("sd", &option) ;
#include <conio.h>
switch (option)
void read str(char *my_str);
{
void display str(char *my_str);
case 1:
void merge str(char *my_strl, char *my_str2,
fflush (stdin) ;
Charzqesimyestr3s));
OAC
teal (Site tail)yp:
void copy(char my _str1[],
int m, int n);
break;
int cal len(char my str]);
GZEOQ Be
void count (char my str[]);
display str(str1) ;
void count _wlc(char my_str[])j;
break;
VOrdereplacesstn (char Ayes)
Casemer
int main ()
BEAU
Ser (Sica),
{
merge _str(strl,
str2, merged_str) ;
char str1 [100], sex2 1100], merged str [200],
break;
copy_str[100];
Case Study for Chapters 6 and 7 | 269 |
case 4: void copy(char my _str1[],
int m, int n)
printf ("\n Enter the position from
{
which to copy the text: ");
int 2=30%
scanf("%d", &m); char *pstr;
printf ("\n Enter the number of Dini Cue nemCOpMeClmS b aiticmeic cmmun)
a
characters to be copied: ");
while(i <n || my_str1[m] !=’\0’)
scanf("%d", &n);
{
Gejoy7 (Sicrsils ving vie)5
*pstr = my stri[m] ;
break;
m++;i++;
case 5:
joneatioheue
(MEXGII |cayoysiene’)) 5
length = cal_len(str1) ;
printf ("\n The length of the
string is: %d", length) ;
break;
iia Cad aeheni(Clicliaanilyancsitsiaele)
SasenG:
{ char *str = my_str;
Counta(Sicris)\e
int len = 0;
break;
while(*str != =\0?)
case 7:
count wlc(str1) ;
{
str++;
break;
len++;
Case 8:
meplacemsits (Sttsd)i;
}
return len;
break;
}
}while (option != 9);
return 0;
void count (char my_str[])
{
char *pstr = my str;
void read_str( char *my_str)
int upper case = 0, lower_case = 0, numbers
{ = 0, spcl_char = 0;
fflush (stdin) ;
while (*pstr != ‘\0’)
printf ("\n Enter the string: ");
gets
(my str); {
use (Bjoeiere Se WAT ES osicie qa 1%”)
upper _case++;
else if (*pstr >= ‘a’ && *pstr <= ‘z’)
void display _str(char *my_ str)
lower _case++;
{ elisesil (Gpsth >=) SOURS cep sitcia<—sao)
numbers++;
jonassonere (Nin Years hereatialey alfaie. VE
else
while(*my_str != ‘\0’)
spel char++;
{
pstr++;
joamiaese
(ely cara rsieng) i;
my str++; }
printf ("\n Upper case character = %d",
upper case) ;
printf ("\n Lower case character i] x Qu

void merge_str(char *my_str1, char *my_str2, lower case) ;


printf ("\n Numbers = %d", numbers) ;
char *my_str3)
printf ("\n Special characters = *d", spel _
{
strcpy (my_str3,my_str1l); char);

strcat (my_str3, my_str2); }


display _str(my_str3) ;
void count _wlc(char my_str[])
|270 | Introduction to C Programming

{ Output
char *pstr = my_ str;
1. Enter the string
int words =1, lines =1, characters = 1;
Display the string
while(*pstr != ‘\0’)
Merge two strings
{ Copy n characters from mth position
Hs (ejeysien” Se. Y\in))
Calculate length of the string
lines++;
DN
FW
Nn Count the number of upper case, lower
sae (wisi Ge YY ee (ity Sinan) ee 8)
case, numbers, and special characters
words++;
7. Count the number of words, lines, and
characters++; t
characters
PSELr++;
8. Replace, with;
} 5 ERNIE
printf ("\n Number of words = %d", words) ;
Enter your option: 1
printf ("\n Number of lines = %d", lines) ;
Enter the string: Hi
printf ("\n Number of characters = %d",
characters) ;
Enter the string
} Display the string
Merge two strings
void replace _str(char my _str[]) Copy n characters from mth position
{ Calculate length of the string
char *pstr=my_str;
FF
HB
Nom
WN Count the number of upper case, lower
while (*pstr != *\07)
case, numbers and special characters
{ 7. Count the number of words, lines and
sie (ogeIe Se YD)
characters
PVOFENENG) ee op
8. Replace, with;
pstr++;
CO) JDCIMIE
} Enter your option: 3
display str(my str); Enter the string: there
The string is Hi there
CHAPTER

‘Structure, Union, and Enu


merated
Data Types

Takeaways
e Structure Declaration, Initialization e Nested Structures
and Access
e Structures and Functions — e Self Referential Structures
° Unions Within Structures © Enumerated Data Types

data_type var-name;

A structure is similar to records. It stores related ns


information about an entity. Structure is basically a user- For example, if we have to define a structure for a
defined data type that can store related information (even student, then its related information probably would be:
of different data types) together. The major difference roll number, name, course, and fees. This structure
between a structure and an array is that, an array contains can be declared as,
related information of the same data type.
struct student
A structure is, therefore, a collection of variables under
{
a single name. The variables within a structure are of
ia. enor
different data types and each has a name that is used to
char name [20];
select it from the structure.
char course [20];
float fees);
8.1.1 Structure Declaration
is
_ Programming Tip: A structure is declared using the
Now, the structure has become a user-defined data
Do not forgetto keyword struct followed by a
type. Each var-name declared within a structure is called
place a semicolon structure name. All the variables
a member of the structure. The structure declaration,
after thedefinition of the structure are declared
however, does not allocate any memory or consume
_ within the structure. A structure
storage space. It just gives a template that conveys to the C
' type is generally declared by
compiler how the structure is laid out in memory and gives
using the following syntax:
details of the member names. Like any other data type,
Struce-struct=name memory is allocated for the structure when we declare a
{ variable of the structure. For example, we can define a
data_type var-name;
variable student by writing,
|272 | Introduction to C Programming

struct student stud1; Example 8.2 Declare a structure to store customer


information.
Here, struct student is a data type and studi is a
variable. Look at another way of declaring variables. In struct customer
the following syntax, the variable is declared at the time {
of structure declaration. ime cust 1d;
char name [20] ;
struct student char address [20] ;
{ long int phone_num;
aGgie iqgelo)s int DOB; t

char name [20]; yi


char course [20];
Example 8.3 Declare a structure to store information of a
float fees;
particular date.
}stud1, stud2;
struct date
In this declaration we declare two variables studi and { .
stud2 of the structure student. So if you want to declare int day;
more than one variable of the structure, then separate the int month;
variables using a comma. int year;

When we declare variables of the structure, separate by


memory is allocated for each variable. This is shown in
Pig. SA. Example 8.4 Declare a structure to store information of a
particular book.
struct BOOK

{
char title[20];
char author [20];
int pages;
float price;
int yr of publication;

8.5 Declare a structure to create an inventory


record.

struct inventory
{
char prod_name [20];
float price;
int stock;
Figure 8.1 ‘Memory allocation fora structure variable
Ve

Let us see some more structure declarations.


: Note

Example 8.1 Declare a structure to store information about


a point in the coordinate system.

struct point
Last but not the least, structure member names and
{ names of the structure follow the same rules as laid down
AGE. Sp Wes
for the names of ordinary variables. However, care should
};
be taken to ensure that the name of structure and the name
Structure, Union, and Enumerated Data Types _| 273 |

of a structure member should not be the same. Moreover, Note that we have not written struct student studl.
structure name and its variable name should also be
different.
8.1.3 Initialization of Structures
A structure can be initialized in the same way as other
8.1.2 Typedef Declarations
data types are initialized. Initializing a structure means
_ The typedef (derived from type assigning some constants to the members of the structure.
_Prograr m [ :Ti: _ definition) keyword enables the When the user does not explicitly initialize the structure,
programmer to create a new data then C automatically does that. For int and float
type name for an existing data members, the values are initialized to zero and char and
type. By using typedef, no new string members are initialized to the ‘\o’ by default (in
data is created, rather an alternate the absence of any initialization done by the user).
- name is given to a known data The initializers are enclosed in braces and are separated
type. by commas. However, care must be taken to see that the
__ The’general syntax of using the initializers match their corresponding types in the structure
. | typedef keyword is given as: definition.
typedef existing data type The general syntax to initialize a structure variable is
new data_type given as follows:
struct struct_name
Note that typedef statement does not occupy any
memory, it simply defines a new type. For example, if we
data_type member namel;
write data_type member name2;
typedef int INTEGER; data_type member name3;

then INTEGER is the new name of data type int. To declare }struct_var = {constantl,
variables using the new data type name, precede the Constant 35...)
variable name with the data type name (new). Therefore,
OR
to define an integer variable, we may now write
rogramming g Tir struct struct_name
INTEGER num=5; Itis an error
assign a structure / data_type member namel;
When we precede a struct name with typedef data_type member _name2;
keyword, then the struct becomes a new type. It is data_type member _name3;
a structure of .
used to make the construct shorter with more meaningful
another type
names for types already defined by C or for types that you
have declared. A typedef declaration is a synonym for the
type. For example, writing struct struct_name struct _var = {constantl,
constant2, constant 3,...};
typedef struct student
{ For example, we can initialize a student structure by
sume: Ge.
NO) writing
char name[20] ;
struct student
char course [20];
float fees;
{
wie, 14ING)E
he
char name [20];
Now that you have preceded the structure’s name char course [20] ;
with the keyword typedef, the student becomes a new float fees;
data type. Therefore, now you can straightaway declare }stud1 = {01, "Rahul", "BCA", 45000};
variables of this new data type as you declare variables of or by writing
type int, float, char, double, etc., to declare a variable
struct student studl “= {01, "Rahul", ."BCA",
of structure student you will just write,
45000};
student studl1;
|274 | Introduction to C Programming

Figure 8.2 illustrates how the values will be assigned to printf ("%£", [Link]);

the individual fields of the structure. Memory is allocated only when we declare variables
of the structure. In other words, memory is allocated only
when we instantiate the structure. In the absence of any
variable, structure definition is just a template that will be
used to reserve memory when a variable of type struct is
declared.
Once the variables of a structure are defined, we can
perform a few operations on them. For‘example, we can
use the assignment operator ‘=’ to assign the values of
one variable to another.

Note Ofall the operators —> a and [] have —


the highest priority. This is evident from
Assigni ng values to structure elements '
the following statement:
When all the members of a structure are not initialized,
stud. feess4 will be interpreted as
it is called partial initialization. In case of partial - ([Link]) ++ :
initialization, first few members of the structure are
initialized and those that are uninitialized are assigned
default values. 8.1.5 Copying and Comparing Structures
We can assign a structure to another structure of the same
8.1.4 Accessing the Members of a Structure type. For example, if we have two structure variables
Each member of a structure can be used just like a normal ou studl and stud2 of type
variable, but its name will be a bit longer. A structure pee s me _ struct student given as,
_Anerrorwilbe =
member variable is generally accessed using a ‘. ’ (dot) generated ifyou | Struct student studi =
operator. The syntax of accessing a structure or a member try to compare two {01 »i#RahulticstBGAr
of a structure can be given as: "structure variables. | 45000};
struct student stud2;
struct_var.member_
name
Then to assign one structure variable to another we will
The dot operator is used to select write,
a particular member of the struc- Stud2 = Scud;
_ ture. For example, to assign value This statement initializes the members of stud2 with
to the individual data members of the values of members of studi. Therefore, now the
the structure variable studi, we values of studi and stud2 can be given as shown in
“use thestructure = may write,
name followed by
Fig..3.3.

the dot Operator ee Oe


: beforespecifying i [Link] = "Rahul";
- truct student studl
t [Link] = "BCA"; = (01,“"Rabul", “BCA,
oo
[Link] = 45000;

To input values for data members of the structure “name : course — rae/-
variable stud1, we may write,
“struct student stud2 = stud1;
scanf("%d", &studl.r_no);
scanf("%s", &[Link]);

Similarly, to print the values of structure variable : name : FOvree oe

studl1, we may write,


Figure 8.3 WA SRE s2 “ oy
printf ("%s", [Link]);
Structure, Union, and Enumerated Data Types | 275 |

C does not permit comparison of one structure ROLL No. = 01


variable with another. However, individual members of NAME = Rahul
one structure can be compared with individual members FEES = 45000.00
of another structure. When we compare one structure DOB = 25-09-1991

member with another structure’s member, the comparison


8.2 Write a program, using structures, to find the biggest
will behave like any other ordinary variable comparison.
of three numbers.
For example, to compare the fees of two students, we will
write, #include <stdio.h>
if ([Link] > [Link]) #include <conio.h>
Fees of studl is greater than stud2 int main()

8.1 Write a program using structures to read and display {


struct numbers
the information about a student.
{
#include <stdio.h> aes cl, Jo), (els
#include <conio.h> int largest;
int main () ie
{ struct numbers num;
struct student CliesGin();
{ printf ("\n Enter the three numbers: ");
auahe wetollil into}; scant ("Sd %d %d", &num.a, &num.b, &num.c);
char name [80]; if (num.a > num.b && num.a > num.c)
float fees; [Link] = num.a;
char DOB[80]; if (num.b > num.a && num.b > num.c)
ie [Link] = num.b;
struct student stud1; if (num.c > num.a && num.c > num.b)
elrscr();
[Link] = num.c;
printf ("\n Enter the roll number: ");
printf("\n The largest number is: %d",
scanf("%d", &Studl.roll_no);
num. largest);
printf ("\n Enter the name: ");
getch();
scanf("%s", [Link]);
return 0;
printf ("\n Enter the fees: "); }
scanf("%f£", &[Link]);
printf("\n Enter the DOB: "); Output
scanm("ss"7 studi. DOB); Enter the three numbers: 7 9 1
peinee(" \n kkKKKKKKSTUDENT’S DETAILS The largest number is: 9
KKKKKK KN)

PEtme
i ( Nie ROMGNOn = sal Studi. rolleno)); 8.3 Write a program to read, display, add, and subtract
printf ("\n NAME = %s", [Link]); two complex numbers.
Dain! nh ou=—ot" Studilanees)),
#include <stdio.h>
painter (\neDOB = ios", Studi. DOB);
#include <conio.h>
getch (); int main ()
return 0; {

} typedef struct complex

Output {
int real;
Enter the roll number: 01
int imag;
Enter the name: Rahul
}COMPLEX ;
Enter the fees: 45000
COMPLEX cl, c2, sum_c, sub_c;
Enter the DOB: 25-09-1991
kk *KKKKEKSTUDENT’S DETAILS ******* int option;
|276 | Introduction to C Programming

elrsexri(): Read the complex numbers


do Display the complex numbers
Add the complex numbers
{
printf ( ("\n *** MAIN MENU ***"); Subtract the complex numbers

printf("\n 1. Read the complex nos."); PF


Om
WN EXIT
(
Enter your option: 1
printf ( ("\n 2. Display
the complex nos.");
Enter the real and imaginary parts of the
printf ("\n 3. Add the complex nos.");
first complex number: 2 3
printf ("\n4. Subtract
the complex nos.");
Enter the real and imaginary parts of the
jopenhohese
(UN ay by indicate");
second complex number: 4 5 ;
printf ("\n Enter your option: "); kkKKKKEKK MATN MENU KKKKKKKEKK

scanf("%d", &option);
1. Read the complex numbers
switch (option) Display the complex numbers
{ . Add the complex numbers
Casen: Subtract the complex numbers
printf ("\n Enter the real and imaginary B®
Om
ND
W EXIT

parts of the first complex number: ") ; Enter your option: 3


scanf ("$d $d", &[Link], &[Link]); The sum of two complex numbers is: 6 + 8i

printf ("\n Enter the real and imaginary 8.4 Write a program to enter two points and then calculate
parts of the second complex number: ") ; the distance between them.
scanf ("3d %d", &[Link], &[Link]);
break; #include <stdio.h>

case 2:
#include <conio.h>
#include<math.h>
printf ("\n The first complex number is:
int main()
$d+%di", [Link], [Link]);

printf ("\n The second complex number is:


{
typedef struct point
$d+%di", [Link], [Link]);
{
break;
sate o,, WWep
case 3: }POINT;
SuMmC rea le— Clr reall C2 real, IHOMGNIE jodi
7 e)A 5
sum_c.imag=[Link]+[Link]; float distance;
printf ("\n The sumof two complex numbers clinsexi();
is: sd+%di", sum_c.real, sum_c.imag); printf("\n Enter the coordinates of the
break; izakietsie, Goloulboiae |)

case 4: scanf ("Sd Sd", &pl.x, &pl.y);


printf("\n Enter the coordinates of the
Subs GOareala= ciyyreali—.c2
oneal ;
second point: ");
sub_c.imag=[Link];
scanf ("$d %d", &p2.x, &p2.y);
printf ("\n The difference
between two
distance = sqrt (pow((pl.x - p2.x), 2) +
complex numbers is: d+ %di",
pow((pl.y - p2.y), 2));
sub _c.real, sub_c.imag);
printf("\n The coordinates of the first
break;
jonas ugg, Kaobe Tish, jolame, jollkay)p
} printf ("\n The coordinates of the second
}while (option |!= 5); point anew sds dye Aor, 2 ave
getch ();
printf ("\n Distance between pl and p2 =
return 0;
%£", distance);
} getch ();
return 0;
Output
KaKKKKKKK MAIN MENU KkKKKKKKKK
Structure, Union, and Enumerated Data Types | 277 |

Output yy, which specify the day, month, and year of the date. To
Enter the coordinates of the first point: 2 3 assign values to the structure fields, we will write,
Enter the coordinates of the second point: 9 9 student stud1;
The coordinates of the first point are: 2x 3y [Link].first_name = "Janak";
The coordinates of the second point are: 9x 9y [Link].mid_
name = "Raj";
Distance between pl and p2 = 9.219544 [Link].last_
name = "Thareja";
[Link] = "BCA";
SHEKollh IDOI Ciel cs tsy
‘RUCTURES [Link] = 09;

A structure can be placed within another structure, i.e., a Studi.


DOB yy = 2990);

structure may contain another structure as its member. A [Link] = 45000;

structure that contains another structure as its member is In case of nested structures we use the dot operator
called a nested structure. in conjunction with the structure variables to access
Let us now see how we declare nested structures or the members of the innermost as well as the outermost
structures that contain structures. Although it is possible structures. The use of nested structures is illustrated in the
to declare a nested structure with one declaration, it is not following program:
recommended. The easier and clearer way is to declare
8.5 Write a program to read and display information of a
the structures separately and then group them in a high-
student, using a structure within a structure.
level structure. When you do this, take care to check that
nesting must be done from inside out (from lowest level to #include <stdio.h>
the most inclusive level), i.e., to say, declare the innermost #include <conio.h>
structure, then the next level structure, working towards int main ()

the outer (most inclusive) structure. {


struct DOB
typedef struct
{
{ int day;
char first_name[20] ;
int month;
char mid_name[20] ;
int year;
char last_name [20];
}NAME; yi;
struct student

typedef struct {
igh 1godkibsineyy
{
int ddy char name[100];

int mm; float fees;

Me. WAue struct DOB date;

}DATE; i
struct student studl;
typedef struct student Giese0).

‘ printf ("\n Enter the roll number: ");


sunk Ge)
Mey scant ("%d", &stud1.roll_
no);
NAME name; printf("\n Enter the name: ");
char course [20] ; scanf("%s", [Link]);
DATE DOB; printf("\n Enter the fees: ");
float fees; scanf("S£", &[Link]);
Le printf ("\n Enter the DOB: ");
In this example, we see that the structure student in scanf("%d %d dad", &[Link],

turn contains two other structures—NAME and DATE. Both &[Link], &[Link]);
these structures have their own fields. The structure NAME pLinté ("\n *** STUDEND’S DETALES +>);

has three fields: first name, mid_name, and last_name. pEiInte (en ROLL NO ws=—od" iS elcHa sOkIEn@)) i
The structure DATE also has three fields: dd, mm, and printf ("\n NAME = %s", [Link]);
|278 | Introduction to C Programming

print£ ("\n FEES = %f£", [Link]); data_type member_name3;


jepersghesa (Niel IDO txel = cel — exes “heibiolal
[Link], [Link], [Link]. Me
year); struct struct_name struct_var [index] ;

getch (); Consider the given structure definition.


return 0;
struct student
} {
age. 1619YO),
Output
char name [20]; ‘
Enter the roll number: 01
char course [20];
Enter the name: Rahul
float fees;
Enter the fees: 45000
ia
Enter the DOB: 25 09 1991
KKKKKKKKOTUDENT’S DETAILS KKKEKKKE
A student array can be declared simply by writing,
ROLL No. = 01 student stud[30];
NAME = Rahul
Now, to assign values to the ith student of the class, we
FEES = 45000.00
will write,
DOB NS e25-09-1997
Studi[i
| rinos="09;

8.3 AR
stud[i].name = "RASHI";
stud[i] .course = "MCA";
stud[i].fees = 60000;
In the above examples, we have seen how to declare a
structure and assign values to its data members. Now we In order to initialize the array of structure variables at
will discuss how to declare an array of a structure. For this the time of declaration, you should write as follows:
purpose, let us first analyse, where we would need array student stud[3] = {{01, "Aman", "BCA",
of structures. 45000},{02, "Aryan", "MCA", 60000}, {03,
In a class, we do not have just one student. But there "John", "BCA", 45000}};
may be at least 30 students.
8.6 Write a program to read and display the information
Programming Tip: So the same definition of the
of all the students in the class.
Itis an: structure can be used for all
#include <stdio.h>
the 30 students. This would be
#include <conio.h>
possible when we will make an
int main()
array of the structure. An array of
{
a structure is declared in the same struct student
way as we had declared an array {
of a built-in data type. sale ageyllil saves
Another example, where an array of structures is desir- char name [80];

able, is in case of an organization. An organization has a int fees;

number of employees. So, defining a separate structure for char DOB[80];


every employee is not a viable solution. So here we can Ve
struct student stud[50];
have a common structure definition for all the employees.
Tigheigl~= abe
This can again be done by declaring an array of the struc-
Gilsaciene
(()
ture employee.
printf ("\n Enter the number of students: ");
The general syntax for declaring an array of a structure
scanf ("%d", &n);
can be given as, for(i = O;1 < n;i++)
struct struct_name {
{ printf("\n Enter the roll number: ");
data_type member _name1; scanf ("d", &Sstud[i] .roll_no);
data_type member name2; fflush (stdin);
Structure, Union, and Enumerated Data Types | 279 |

printf("\n Enter the name: "); {


gets (stud [i] .name); struct student
£flush (stdin); {
printf("\n Enter the fees: "); int roll_no;
scanf ("%d", &stud[i]
. fees); char name [80];
fflush (stdin); int fees;
printf("\n Enter the DOB: "); char DOB[80];
gets (stud [i] .DOB); };
fflush (stdin); struct student stud[50];
} int n, i, rolno, new_rolno;
fOr (Gs=" Ora) <1 ) y int new fees;
{ char new _DOB[80],
new name [80];
printf ("\n ********DETAILS OF STUDENT clrscr ();
BU eke My eal1); printf("\n Enter the number of students: ");
printf ("\n ROLL No. = $d", stud[i]. scanf ("%d", &n);
roll_no); , for(i = 0;i < n;i++)
printf ("\n NAME = $s", stud[i] .name); {
printf ("\n FEES = $d", stud[i] .fees); printf ("\n Enter the roll number: ");
printf ("\n DOB = $s", stud[i] .DOB); scanf("%d", &stud[i] .roll_no);
} fflush (stdin);
getch (); printf("\n Enter the name: ");
return 0; gets (stud [i] .name);
} fflush (stdin);
printf("\n Enter the fees: ");
Output scanf ("$d", stud[i]
.fees);
Enter the number of students: 2 fflush (stdin);
Enter the roll number: 1 printf ("\n Enter the DOB: ");
Enter the name: kirti gets (stud
[i] .DOB);
Enter the fees: 5678 fflush (stdin);
Enter the DOB: 9 9 91 }
Enter the roll number: 2 fOr (Ga=— Opa Taya)
Enter the name: kangana {
Enter the fees: 5678 printf ("\n ********DETAILS OF STUDENT
PNtercetne DOB. 27-3 Oi! SARK" G41);
KXKEKKEKDETATLS OF STUDENT 1******* jongationere (Wa) ING; Woy, = wel, sieuiel((m))
ROLL No. = 1 Fold eno) 7
NAME = kirti printf ("\n NAME = %s", stud[i] .name);
FEES = 5678 printf ("\n FEES = %d", stud[i] .fees);
IDG. S 3) -S) Sab pranté ("\n) DATE, OF BIRTH )=)%s",
**kKKKKEXDETAILSG OF STUDENT 2******* stud [i].DOB);

ROLLE No; = 2 }

NAME = kangana printf ("\n Enter the roll no. of the


FEES = 5678 student whose record has to be edited: ");
Der ie i Brae scan£t ("%d", &rolno);

8.7 Write a program to read and display the information Print’ (i Entesither new) cold aunber ane);
scanf ("%d", &new_rolno);
of all the students in the class. Then edit the details of
printf ("\n Enter the new name: ");
the ith student and redisplay the entire information.
scanf("%s", new_name);
Hinclade <stdio
b> printf("\n Enter the new fees: ");

#include <string.h>
scanf("%d", &new fees);
printf ("\n Enter the new date of birth: ");
#include <conio.h>
int main() scanf ("%s", new DOB);
|280 introduction to C Programming

stud [rolno].roll
no = new_rolno; ROLL, Nos" =22
strcpy (stud[rolno].name, new_name); NAME = kangana
stud [rolno].fees = new fees; FEES = 7000
strcpy (stud [rolno] .DOB,new DOB); DOB = 27 8 92
for (1=0;i<m; i++)

printf ("\n ********DETAILS OF STUDENT 8.4 STRUCTURES AND FUNCTIONS


cy ati talacioless Nan S For structures to be fully useful, we must have a mechanism
printf("\n ROLL No. = #d", stud[i}. to pass them to functions and return them. A function may
roll_no); access the members of a structure in three ways as shown
printf ("\n NAME = ¢s", stud[i] .name); in Fig. 8.4.
printf ("\n FEES $d", stud[i]
. fees);
printf ("\n DATE OF BIRTH = <s",

stud
[i] . DOB);

Passing structures
to functions

Emter the number of students: 2

sean sIg
games sakes Passing structures toa function __
} kirti
5678
99 91 8.4.1 Passing Individual Members
ee To pass any individual member of the structure to a
5673 function we must use the direct selection operator to
Enter the DOB: 27 8 91 refer to the individual members for the actual parametres.
##******DETAILS OF STUDENT 1******* The called program does not know if the two variables
ROLL No. = 1 are ordinary variables or structure members. Look at the
NAME = Kirti following code that illustrates this concept.
noRB =99 91 #include <stdio.h>
Heee**LEDETAILS OF STUDENT 2*****%% typedef struct

ROLL No. = 2 {
NAME = kangana coke si)
= Hine, Vis
FEES = 5678
}POINT;
DOB = 27 8 91
Enter the roll number. of the student whose Void 'Gheplavitent, ine);
main ()
record has to be edited: 2
Enter the mew roll number: 2 {
POINT -p1..= {2; 3};
Enter the new name: kangana khullar
display (p1.x, pl.y);
Enter the new fees:
hh 7000
Enter the new date of birth: 27 8 92 eee a!
#eee2***DETAILS OF STUDENT 1******* }
ecni? Ne z void display(int a, int b)
Ei/isls IN => +

NAME = kirti {
pers = 5678 printf ("The coordinates of the point are:
—s Ne Fal sd 3d",
a, b)-
DOR = 39 9 YL

###£*"**DETAILS OF STUDENT 2***#*** }


Structure, Union, and Enumerated Data Types | 281 |

Output }DISTANCE ;
DISTANCE add_distance (DISTANCE, DISTANCE);
The coordinates of the point are: 2 3
DISTANCE subtract _distance (DISTANCE,
DISTANCE);
8.4.2 Passing the Entire Structure DISTANCE dl, d2, d3, d4;
int main()
Just like any other variable, we can pass an entire structure
as a function argument. When a structure is passed as an {
int option;
argument, it is passed using the call by value method, i.e.,
Giisseni()>
a copy of each member of the structure is made. This is do
a very inefficient method especially when the structure
{
is very big or the function is called frequently. In such a printf ("\n *** MAIN MENU ***");
situation passing and working with pointers may be more printf("\n 1. Read the distances ");
efficient. printf("\n 2. Display the distances");
The general syntax for passing a structure to a function printf("\n 3. Add the distances");
and returning a structure can be given as, printf("\n 4. Subtract the distances");
jonesniatene (Win 5 iam).
struct struct_name func_name(struct struct_
printe ("\neEntertyourmoptronta);
name struct _var); 1 $d", &option);
This syntax can vary as per need. For example, in some switch (option)
situations we may want a function to receive a structure {
but return a void or value of some other data type. The Casenii:

following code passes a structure to the function using the printf ("\n Enter the first distance in
kms and metres:
");
call by value method.
scant ("3d %d", &[Link], &[Link]);
#include <stdio.h>
printf ("\n Enter the second distance
typedef struct
kms and metres: ");
{ scant ("Sd $d", &[Link], &[Link]);
Stine SE
break;
nbraes Sve
Gase 2:
}POINT; printf("\n The first distance is: %d
void display (POINT);
kms *d metres",
[Link], [Link]);
main ()
printf ("\n The second distance is: %d
{ kms @d metres",
[Link], [Link]);
POINT pl = {2, 3};
break;
display (p1);
Casemon
return 0;
d3y=saddedistance(ditad2));
} printf ("\n The sum of two distances
void display (POINT p)
is: ¢d kms %d metres", [Link], [Link]);
{ break;
jougatiaye
se (Pel Gel Goar<, aw
case 4:
d4 = subtract distance (dl, d2);
printf("\n The difference between two
8.8 Write a program to read, display, add, and subtract distances is: *d kms %d metres", [Link],
two distances. Distance must be defined using kms [Link]);

and metres. break;

}
#include <stdio.h> }while (option != 5);
#include <conio.h> getch ();
typedef struct distance Geturnm (0);

}
int kms; DISTANCE add_ distance (DISTANCE d1, DISTANCE d2)
int metres;
282 Introduction to C Programming


8.9 Write a program, using pointer to structure, to
initialize the members in the structure. Use functions
tT fj i cr ny wD ah iT] jenied a ct a] a) VF) 4 QuNo 3 a) cr KK a) 10)
to print the student’s information.
#include <stdio.h>
#include <conio.h>
struct student
[Link] = [Link]%1000;
[Link] += 1; {
Ines TrNO;
char name [20];
char course [20];
float fees;
DISTANCE subtract distance (DISTANCE dl,
DISTANCE d2) ie
void display(struct student *);
main ()
DISTANCE sub;
if ([Link] > [Link]) {
Stnuct student *prer studl; ig
os

[Link] = [Link] - d2. metres;


struct student studl = {01, "Rahul",

[Link] = [Link] —- [Link]; "BCA", 45000};


clrscr
();
ptr_studl = &studl;
display (ptr_stud1);
[Link] = [Link] - dl. metres; return 0);
[Link] = [Link] - [Link]; }
void display(struct student *ptr_stud1)

{
printf("\n DETAILS OF STUDENT");
printf£("\n -----------------------=----- );
printf ("\n ROLL NO. =%d", ptr studi —>\r no);
printf ("\nNAME =", puts (ptr_studl1
— name) );
printf ("\n COURSE =", puts (ptr_stud1— course) );
printf ("\n FEES = $£", ptr _studl1 —> fees);
Output }
SERRE EESE MA N MENU we
Output
Lt. Read the distances
DETAILS OF STUDENT
2. Display the distances
3. Add the distances
ROLL NUMBER = 01
4. Subtract the distances
5. EXIT NAME = Rahul

a) i a 1) ' JF ue}(a bh oO 3] te
COURSE = BCA
oo FEES = 45000.00

Enter the secont distance in kms and metres: 8.10 Write a program to read, display, add, and subtract
two time defined using hour, minutes, and values of
seconds.

#include <stdio.h>

#include <conio.h>
4. Subtract the distances
5. EXIT
typedef struct
Drrer
Beer
torr
your
omrtion-
Opcion: W {
=
The sum of two distamces is: 8 kms 700 metres shale wleaen
Structure, Union, and Enumerated Data Types | 283 |
int min; }

int sec; }while (option != 5);


}TIME; getch ();
TIME C1 V2 /°t3:/' 45 return 0;
TIME subtract time(TIME, TIME); }
TIME add_time (TIME ed. WA YI {e2))
TIME add_time (TIME, TIME);
{
int main()
TIME sum;
{ [Link] = [Link] + [Link];
int option; while([Link] >= 60)
clrscr (); {
do [Link] —=60;
{ [Link]++;

printf("\n **** MAIN MENU *****"), }


printf ("\n 1. Read time ") [Link] = [Link] +[Link];
printf ("\n 2. Display time"); while([Link] >= 60)
printé ("\n 3. Addi"); {
DPismies (UNA SU tica cia). Ba ome
prince (“\n"S. EXIT") gens ee
printf("\n Enter your option: "); }
Sioialgke 3 weal Joke <b ee loves
scanf("%d", &option);
return sum;
switch (option)
}
TIME subtract_time (TIME tl, TIME t2)
CGasenik: {
printf ("\n Enter the first time in TIME sub;
hrs, mins, and secs: "); TEM eet ne)
scanf ("4d %d%d", &[Link], &[Link], &[Link]); {

fflush (stdin); if([Link] < [Link])


printf("\n Enter the second time in {
hrs, mins, and secs: "); t1.sech4= 60:
scanf ("S$d%d%d", &[Link], &[Link], &[Link]); [Link]--;
fflush (stdin); }

break; [Link]) = [Link].— [Link];


case 2: ae (od ui <b [Link])
printf ("\n The first time is: %d hr %d {
MinesGdssecly til hr [Link],
tladec): [Link] += 60;
printf ("\n The second time is: %d hr tl .hr--;
[Link] sec". b2 shi, 22min, t2)-sec}): }
break; subzmin )= ti mine- [Link];
case 3: SUlopign site giganto uence

t3 = add time(t1, t2); }


printf ("\n The sum of the two time else
values is: tdhr %*dmin %dsec", [Link], {
if ([Link] <’[Link]éc)
SMM
A to see);
break; {
[Link] += 60;
case 4:
[Link]--;
t4i=wsubtractitimei(tl;\t2)
printf£("\n The difference in time
}
[Link] = [Link] - [Link];
is: $d hr $d min %d sec", [Link], [Link], wteconi Bwana

[Link]); {
break;
|284 | Introduction to C Programming

[Link] += 60; types. It is extremely common


[Link]--; to create pointers to structures.
Like in other cases, a pointer to a
[Link] = [Link] - [Link];
structure is never itselfa structure,
Ciloj slabs fe wa sins > jell, wlaka’y
_ but merely a variable that holds
} I-by-va the address of a structure. The
return sub;
7 syntax to declare a pointer to a
}
structure can be given as,
Output struct struct_name ,
KKKKKKKK MAIN MENU *****¥*¥***
{
1. Read time data_type member namel;
2. Display time data_type member name2;
3. Add two time data_type member _name3;
4. Subtract two time
yp 1 GEG
Enter your option: 1
OR
Enter the first time in hrs, mins, and secs:
PX M0} AHO) SEDUCE SELUCE Name *per;

Enter the second time in hrs, mins, and For our student structure we can declare a pointer
secs; 3 20 30 variable by writing,
KkKKKKKKK MATN MENU **¥*****R*

SErUCcERSeGUudenE Apenistudyeseud,
1. Read time
. Display time The next thing to be done is to assign the address of
. Add stud to the pointer using the address operator (&) as we
. Subtract would do in case of any other pointer. So to assign the
ND
WwW
fF
oO EXIT address, we will write
Enter your option: 3
ptr stud = «stud;
The sum of the two time value is: 5 hr 50
min 50 sec To access the members of the structure, one way is to
write,
Let us summarize some points that must be considered
while passing a structure to the called function. /* get the structure, then select a member */
GpeaEstud) muelimno:
e If the called function is returning a copy of the
Since parenthesis have a higher precedence than *,
entire structure then it must be declared as struct
writing this statement would
followed by the structure name.
work well. But this statement is
e The structure variable used as parameter in the _ The selection
a not easy for a beginner to work
function declaration must be the same as that of operator (—>)is with. So C introduces a new
the actual argument in the called function (and that operator to do the same task.
should be the name of the struct type). This operator is known as the
e When a function returns a structure then in the calling | pointing-to operator (—>). Here
function the returned structure must be assigned to a it is being used:
structure variable of the same type. /* the roll_no in the structure, ptr stud
jstenliakers! (ele) =3//
8.4.3 Passing Structures Through Pointers peLEstudi—Sirollsno: = 01;

Passing large structures to function using the call by value This statement is far easier than its alternative.
method is very inefficient. Therefore, it is preferred to 8.11 Write a program, using a pointer to a structure, to
pass structures through pointers. It is possible to create initialize the members in the structure.
a pointer to almost any type in C, including user-defined #include <stdio.h>
Structure, Union, and Enumerated Data Types | 285 |

#include <conio.h> Enter the Name = Aditya


struct student Enter the Course = MCA
{ Enter the Fees = 60000
intiez§ OF
char name [20]; DETAILS OF FIRST STUDENT
char course [20];
int fees; ROLL NUMBER = 01
F NAME = Rahul
COURSE = BCA
main () FEES = 45000.00

{
DETAILS OF SECOND STUDENT
struct student studl, stud2, *ptr_studl,
*pir stud2;
ROLL NUMBER = 02
clrscr
();
NAME = Aditya
ptr _studl = &stud1;
COURSE = MCA
ptr_stud2 = &stud2;
FEES = 60000.00
DiEGestudl—>
reno Oil;
strcpy (ptr_studl1—>
name, "Rahul"); 8.12 Write a program, using a pointer to a structure, to
strcpy (ptr_studl—>course, "BCA"); initialize the members in the structure using an
PEnEScudi
> tees! = 45000) alternative technique.
#include <stdio.h>
printf ("\n Enter the details of the
#include <conio.h>
second student:");
struct student
printf("\n Enter the Roll Number =");
scanf ("d", &ptr_stud2—r_no),;
{
ahioie, 3¢i9le\f
fflush (stdin);
char name[20];
printf ("\n Enter the Name = ");
char course [20];
gets (ptr_stud2 —name);
float fees;
f£lush (stdin);
}i
printf ("\n Enter the Course = ");
gets (ptr _stud2— course); main()
fflush (stdin);
{
printf ("\n Enter the Fees = "); struct student *ptr studi;
scanf ("$d", &ptr_stud2—
fees); struct student studl = {01, "Rahul",
"BCA", 45000};
printf ("\n DETAILS OF FIRST STUDENT");
clrscr
();
printé ("\n) ---=--->-------———
---- ts
ptr_studl = &studl;
printf ("\n ROLL NUMBER = %d", ptr _studl—r_no);
printf ("\n DETAILS OF STUDENT");
printf ("\n NAME = %s", ptr _studl—name);
printf ("\n -----------<--------------=- uM).
printf ("\n COURSE = %s", ptr_studl—course);
printf ("\n ROLL NUMBER = %d", ptr _studl—r_no);
Pili UVa vetCu—mcd ep tiastudil—>
fees);
printf ("\n NAME = %s ", ptr _studl -> name);
printf ("\n\n\n\n DETAILS OF SECOND printf ("\n COURSE = $f", ptr_studl
STUDENT" ); —> course);
ET Wile n= nm ee ayy printf ("\n FEES = %£", ptr studl— fees);
printf ("\n ROLL NUMBER = %d", ptr_stud2—r_no); return 0;

printf("\n NAME = %s", ptr_stud2—>name); }


printf ("\n COURSE = %s", ptr_stud2—>course);
printf£("\n FEES = %d",.ptr.stud2—> fees); Output
DETAILS OF STUDENT
return 0;

} ROLL NUMBER = 01

Output NAME = Rahul

Enter the details of the second student: COURSE = BCA

Enter the Roll Number = 02 FEES = 45000.00


|286 | Introduction to C Programming

8.13 Write a program, using an array of pointers to a NAME: Rahul

structure, to read and display the data of a student. COURSE: BCA


FEES: 45000
#include <stdio.h>
#include <conio.h> 8.14 Write a program to read, display, add, and subtract
#include <alloc.h> two heights. Height should be given in feet and
typedef struct student inches.
{ #include <stdio.h>
Lite Oy #include <conio.h>
char name [20]; typedef struct
char course[20];
{
int fees; Tie ety
rr int inch;
struct student *ptr[10]; }HEIGHT;
main ()
HEIGHT hi, ho h3; 7
{
HEIGHT add_height (HEIGHT *, HEIGHT *);
Tit aL 7
HEIGHT subtract height (HEIGHT *, HEIGHT *);
for (i=0;1<10;1i++)
main ()
{
ptr[i] = (struct student *)malloc(size
{
int option;
of (struct student));
clrscr
();
printf("\n Enter the data for student
do
$d "i+1);
print£("\n \t ROLL NO.: ");
{
printf ("\n *** MAIN MENU ***");
secant ("sd", ‘ptr [i] —>r no)
printf("\n 1. Read height ");
popehbatess (UMGay Mek ISPs a)
printf("\n 2. Display height");
gets (ptr [i] —>name);
jopeatayese
(UINigt She. PNotell)y
DLintl
Ue \ be COURSE. all);
jonga aiese (Oa AY, YSlonereeKeie)}
gets (ptr [i] —> course);
jopenbintetay
(QUE avedsys [Link])
print£("\n \t FEES: ");
Prints ("\n Enters vour option: ):
scanf ("%d", ptr[i]
—> fees); scanf("%d", &option);
} switch (option)
printf ("\n DETAILS OF STUDENT");
{
printf ("\n --<-----<5--------20---5----- i; case 1:
for (i=0;1<10;1++) printf("\n Enter the first height in
{ feet and inches: ");
printf ("\n ROLL NUMBER = %d", scanf ("$d %d", &[Link], &[Link]);
ptr_stud[a] ->+r_no) printf ("\n Enter the second height in
printf("\n NAME = $%f", feet and inches: ");
ptr_stud[i] —>name); scanf("%Sd ¢d", &[Link], &[Link]);
print£("\n C@URSE = %f", break;
ptrestud
[1))—> course); Caseez:
printf ("\n FEES = %d", printf("\n The first height is: %d ft
ptr_stud [i] —> fees); SQ INeh" hd set, Wis tren):
} printf("\n The second height is: $d ft
return 0;
Eol Giavelnlly,
InP ete, law? seven)
} break;
Cases:
Output
h3 = add_height(&h1, &h2);
Enter the data for the student 1
printf ("\n The sum of two heights is:
ROLE NG. Y Od
sa ft sd inch)
hs. ftw hse annem;
Structure, Union, and Enumerated Data Types _| 287 |

break; 2. Display height


case 4: 3. Add
h3 = subtract_height
(&h1, &h2); 4. Subtract
printf("\n The difference of two Di, VEG
heightsrmis :id-ft: 3d Gnuechs) hs) ft, Enter your option: 1
h3 . inch); Enter the first height in feet and inches: 2 3
break ; Enter the second height in feet and inches:
} 45
}while (option != 5): keKKKKKK MAIN MENU *** eee RR

getch (); 2 1. Read height


return 0; 2. Display height
} 3. Add
HEIGHT add_height (HEIGHT *h1l, HEIGHT *h2) 4. Subtract
{ 5. EXIT
HEIGHT sum; Enter your option: 3
[Link] = hl—>inch + h2— inch; The sum of two heights is: 6 ft 8 inch
while([Link] > 12)
{ 8.15 Write a program that passes a pointer to a structure
[Link] -= 12; to a function.
sum. ft++;
} #include <stdio.h>
sum. ft = hi— ft + h2—-ft; #include <conio.h>
return sum; #include <alloc.h>
} typedef struct student
HEIGHT subtract _height (HEIGHT *h1, HEIGHT *h2) {
{ int x<no;
ee sub; char name [20];
if (hi—>£t > h2— ft) Bhar coures (201:

{ int fees;
if (hl—inch < h2— inch) os

{
hi—>ineh += 12; : ;
void display(struct student *);
hi—ft--; ;
} main ()

[Link] = hl—inch - h2— inch; {


SGRCE We hea ROSS EE: struct student *
*ptr; *
} ptr = (struct student *)malloc(sizeof
atae (struct student));
{ printf ("\n Enter the data for the student ");
if (h2—>inch < hl— inch) printf£("\n \t ROLL NO.: ")

{ scanf("%d", ptr—r_no)}
h2—>inch += 12 t printf ( " \n \t NAME: " );

h2—>ft--;
gets (ptr —> name);
} print£ ("\n"\t COURSE: “);
[Link] = h2—>inch - hl—jdinch;
gets (ptr— course);
[Link] = h2—ft - hl—ft;
} printt ("\n \t FEBS: ™);

return sub; scanf("%d", ptr—> fees);

} display (ptr);
getch ();

Quiput return 0;
kKAKKKKKE MAIN MENU ********* }

1. Read height ");


|288 | Introduction to C Programming

void display(struct student *ptr) eillrser());


{ for(i = 0;1 < 2;i++)
printf ( ("\n DETAILS OF STUDENT"); {

printf ( WNT anc sie eee he aa i 8 "). s[i]=(struct student*)

printf ( ("\n ROLL NUMBER = %d", ptr—>r_no); Wek Oe Mee O a


t))
( printf ("\n\n Enter the name of student
printf("\n NAME = ", puts (ptr—>name)); At ae
Sd: pal)
jonastiotesa (Wal OWS}, ce 0, asia enane’
puts (ptr—>course) ); ££lush (stdin);
printf("\n FEES = %d", ptr—> fees); printf ("\n Enter the roll’ number of
} student %d: ", i)
scanf("%d", &s[i] —>roll_no),;
Output printf ("\n Enter the marks obtained in
Enter the data for the student three subjects by student %d: ", i)
ROLL NO.: 01 fOr (js 079" <- 37447
NAME: Rahul scanf ("%d", &s [i] —>marks [j] );
fflush (stdin); .
COURSE: BCA
FEES: 45000 } y
printf ("\n \n\n ******DETAILS*****");
for (1=0;1<5;1i++)
DETAILS OF STUDENT display (s [il] );
getch ();
ROLL NUMBER = 01 eae ioe
NAME = Rahul }
COURSE = BCA
FEES = 45000.00 Output
Enter the name of student 1: Goransh
8.16 Write a program to illustrate the use of arrays within Enter the roll number of student 1: 01
a structure. Enter the marks obtained in three subjects
by student 1: 99 100 99
#include <stdio.h>
Enter the name of student 2: Pranjal
#include <conio.h>
Enter the roll number of student 1: 02
#include <alloc.h>
Enter the marks obtained in three subjects
typedef struct student by student 2: 90 100 89
{
char name [20];
sughe seouhilky watoyr
telalophian a eet ar ate ae os . -
Self-referential structures are those structures that contain
};
a reference to data of its same type, i.e., in addition to
yoid aLaplay (eto ucesethdent* =) other data, a self-referential structure contains a pointer
{ to a data that is of the same type as that of the structure.
Tie) Shep For example, consider the structure node given as follows.
printf ("\n\n\n NAME: %s \n ROLL NO = econ os struct node
sd\n", s—>name, s—roll_no); {
for(i = O;i < 3;1++) int val;
} struct node *next;
print£(" $d", s—>marks
[i] ); re
} Here the structure node will
main ()
contain two types of data—an
{ integer val and next, which is
struct student *s[2];
a pointer to a node. You must be
SHOE aly
Wi
wondering why we need such a
Structure, Union, and Enumerated Data Types 4] 289

structure. Actually, self-referential structure is the foun- 8.6.3 Initializing Unions


dation of other data structures. We will be using them
throughout this book and their purpose will be clear to you _ A striking difference between a
when we will be discussing linked lists, trees, and graphs. structure and a union is that in
case of a union, the fields share
_ the same memory space, so fresh
data replaces any existing data.
Look at the following code and
Similar to structures, a union is a collection of variables | observe the difference between
of different data types. The only difference between a a structure and union when their
structure and a union is that in case of unions, you can fields are to be initialized.
only store information in one field at any one time.
#include <stdio.h>
To better understand a union, think of it as a chunk of
typedef struct POINT1
memory that is used to store variables of different types.
{
When a new value is assigned to a field, the existing data HME. Se Syn
is replaced with the new data. hi
Thus unions are used to save memory. They are useful
for applications that involve multiple members, where typedef union POINT2
values need not be assigned to all the members at any one {
time. alige, Sop
AME WWE
Ni
8.6.1 Declaring a Union main ()

The syntax for declaring a union is the same as that of {


declaring a structure. The only difference is that instead POINT1 P1 = {2,3};
// POINT2 P2 ={4,5}; Illegal with union
of using the keyword struct, the keyword union would
be used. The syntax for union declaration can be given as
PON TEZS P2e
PPy es = ale
union union-name
P2.y = 5;
printf ("\n The co-ordinates of Pl are %d
data_type var-name;
etal Zell, il oe, ah Wy
data_type var-name;
printf("\n The co-ordinates of P2 are %d
havol oll, Isla, IBSw)
[pe
ee wUaoy (OK

Again, the typedef keyword }


can be used to simplify the Output
declaration of union variables. The co-ordinates of Pl are 2 and 3
The most important thing to The co-ordinates of P2 are 5 and 5
remember about a union is that
In this code, POINT1 is a structure name and POINT2 is a
the size of a union is the size of
union name. However, both the declarations are almost
its largest field. This is because a sufficient number of
bytes must be reserved to store the largest sized field. same (except the keywords—struct and union); in
main(), you see a point of difference while initializing
values. The fields of a union cannot be initialized all at once.
8.6.2 Accessing a Member of a Union
Look at the output carefully. For
A member of a union can be accessed using the same the structure variable the output
syntax as that of a structure. To access the fields of a union, is fine but for the union variable
use the dot operator (.), i.e., the union variable name the answer does not seem to be
followed by the dot operator followed by the member correct.
name.
|290 | Introduction to C Programming

To understand the concept of union, execute the {


following code. The code given below just re-arranges the baycl) bie
printf statements. You will be surprised to see the result. union POINT points [3];

#include <stdio.h> points [0].


typedef struct POINT1 points [0].
{ points[1].
reales Sig, WF points [1]. Hl
Vy points [2].
points[2]. Se
ES
Games
ip
eM aR
(OW
G)
2=I)
typedef union POINT2
{
Thales be for (i=0;i<3;i++)
aa, Yeh printf ("\n Co-ordinates of Point [%d]
ha are *d and %d", i, points[i].x,
main ()
points ey);
{ return 0;
POINTI Pl = {2,3};
POINT2 P2; }
printf("\n The co-ordinates of Pl are %d and
Output
Hell. Ieal orepy Nsaiesi
Co-ordinates of Point[0] are 3 and 3
ee eS abe
printf("\n The x co-ordinate of P2 is %d", Co-ordinates of Point[1] are 5 and 5

P2.x); Co-ordinates of Point[2] are 7 and 7

P2.y = 5;
printf ("\n The y co-ordinate of P2 is
sd! D2. v7);
return 0;
You must be wondering, why do we need unions?
} Generally, unions can be very useful when declared inside
Output a structure. Consider an example in which you want a field
of a structure to contain a string or an integer, depending
The co-ordinates of Pl are 2 and 3
on what the user specifies. The following code illustrates
The x co-ordinate of P2 is 4
such a scenario.
The y co-ordinate of P2 is 5
#include <stdio.h>
Here although the output is correct, the data is still over- struct student
written in memory.
{
union

{
char name [20];
Like structures we can also have an array of union Gate, setoplil. iare}s
variables. However, because of the problem of new data be
overwriting existing data in the other fields, the program int marks;

may not display the accurate results. te


main ()
#include <stdio.h>
{
union POINT
struct student stud;
{ char choice;
BSBAS! Dee teidgh pEinNeh!
\n You can enter the name or roll
pe number of the student");
printf ("\n Do you want to enter the name?
main () (Y¥ tom N) SS)
Structure, Union, and Enumerated Data Types | 291 |

gets (choice); The enum keyword is basically used to declare


LE (choice=='y’ || choice=='Y’) and initialize a sequence of integer constants. Here,
{ enumeration name is optional. Considerthe following
printf£("\n Enter the name: ");
example, which creates a new type of variable called
gets ([Link]);
COLORS to store color constants.
}
else enum COLORS {RED, BLUE, BLACK, GREEN,
{ YELLOW, PURPLE, WHITE};
printf ("\n Enter the roll number: ");
scanf ("%d", &stud.roll_ no);
Note that no fundamental data type is used in the
} declaration of COLORS. After this statement, COLORS has
printf ("\n Enter the marks: "); become a new data type. Here, COLORS is the name given to
scanf("%d", &[Link]); the set of constants. In case you do not assign any value to
if (choice==‘y’ || choice=='Y’) a constant, the default value for the first one in the list—RED
printf("\n Name: %s ", [Link]); (in our case), has the value of 0. The rest of the undefined
else
constants have a value | more than its previous one. That
printf ("\n Roll Number: $d", stud.
is, if you do not initialize the constants, then each one
roll no);
would have a unique value. The first would be zero and
printf ("\n Marks: %d", [Link]);
return. (0) the rest would count upwards. So, in our example,

RED = 0, BLUE = 1, BLACK = 2, GREEN = 3,


YELLOW = 4, PURPLE = 5, WHITE = 6
Now in this code, we have a union embedded within
a structure. We know, the fields of a union will share If you want to explicitly assign values to these integer
memory, so in the main program we ask the user which constants then you should specifically mention those
data he/she would like to store and depending on his/her values shown as follows.
choice the appropriate field is used. enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN
= 7, YELLOW, PURPLE, WHITE = 15};

As a result of this statement, now RED = 2, BLUE =


3, BLACK = 5, GREEN = 7, YELLOW = 8, PURPLE =
9, WHITE = 15.
Look at the code which illustrates the declaration and
access of enumerated data types.
ENUMERATED DATATYPES #include <stdio.h>
The enumerated data type is a user-defined type based main ()

on the standard integer type. An enumeration consists { enum {RED=2, BLUE, BLACK=5, GREEN=7,
of a set of named integer constants. In other words, YELLOW, PURPLE, WHITE=15};
in an enumerated type, each integer value is assigned printf ("\n RED = $d", RED);
printé£ ("\n BLUE = 7d", BLUE):
an identifier. This identifier (which is also known as an
printf ("\n BLACK = $d", BLACK);
enumeration constant) can be used as a symbolic name to
printf ("\n GREEN = %d", GREEN);
make the program more readable.
printf ("\n YELLOW = %d", YELLOW);
To define enumerated data types, we use the keyword
printf ("\n PURPLE = %d", PURPLE);
enum, which is the abbreviation for ENUMERATE.
printf ("\n WHITE = %d", WHITE);
Enumerations create new data types to contain values that
return 0;
are not limited to the values that fundamental data types
}
may take. The syntax of creating an enumerated data type
can be given as follows: Output
RIGID) es 2
enum enumeration name { identifier,,
BLUE = 9S
identifiers; s....2, (identifier, |};
|292 Introduction to C Programming

BLACK = 5 So to create a variable of COLORS, we may write


GREEN = 7
enum COLORS bg color;
YELLOW = 8
PURPLE = 9 This declares a variable called bg_color, which is of the
WHITE = 15 enumerated data type, coLors. Another way to declare a
variable can be as illustrated in the following statement:
Note, The value of an enumerator constant is
enum COLORS {RED, BLUE, BLACK, GREEN,
always of the type int. Therefore, the YELLOW, PURPLE, WHITE}bg color, fore color;
storage associated with an enumeration
t
variable is the storage required for
a single int value. The enumeration 8.9.2 Using the typedef Keyword
constant or a valueofthe enumerated
type can be used anywhere in the C also permits to use the typedef keyword for enumerated
~ program where the C language permits data types. For example, if we write
an integer expression. typedef enum COLORS color;

Then, we can straight-away declare variablés by writing


The following rules apply to the members of an
enumeration list: Color forecoliom = RED;

e An enumeration list may contain duplicate constant


values. Therefore, two different identifiers may be 8.9.3 Assigning Values to Enumerated
assigned the same value, say 3. Variables
e The identifiers in the enumeration list must be
Once the enumerated variable has been declared, values
different from other identifiers in the same scope
can be stored in it. However, an enumerated variable can
with the same visibility including ordinary variable
hold only declared values for the type. For example, to
names and identifiers in other enumeration lists.
assign the color black to the back ground color, we will
e Enumeration names follow the normal scoping rules. write,
So every enumeration name must be different from
bg_color = BLACK;
other enumeration, structure, and union names with
the same visibility. An important thing to note here is that once an
enumerated variable has been assigned a value, we can
Note, If we create an enumerated type store its value in another variable of the same type. The
Ce without enumeration_name, it isknown following statements illustrate this concept:
as an anonymous enumerated type.
enum COLORS bg color, border color;
For example, enum {OFF, ON}; declares
bg_color = BLACK;
| an enumerated type that has two ©
border
color = bg: color;
- constants OFF with a value 0 and ON
with a value 1.
8.9.4 Enumeration Type Conversion
Enumerated types can be implicitly or explicitly cast. For
8.9.1 enum Variables
example, the compiler can implicitly cast an enumerated
We have seen that enumerated constants are basically integers, type to an integer when required. However, when we
so programs with statements such as int fore color implicitly cast an integer to an enumerated type, the
= RED; is considered to be a legal statement in C. compiler will either generate an error or a warning
In extension to this, C also permits the user to declare message. To understand this, answer one question. If we
variables of an enumerated data type in the same way as write:
we create variables of other basic data types. The syntax
enum COLORS{RED, BLUE, BLACK, GREEN, YELLOW,
for declaring a variable of an enumerated data type can be
PURPLE, WHITE};
given as
enum COLORS c;

enumeration
name variable name; c = BLACK + WHITE;
Structure, Union, and Enumerated Data Types | 293 |

Here, c is an enumerated data type variable. If we available in the C language. When we read or write an
write, c = BLACK + WHITE, then logically, it should be 2 enumerated type, we read/write it as an integer. The com-
+ 6 = 8, which is basically a value of type int. However, piler would implicitly do the type conversion as discussed
the left-hand side of the assignment operator is of the type earlier. The following statements illustrate this concept.
enum COLORS. So the statement would report an error. To
enum COLORS (RED, BLUE, BLACK, GREEN, YELLOW,
remove the error, you can do either of two things. First,
PURPLE, WHITE};
declare c to be an int. Second, cast the right-hand side in enum COLORS c;
the following manner: fefaione (WEI. tere)

c = enum COLORS (BLACK + WHITE); jorcalinieie (O\sn Collen = Sel! el)Fz

To summarize, 8.17 Write a program to display the name of the colors


enum COLORS (RED, BLUE, BLACK, GREEN, YELLOW,
using an enumerated type.
PURPLE, WHITE};
enum COLORS c; #include <stdio.h>
Gs TWINGE /yAigaulitel alee enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW,
c = 2; // illegal
in ¢c PURPLE, WHITE};
c = (enum COLORS)2;// Right way main ()

{
enum COLORS c;
8.9.5 Comparing Enumerated Types char *color name[] = {"RED", "BLUE",
"BLACK", "GREEN", "YELLOW", "PURPLE",
C also allows using comparison operators on enumerated
"WHITE"};
data type. Look at the following statements, which
for(c = RED; c <= WHITE; c++)
illustrate this concept.
bg color = (enum COLORS)6; print£("\n ss", color namee]));
if (bg color == WHITE) return 0;
fore color = BLUE;
fore color = BLACK;
if (bg color == fore color) OR
printf ("\n NOT VISIBLE");

Since enumerated types are derived from integer #include <stdio.h>

type, they can be used in a switch case statement. The #include <stdlib.h>
#include <conio.h>
following code demonstrates the use of the enumerated
enum COLORS {red, blue, black, green, yellow,
type in a switch case statement.
purple, white};
enum {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, main ()
WHITE}bg_ color; {
switch
(bg color) enum COLORS c;

{ ¢ = rand() 37;
case RED: switch (c)
case BLUE: {
case GREEN: case red: printf("\n RED"); break;
pirantel (¥\n Tie ws alpramary =color"); case blue: printf ("\n BLUE"); break;
break; case black: printf ("\n BLACK"); break;
case default: case green: printf ("\n GREEN"); break;
printf ("\n It is not a primary color") case yellow: printf ("\n YELLOW");
break; break;
case purple: printf ("\n PURPLE");
break;
case white: printf ("\n WHITE"); break;
8.9.6 Input/Output Operations on Enumerated }
Types return 0;

Since enumerated types are derived types, they cannot Output


be read or written using formatted input/output functions GREEN
294 | Introduction to C Programming

e A structure is similar to records. It stores related memory and gives details of the member names.
me information about an entity. Structure is basically Like any other data type, memory is allocated for th e.
7 structure when we declare a variable of the structure. .
a user-defined data type that can store related
oo
i
information (even of different data types) together. e When we precede a struct name with typedef
The major difference between a structure and an keyword, then the struct becomes anew data type. _
nan array is that, an array contains related information e When the user does not ‘explicitly initialize the |
of the same data type. structure C automatically does ‘this. For int and
Oo e A structure is declared using the keyword struct float members, the values are initialized toeto |
followed by a structure name. The structure definition and char and string members are initializedto’ \ _
however, does not allocate any memory or consume by default. oo
storage space. It just gives a template that conveys e A structure ‘member variable is generally acce
to the C compiler, how thestructure is laid out in using a ‘ ’ (dot operator).

Copying structures Assigning a structure to another Structure initialization Initializing astructure means —
structure of the same type. assigning some constants to the ‘members of the
Nested structure A structure placed within ms, ‘ structure. When the user does not explicitly initializes
structure, i.e., a structure that contains another struc- _the structure C automatically does this. For int and
ture as its member.
GLOSSARY
| Self-referential structures Structures that contain a
float members, the values are initialized to zero and
char and string members are initialized to the*\o ‘ by .
reference to data of its same type. A self referential default,
structure, in addition to other data, contains a pointer typedef declaration When we precede a oo:
to a data that is of the same type as that of the name with typedef keyword, then the struct e-
structure. comes a new data type. It is used to make the construct :
Structure Structure is a user-defined data type that shorter with more meaningful names for types already
can store related information (even of different data defined by C or for types that you have declared. A ty
types) together. pedef declaration, is a synonym forthe type.

Fill in the Blanks


1. Structure isa data type. 9. When we precede a struct name with =
2. A structure is similar to then the struct becomes a new datatype. _
3. contains related information of the same 10. For int and float structure members, the va
data type. are initialized to :
a contains related information of the same 11. char and string structure members | are
or different data type(s). initialized to the by default. =
5. Memory is allocated for a structure when 12. A structure member variable is generally accessed
is done. using a
6. isjust a template that will be used to
13. A structure placed within pee strucuae: is
reserve memory when a variable of type struct
called a
is declared.
Tok is a collection of variables under a 14. structures contain a reference to data of —
single name. their same type. °
8. A structure is declared using the keyword struct 15. The keyword typedef is used to
followed by a
Structure, Union, and Enumerated Data Types | 295|

is acollection of data under one name in 2. Astruct type is a primitive data type.
h memory is shared among the members. 3. Structure declaration reserves memory for the
rhe selection operator is used to structure.
permits sharing of memory among 4. \nitializing a structure means assigning some
EXERCISES
different types of data. constants to the members of the structure.
5. When the user does not explicitly initialize the
‘Multiple Choice Questions structure C automatically does this.

1. Adata structure that carrstore related information 6. The dereference operator is used to select a
_ together is particular member of a structure.

(a) array (b) string 7. New variables can be created using the typedef
keyword.
(c) structure (d) all of these
A data structure that can store related information
8. Memory is allocated for a structure only when we
o aren data types together declare variables of the structure.
9. A nested structure contains another structure as
oS ne its member.
_ (d) all ofthese 10. C permits copying of one structure variable to
another.
11. Union and structure are initialized in the same
way.
12. A structure cannot have a union as its member.
13. C permits nested unions.
14. In an enumerated type, an integer value can be
assigned to only one enumeration constant.
ddress operator _(b) dot operator
15. Declaring an enumerated type automatically
omma operator - (d) ternary operator
creates a variable.
16. The identifiers in an enumerated type are
automatically assigned values.
17. A field in a structure can itself be a structure.
18. No two members of a union should have the same
name.
19. No two identifiers in an enumerated type must
ion. member variable is generally accessed
have the same value.
he —
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
7. typedef can be used with which of these data Review Questions
types?
(a) struct (b) union 1. Declare a structure(s) that represents the following
(c) enum (d) allofthese hierarchical information:
The enumerated type is derived from which data (a) Student
type? (b) Roll Number
f@ int (b) float (c) Name
(c) double (d) char (i) First name
(ii) Middle Name
tate True cr False (iii) Last Name
_ 1. Structures contain related information of the same (d) Sex
data type.
|296 | Introduction to C Programming

(e) Date of Birth 18. Write a menu-driven program to add and


subl act_
(i) Day - 7 S+6iand4-2i.
(ii) Month 19. Write a short note on nested structures.
&ui (iii) Year 20. Writea program toread and display the informatio
about an employee Using nested s
~~ (f) Marks oy
(i) English Write a program to read“and display the
information about the entire faculty ° a particu
(ii) Mathematics —
department. | a
(iii) Computer Science
22. Write aprogram toread and displaythe infor
2. Define a structure to store the name, an array
about all the employees. ina department. ‘Edi
marks[] which stores marks of five different
the details of the ith employes and redpiay, the
subjects and a character grade. Write a program
information.
to display the details of the student whose name is
23. Write a program to”add and subtract dist
entered by the user. Use the structure definition of
6 km and 300 mand 4 Km and 700 m.
first question to make
an array of student. Display
24. Write a program to add and subtractheight62
the name of the students who have secured less
than 40% of aggregate. anda, 7
3. Modify question 2 to print each student'ss average eS Write aprogram to add and subtract 10hrs2 mins —
50sec and Shrs 30min 40sec.
marks, class average (that includes average of all
the student’s marks). 26. Write a program that uses a structure called date
____ that hasis passed to an isLeapYear eke to”:
4. Make an array of student as illustrated in question
determine ifthe year isa leap year.
1 and write a program to display the details of ay
student with the given DOB. 27. Write a program using pointer to “structure :
initialize the members in the [Link]
5. Make an array of student as sosueted {in question
functions to print the student’s information.
1 and write a program to delete the record ofthe
student with the given last name. 28; Write a program using pointer to structure ‘ :
‘initialize the members inthe structure an. a
6. What is the advantage of using structures?
alternative technique. ;
7. Differentiate between a structure and a union.
Define a structure date containing tree integers—
8. Howis a structure name different froma structure
day, month, and year. Write a program using —
variable? functions to read data, to validate the date entered
9. Structure declaration reserves memory for the by the user and then print the date on the screen.
structure. Comment on this statement with valid For example, if you. ehter 29,2, 2010 then that is :
justifications. an invalid date as 2010 is not a leap year. Similarly—
10. Differentiate between a structure and an array. 31,6,2007 is invalid as June does not have 31 days.
11. Write a short note on structures and inter ‘Process 30. Using the structure definition of the above —
communication. program, write a function to increment that. Ma
12. Explain the utility of typedef keyword in structures. sure that the incremented date iisa valid date.
13. Explain with an example how structures are 31. Modify the above program to add a specifi -
initialzed. : number of days to the given date. .

14. Is it possible to create an array of structure? 32. Using the structure definition of ‘28th question, ©
Explain with the help of an example. write a function to compare two date variables.
15. Write a program using structures to read and 23. Write a program to define a structure vector. Then .
display the information about an employee. write functions to read data, print data, add Wo '
vectors and ae the mempers ofa Bs) Ny
16. Write a program to find the sneer of three
factor of 10. _
numbers using structures.
34. Write a program to define 2a: structure tor a hotel
17. Write a program to calculate the distance between
that has members—name, address, grade, nu
the given points (6,3) and (2, 2).
Structure, Union, and Enumerated Data Types | 297 |

Wn Employee[10]
fy
4
Oo
~<
(rT
x<
uid

: main() |
{
struct values

re re with infor-
Then read and print the data.
298 | Introduction to C Programming

too
«f= 23:
printé("\n *d %£", v.
3
a. struct value
EXERCISES

printé ("\n
}
“3. 8b ruct values ©
{

static values v = {
‘printi(’\n 4d %f",

struct values
:

static values v;
printfl("\n $d 4£", v.L, v.f),
}
struct values
{
anc ee
float £-

main ()
i

~Printe('\n td 26", vii, vif),


}
_ANNEXURE 6
A6.1_ BIT FIELDSINSTRUCTURE e When a value that is out of range is assigned to a bit
field, the lower-order bit pattern is preserved and the
C facilitates the users to store integer members in memory
appropriate bits are assigned.
spaces smaller than what the compiler would ordinarily
e Although, the maximum bit field length is 64 bits,
allow. These space-saving structure members are called
for portability reasons, do not use bit fields that are
bit fields. In addition to this, C also permits the users to
greater than 32 bits in size.
explicitly declare the width in bits. Bit fields are generally
used in developing application programs that must e Bit fields with a length of 0 must be unnamed.
force a data structure to correspond to a fixed hardware Let us look at a structure that has bit fields.
representation and are unlikely to be portable.
SERUCE
Therefore, besides having declarators for members of
{
a structure or union, a structure declarator can also be a unsigned short a: 2;
specified number of bits, genérally known as a bit field. A unsigned short b: 1;
bit field is interpreted as an integral type. The syntax for Hite (ee Wp
specifying a bit field can be given as, unsigned short d: 4;

type-specifier declarator: constant-


te
expression In the above structure, the size of the structure is 2 bytes.
Bit fields have the same semantics as the integer type. This
In the syntax, the constant-expression is used to
means a bit field is used in expressions in exactly the same
specify the width of the field in bits. The type-specifier
way as a variable of the same base type would be used,
for the declarator must be unsigned int, signed int, or int,
regardless of how many bits are in the bit field.
and the constant-expression must be a non-negative
The C99 standard requires the allowable data types for
integer value. If the value of the constant expression is
a bit field to include qualified and unqualified signed int
zero, the declaration has no declarator.
and unsigned int in addition to the following types:
Key Points About Bit Fields e int
e short, signed short, and unsigned short
e C does not permit arrays of bit fields, pointers to bit
e char, signed char, and unsigned char
fields, and functions returning bit fields.
e long, signed long, and unsigned long
e C permits ordinary member variables along with bit
fields as structure members. e long long, signed long long, and unsigned long long
e The declarator is optional and is used to name the
bit field. Note,“In all implementations, tt
integer type for a bit field isunsigned.
e Bit fields can only be declared as part of a structure.
e The address-of operator (&) cannot be applied to
bit-field components. This means that you cannot Drawbacks
use scanf to read values into a bit field. To read a
value, you may use a temporary variable and then Bit fields are basically used to represent single bit flags,
with each flag stored in a separate bit. However, bit
assign its value to the bit field.
members in structs have practical drawbacks.
e Bit fields that are not named cannot be referenced,
and their contents at run time are unpredictable. e First, the ordering of bits in memory 1s architecture-
dependent and memory padding rules vary from
However, they can be used as dummy fields, for
compiler to compiler. Moreover, many C compilers
alignment purposes.
that are used today generate inefficient code for
e Bit fields must be long enough to contain the bit
reading and writing bit members.
pattern. Therefore, the following statement is invalid
e Second, bit fields can require a surprising amount of
in C language:
run-time code to manipulate the values and therefore,
short num? 15 the programs may end up using more space than they
save.
|300 |_Introduction to C Programming

A6.2 SLACK BYTE | First char grade will reserve two bytes and store the
data only in the first byte. Now char promotion_due will
In order to store any type of data in a structure, there is search for one byte and since one byte is available it will
a minimum fixed byte which must be reserved by the store the data in that byte. Now int id will reserve two
memory. This minimum byte, which is usually machine- bytes and store the data in the two bytes allocated to it.
dependent is known as that word boundary. For example, Similarly, int emp code will reserve two bytes to store
TURBO C is based on the 8086 microprocessor and has the data and float salary will reserve four bytes to do the
two-byte word boundary. So any data type reserves at same. Note that by re-arrangement of the fields, there is no
least two bytes of memory space. To understand it clearly, slack byte, and we have saved the wastage of memory and
consider the following structure: structure employee_m is a balanced structure.
struct employee To understand the concept with clarity, execute the follow-
{ ing code. However, before executing it, make sure that you
char grade; first go to Options menu, then go to compiler, then to code
chee alols generation, finally select word alignment, and press OK.
int emp_code; main ()
float salary; { .
char promotion due; struct employee
{
char grade;
alae, suolt
int emp code;
float salary;
char promotion due;
grade slack ie
byte promotion_due byte struct employeem

In the figure, char grade will reserve two bytes but store
char grade;
the data only in the first byte since size of char is one byte. char promotion due;
Now int id has a size of two bytes and will search for two iieie, aiole
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 sal;
will be useless as it will not be used to store any data. Such Ne
elrser
();
a useless byte is known as s/ack byte and the structure is
printf (“\n Size of employee =
called an unbalanced structure.
sda” ,sizeof (struct employee));
Converting an unbalanced structure into a balanced printf (“\n Size of employeem =
structure sd” ,sizeof (struct employee
m) );
getch ();
Now consider the same structure in which the sequence of
fields has been altered. }
struct employeem
Output
{ Size of employee = 12
char grade;
Size of employeem = 10
char promotion due;
dale, Skolt Hence, slack byte is useful for speed optimization as
int emp_code; it aligns bytes so that they can be read from the structure
ikeeye Selly faster.

promotion_due
CHAPTER

2ading andWriting Data from Files @ Error Handling


° Random Access of Data Renaming Files

I/O, the only difference is that when doing file I/O, the user
must specify the name of the file from which data should
A file is a collection of data stored on a secondary storage be read/written.
device like hard disk. Till now, we had been processing
data that was entered through the computer’s keyboard. 9.1.1 Streams in C
But this task can become very tedious especially when
there is a huge amount of data to be processed. A better In C, the standard streams are termed as pre-connected
solution, therefore, is to combine all the input data into a input and output channels between a text terminal and the
program (when it begins execution). Therefore, stream is
file and then design a C program to read this data from the
a logical interface to the devices that are connected to the
file whenever required.
computer.
Broadly speaking, a file is basically used because real-
Stream is widely used as a logical interface to a file
life applications involve large amounts of data and in such
where a file can refer to a disk file, the computer screen,
applications the console-oriented I/O operations pose two
keyboard, etc. Although files may differ in the form and
major problems:
capabilities, all streams are the same.
e First, it becomes cumbersome and time-consuming The three standard streams (Fig. 9.1) in C languages are
to handle huge amount of data through terminals. as follows:
e Second, when doing I/O using terminal, the entire e standard input (stdin)
data is lost when either the program is terminated
e standard output (stdout) and
or computer is turned off. Therefore, it becomes
e standard error (stderr) .
necessary to store data on a permanent storage device
(the disks) and read whenever necessary, without Standard input (stdin) Standard input is the stream from
destroying the aata. which the program receives its data. The program requests
In order to use files, we have to learn file input and transfer of data using the read operation. However, not all
output operations, i.e., how data is read or written to a file. programs require input. Generally, unless redirected, input
Although file I/O operations is almost same as terminal for a program is expected from the keyboard.
|302 |_Introduction to C Programming

KEYBOARD Program
Data from the
buffer is
stdin writes data written to the ;
to buffer disk file ©
PROGRAM
stdout stderr

SPT Buffers associated with streams


Figure 9.1 Standard streams ‘

Standard output (stdout) Standard output is the stream 9.1.3 Types of Files
where a program writes its output data. The program
In C, the types of files used can be broadly classified into
requests data transfer using the write operation. However,
two categories—ASCIHI text files and binary files.
not all programs generate output.
-

ASCII Text Files


Standard error (stderr) Standard error is basically an
output stream used by programs to report error messages A text file is a stream of characters that can be sequentially
or diagnostics. It is a stream independent of standard processed by a computer in forward direction. For this
output and can be redirected separately. No doubt, the reason, a text file is usually opened for only one kind of
standard output and standard error can also be directed to operation (reading, writing, or appending) at any given
the same destination. time. Because text files only process characters, they can
A stream is linked to a file using an open operation and only read or write data one character at a time. In C, a text
disassociated from a file using a close operation. stream is treated as a special kind of file.
Depending on the requirements of the operating
9.1.2 Buffer Associated with File Stream system and on the operation that has to be performed
(read/write operation) on the file, newline characters
When a stream linked to a disk file is created, a buffer
may be converted to or from carriage return/line feed
is automatically created and associated with the stream. combinations. Besides this, other character conversions
A buffer is nothing but a block of memory that is used may also be done to satisfy the storage requirements of
for temporary storage of data that has to be read from or the operating system. However, these conversions occur
written to a file. transparently to process a text file.
Buffers are needed because disk drives are block- In a text file, each line contains zero or more characters
oriented devices as they can operate efficiently when data and ends with one or more characters that specify the end
has to be read/written in blocks of certain size. An ideal of line. Each line in a text file can have maximum of 255
buffer size is hardware dependent. characters. A line in a text file is not a C string, so it is not
The buffer acts as an interface between the stream terminated by a null character. When data is written to a
(which is character-oriented) and the disk hardware (which text file, each newline character is converted to a carriage
is block-oriented). When the program has to write data to return/line feed —_ character.
the stream, it is saved in the buffer till it is full. Then the Programming Tip: Similarly, when data is read from
entire contents of the buffer are written to the disk as a The contents of a a text file, each carriage return/
binary file are not line feed character is converted
block. This is shown in Fig. 9.2.
human readable. into newline character.
Similarly, when reading data from a disk file, the data
Ifyouwantthe >
is read as a block from the file and written into the buffer. Another important thing is that
data stored in the
The program reads data from the buffer. The creation and __ when a text file is used, there are
file to be human- —
operation of the buffer is automatically handled by the readable, then actually two representations of
operating system. However, C provides some functions storethe data ina data—internal or external. For
for buffer manipulation. The data resides in the buffer | example, an int value will be
until the buffer is flushed or written to a file. represented as 2 or 4 bytes of
Files | 303 |

memory internally, but externally the int value will be value 123 we need 3 bytes. However, in a binary file, the
represented as a string of characters representing its decimal int value 123 will be stored in 2 bytes in the binary form.
or hexadecimal value. To convert internal representation This clearly indicates that binary files take less space to
into external, we can use printf and fprintf functions. store the same piece of data and eliminates conversion
Similarly, to convert an external representation into internal between internal and external representations and are thus
scanf and fscanf can be used. We will read more about more efficient than the text files.
three functions in the coming sections.

e Note
) Ina text file, each lineo'data ends with © 9.2 USING FILES INC
ws: ends with
To use files in C, we must follow the steps given below:
1d-of-file.
(EOF) marker. e declare a file pointer variable
e open the file

Binary Files e process the file


e close the file
A binary file may contain any type of data, encoded in
In this section, we will go through all these steps in detail.
binary form for computer storage and processing purposes.
Like a text file, a binary file is a collection of bytes. In C, a
byte and a character are equivalent. Therefore, a binary file 9.2.1 Declaring a File Pointer Variable
is also referred to as a character stream with the following There can be a number of files on the disk. In order to
two essential differences: access a particular file, you must specify the name of
e A binary file does not require any special processing the file that has to be used. This
of the data and each byte of data is transferred to or is accomplished by using a file
from the disk unprocessed. _ pointer variable that points to
e C places no constructs on the file, and it may be read a structure FILE (defined in
use the fens: stdio.h). The file pointer will
from, or written to, in any manner the programmer
access a file rather then be used in all subsequent
wants. than the file pointer. / operations in the file. The syntax
While text files can be processed sequentially, binary ' for declaring a file pointer is
files, on the other hand, can be either processed sequentially
FILE *file pointer name;
or randomly depending on the needs of the application. In
C, to process a file randomly, the programmer must move For example, if we write
the current file position to an appropriate place in the file FILE *fp;
before reading or writing data. For example, if a file is Then, fp is declared as a file pointer.
used to store records (using structures) of students, then
to update a particular record, the programmer must first 9.2.2 Opening a File
locate the appropriate record, read the record into memory,
update it, and finally write the record back to the disk at its A file must first be opened before data can be read from it
appropriate location in the file. or written to it. In order to open a file and associate it with
a stream, the fopen() function is used. The prototype of
- Note, _«Bir
i fopen() can be given as,
FILE *fopen(const char *file name, const char
se will be stored in any formasa2_
*mode) ;
value. The same format is used _
data in memory as well as in file. Using the above BI OUES the file whose pathname is the
ile, binary file also ends with an - string pointed to by file name
Programming
is opened in the mode specified
Tip: A file must be
opened before any using the mode. If successful,
In a text file, an integer value 123 will be stored as fopen() returns a pointer-to-
~ Operation can be
a sequence of three characters—1l, 2, and 3. So each structure and if it fails, it
performed on it. —
character will take 1 byte and therefore, to store the integer returns NULL.
|304 | Introduction to C Programming

File Name fp = fopen(filename, "r+");


if (£p==NULL)
Every file on the disk has a name known as the file name.
{
The naming convention of a file varies from one operating
printf ("\n The file could not be opened");
system to another. For example, in DOS the file name can exit (1);
have one to eight characters optionally followed by a
period and an extension that has one to three characters.
However, Windows and UNIX permit filenames having
maximum of 256 characters. Windows also lays some LE oes File modes—
restrictions on usage of certain characters in the filenames,
"Description
i.e., characters such as /,\, ,*,?,",<,>, and ! cannot
Open a text file for reading. Ifthe:stream
be part of a file name.
(file) does not exist, then an error will be
In C, the fopen() may contain the path information
reported.
instead of specifying the filename. The path gives infor-
mation about the location of the file on the disk. If a file- Open a text file for writing. If the stream does
not exist, then it is created. If the file already
name is specified without a path, it is assumed that the file
exists, then its contents would be deleted.
is located in the current working directory. For example, if
a file named Student. DAT is located on D drive in directo- Append to a text file. If the file does not
exist, it is created.
ry BCA, then the path of the file can be specified by writing,
Open a binary file for reading. b indicates
D: \BCA\Student.
DAT
binary. By default this will be a sequential
In C, a backslash character has a special meaning with file in Media 4 format.
respect to escape sequences when placed in a string. So
Open a binary file for writing.
in order to represent a backslash character in a C program,
Append to a binary file.
you must precede it with another backslash. Hence, the
above path will be specified as given below in the C r+ Open a text file for both reading and
program. writing. The stream will be positioned at
the beginning of the file. When you specify
D: \\BCA\\Student.
DAT
'r+', you indicate that you want to read the
file before you write to it. Thus, the file
File Mode must already exist.
The second argument in the fopen() is the mode. Mode Open a text file for both reading and
conveys to C the type of processing that will be done with writing. The stream will be created if it does
the file. The different modes in which a file can be opened not exist, and will be truncated if it exists.
for processing are given in Table 9.1. Open a text file for both reading and
Look at the code given below which opens a file using writing. The stream will be positioned at
the end of the file content.
the fopen() .
Open a binary file for read/write.
FILE *fp;
fp = fopen("[Link]", Wat) w+b/wb+ | Create a binary file for read/write.
if (fp==NULL) Append a binary file for read/write.
{
jonestia} ene (UNA The; file could not be opened"); We have already discussed that fopen() returns a
exit (1); ; pointer to FILE structure if
} Programming Lake _ successful and a NULL otherwise.
OR An error will be So it is recommended to check
generated if you try_ whether the file was successfully
char filename [30] ;
to open a file that _ opened before actually using the
FILE *fp;
does not exist, | file. The fopen () can fail to open
gets (filename);
Files | 305 |

the specified file under certain conditions that are listed Wy

9.3 READ DATA FROM FILES


Yj

below:
C provides the following set of functions to read data from
e opening a file that is not ready for use
a file:
© opening a file that is specified to be on a non-existent
® fscan€()
directory/drive
e fgets()
¢ opening a non-existent file for reading
e fgetc()
e opening a file to which access is not permitted e fread()

In this section, we will read about these functions.


9.2.3 Closing a File Using folose ()
To close an open file, the fclose() function is used 9.3.1 fscanft ()
which disconnects a file pointer from a file. After the
fclose() has disconnected the file pointer from the file, The fscanf() is used to read formatted data from the
the pointer can be used to access a different file or the stream. The syntax of the fscanf () can be given as
same file but in a different mode. The fclose() function
int fscanf (FILE *stream, const char *format,...);
not only closes the file, but also flushes all the buffers that
are maintained for that file. The fscanf() is used to read data from the stream and
If you do not close a file after
store them according to the parameter format into the
using it, the system closes it
locations pointed by the additional arguments. However,
_ automatically when the program
exits. However, since there is a these additional arguments must point to the objects that
limit on the number of files which have already occupied memory. These objects are of type
can be opened simultaneously; as specified by their corresponding format tag within the
the programmer must close a format string.
file when it has been used. The Similar to the format specifiers used in scanf(),
prototype of the fclose()
in fscanf() also the format specifiers is a C string that
function can be given as
begins with an initial percentage sign (%). The format
int fclose(FILE *fp);
specifier is used to specify the type and format of the data
Here, fp is a file pointer which points to the file that has
to be closed. The function returns an integer value which that has to be obtained from the stream and stored in the
indicates whether the fclose() was successful or not. A memory locations pointed by the additional arguments.
zero is returned if the function was successful; and a non- The prototype of a format specifier can be given as,
zero value is returned if an error occurred.
[=% [*] [width] [modifiers] type=], where
lose () is execu:
reddata for the stream — ‘*’ is an optional argument that suppresses assignment
the file and any unread of the input field. It indicates that data should be read
iscarded. from the stream and ignored (not stored in the memory
location).
In addition to £close(), there is a _ func-
tion £closeall() which closes all the streams that are cur- width specifies the maximum number of characters to be
rently opened except the standard streams (such as stdin, read. However, fewer characters will be read if the £scanf
stdout, andstderr). The prototype of £closeall() can function encounters a white space or an unconvertible
be given as, character.
int fcloseall (void);
modifiers can be h, 1, or L for the data pointed by the
fcloseall() also flushes any stream buffers and returns
corresponding additional arguments. Modifier h is used
the number of streams closed.
for short int or unsigned short int, 1 is used for
If a file’s buffer has to be flushed without closing it then
use fflush() or flushall() to flush the buffers of all long int, unsigned long int, or double values.
open streams. Finally, L is used for long double data values.
|306 | Introduction to C Programming

type specifies the type of data that has to be read. It also // READ FROM KEYBOARD

indicates how this data is expected to be read from the fscanf(stdin, "%s td", name, &roll no);
/* read from keyboard */
user.
printf ("\n NAME: %s \t ROLL NUMBER
The type specifiers for fscanf function are given in $a", name, roll no);
Table 9.2 // READ FROM FILE Student .DAT

Fscant(£p pass sa"; name, &roll_no);


printf ("\n NAME: %s \t ROLL NUMBER
odll mame,
col lLino));
fclose (fp); ;
for single character return 0;

}
for decimal values
Output

eo
erecainunier Enter

NAME:
the
student:
Zubin
name
01
and
Zubin
ROLL
roll

NUMBER
number

= O1
of the

NAME: Goransh ROLL NUMBER = 03


for unsigned decimal value
_ Note, If you want to use fprint
for hexadecimal value
on thed screen, then specify _
instea of specifying any other file pointer.
The fscanf function has some additional arguments.
Each of this additional argument must point to an object of
the type specified by their corresponding % tag within the 9.3.2 fgets ()
format string, in the same order. The function fgets () stands for file get string. The
fgets() function is used to get a string from a stream.
The fscanf functi larto the
|
Note,
The syntax of fgets () can be given as,
scanf function, excep the first
argument of fscanf specifies astream _ char *fgets(char
*str, int size, FILE *stream);
from which to read, whereas scanf can The fgets() function reads atmost one less than the
onlyread from standardinput. =
number of characters specified by size (gets size - 1
characters) from the given stream and stores them in
Let us look at an example which illustrates the use of
the string str. The fgets() terminates as soon as it
fscanf (). Here, we will not give the complete program
encounters either a newline character, EOF, or any other
but just a partial program to demonstrate the use of
error. However, if a newline character is encountered it
fscanf ().
is retained. When all the characters are read without any
#include <stdio.h> error, a ‘\0’ character is appended to the end of the string.
main ()
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 name [80] ;
a newline character, it does not retain it, i.e., the newline
amis waeleil Sake),
character (if any) is not stored in the string.
ED) LODeHIMSeudenta
WAIIn wlll!) i
On successful completion, fgets() will return str.
if (fp==NULL) ©
However, if the stream is at EOF, the EOF indicator for the
{ stream will be set and fgets() will return a null pointer.
printf ("\n The file couldnotbe opened");
In case, fgets () encounters any error while reading, the
exit (1);
error indicator for the stream will be set and null pointer
} will be returned. Look at the program code given below
printf ("\n Enter the name and roll number
which demonstrates the use of fgets () .
of the student: ");
Files | 307 |
#include <stdio.h> fp = fopen("Program.C", UaeWyye

main () if (£p==NULL)
{ {
FILE *fp; printf ("\n The file could not be
opened");
char str[80];
exit (1);
fp = fopen("[Link]", Urata) ee

if (f£p==NULL)
}
// Read 79 characters and store them in str
{ ch = fgetc(fp);
printf("\n The file could not be opened"); for (1=07) (a9) && (heOE (Ep) ==" 0) aart
+)
exie (1) {
} gee lial) es (Celaebe)) cles
/* the file will read 79 characters ch = fgetc(stream) ;
during each iteration and prints them on // veads character by character

the screen */ ' }


Shera (fab) es NOE.
while (fgets(str,
80, fp) != NULL)
// append the string with a null character
OAC (UNIaees Sl! pester)
Deintes (ne ssity asta)
printf ("\n\n File Read. Nowclosing
the file");
fclose (fp);
f£close (fp);
}
return 0;
Output
}
#include <stdio.h>
Output
mara (err
Abdceweeferrttet gfejjherroiew tjketjer displays either first 79 characters or less
fddfgdfgfd characters if the file contains less than
File Read. Now closing the file 79 characters

The feof () is used to detect the end of file. We will read


9.3.3 fgetc() more on this function later in this chapter.
The fgetc() function returns the next character from
stream, EOF if the end of file is reached, or if there is an 9.3.4 fread ()
error. The syntax of fgetc() can be given as,
The fread() function is used to read data from a file. Its
int fgetc(FILE *stream) ;
syntax can be given as,
fgetc returns the character read as an int or return EOF
int fread(void *str, size_t size, size t num,
to indicate an error or end of file.
FILE *stream);
fgetc() reads a single character from the current
position of a file (file associated with stream). After The function fread() reads num number of objects
reading the character, the function increments the (where each object is size bytes) and places them into the
associated file pointer (if defined) to point to the next array pointed to by str. The data is read from the given
character. However, if the stream has already reached the input stream.
end of file, the EOF indicator for the stream is set. Look at Upon successful completion, fread() returns the
the following program code which demonstrates the use of number of bytes successfully read. The number of objects
fgets () function: will be less than num if a read error or end-of-file is
#include <stdio.h> encountered. If size or numis 0, fread() will return 0
main () and the contents of str and the state of the stream remain
{ unchanged. In case of error, the error indicator for the
FILE *fp; stream will be set.
char str[80]; The fread() function advances the file position
ahaie, oh7 elales indicator for the stream by the number of bytes read.
|308 | Introduction to C Programming

// explicitly store null character at the


Note The fread () function joes not /
end of str
distinguish between end-of- fileand error.
printf("\n First *d characters of the
he programmer must use ands
file are: %s", bytes read, str);
error to determine which | the two -
fclose (fp);
has occurred. ee
}
Look at the program given below which illustrates the Output
use of fread() . Output will depend on the contents of the

#include <stdio.h> file. Assuming 14 characters were read,

main () the output can be given as


Hello how r u?
{
This program assumes that you have created
FILE *fp;
a file [Link] that conatins 14
chariistr [aa |i-
characters which has been displayed above
fp = fopen("[Link]", Miers

if (fp==NULL) The function fread() does not check for overflow in


{ the receiving area of memory. It is the programmer’s job
printf ("\n The file could not be opened"); to ensure that the memory pointed to by 'str' must be
exit (1); large enough to hold the number of objects being read.
} If you have opened a stream for updating and later you
imaeservel (sie, aby, ALO), sFe))p want to switch from reading to writing or vice versa, you
/* In the str 10 objects of 1 byte are must first use the fseek () or rewind () function. However,
read from the file pointd by fp */ if you have been reading and have reached end-of-file, then
StakLoill=s S\0us; you can immediately switch to writing. We will discuss the
printf("\n First 9 characters of the file fseek() and rewind functions later in this chapter.
are: %s", str);

9.4 WRITING DATA TO FILES —


fclose (fp);

C provides the following set of functions to read data from


Output a file:
First 9 characters of the file are: Hello e fprintf()
how e fputs()
oe EpuUrei()
Since fread () returns the number of bytes successfully
e fwrite()
read, we can also modify the above program to print the
number of bytes read. This would be helpful to know how In this section, we will read about these functions.
many characters were read.
#include <stdio.h> 9.4.1 fprinté£ ()
main ()
The fprintf () is used to write formatted output to stream.
{
FILE *fp; The syntax of the fprintf () can be given as
char str[80]; int fprintf (FILE * stream, const char * format, ...);
size_t bytes, read;
fp. = fopen("Letter.
Txt", Wei) The function writes data that is formatted as specified
if (fp==NULL) by the format argument to the specified stream. After the
{ format parameter, the function can have as many additional
printf ("\n The file could not be opened"); arguments as specified in format.
exit(1); The parameter formatin the fprintf () is nothing but
} a C string that contains the text that has to be written on to
bytesi read = fread (str, 1797 1£p); the stream. Although not mandatory, the fprintf() can
str [bytes read+1]= ‘\0'; optionally contain format tags, that are replaced by the
Files | 309 |

values specified in subsequent additional arguments and


Table 9.4 Length field in print o :
are formatted as requested.
Description 7 ;
Netey There must
be enough arguments for When the argument is a short int or unsigned
>
format becauseifthere are not, then - short int
result will be completely unpredictable.
However, if by mistake you specify When the argument is a long int or unsigned
_ more number of arguments,
the excess long int for integer specifiers
arguments will simply be
ignored. When the argument is a long double (used for
floating point specifiers)
The prototype of the format tag can be given as

% [flags] [width] [.precision]


[length] specifier Specifier is used to define the type and the interpretation
of the value of the corresponding argument.
Each format specifier must begin with a % sign. The % sign
The fprint£ () maycontain some additional parameters
is followed by:
as well depending on the format string. Each argument
Flags which specifies output justification such as decimal must contain a value to be inserted instead of each % tag
point, numerical sign, trailing zeros, or octal or hexa- specified in the format parameter, if any. In other words,
decimal prefixes. Table 9.3 shows the different types of the number of arguments must be equal to the number of %
flags with their description. tags that expect a value.
Look at the program given below which demonstrates
beeicrey Flags in printé () the use of fprintf () .
#include <stdio.h>
scription main ()

{
Left justify within the data given field width FILE *fp;
ibehe, Als
Displays the data with its numeric sign (either + or —)
char name[20];
float salary;
Used to provide additional specifiers such as 0, x,
UR Au
fpR=ntopeni(tDetailc
uy
X, 0, Ox, or OX for octa and hexadecimal values,
if (£p==NULL)
respectively, for values except zero.
{
The number is left-padded with zeros (0) instead printf ("\n The file could not be opened");
of spaces. exit (1);
}
for(i = O71 < 10;1++)
Width specifies the minimum number of characters to
{
print after being padded with zeros or blank spaces. puts("\n Enter your name: ");
gets (name);
Precision specifies the maximum number of characters to
fflush(stdin);
print. puts("\n Enter your salary: ");
e For integer specifiers (d, i, 0, u, x, X): precision scanf("%£", &salary);

flag specifies the minimum number of digits to be Eprints’ (Fp eo" S(sd) NAME SLs 10s LOS
\t SALARY %5.2f£",
i, name, salary);
written. However, if the value to be written is shorter
than this number, the result is padded with leading
fclose (fp);
zeros. Otherwise, if the value is longer, it is not
}
truncated.
e For character strings, precision specifies the Output
Enter your name: Aryan
maximum number of characters to be printed.
Enter your salary: 50000
Length field can be explained as given in Table 9.4. Enter your name: Anshita
|310 | Introduction to C Programming

Enter your salary: 65000 // feedback stored


Enter your name: Saesha fputs (feedback,
fp);
Enter yeue mares 70000 fclose (fp);

This example asks the user to }


a you open afile enter the name and salary of Output
for writing using : 10 people. Each time the user
Provide feedback on this book: good
enters the name and salary, the
data read is written to Details.
9.4.3 fputc () ‘
_TxT. The names are written
on new lines in the file. In this The fputc() is just the opposite of fgetc() and is used
example, we have used three to write a character to the stream. ;
_| format tags: int fputc(int c, FILE *stream);
e %d to specify a signed decimal
The fputc() function will write the byte specified by
integer.
c (converted to an unsigned char) to the output stream
e %-10.10s. Here — indicates that the characters must be pointed to by stream. On successful completion, fputc ()
left aligned. There can be minimum of 10 characters as will return the value it has written. Otherwise, in case of
well as maximum of 10 characters (.10) in the strings. error, the function will return EOF and the error indicator
e %f to specify a floating point number. for the stream will be set.
#include <stdio.h>
main ()
{
FILE *fp;
char feedback[100];
Talteeeg.
9.4.2 fputs ()
fp = fopen("[Link]",
"w");
The opposite of fgets() is fputs(). The fputs() is if (fp==NULL)
used to write a line to a file. The syntax of fputs() can {
be given as printf ("\n The file could not be opened");
int fputs(const char *str, FILE *stream); Ghia (a) s
}
The fputs() writes the string pointed to by str to the printf ("\n Provide feedback on this book: ");
stream pointed to by stream. On successful completion, gets (feedback);
fputs() returns 0. In case of any error, fputs() returns for(i = 0;i < feedback
[i] ; i++)
EOF. fputc (feedback
[i], fp);

#include <stdio.h> fclose (fp);

main () }
{ Output
FILE *fp;
Provide feedback on this book: good
char feedback [100] ;
fp = fopen("[Link]", Nw'l) >

if (fp==NULL)
{ ’

On the antiare the standard file


printf ("\n The file could not be opened");
is usually unbuffered. However, the
exit (1);

} 2 changed using
printf ("\n Provide feedback on this book: ");
gets (feedback); When an output stream is unbuffered, information
fflush(stdin); appears on the destination device as soon as it is written.
Files | 311 |

‘ogramming Tip: When it is buffered, characters


: Note, fwrite () can be used to write characters,
_ EOF is an integer are saved internally and then integers, or structures to a file. However, _
_ type defined in
/
written out as a group. In order _ fwrite ()can be used only with files that
-[Link] to force buffered characters to be are opened inbinary mode. ee
value ‘1’. | output before the buffer is full,
use the fflush().

9.5 DE 1£END-OF-FIL
9.4.4 fwrite()
When reading or writing data from files, we often do
The fwrite() is used to write data to a file. The syntax of not know exactly how long the file is. For example,
fwrite can be given as while reading the file, we usually start reading from the
beginning and proceed towards the end of the file. In C,
int fwrite(const void *str, SuzeneesLze,
size_t count, FILE *stream);
there are two ways to detect EOF:
e While reading the file in text mode, character by
The fwrite() function will write objects (number of
character, the programmer can compare the character
objects will be specified by count) of size specified by that has been read with the EOF, which is a symbolic
size, from the the array pointed to by ptr to the stream
constant defined in stdio.h with a value -1. The
pointed to by stream.
following statement, does that
The file-position indicator for the stream (if defined)
while (1)
will be advanced by the number of bytes successfully
written. If an error occurs, the resulting value of the file- {
Cl=nEgete (Ep)
position indicator for the stream is unspecified. // here c is an int variable
On successful completion, the fwrite() function Wie (GeS=110)9))
returns the number of objects successfully written. The break;
number of objects will be less than count if an error is jorentianere (USE, C)F
encountered. If size or count is 0, fwrite() will return }
0 and the contents of the stream remains unchanged. In
e The other way is to use the standard library function
case of error, the error indicator for the stream will be set.
feof () which is defined in stdio.h. The feof () is
#include <stdio.h> used to distinguish between two cases:
#include <string.h>
= When a stream operation has reached the end of
#include <stdlib.h>
main (void)
a file
{ a When the EOF (end of file) error code has
FILE *fp; returned an error indicator even when the end of
Suzemt Count, the file has not been reached
char str[] = "GOOD MORNING";
fp = fopen("[Link]", "whb"); The prototype of feof () can be given as
if (£p==NULL) int feof (FILE *fp);
{
printf ("\n The file could not be opened"); The function takes a pointer to the FILE structure of the
xan) stream to check as an argument and returns zero (false)
} when the end of file has not been reached and a one (true)
count = fwrite(str,1, strlen(str),
fp); if the EOF has been reached. Look at the following:
printf ("\n %d bytes were
(The output assumes that a file Student .DAT
written to the file", count);
already exists and conatins the following
fclose (fp);
data: 1 Aditya 2 Chaitanya 3 Goransh)
return 0;

} #include <stdio.h>
main ()
Output
{
13 bytes were written to the file FILE *fp;
|312 | Introduction to C Programming

char str[80]; a non-zero value if there is an error. The error indication


ED =sLopen (Student.
DAT Uy atratl)i. will last until the file is closed unless it is cleared by the
if (fp==NULL) clearerr() function. Look at the code given below
{ which uses the ferror() .
printf ("\n The file could not be opened");
exit (1); #include <stdio.h>
main ()
}
/* The loop continues until fp reaches {
the end-of-file */ FILE *fp;
while (!feof (fp) char feedback[100] ; i

{ 5 gley atlas

fgets(str,
79, fp); fp = fopen("[Link]",
"w!');

// Reads 79 bytes at a time if (fp==NULL)


joreshahere (Ue ESM fsiera))p {
printf ("\n The file could not be opened");
}
printf ("\n\n File Read. Nowclosingthe file"); exit (1);
} .
Eclose (£p);
Betuxy 07 printf ("\n Provide feedback on this book: ");
} gets (feedback);
for(i = 0; i < feedback
[i] ;i++)
Output fputc(feedback[i], fp);
1 Aditya 2 Chaitanya 3 Goransh if (ferror
(fp) )
{
printf ("\n Error writing in file");
9.6 ERROR HANDL NG DUR .FILE. exit (1);

- OPERATIONS | 2 , }
fclose (fp);
It is quite common that an error may occur while reading
data from or writing data to a file. For example, an error
}
may arise When you execute this code and an error occurs while
_ProgrammingTip: ° when trying to read a file writing the feedback, the program will terminate and a
| beyond EOF indicator message indicating “Error writing in file’ will be displayed
on the screen.
e when trying to read a file that
to read afil that is
: does not exist
_opened in 9.6.1 clearerr ()
‘and vice versa. e when trying to use a file that
has not been opened The function clearerr() is used to clear the end-of-
e when trying to use a file in an inappropriate mode, file and error indicators for the stream. Its protoype can
i.e., writing data to a file that has been opened for be given as
reading void clearerr(FILE *stream);
e when writing to a file that is write-protected (1.e.,
The clearerr () clears the error for the stream pointed to
trying to write to a read-only file)
by stream. The function is used because error indicators
If we fail to check for errors, then the program may
are not automatically cleared; once the error indicator for a
behave abnormally. Therefore, an unchecked error may
specified stream is set, operations on that stream continues
result in premature termination of the program or incorrect
to return an error value until clearerr, fseek,
output.
fsetpos, or rewind is called. Look at the code given
In C, the library function ferror () is used to check for
below which use the clearerr ()
errors in the stream. Its prototype can be given as
#include <stdio.h>
int ferror (FILE *stream);
#include <stdlib.h>
The ferror() function checks for any errors in the #include <errno.h>
stream. It returns value zero if no errors have occurred and main ()
Files | 313 |

Usually the program’s action will be determined by


FILE *fp; checking the value of errno and the nature of the error.
fp = fopen("[Link]", Mwy)
In order to use the external constant errno, you must
if (fp==NULL)
include the header file ERRNO .H. The program given below
{ illustrates the use of perror(). Here we assume that the
perror ("OOPS ERROR");
file [Link] does not exist.
printf ("\n error no = $d", errno);
@paike, ((il))p #include <stdio.h>
#include <stdlib.h>
}
#include <errno.h>
printf ("\n Kindly give the feedback on
main ()
this book: ");
gets (feedback); {
FILE *fp;
for(i = 0; i < feedback[i] ;i++)
fp = fopen("[Link]", Univ) 0

{ if (fp==NULL)
fputc (feedback
[i], fp);
aise (GeSsere(ons ((15)6)) ))
{
perror ("OOPS ERROR");
{ printf("\n error no = $d", errno);
clearerr (fp);
exit (1);
break;
}
/* clears the error indicators and
printf ("\n Provide feedback on this book: ");
jump out of for loop */
gets (feedback) ;
for (i=0; i<feedback
[i] ;i++)
} fputc (feedback[i], fp);
// close the file
fclose (fp);
fclose (fp);
}
Output
9.6.2 perror () OOPS ERROR: No such file or directory
errno =2
The function perror () stands for print error. In case of an
error, the programmer can determine the type of error that
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
C facilitates its programmers to pass command arguments.
message on stderr describing the most recent error that
Command line arguments are given after the name of a
occurred during a library function call or system call. The
program in command-line operating systems like DOS or
prototype of perror() can be given as
Linux, and are passed in to the program from the operating
void perror(char *msg); system.

The perror() takes one argument msg which points to Till now, no arguments were passed to the main().
But now in order to understand command-line arguments,
an optional user-defined message. This message is printed
you must first understand the full declaration of the main
first, followed by a colon, and the implementation-defined
function. The main() can accept two arguments,
message that describes the most recent error.
If a call to perror() is made when no error has e The first argument is an integer value that specifies
actually occurred, then a 'No error' will be displayed. number of command-line arguments.
The most important thing to remember is that a call to e The second argument is a full list of all of the
perror() does nothing to deal with the error condition. It command-line arguments.
is entirely up to the program to take action. For example,
The full declaration of main() can be given as
the program may prompt the user to do something such as
int main (int arg c, char *argv[])
terminate the program.
|314 | Introduction to C Programming

The integer, arg c specifies the number of arguments


passed into the program from the command line, including printf ("\n Error Opening the File");
exit (1);
the name of the program.
The array of character pointers, argv contains the list }
Gh=—fogetel(tp))
of all the arguments. argv [0] is the name of the program,
while (ch! =EOF)
or an empty string if the name is not available. argv [1] to
{
argv [argc - 1] specifies the command line argument. In putchar (ch);
the C program, every element in the argv can be used as Gin = tHeGiee
(ie o))5
a string. Moreover, elements of argv can also be accessed } Ly

as a two-dimensional array. Note that argv[argc] is a fclose (fp);


null pointer. }
In other words, each element of the array argv is
a pointer where each pointer points to a string. Thus, Output
argv [0] points to a string that contains the first parameter Enter the filename: [Link]
Hello how are you?
on the command line which is the program’s name, =

argv [1] points to the next parameter, and so on. Look 9.2 Write a program to count the number of characters
at the program given below which illustrates the use of and number of lines in a file.
command line arguments.
#include <stdio.h>
int main(int argc, char *argv[]) #include <string.h>
{ main ()
cake ales {
printf ("\n Number of argumnets passed = FILE *fp;
$d" ,argc); int ch,)no of characters = 0, no of lines = 1;
mone (Gt Op al & ebRepels ays) char filename [20];
jopaibmere
(WI Wan eraep|iahl] sa Bye ents pye(istl|))e printf("\n Enter the filename: ");
return 07 fp = fopen(filename, "r");

} if (fp==NULL)
{
In the program, the main () accepts command line argu- printf ("\n Error Opening the File");
ments through argc and argv. In the main() function, exit (1);
the value of argc is printed which gives the number of }
arguments passed. Then each argument passed is printed ch= fgetc(fp);
in the for loop using the array of pointers, argv. while
(ch! =EOF)
For example when you execute this program {
from dos prompt by writing L£ (ch=='\n’)

C:\>tc clpro.c Reema Thareja


no of lines++;
no_ of characters++;
Then argc = 3, where argv[0] = clpro.c
chy =" fgetel(£p))-
argv[1] = Reema and argv[2] = Thareja
}
9.1 Write a program to read a file character by character, if (no_of characters > 0)
and display it simultaneously on the screen. print£é ("\n In) the £idie Ss there are’ sd
lines and %d characters", filename, no_
#include <stdio.h>
of lines, no of characters);
#include <string.h>
else
main ()
printf ("\n File is empty");
{ fclose (fp);
FILE *fp;
}
int ch;
char filename [20] ; Output
printf("\n Enter the filename: ");
Enter the filename: [Link]
fp = fopen(filename, "r");
In the file [Link], there are 1 lines
if (fp==NULL) and 18 characters
O_o 08 teas Bi
9.3. Write a program to print the text of a file on screen by {
printing the text line by line and displaying the line FILE *fpl, *fp2;
numbers before the text in each line. Use command Intechiyoh2':

line argument to enter the filename. char filenamel1[20], filename2


[20] ;
elrser ();
#include <stdio.h>
printf ("\n Enter the name of the first file: ");
#include <conio.h>
gets (filenamel1);
int main ()
fflush(stdin);
{ printf ("\n Enter the name of the second file: ");
FILE *fpl;
gets (filename2);
char text[100], ch; Z
int line = 1;
fflush (stdin);

IOV, Skees (0) if ((fpl=fopen(filenamel,


"r") ) ==0)
eElrsexni)) {
if(axnge != 2)
{ print£ ("\n Error opening the first file");
printf ("\n Full information is not epee (al)
provided. Please provide a filename"); }
return 0; if ( (fp2=fopen (filename2, 'y") ) ==0)

} {
fpl = fopen(argv [1], Vise)
printf ("\n Error opening the second file");
if (fp1 == NULL) exit (1);
{ }
printf ("\n File Opening Error");
chi = foetc (£p1);
return 0;
ch2 = fgetc(fp2);
} while(chl1!=EOF && ch2!=EOF && chi==ch2)
a, = 09
while (feof (fp1) == 0)
{
/* Reading and comparing the contents
{
of two files */
ESCan tape. ese ly &ch) ;
if (ch == ‘\n’)
lq es ike Siere) (soil);
Ch2e=siGgerci(fo2));
{
line++; }
textiia) = S\0"%> lie (Gevalia)
jopenisgyene (Wexel rar, line, text); printf("\n Files are identical");
er—e ( else
printf ("\n Files are not identical");
text fi] = ch; fclose(fpl);
1++; fclose(fp2);
} getch();
teeacten
ie lhme= S084 return 0F
DEinem icc, text);
}
fclose(fpl);
getch(); Output
return 0;
Enter the name of the first filename:
} Comments
. TXT
Enter the name of the second filename:
Output
Letter. TXT
1 Hello how are you?
Files are not identical
9.4 Write a program to compare two files to check
9.5 Write a program to copy one file into another. Copy
whether they are identical or not.
one character at a time.
#include <stdio.h>
#include <stdio.h>
#include <conio.h>
#include <conio.h>
main ()
|316 | Introduction to C Programming

main () main ()

{ {
FILE *fpl, *fp2; FILE *fpl, *fp2;
igs Cleve char filenamel1[20], filename2[20],
char filenamel1
[20], filename2 [20] ; Stet Olles

ulbasyenen()) Glimseri()
printf ("\n Enter the name of the first file: "); printf("\n Enter the name of the first
gets (filenamel1); filename: ");
fflush (stdin); gets (filenamel); ‘

printf ("\n Enter the name of the second fflush (stdin);

£iless !); printf ("\n Enter the name of the second


gets (filename2); filename: ");

fflush (stdin); gets (filename2);

if ((f£pl=fopen (filenamel, "r")) ==0) fflush (stdin);

{ if ((fpl=fopen (filenamel, "r") )==0)

printf ("\n Error opening the first file"); {


exit (1); printf ("\n Error opening the first file");

} exit (1);

if ( (£p2=fopen (filename2, "w") )==0)


}
{ if ( (fp2=fopen (filename2, "w") ) ==0)

printf ("\n Error opening the second file"); {


exit (1); printf ("\n Error opening the second file");
exit (1);

[/@Copye£ HOmeEpIto -Ep2 }


chi=) get
el fpi) while ((fgets(str, sizeof(str),

while (ch! =EOF) fp1) ) !=NULL) fputs(str, fp2);

{ fclose(fp1);
MuUteC(ChreO2))- fclose(fp2);
ch = fgetc(fpl); getch();

return 0;
printf ("\n FILE COPIED"); }
fclose(fpl);
Output
fclose(fp2);
Enter the name of the first filename:
Comments
. TXT
getch();
Enter the name of the second filename:
return 0;
User Comments
.TXT
} FILE COPIED

Output
9.7 Write a program to read a file that contains characters.
Enter the name of the first filename:
Encrypt the data in this file while writing it into
Comments .TXT
another file. (For example while writing the data in
Enter the name of the second filename: User_
another file you can use the formula ch = ch —2, i.e.,
Comments .TXT
if the data contains character ‘red’ the encrypted data
FILE COPIED
becomes ‘pcb’.
9.6 Write a program to copy one file into another. Copy
#include <[Link]
multiple characters simultaneously.
#include <conio.h>
#include <stdio.h> int main(int argc, char *argv[])
#include <conio.h> {
Files | 317 |
FILE *fpl, *fp2; if(arge != 3)
char ch, {
clrscr (); printf£("\n Full information is not
if(arge != 3) provided");
{ return 0;
printf ("\n Full information is not }
provided"); Eply=— fopen\iargvl
lit a)
return 0; Se (Ee — NU)
} {
fpl = fopen(argv[1], "r'9; printf ("\n File Opening Error");
if(fpi == NULL) return 0;
{ }
printf ("\n File Opening Error"); £p2 = fopen(argv
[2], "w"');
return 0); alge (EO SS INU NLL)
} | {
fp2 = fopen(argv[2], "w"); printf ("\n File Opening Error");
ee (Fo2 == NUL) return 0;

{ }
printf ("\n File Opening Error"); while (feof(fp1) == 0)
saSeybhanal AOE {
} Escant (plaice ech)
while (feof(fp1) == 0) EPEINGE
(Ep2 a oC Chae),
{ }
EScanm(rplyesc!) ech). fcloseall
();
fprintiaGip2ra!
oo"; che—= 2) printf ("\n File copied with upper case
/*encrypted character is printed on characters");
the screen */ getch();
} return 0;
printf ("\n The encrypted data is }
written to the file");
fclose(fp2); TS
fcloseall (); File copied with upper case characters

getch();
LS reemaie 9.9 Write a program to merge two files into a third
} file. The names of the files must be entered using
command line arguments.
Output
7 #include <stdio.h>
The encrypted data is written to the file #include <conio.h>

; int main(int argc, char *argv[] )


9.8 Write a program to read a file that contains lower case {
characters. Then write these characters into another FILE *fp1, *fp2, *fp3;
file with all lower case characters converted into charac
upper case. (e.g., if the file contains data—‘red’ it clrser ();
must be written in another file as “RED’). if(argc != 4) // Read three filenames
from the user
#include <stdio.h>
#include <conio.h> { ; f ;
printf ("\n Full information is not
int main(int argc, char *argv[]) ;
provided");
{ return 0;
FILE *fpl, *fp2;
naan Epi fopeni(axrgy
ly, axel);
Girser
(7
|318 Introduction to C Programming

gets (str);
fflush(stdin);
printf("\n File Opening Error"); iBopenwonene
(Geo), Uys", ihere))p
reSiebhan, (0)F fclose (fp);
} }
£p2 = fopen(argv
[2], "2");
Ge (SejO2 Ser NUP)
Output
{ Enter the filename: [Link]
printf ("\n File Opening Error"); Enter the text: Good Morning
ig aibheg\, (0)F
9.11 Write a program to read the details' of a student and
} then print it on the screen as well as write it into a
£p3 = fopen
(argv [is] , -"w");
file. ;
if (fp3 == NULL)
{ #include <stdio.h>
printf("\n File Opening Error"); #include <conio.h>
return 0; int main ()

} {
while (feof (fp1) != 0) FILE *f£p;
typedef struct student
{
fscanf
(fpl1, "Sc", &ch); {
Inte LOM Meno
isjonenjayere
(sos, exe _ Clay))p
char name [80] ;
}
float fees;
while (feof (fp2) != 0)
char DOB[80];
{
}STUDENT;
fscanf
(fp2, "Sc", &ch);
STUDENT stud1;
EpIEintitr
psa! oe, Chi)
clrscr();
}
fcloseall
(); fp = fopen("student [Link]", "w");
printf ("\n File merged"); if (fp == NULL)
getch();
{
rajevhagl (0)7
printf ("\n File Opening Error");
} return 0;

Output }
printf("\n Enter the roll number: ");
File merged
scanf ("sd", &stud1l.roll_no);

9.10 Write a program to read some text from the keyboard printf("\n Enter the name: ");

and store it in a file. scanf ("%s", [Link]);


printf ("\n Enter the fees: ");
#include <stdio.h>
scanf ("S£", &[Link]);
#include <string.h>
main () printf ("\n Enter the DOB: ");

{ scanf ("%s", [Link]);

FILE *fp;
char filename[20], str[100]; // PRINT ON SCREEN
printf("\n Enter the filename: ");
fp = fopen(filename,
"w"); printf ("\n *** STUDENT’S DETAILS ***");
if (fp==NULL) printf("\n ROLL No. = $d", studl.roll_no);
{ printf ("\n NAME = %s", [Link]);
printf ("\n Error Opening The File");
printf ("\n FEES,= %f", [Link]);
exit (1);
printf ("\n DOB = %s", [Link]);
} // WRITE TO FILE
printf ("\n Enter the text: ");
Files | 319 |

printf ("\n NAME = $s", [Link]);


Hjoveatralicse
(ee) WEXSl Cs See Creu studl.roll_ no, printf ("\n FEES = %f£", [Link]);
[Link], [Link], [Link]); printf ("\n DOB = $s", [Link]);

£close (fp); fclose (fp);


getch (); getch();
i@=shebhaial) 10)A return 0;

Output y Output
Enter the roll number: 01 kk KK KKKSTUDENT’S DETAILS **** ee
Enter the name: Aman ROLL No. = 01
Enter the fees: 45000 NAME = Aman
Enter the DOB: 20-9-91 FEES = 45000
*kAKKKKEKSGTUDENT’S DETAILG **
ee eeK DOB = 20-9-91

ee ee 9.13 Write a program to read the details of student until a


NAME = Aman ‘_]’ is entered and simultaneously write the data to a
FEES = 45000 file.
DOB = 20-9-91 ;
#include <stdio.h>
9.12 Write a program to read the details of a student from #include <conio.h>
a file and then print it on the screen. int main()
#include <stdio.h> {
FILE *fp;
#include <conio.h>
typedef struct student
int main() {

{ aiiahe eCoyll
dL igteys
FILE *fp; char name [80] ;
typedef struct student float fees;
{ char DOB[80] ;
int rolleno; }STUDENT ;
char name [80] ; STUDENT stud1;
float fees; elleexene
())5
char DOB[80]; fp = fopen("student_details.dat", "w");
} STUDENT ; if (fp == NULL)
{
STUDENT stud1; printf ("\n File Opening Error");
clrscr(); igaebban, (OF

fp = fopen("student_details.dat",
"r"); }
‘ '
GF fpt== NULL) printf("\n Enter the roll number: e
");
Dire

{ scanf("%d", &stud1.roll_no);
é i Ab, ceo ens
printf("\n File Opening Error"); 7 eeunet wee | )
return 0;
printf("\n Enter the name: ");
} scanf ("%s", [Link]);
// READ FROM FILE
printf ("\n Enter the fees: ");
fscanf(fp,"sd ts tf %s", &Studl.roll_no,
scanf ("%f", &[Link]);
[Link], &[Link], [Link]);
printf ("\n Enter the DOB: ");
// PRINT ON SCREEN
scanf ("$s", [Link]);
printf ("\n *** STUDENT’S DETAILS KKM) forinté(Fp, "sds ss tite, Sicucisecollee
print£("\n ROLL No. = %d", studl.roll_no); no, [Link], [Link], studl.
|320 |_Introduction to C Programming

DOB); }
fflush(stdin);
printf ("\n Enter the roll number: "); Output
scanf("%$d", &[Link] no); Enter the characters: abcdef*
} Written to the file

por geS (EDN 9.15 Write a program to count the number of lower case,
Sees upper case, numbers, and special characters present
ee Thee in the contents of a file. (Assume that the file contains
the following data: 1. Hello, How are you?)
Output #include <stdio.h>
Enter the roll number: 01 #include <conio.h>
Bote the vanes Minn int main(int arg c, char *argv[])

Enter the fees: 45000 {


FILE *fp;
Enter the DOB: 20-9-91
int ch, upper_case = 0, lower_case = 0.
Enter the roll number: 02
numbers = 0, special chars = 0;
Enter the name: Divij
elrsecr();
Enter the fees: 45000
ii(arge != 2)
Enter the DOB: 29-10-91
Enter the roll number: 03
{
printf ("\n Full information is not
Enter the name: Saransh
provided");
Enter the fees: 45000
return 0;
Enter the DOB: 2-3-92 }
Enter the roll number: -1 fp = fopen(argv([1], “*")7
if (fp == NULL)
9.14 Write a program to read characters until a ‘*’ is {
entered. Simultaneously store these characters in a printf£("\n File Opening Error");
file. return 0;
#include <stdio.h> }
#include <conio.h> 1 0;
while (feof (fp) == 0)
int main()
{
{ Fe, ey BSecant (fp, "sol ech).
(ch s= ‘AY &&S ch <= \Z")
ate
char _—
upper case++;
Lieay
"w");
fp = fopen("[Link]", ‘a && NEch <= ‘z’
(ch >=>= ‘a’
ifif (ch z')
: lower _case++;
if (fp == NULL)
ae (Clases VOR is lay cS Cy)
{ numbers++;
printf ("\n File Opening Error"); 1
else
return 0;
special _chars++;

printf("\n Enter the characters: ");


fclose (fp);
scant ("%c" , &ch)-
printf ("\n Number of upper case
while(ch != ‘*’)
characters = sd", upper case);
{ 1 printf ("\n Number of lower case
7 no "W .

fprintf (fp, "se", ch); characters = %d", lower case);


scanf ("%c",- &ch);
printf("\n Number of digits = $d",
numbers);
printf("\n Written to the file"); printf ("\n Number of special characters
fclose (fp); = %d", special chars);
getch(); getch();
return 0;
return 0;
Files 321 |

} stud1[i].name, stud1
[i] .marks);

Output
printf ("\n Data Written to the file");
Number of upper case characters = 2
fclose (fp);
Number of lower case characters =
Number of digits = 1 See i
Number of special characters = 2 peanfoe

9.16 Write a program to write record of students to a file


using array of structures. Output
bs KkKKKKKEXSTUDENT’S DETAILG *******
#include <stdio.h> ROLL No. = 01
#include <conio.h> NAME = Aditya
int main() MARKS = 78
{ ane sss
KKKKKKKKSTUDENT’S DETAILS KKKEKKKK

typedef struct student ROLL No. = 02


{ NAME = Goransh

Inte roligenoy; MARKS = 100


char name [80]; *kk*KAKKEXOTUDENT’S DETAILG *******

NESS ROLL No. = 03


} STUDENT ; NAME = Sarthak
STUDENT stud1[5]; MARKS = 81
shige al.9 Data Written to the file
Elllzasyetie
(5
9.17 Write a program to append a record to the student’s
Epes copen Mstudentadetarlsntsctel,.
Mw); file
if (fp == NULL)
#include <stdio.h>
{ #include <conio.h>
printf ("\n File Opening Error"); int main()
return 0; {

} FILE *fp;
sgope(Gl es Op ak << Sygaures)) ae struct student

sighs iaoyliily sayeiR


printf ("\n Enter the roll number: "); =
char name[80] ;
eeaiaue (WECM,
noe "
weieurelil
[lal]]
7
setollil, ive);. din eimackss

printf ("\n; Enter the name: "); } STUDENT;


scanf("%$s", studl1
[i] .name); STUDENT studi;
printf ("\n Enter the marks: "); clrscr ();
scanf("$d", &studl1[i] .marks); fp ="ftopen (student,
detarlis txt", Yall)
} Hae (Ges) Se NONE IB))
// PRINT ON SCREEN {
fortite 050 eS ee) printf("\n File Opening Error");
return 0;
{
}
printf ("\n *** STUDENT’ S DETAILS ***"); printf ("\n Enter the Roll Number = ");
printf ("\nROLL No.
=%d", stud1 [i] .roll_no);
scanf("%d", &stud1.roll_
no);
Rote een ce eae
printf ("\n NAME = $s", stud1 [i] .name);

[i] .marks);
1 PEST eet Cosy
MARKS = $d", stud
("\nnté
pri
// WRITE TO FILE printi ("\n Enter the Marks =");
fprint£(fp,"sd %s a"; studi[i] .roll_no, scanf("%$d", &[Link]);
|322 | Introduction to C Programming

Fominth (ito Wms ws ital studd. printf ("\n The details of student are");
roll_no, [Link], [Link]);
/* After entering the record add a -1 to prints(" *dts sd" studisroilleno,
the file to denote the end of records */ [Link], [Link]);
shovaubmeng (awe, tyelU, cul))s break;
printf("\n Data Appended"); }
fclose (fp);
getch(); if (found==0)
return 0; printf ("\n Record not found in the file");
} fclose(fp1); '
return 0;
Output
}
Enter the Roll Number = 04
Enter the Name = Sanchita Output
Enter the Marks = 50 Enter the roll number of the student whose
Data Appended record has to be read: 02
The details of student are - 02 Goransh 100
9.18 Write a program to read the record of a particular
student. 9.19 Write a program to edit the record of a particular
student.
#include <stdio.h>
#include <conio.h> #include <stdio.h>
int main() #include <conio.h>

{ int main()
FILE *fpl; {
typedef struct student FILE *fpl, *fp2;
typedef struct student
{
abaye vaoylhil Saloyp {
ubiaie, etepll water
char name [80];
char name [80] ;
int marks;
int marks;
}STUDENT;
}STUDENT;
STUDENT studl1;
STUDENT studl;
int found =0, rno;
Int £ound )=0), uno];
elrscr();
clrscr();
fpl = fopen("student [Link]", "r");
£pl = £open("student
details txt", "r");
if (fpl == NULL) if(fp1l == NULL)
{ {
printf("\n File Opening Error"); printf ("\n File Opening Error");
return 0; igeyblian, (0)A
} }
printf("\n Enter the roll number of the £p2 =—topen (tempor
txt twill)
student whose record has to be read: "); al (poe = =e NUL)
scanf ("%Sd", &rno); {
while (1) printf ("\n File Opening Error");
{ igSebaggy (0)F

fscanf(fpl, "%d ss 2d", &[Link]


no, }
[Link], &[Link]); printf ("\n Enter the roll number of the
hig (GShebYolil jwafephall. sete) ey Sh) student whose record has to be
modified: ");
break;
scanf ("%d", &rno);
if (studl.roll_
no == rno)
while (1)
{
found! j=" Ai.
{
Files | 323

fscanf (fp1, "td", &studl-roll_no); /* Copy the contents of temporary file


if ([Link]
no == -1) into actual file */
break; while (1)
if (studl..roll»no: ==srmoe) {
{ Escant (fp2, "sd" /estudilyizolis
no);
found = 1; bing (Siebel
.reenlil, iaio=——11))
fscant (fpl, "%s Sd", [Link], break;
&[Link]); fscanf (fp2, "Ss $d",[Link],
printf ("\n The details of existing &[Link]);
record are "); Eprint& (Epil, "sd ssmcdN, Studios
printé(" +d ts td", s€udlirollino, no, [Link], [Link]);
[Link], [Link]);
printf("\n Enter the modified name of }
the student: "); fclose(fpl1);
scanf("Ss", [Link]); fclose(fp2);
printf ("\n Enter the modified marks of printf ("\n Record Updated");
the student: "); getch();
scanf("%d", &[Link]); return 0;
/* Write the modified record to the }
temporary file */
EpmInee (Ep2, Usd ssecd' Sstudienoll
no), Output
[Link], [Link]); Enter the roll number of the student whose
} record has to be modified: 03
else The details of exisitng record are - 03
{ Sarthak 81
/* Copy the non-matching records to Enter the modified name of the student:
the temporary file */ Sarthak
Escant(ipl,
'ss +d" -[Link], Enter the modified marks of the student: 85
&[Link]); Record Updated
fprintf (£p2, "sd %s sd", [Link]
no,
[Link], [Link]); 9.20 Write a program to delete the record of a particular
student.
} #include <stdio.h>
eversayese
(Teo, Werel | Sal))p
#include <conio.h>
fclose(fp1);
int main()
fclose (fp2);
ise (Ee uINC==0)) {
EILE, <p Lp2
printf ("\n The record with roll number &d
typedef struct student
was not found in the fille”, ro);
else {
HME, TOIL soles
{ char name [80];
fpl = fopen("student_ [Link]", "w");
int marks;
if (fpl == NULL)
}STUDENT ;
{
STUDENT studl1;
printf("\n File Opening Error");
ani LOUNGs:=OheeEhoy
return 0;
elilrasxens
(jis
} fpilm——p open studentmdetarl
ste lysis OT
£p2 =) fopen("[Link]"
"r");.
i£ (Ep1, == NULD)
te (fp2 == NUL)
{ {
printf ("\n File Opening Error");
printf ("\n File Opening Error");
return OF
return 0;

}
|324 | Introduction to C Programming

fp2 = fopen("[Link]",
"w"); }
PEE p25=—6 NU) // Copy the contents of temporary file
{ into actual file
printf ("\n File Opening Error"); while (1)
return 0; {
} fscanf (fp2,"%d",
&stud1. roll. no);
printf("\n Enter the roll number of the if (stud1l.roll_no==-1)
student whose record has to be break;
deleted: "); fscanf(fp2, "%s td",[Link],
scanf ("%d", &rno); &[Link]); t
while (1) Eprmintiatipd
sd st Fda Steud
iss rol ae
{ no, [Link], [Link]);
fscanf (fp1, "$d", &stud1l.roll_no); }
if (studl.roll_no == -1) }
break; forint
s (Epi sd “sea e
if (studl -roll_no == rno) ECTOSeGEp
IN);
{ fclose (£p2); 7
found = 1; printf ("\n Record Deleted");
fscanf (fpl, "Ss $d", [Link], /* The programmer may delete the temp
&[Link]); file which will no longer be required */
} getch();
// The matching record is not copied return 0;
to temp file }
else
Output
{
// Copy the non-matching records to Enter the roll number of the student whose
the temporary file record has to be deleted: 01

fscanf(fpl,
"Ss %d", [Link], Record Deleted

&[Link]);
9.21 Write a program to store records of an employee in
Spanish (E27. sd eose od), Stud rolls)
employee file. The data must be stored using binary
no, [Link], [Link]);
file.
}
} #include <stdio.h>
seoyesinie (bee. Exel salir #include <conio.h>
fclose(fp1); main ()
fclose(fp2); {
if (found==0) typedef struct employee
printf ("\n The record with roll number &d {
was not found in the file", rno); int emp_code;
else char name [20] ;
{ int hra;
fpl = fopen("student_details.txt",
"w"); int da;
if (fp1 == NULL) int ta;
{ bi
printf("\n File Opening Error"); FILE, *Epy
return 0; struct employee e[5];
} int i;
fp2 = fopen("[Link]",
"r"); fp = fopen("[Link]",
"wb");
if (fp2 == NULL) if (f£p==NULL)
{ {
printf("\n File Opening Error"); printf ("\n Error opening file");
return 0; pia ((al))e
Files | 325 |

printf ("\n Enter the details ");


ar@S (Sl SS Waal a Gyn shes) fread(&e,
sizeof (e), 1, fp);
{ if (feof (fp) )
printf ("\n\n Enter the employee code:"); break;
scanf ("%d", &e[i] .emp_code); printf ("\n\n Employee Code: d", e.emp_ code);
printf ("\n\n Enter the name of the printf ("\n\n Name: %s", [Link]);
employee: "); printf ("\n\n HRA, DA, and TA: %d %d
scanf ("%s", e[i] .name); sd", [Link],
[Link], [Link]);
printf ("\n\n Enter the HRA, DA, and TA: ");
}
scanf("%d %d %d", &e[i] .hra, &e[i] .da, fclose (fp);
&e [i] .ta); i getch();
fwrite(&e[li], sizeof(e[i]),1, fp); return 0;
}
fclose (fp); Output
getch (); Employee Code: 01
recuse Ol. Name: Gargi
} HRA, DA and TA: 10000 5000 2000
Employee Code: 02
Output
Name: Nikita
Enter the employee code: 01
HRA, DA and TA: 10000 5000 2000
Enter the name of the employee: Gargi
Enter the HRA, DA and TA: 10000 2000 5000 9.23 Write a program to append a record in the employee
Enter the employee code: 02 file (binary file).
Enter the name of the employee: Nikita
#include <stdio.h>
Enter the HRA, DA and TA: 10000 2000 5000
#include <conio.h>
9.22 Write a program to read the records stored in main ()
‘[Link]’ file in binary mode. {
typedef struct employee
#include <stdio.h>
#include <conio.h> {
iit. empEcode;
main ()
char name[20] ;
{
int hra;
typedef struct employee
int da;
{
int emp code; SANE, WEP

char name [20]; iG


int hra; FILE *fp;
int da; SEBUCE RCmplOVeeme),
int ta; Ibe: als

We fp = fopen("[Link]", "ab");
FILE *fp; Ae (sfo=— NU)
struct employee e; {
iighe, Al2 printf ('\n Error opening file");
elrser (); exit (1);

fp = fopen("[Link]",
"rb"); }
if (fp==NULL) printf ("\n\n Enter the employee code:");
{ scanf ("%d", &e.emp_code);
Pratite ("\n Error opening tile"); printf ("\n\n Enter the name of employee: ");
exit (1); scanf("%s", [Link]);
} printf ("\n\n Enter the HRA, DA, and TA:");
printf ("\n THE DETAILS OF THE EMPLOYEES ARE Mh scanf ("$d $d $d", &[Link], &[Link], &[Link]);
while (1) fwrite(&e, sizeot(e), 1, fp);
|326 z Introduction to C Programming

fclose (fp); found=1;


printf ("\n Record Appended"); printf ("\n The existing record is: *d
getch(); $s td %d sd", e.emp_code, [Link],
return 0; [Link], [Link], [Link]);

} printf ("\n Enter the modified name: ");


scanf("%s", [Link]);
Output printf ("\n Enter the modified HRA, TA,
Enter the employee code: 06 and DA: ");

Enter the name of employee: Tanya scanf ("$d $d $d", &.hra, &[Link], &[Link]);

Enter the HRA, DA and TA: 20000 10000 3000 fwrite(&e,


sizeof (e) ,1,f£pa);
}
9.24 Write a program to edit the employee record stored else *
in a binary file. fwrite(&e,
sizeof (e),1,fp2);

#include <stdio.h> }
#include <conio.h> fclose(fpl);

main () fclose(fp2);
if (found==0)
{
printf("\n Record not found");
typedef struct employee
else
{
int emp_code; {
fpl = fopen("[Link]",
"wb");
char name [20];
if (£p1==NULL)
int hra:
int da;
{
printf ("\n Error opening file");
int tai;
exit (1);
ba
FILE *fpl, *fp2;
}
£p2 =" £open\(“temprcmp.
ets, Leb)
struct employee e;
if (£p2==NULL)
int i, ec, found = 0;
{
elnscr
());
printf ("\n Error opening file");
£pis =) fopen ("emplloyeesext Fatrbl);
exit (1);
if (fp1==NULL)
}
{ while (1)
printf ("\n Error opening file");
{
exit (1); fread(&e, sizeof(e),1,fp2);
} if (feof (£p2) )
£p2> = fopen ("temp emp. txt" 7 "wo"; break;
if (fp2==NULL) fwrite(&e,
sizeof (e),1, fpl);
{ }
printf ("\n Error opening file"); }
exit (1); fclose(fpl1);
} fclose(fp2);
printf ("\n Enter the code of the employee printf("\n Record Edited");
whose information has to be edited:"); getch();
scanf ("%d", &ec)); return’ 0;

while (1) }
{ Output
fread (&e, sizeof (e),1,fp1);
Enter the code of the employee whose
if (feof (£p1) )
information has ‘to be edited: 01
break;
The existing record is: 01 Gargi 10000 5000
if (e.emp_ code==ec)
2000
{ Enter the modified name: Gargi
Files | 327 |

Enter the modified HRA, TA, and DA: 20000


10000 30000
Notey ‘Ifa file has bee update and —
Record Edited
later ifyou want to switchfrom reading to
writing or vice versa, thenyoumust use —
the fseek(). — /

9:a FUNCTIONS FOR SELECTING A


Table 9.5 gives the interpretation of the fseek () .
- RECORD RANDOMLY © :
In this section we will read about functions that are BE\atac Beye Origin field in fseek ()
used to randomly access a record stored in a binary file.
These functions include fseek(), ftell(), rewind (),
fgetpos( ), and fsetpos (). Saakes OL, SEEK SET); move tosithe SARE of Hel

9.8.1 fseek()

The function £seek () is used to reposition a binary stream. fseek (fp, OL, SEEK_END); | go to the end of the file
The prototype of fseek() function which is defined in
[Link] be given as, fseek (fp, m, SEEK_CUR); | move forward by m bytes
in the file from the current
int fseek(FILE *stream, long offset, int location
origin);
fseek (fp, -m, SEEK_CUR); |move backwards by m bytes
fseek() is used to set the file position pointer for the in file from the current
given stream. The variable offset is an integer value that location
gives the number of bytes to move forward or backward in fseek (fp, -m, SEEK_END); |move backwards by m bytes
the file. The value of offset may be positive or negative, from the end of the file
provided it makes sense. For example, you cannot specify
The fseek() is primarily used with binary files as it has
a negative offset if you are starting at the beginning of the
limited functionality with text files.
file. The origin value should have one of the following
values (defined in stdio.h): 9.25 Write a program to randomly read the nth records of
e SEEK_SET: to perform a binary file.
input or output on offset Programming— #include <stdio.h>
Tip: While using—
bytes from start of the file #include <conio.h>
_fseek 6, ifthe main ()
e SEEK CUR: to perform third paramet
input or output on offset {
typedef struct employee
bytes from the current
position in the file
{
int emp) code;
e SEEK END: to perform char name[20];
input or output on offset int hra;
bytes from the end of the int da;
file int ta;

e SEEK SET, SEEK CUR and SEEK _END are defined Ve


FILE *f£p;
constants with value 0, 1, and 2, respectively.
struct employee e;
On successful operation, fseek() returns zero and in Interesult,
rec! no;
case of failure, it returns a non-zero value. For example, fp = fopen("[Link]",
"rb");

if you try to perform a seek operation on a file that is not if (£p==NULL)

opened in binary mode then a non-zero value will be {


printf("\n Error opening file");
returned. fseek() can be used to move the file pointer
exit (1);
beyond a file, but not before the beginning.
|328 | Introduction to C Programming

printf ("\n\n Enter the rec no you want to if (fp==NULL)


read: "); {
scanf ("%d", &rec_no); printf ("\n Error opening file");
if(rec_no >= 0) exit (1);

of ‘
/* from the file pointed by fp read a for tiesise0 ee)
record of the specified record
starting from the beginning of the
{
fseek(fp, i*sizeof(e), SEEK_SET);
file*/
fread (&e, sizeof(e), 1, fp);
fseek (fp, (rec_no-1) *sizeof (e) , SEEK_SET);
printf ("\n EMPLOYEE CODE: $d", e.emp_ code);
result = fread(&e, sizeof(e),1, fp);
if (result printf("\n Name: %s", [Link]);
==" :
{ printf ("\n HRA, TA, and DA: %d %d %d",

printf ("\n EMPLOYEE CODE: %d", e.emp_code); [Link], [Link], [Link]);


printf ("\n Name: $s", [Link]); }
printf ("\n HRA, TA and DA: %d %d %d", fclose (fp);
e-hra;--esta;-[Link]) +; getch (); .

} return 0;
else
printf ("\n Record Not Found");
} Output
foto Saee ys EMPLOYEE CODE: 06
getch (); Name: Tanya
og ete, HRA, DA and TA: 20000 10000 3000
} EMPLOYEE CODE: 05

Output Name: Ruchi


HRA, DA and TA: 10000 6000 3000
Enter the rec_no you want to read: 06
EMPLOYEE CODE: 06 9.27 Write a program to edit a record in binary mode
Name: Tanya using fseek ().
HRA, DA and TA: 20000 10000 3000
#include <stdio.h>
9.26 Write a program to print the records in reverse Pineladeue condo:hs
order. The file must be opened in binary mode. Use mai
fseek().
{
#include <stdio.h> typedef struct employee

#include <conio.h> {
main () int emp code;

{ char name [20];

typedef struct employee int hra;

{ int da;
inte emp codes, int ta;
char name [20]; La
int hra; FILE *f£p;
int da;
struct employee e;
int ta;
sas TRE 1916)
us fp = fopen("[Link]",
"r+");
FILE *fp; if (fp==NULL)
struct employee e;
{
int result,i;
printf ("\n Error opening file");
fa fopen ("[Link]",
"rb");
exit (1);
Files | 329 |

} main ()
printf ("\n Enter record no. tobe modified: "); {
scanf ("%d", &rec_no); FILE *fp;
elniie Cp
fseek(fp, (rec_no-1)*sizeof(e),
SEEK SET);
shige aly
fread(&e, sizeof(e), 1, fp);
fp=fopen ("abe", "w");
printé£ ("\n Enter modified name of the employee: ");
if (fp==NULL)
scanf("%s", [Link]);
{
printf ("\n Enter the modified HRA, TA, printf ("\n Error Opening The File");
and DA of the employee: "); exit (1);

scant ("td %d %d", &e. hraf&[Link], &[Link]); }


fwrite(&e, sizeof(e), 1, fp); while ((c=getchar()
) !=EOF)
joule
(CS, Elo)
fclose (fp);
ial Se Geel (GE\o)))
printf ("\n Record Edited");
fclose (fp);
getch ();
fD—LOpen (alocuiat))F
return 0; if (fp==NULL)
} {
printf ("\n Error Opening The File");
Output exit (1);
Enter record no. to be modified: 04 }
Enter the modified HRA, TA, and DA of the while (ftell (fp) <n)

employee: 30000 1000 5000 {


Record Edited G= fEgete (£p));
jouenbanene (TRG ele

}
9.8.2 ftell () fclose (fp);

The ftell1() function is used to know the current position }


of file pointer. It is at this position where the next input Output
or ouput operation will be performed. The syntax of
abcdefghijkjdqjdh
ftell(), defined in stdio.h, can be given as
long ftell (FILE *stream); Note g " ttell 0) is useful \ ve todeal
Q ©
Here, stream points to the file whose file position indicator with text files for w jonofthe
has to be determined. If successful, ftel1() function
_ data cannot
be calculated. —
returns the current file position (in bytes) for stream.
However, in case of error, ftel1() returns -1. 9.8.3 rewind ()
When using ftell(), error can occur either because
of two reasons: rewind() is used to adjust the position of file pointer so
that the next I/O operation will take place at the beginning
e First, using ftell() with a device that cannot store of the file. It is defined in stdio.h and its prototype can be
data (e.g., keyboard). given as
e Second, when the position is larger than that can
void rewind(FILE *f);
be represented in a long integer. This will usually
happen when dealing with very large files. rewind () is equivalent to calling fseek () with following
parameters:
Look at the program code which illustrates the use of
fseek(£,0L,SEEK_
SET);
TEESHUIN(()
/*The program writes data to a file, saves the number We have seen earlier that if a file is opened for
of bytes stored in it in a variable n (by using ftel11()) writing and you want to read it later, then you have to close
and then re-opens the file to read n bytes from the file and the existing file and reopen it so that data can be read from
simultaneously display it on the screen.*/ the beginning of the file. The other alternative is to use the
|330 | Introduction to C Programming

rewind (). Look at the program code given below which On success, fgetpos() returns zero and in case of
demonstrates the use of rewind (). an error a non-zero value is returned. The value of pos
#include <stdio.h>
obtained through fgetpos () can be used by the £setpos ()
main () to return to this same position.
{
FILE *fp; 9.8.5 fsetpos ()
char feedback
[80] ;
Lint. =O The fsetpos() is used to move the file position indicator
fp = fopen("[Link]",
"w+"); of a stream to the location indicated by the information
if (£p==NULL) obtained in ‘pos’ by making a call to the fgetpos() .
{ Like fgetpos(), fsetpos() is defined in stdio.h and
printf ("\n Error Opening The File"); its prototype can be given as .
exit (1);
int fsetpos(FILE *stream, const fpos_t pos);
}
printf ("\n Provide comments on this book: "); Here, stream points to the file whose file pointer
scanf("%s", feedback); indicator has to be re-positioned. pos points to positioning
while (feedback
[i] !=’\0’)
information as returned by fgetpos. j
{ On success, fsetpos() returns a zero and clears the
fputc (feedback
[i], fp);
EOF indicator. In case of failure it
i++;
returns a non-zero value.
}
rewind (fp);
After the successful call to
printf("\n Contents of the file are: "); fsetpos(), the next operation
while (feof (fp) ==0) on a stream in update mode may
jousstiayene (Weel SRe(Siee!(Gie)0)))h __ be input or output. Look at the
fclose (fp); "before the first byte | program code given below which
return 0; of the fi illustrates the use of fgetpos ()
} and fsetpos () functions.
// The program opens a file and reads bytes at several
Output
different locations.
Provide comments on this book: Good
Contents of the file are: Good #include <stdio.h>
main ()
However, you must prefer to use fseek() equivalent
code rather calling rewind() because it is impossible to {
FILE *fp;
determine if rewind() was successful or not.
fpost_pos;
char text [20];
9.8.4 fgetpos () Epy-=y open ("practise
.c", Nivaboi Ne)

Lf (Ep ==) NUL)


The fgetpos() is used to determine the current position
of the stream. The prototype of the fgetpos () as given in
printf ("\n Error opening file");
[Link]
exit (1);
int fgetpos(FILE *stream, fpos_t *pos); }
/* Read some data and then check the
Here, stream is the file whose current file pointer position
position. */
has to be determined. pos is used to point to the location
Ereadi(textr eswzeom (Chai) 20) tp);
where fgetpos() can store the position information. In if (fgetpos(fp, &pos) != 0)
simple words, fgetpos () stores the file position indicator
{
of the given file stream in the pos variable. The pos printf ("\n Error in fgetpos()");
variable is of type fpos_t which is defined in stdio.h exit (1);
and is basically an object that can hold every possible }
position in a FILE. fread (text pasizeoh (Char) 20peeo);
Files | 331 |

printf ("\n 20 bytes at byte %ld: %s",


pos, text);
9.10 RENAMING THE FILE
The function rename () as the name suggests is used to
/* Set a new random position and read rename a file. The prototype of the function is
more data */
pos) =" 90); int rename(const char *oldname, const char

if (fsetpos(fp,
&pos) != 0) *newname)

{ Here, oldname specifies the pathname of the file to be


printf("\n Error in fsetpos()"); renamed and newname gives the new pathname of the file.
exit (1); On success, rename () returns zero. In case of error,
} Z it will return a non-zero value and will set the errno to
fread(text,
sizeof (char), 20, fp);
indicate the error. When an error occurs neither the file
printf ("\n 20 bytes at byte %ld: $s",
named by oldname nor the file named by newname shall
pos, text);
be changed or created.
fclose (fp);
Points to remember about rename ()
}
e Ifthe oldname specifies pathname of a file that is not
Output
a directory, the newname shall also not point to the
20 bytes at byte 20: #include <conio.h>
pathname of a directory.
ma
20 bytes at byte 90: getch(); e Ifthe oldname specifies the pathname of a directory
return 0; then the newname shall not point to the pathname of a
} file that is not a directory. In this case, if the directory
Only use values for fsetpos() that are returned from named by the newname already exists then it shall be
removed and oldname will be renamed to newname.
fgetpos().
Look at the program code given below which illustrates
the use of rename().
9.9 xremove() _ #include <stdio.h>
The function remove() as the name suggests is used main()
to erase a file. The prototype of remove() as given in {
int success=0;
stdio.h can be given as
success = rename("[Link]",
int remove(const char *filename); "[Link]");
if (success != 0)
The remove () will erase the file specified by filename.
printf ("\n The file could not be renamed");
On success, the function will return zero and in case of
return 0;
error, it will return a non-zero value.
If filename specifies a directory, then remove (file-
name) is the equivalent of rmdir (filename). Other-
wise, if filename specifies the name of a file then remove
(filename) is the equivalent of unlink (filename).
The tmpfile() function is used to create a temporary
Look at the program given below which deletes the file
file. The tmpfile() opens the corresponding stream
"[Link]" from the current directory.
with access parameters set as "w+". The file created
#include <stdio.h> with tmpfile() will be automatically deleted when all
main ()
references to the file are closed, i.e., the file created will
be automatically closed and erased when the program has
remove ("[Link]");
return 0;
been completely executed. The prototype of tmpfile() as
given is stdio.h header file is

, You may specifthe


y pathof the file which has FILE * tmpfile (void);

¢ 9¢ deleted as theargument of remove (). On success, tmpfile() will return a pointer to the stream
of the file that is created. In case of an error, the function
|332 | Introductionto C Programming

will return a null pointer and set errno to indicate the error. Now the file created can be used in the same way as any
The function can be used in the following manner: other text or binary file.
FILE *tp = tmpfile();

a
e A file is a collection of data stored on a secondary ten. When it is bufece. characters are aed inte -
storage device such as a hard disk. nally and then written out as a group. In order toforce
a e When a stream linked to a disk file is created, a buffered characters to be output on the destination .
buffer is automatically created and associated with device before the buffer is full, use the 1fflush of
_the stream. e fseek() is used to reposition a bi rystream.
ts
e A file must be first opened before data can be read The ftell1() function is used to know the current
= position of file pointer. It is at this position at
from it or written to it. In order to open a file and asso-
© ciate it with a stream, the fopen () function is used. which the next input or output operation will be —
performed.
e To close an open file, the fclose () function is used —
which disconnects a file pointer from a file. Eclose e The fgetpos() is used to determine the current —
() function not only closes the file but also flushes position of the stream. The rename() function Ss.
all the buffers that are maintained for that file. used to rename a file. The remove() function is
used to erase a file.
e If you have opened a stream for updating and later
you want to switch from reading to writing or vice e The tmpfile() function is used to create a tempo-
versa, you must first use the fseek() or rewind rary file. The tmpfile() opens the corresponding
() function. : stream with access parameters set as "w+". The file
created with tmpfile() will be automatically de-
e When an output stream is unbuffered, information
leted when all references to the file are closed.
appears on the destination device as soon as it is writ-

Binary file A binary file is a file which may contain any Standard input Standard input is the ae from
type of data, encoded in binary form for computer
which the program receives its data.
storage and processing purposes.
Standard output Standard output is the stream where
Buffer A buffer is a block of memory that is used for
temporary storage of data, that has to be read from or
a program writes its output data.
written to a file. Stream Stream is a logical interface to the devices that
File A file is a collection of data stored on a secondary are connected to the computer. ~
storage device like hard disk. Text file A text file is a stream of characters that can be
Standard error Standard error is basically an output sequentially processed by a computer in the forward
stream used by programs to report error messages or direction. ~~
diagnostics.

Fill in the Blanks 4. A file must be opened in mode if it is


1. is a collection of data. being opened for updating.
® the standard <ircams in © Gre / 5. function can be used to move the file _
, and marker at the beginning of the file.
Se are pre-connected input and output 6. If a file is opened in ‘wb’ mode then it is a
channels between
a text terminal and the program. file opened for writing.
__Files_| 333 |

7. Block input in binary file is done using the 7. Which function returns the next character from
function. stream, EOF if the end of file is reached, or if there
is the stream where a program writes is an error?
its output data. (a) fgetc() (b) fgets()

EXERCISES
temporary
is a block of memory that is used for
storage of data.
(c) fputc() (d) fwrite ()

10. The creation and operation of the buffer is State True or False
automatically handled by the
1. You can use a file without opening it.
ik. file can be processed sequentially as
2. It is mandatory to close all the files before exiting
well as randomly.
the program.
function closes the file and flushes all
3. stderr is a standard stream in C.
_the buffers that are maintained for that file.
4. Anerror will be generated if you try to position the
. To use fprintf (),to write on the screen specify
file marker beyond EOF.
in place of the file pointer.
5. A file can be read if and only if it is opened in “r”
14. If you have opened a stream for updating and
mode.
later you want to switch from reading to writing or
6. Binary files are slower than text files.
vice versa, you must first use the or
function. 7. In text files, the data is stored in internal format of
the computer.
15. The symbolic constant EOF is defined in
_ and has the value 8. Text files can store only character data.
9. Standard output is an output stream used by
Multiple Choice Questions programs to report error messages or diagnostics.
10. Each line in a text file can have maximum of 80
1. Which function gives the current position of the
characters.
file?
11. Binary file stores data in a human readable format.
(a) fseek() (b) £setpos ()
12. fread() returns the number of elements
(c) ftell() (d) Rewind()
successfully read.
1. Which function is used to perform block output in
13. fseek() is used to reposition a binary stream.
binary files?
14. The tmpfile() opens the corresponding stream
(a) fwrite() (b) fprinté()
with access parameters set as “w+”.
(c) fputc() (d) fputs() 15. The value obtained by using fgetpos() can be
_ Select the standard stream in C. | used only with the fsetpos() .
(a) stdin (b) stdout
(c) stderr (d) all of these Review Questions
4. From which standard stream does a C program 1. What is a file?
read data? 2. Why do we need to store data in files?
(a) stdin (b) stdout
3. Define the term stream.
(c) stderr (d) all of these 4. Differentiate between a text file and a binary file.
5. What actsas an interface between stream and 5 . Explain the different modes in which a file can be
hardware? opened in a C program.
(a) file pointer (b) buffer 6. Under which circumstances does the fopen() fail?
—— (¢) stdout (d) stdin 7. Why should you close a file after it is used?
6. Which function is used to associate a file with a 8. What is the impact of fclose() on buffered data?
stream? 9. Differentiate between gets() and fgets().
(a) rread() (b) fopen ()
10. What is the difference between a buffered output
(c) floes () (d) £f1ush() stream and an unbuffered output stream?
|334 | Introduction to C Programming

. With the help of a program code, explain the 35. Write a program to read a text file using Escanf ().
Ww significance of ftell (). 36. Write a program to read a text file using Egetc ().
Lu
wy . Under what circumstances does the ftell () fail? 37. Write a program to illustrate the use of fprinté£ ().
&)| . Where can ftell () be used? 38. Write a program to illustrate the use of fputc ().
ce
Liu . With the help of a program, explain the significance 39. Differentiate between fscanf () and fread().
x< of command line arguments.
lu 40. Write a program to count the number of characters
. Write a short note on fgetpos() and fsetpos ina file.
(). Give a program to illustrate their usage in a C
41. Write a program that reads the file name and text
program. of 20 words as command line arguments. Write
. What will happen if the argument to remove() the text into a file whose name is given as the file
specifies a directory? Also state its behaviour name. E
when the argument is a filename.
42. Assume that a file [Link] stores only integer
. Give a program that uses a temporary file created numbers. A value ‘-1’ is stored as the last value to
using the tmpfile(). indicate EOF. Write a program to read each integer
. Give the importance of associating a buffer with value stored in the file. While reading the value,
the stream. compute whether the value is even or odd. If it is
. Write a short note on functions that are used to: even then write that value in a file called [Link]
(a) read data from a file, (b) write data to a file. else write it in [Link]. Finally display the contents
. Write a short note on the following functions. of the two files— [Link] and [Link].
For each function, give a program code that Hint: You may use getw and putw functions. They
demonstrates its usage. are same as getc() and putc(). The prototypes
(a) open() (b) Eclose () of getw() and putw() are
(c) ferror () (d) clearerr () int getw(FILE *£p); and putw(int value, FILE *fp);
. What do you understand by EOF? : 43. Write a program to read data from the keyboard
. How will you check for EOF when reading a file? _ and write it to a file. Read the contents stored in
. Why is it not possible to read from a file and write the file and display it on the screen.
to the same file without resetting the file pointer? 44. Write a menu-driven program to read, insert,
. Write a short note on error handling while append, delete, and edit a record stored ina binary
performing operations. file.
. Give the importance of rewind (). 45. Write a program to read data from a text file and
. Differentiate between rewind() and fseek(). store it in a binary file. Also read the data stored in
Can fseek() work as an alternative to rewind the binary file and display it on the screen.
()? If yes, how? 46. Write a program to read a text file, convert all
. Write a program to write employees details in a the lower case characters into upper case and re-
file called [Link]. Then read the record of write the upper case characters in the file. Before
the nth employee and calculate his salary. the end of the program, aHtemperely files must
. Write a program to read the nth record and display be deleted.
it on screen. Repeat the procedure until —1 is 47. Modify the above code fragment to allow the
entered. user three chances to enter a valid file name. If a
. Write a program to copy a file using feof (). valid file name is not entered after three io
. Create a file and store some names in it. Write a terminate the program.
program read the names in the file in the reverse 48. Assume that there are two files—Names1 and
order without re-opening the file. Names2 that stores sorted names of students who
. Why do we need fflush()? would be participating in Activity1 and Activity2,
. Write a program to read the contents of a binary respectively. Create a file NAMES . TXT which stores
file. the names from both the files. Note that there
. Write a program to read the contents of a text file. should be no repetition of names in [Link]
and while writing name me iensure that the file
. Write a program to write some contents into (a) a
is also sorted.
binary file (b) a text file.
Files | 335 |
: Write a program to create a file that stores only FILE *fp;

integer values. Append the sum of these integers fp = fopen("temp", "w+b") )


at the end of the file. for(c = 'A’;e <= ‘i’, c++)
- 50. Write a program that reads a binary file that stores fweite(&c, 1,1, =p;
employees records and prints, on the screen, the rewind (fp);
fread(&c,1,1,fp);
number of records that are stored in the file.
EXERCISES
- 51. Write a program to eppene a binary fle atthe end
printf ("sc", ¢);
_ fclose(£p);
of another.
}
| Program output 5. wseint

- Give the output of the following code.


{
char c;
1 main () FILE *fp;
long int pos;
FILE *fp; fo = fopen("temp", "w+b"))
for (c — RC ee 11), crt)
: fwrite(&c, 1,1, fp);
while ((c=getchar ()) !=E0F) pos = es
putcle, fp _ pos = -3;
printf (* \n No. of characters entered fseek (fp, pos, SEEK END);
= $1a", ftell(fp)); fread(&c,1,1,fp);
fclose (fp);
prince sc4 ¢),
aD fclose (fp);
aint
6 meind
pele! ; -
int =
FILE Ftp;
Po vroped (recdbacks" wo:
long int pos;
For{t = O74 =< & pitt)
fp = fopen("temp", Habre
"Eo", comme for(i = 1;i <= 10;i4++) :
print (ip, (ss", comment); fwrite(&i, sizeof (int), 4, fp); 9
fseek (fp, sizeof (int) *2, SEEK SED):
- fclose (fp); fread(&i, sizeof (int), 1,8); .
princi
2a) 1);
_ felose(fp); |
C} .

7. main’)—
{
fopen("temp", nwab") ) int i;
ti? G++) FILE *fp;
long int pos;
fp — topern este ois
for(i = i;i <= 10;i++)
Ewrite (&i, sizeof (int) , LED)?
ficlose P)i fseek (fp, -sizeof (int) *2, SEEK_CUR);
fread(&1i,sizeof (int) ,1, fer
printe('s Sd", i);
fclose (fp);
CHAPTER

Preprocessor Directives

Takeaways
e Preprocessor Directives e@ Pragma Directives e Conditional Directives
e #error Directive e Predefined Macro Names

10.1 INTRODUCTION Notey


a
In order to extend a preprocessor
2 directive to multiple lines; place a
The preprocessor is a program that processes the source
backslash character (\) as the last
code before it passes through the compiler. It operates character of the line. This means that the
under the control of preprocessor directive which is placed line is continued in the line following it.
in the source program before the main (). Before the source
code is passed through the compiler, it is examined by the Although the preprocessor directive is usually placed
preprocessor for any preprocessor directives. In case the before the main(), practically speaking, it can appear
program has some preprocessor directives, appropriate anywhere in the program code. However, if written in
actions are taken (depending on the directive) and the between, the directive will be applied only in the remainder
source program is handed over to the compiler. of the source file. The advantages of using preprocessor
Preprocessor directives are lines included in the C directives ina C program include:
program that are not program statements but directives for
e Program becomes readable and easy to understand.
the preprocessor. The preprocessor directives are always
preceded by a hash sign (#) directive. The preprocessor e Program can be easily modified or updated.
directive is executed before the actual compilation of e Program becomes portable as preprocessor directives
program code begins. Therefore, the preprocessor expands make it easy to compile the program in different
all the directives and takes the corresponding action before execution environments.
any code is generated by the program statements. e Due to the aforesaid reasons, the program also
The preprocessor directives are only one line long becomes more efficient to use.
because as soon as a newline character is found, the
preprocessor directive iS
Programming Tip: — considered to end. No semicolon
10.2 TYPES OF PREPROCESSOR |
Preprocessor (;) can be placed at the end of a
directives must _ preprocessor directive. However,
DIRECTIVES.
start with a hash | the preprocessor directives may We can broadly categorize the preprocessor directives into
sign. — contain a comment (which will two groups—conditional and unconditional preprocessor
be simply ignored).
Preprocessor Directives | 337

directives. Figure 10.1 shows the categorization of Then the above line defines a macro named PI as an
preprocessor directives. abbreviation for the token 3.14. If somewhere after this
The conditional directives are used to instruct the
#define directive there comes a C statement of the form
preprocessor to select whether or not to include a chunk
of code in the final token stream passed to the compiler. area = PI * radius * radius;

Such directives comprise directives such as #if, #else, Then the C preprocessor will recognize and expand
#elif, #ifdef, #ifndef,
and #endif. the macro PI. The C compiler will see the same tokens as
The unconditional directives such as #define, it would if you had written
#line, #undef, #include, #error, and #pragma
area
= 3.14 * radius * radius;
perform well-defined task. In this chapter we will learn
about all these directives in detail. A macro definition can also
Programming Tip: include an expression. However,
A semicolon (;) when using expressions for
10.3 # should not be _ replacement, make sure that the
placed at the end _ order of evaluation is correct. As
To define preprocessor macros we use #define. The
ofapreprocessor | a good programming habit, use
#define statement is also known as macro definition or
directive.
simply a macro. There are two types of macros: parenthesis in the expression. For
e object-like macro and example, consider the following
e function-like macro
macro definitions:
#define ROWS 3
Programming Tip:
#define COLS 3
10.3.1 Object-Like Macro In ordertoextend _
#define SIZE (ROWS * COLS)
An object-like macro 1s a simple identifier which will be a preprocessor
Look at the following directive to
replaced by a code fragment. They are usually used to give
program which illustrates the multiple lines;
symbolic names to numeric constants. Object-like macros
use of #define for literal text place a backslash
do not take any argument. It is the same what we have
substitution: character (\) as the A
been using to declare constants using #define directive.
_ jast character of the |
The general syntax of defining a macro can be given as #include <stdio.h>
fine. 4
#include <conio.h>
#define identifier string
#define INPUT printf("\n
The preprocessor replaces every occurrence of the Enter a number: ");
identifier in the source code by a string. The macro must scant ("%d", &mnum);
start with the keyword #define and should be followed #define EQUALS ==
by an identifier and a string with at least one blank space #define PRINT1 printf ("\n GREAT")
between them. The string may be any text, a statement, or #define PRINT2 printf ("\n TRY AGAIN")

anything. However, the identifier must be a valid C name. #define START main() {
If we write, #define END getch()
;\
return 0; }
#define PI 3.14

Preprocessor directive -

Inconditional.

arate lees Preprocessor directives —


|338 | Introduction to C Programming

START space cannot separate the identifier (which is the name of


int num; the macro) and the left parenthesis of the parameter list. A
INPUT comma must separate each parameter.
1£ (num EQUALS 100)
PRINT1 ;
Invoking a Function-like Macro
else
PRINT2 ;
A function-like macro is invoked by writing the identifier
END followed by a comma-separated list of arguments in
parentheses. However, make sure that the number of
By convention, macro names are written in uppercase.
arguments should match the number of parameters in the
This makes the program easy to read as anyone can tell at
macro definition. One exception to this is if the parameter
a sae which names are macros.
list in the definition ends with an ellipsis..In that case, the
nidentifier is never replaced if it number of arguments in the invocation should exceed
appears in a comment, within a string, or — the number of parameters in the definition. The excess
as part of a longer identifier. arguments are called trailing arguments.
When the preprocessor encounters a function-like macro
invocation, argument substitution takes place. A parameter
10.3.2 Function-like Macros in the replacement code is replaced by the corresponding
Function-like macros are more complex than object-like argument. If there are trailing arguments (as permitted
macros. They are known as function-like macros because by the macro definition), then they are merged with the
they are used to stimulate functions. When a function is intervening commas as if they were a single argument.
stimulated using a macro, the macro definition replaces In case of nested macros (macro within another
the function definition. The name of the macro serves as macro definition), 1.e., if there are any macro invocations
the header and the macro body serves as the function body. contained in the argument itself, they are completely
The name of the macro will then be used to replace the replaced before the argument replaces its corresponding
function call. parameter in the replacement code.
The function-like macro includes a list of parameters. The following line defines the macro MUL as having two
References to such macros look like function calls. We parameters a and b and the replacement string (a * b):
have studied that when a function is called, control passes
#define MUL(a,b) (a*b)
from the calling function to the called function at run time.
However, when a macro is referenced, source code is Look how the preprocessor changes the following
inserted into the program at compile time. The parameters statement provided it appears after the macro definition.
are replaced by the corresponding arguments, and the text
inteat= 2) b= psncy
is inserted into the program stream. Therefore, macros are C= MUL (a,b) ; {/{ co = atb;
considered to be much more efficient than functions as
they avoid the overhead involved in calling a function. Programming Tip: _____ Inthe output of the preprocessor,
A function-like macro definition Use macros instead __ the above statement would appear
Programming Tip: declares the names of formal offunctionsas =— as: c = at*b;
Macro names can parameters within parentheses, macros are much While using function-like mac-
bein lower separated by commas. In case more efficientthan ros, you must use parentheses
the function-like macro does not functions since they to ensure correct evaluation of
accept any argument, then an _ avoid the overhead replacement text. For example, if
must write acro empty formal parameter list can invened in calling a | amacro SQUARE is defined as:
names in upper function.
| be provided.
#define SQUARE(x) (x*x)
case characters. | The syntax of defining a function
like macro can be given as Then invoking the macro by writing,

# define identifier(argl,arg2,...argn) inte-a~= 2, b-="3: a;

string c = SQUARE (a); Nu / fees 2e2.

An identifier is followed by a parameter list in The above statement is fine and would return the value
parentheses and the replacement string. Note that white 4. However, had you written the statements given below,
Preprocessor Directives | 339 |

you would have got incorrect results. For example, if had e When referencing a macro,
you written, you may use comments and
soley Byes Ph, ciel eee white-space characters free-
C = SQUARE (a+b) ; ly. Comments are replaced
Vf Kea DEBI Soy ie Ss Ges) = sal with a single space. How-
It is, therefore, very important that you put parentheses ever, white-space characters
around each parameter in the definition to correctly (except leading and trailing
evaluate an expression. So let us redefine our SQUARE white space) are preserved
macro by writing during the substitution.
Oo
#define SQUARE (x) ((x)
* (x) ) e The number of arguments in
Now a statement like, the reference must match the
number of parameters in the
c = SQUARE (a+b) ;
macro definition.
would be expanded as
Crate -4—b) F(a 4 b)s);
10.3.5 Operators Related to Macros
In this section, we will read about some operators that are
directly or indirectly related to macros in C language.

# Operator to Convert to String Literals


10.3.3 Nesting of Macros The # preprocessor operator which can be used only in
a function-like macro definition is used to convert the
We can use a macro in the definition of another macro. For
argument that follows it to a string literal. For example:
example, consider the following macro definitions:
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
#define PRINT(num) printf(#num " = %d", num)
#define CUBE(x) (SQUARE(x) * (x))
main ()
#define FOURTH _POWER(x) (CUBE(x) * (x)) {
#define FIFTH POWER(x) (FOURTH POWER (x) * (x) ) PRINT (20) ;

In these definitions, the preprocessor will expand each


}
The macro call expands to
macro until all the macros do not exhaust in the text. For jorgndigene (MWragbhat!! Wh = yell salbiqal)
example, the macro CUBE will be expanded as
Finally, the preprocessor will automatically concatenate
CUBE (x) => SQUARE(x) * (x) => ((x) * (x))* (x)
two string literals into one string. So the above statement
Generally, in C a macro can be nested to 31 levels. _ will become
printf ("num = %d", num)
10.3.4 Rules for Using Macros Hence, the unary # operator
Let us summarize some rules that must be used when produces a string from _ its
specifying macro definitions and invoking them from an operand. Consider another macro
arbitrary place within the program. MAC which is defined as
e The macro name and the formal parameters are #define MAC (x) Hx
identifiers, so they must be specified in accordance MAC("10") gives a_ string
with the rules for identifiers in the C language. literal equal to "10". Similarly,
e Spaces, tabs, and comments are allowed to be used MAC ("HI") would give a string
freely within a #define directive. All the spaces, literal "HI".
tabs, and comments are replaced by a single space.
Rules of using the # operator in a function-like macro
e White space in between the identifier and the left definition
parenthesis that introduces the parameter list is not The # operator must be used in a function-like macro by
allowed. following the rules mentioned below:
|340 | Introduction to C Programming

e A parameter following # operator in a function-like written. The #include directive is used to inform the
macro is converted into a string literal containing the preprocessor to treat the contents of a specified file as if
argument passed to the macro. those contents had already appeared in the source program
e Leading and trailing white-space characters (those at the point where the directive appears.
that appear before or after) in the argument passed to The #include directive can be used in two forms.
the macro are deleted. Both the forms make the preprocessor insert the entire
contents of the specified file into the source code of our
e If the argument passed to the macro has multiple
program. However, the difference between the two is the
white-space characters, then they are replaced by a
way in which they search for the specified.
single-space character.
e Ifthe argument passed to the macro contains a string #include <filename>

literal and if a \(backslash) character appears This variant is used for system header files. When we
within the literal, then on expansion of the macro, a include a file using angular brackets, a search is made
second \ character is inserted before the original \. for the file named filename in a standard list of system
e If the argument passed to the macro contains a " directories.
(double quotation mark) character, then on expansion #include "filename"
of the macro, a \ character is inserted before the ".
This variant is used for header files of your own
e The conversion of an argument into a string literal
program. When we include a file using double quotes,
occurs before macro expansion on that argument.
the preprocessor searches the file named filename first
e Ifthere is more than one # operator in the replacement
in the directory containing the current file, then in the
list of a macro definition, the order of evaluation of
quote directories and then the same directories used for
the operators is not defined.
<filename>.
e If the result of the macro expansion is not a valid
character string literal, the behaviour is undefined. Note, The filename
canop 7 ally be preceded
_ bya directory spe ion. For example,
Merge Operator (##) you may specify ct path by writing
“c:\students\my_header.h”.
At times you need macros to generate new tokens. Using
the merge operator you can concatenate two tokens into a
third valid token. For example, Points to Remember

#include <stdio.h>
The preprocessor stops searching the directory as soon as
#define JOIN(A,B) A##B it finds a file with the given name.
main () If a completely unambiguous path for the file is
{ specified between double quotation marks (" "), then
SWigce BL the preprocessor searches only that path specification and
for(i = 1;i <= 5;i++) ignores the standard directories.
joreatianese (Wier ISHG aKONINVUISIaIe,.
AL)e WY) 5 If an incomplete path is specified for the filename in
} double quotes, then the preprocessor first searches the
The above program would print parent file’s directory (where a parent file is the one which
HI USER1 contains the #include directive. For example, if you
HI USER2 include a file named £ile2 within a file named filei,
HI USER3 file1 is the parent file).
HI USER4 File inclusion can be ‘nested’; i.e., a #include directive
HI USER5 can appear in a file named by another #include directive.
For example, filel can include file2, and in turn file2
can include another file named £1i1e3. In this case, file1
10.4 #include would be the parent of file2 and the grandparent of
An external file containing function, variables or macro file3.
definitions can be included as a part of our program. When file inclusion is nested and when compiling is
This avoids the effort to re-write the code that is already done from the command line, directory searching begins
Preprocessor Directives | 341 |

with the directories of the parent file and then proceeds #undef MAX
through the directories of any grandparent files. #undef MIN

10.6 #1ine
Notes Nesting of include files can continue up to”
10 levels.

Compile the following C program:


#include <stdio.h>

10.5 #undef main


{
()

As the name suggests, the #undef directive undefines or Tighe 2 = ILOs


removes a macro name previously created with #define. jopcaligiene (WizolW . i) 9
Undefining a macro means to cancel its definition. This is }
done by writing #undef followed by the macro name that
The above program has a compile-time error because
has to be undefined.
instead of a semicolon there is a
Like definition, undefinition also occurs at a specific
colon that ends the line, int a =
point in the source file, and it applies starting from that 10. So when you compile this
point. Once a macro name is undefined, the name of the | program an error is generated
macro ceases to exist (from the point of undefinition) and during the compiling process and
the preprocessor directive behaves as if it had never been the compiler will show an error
a macro name. message with references to the
Therefore, the #undef directive removes the current name of the file where the error has
definition of macro and all subsequent occurrences of happened and a line number. This makes it easy to detect the
macro name are ignored by the preprocessor. erroneous code and rectify it.
The #1ine directive enables the users to control the line
numbers within the code files as well as the file name that
appears when an error takes place. The syntax of #line
directive is
#line line number filename

Here, line number is the new line number that will be


You can also apply the #undef directive to a macro assigned to the next line of code. The line numbers of
name that has not been previously defined. This can be
successive lines will be increased one by one from this
done to ensure that the macro name is undefined.
point onwards. The parameter Filename is an optional
The #undef directive when paired with a #define
parameter that redefines the file name that will appear
directive creates a region in a source program in which
in case an error occurs. The filename must be enclosed
the macro has a special meaning. For example, a specific
within double quotes. If no filename is specified, then the
function of the source program can use certain constants
compiler will show the original file name. For example:
to define environment specific values that do not affect the
rest of the program. #include <stdio.h>
The #undef directive can also be paired with the #if main ()

directive to control conditional compilation of the source {


program. We will read about the #if directive later in this glbakakey aloe Winkanonegieul
ewe —aKOk
section.
#line 20
Consider the following example in which the #undef
joneamnanese (Wesel, ey)5
directive removes definitions of a symbolic constant and a
macro. }
This code will generate an error that will be shown as
#define MAX 10
error in file "Error.c",
lines 10 and 20. Please
#define MIN (X, Y)
execute this program with the #line directive and
without the #line directive to visualize the difference.
342 | Introduction to C Programming

Hence, we see that #line directive can be used to make If no date is specified using pragma COPYRIGHT_DATE,
the compiler provide more meaningful error messages. then the current year is used in the copyright message.
For example, if we write
Notes A preprocessor line control directive
= supplies line numbers for compiler #pragma COPYRIGHT "JRT Software Ltd"
messages. It tells the preprocessor to Then the following string is placed in the object code
change the compiler’s internally stored (assuming the current year is 2011):
line number and filename to a given line
© Copyright JRT Software Ltd, 2011. All rights
number and filename.
reserved. No part of this program may be photocopied,
reproduced, or transmitted without prior written consent
of JRT Software Ltd.
10.7 PRAGMA DIRECTIVES
The #pragma directive is used to control the actions of pragma COPYRIGHT DATE
the compiler in a particular portion of a program without The syntax of pragma COPYRIGHT DATE can be given as
affecting the program as a whole. You can include the
#pragma COPYRIGHT DATE "string"
pragma directive in your C program from the point where
you want them to take effect. The effect of pragma will be Here, the string is a date which will be used by the
applied from the point where it is included to the end of COPYRIGHT pragma.
the compilation unit or until another pragma changes its For example, consider the pragma given below
status. #pragma COPYRIGHT DATE "1999-2011"
A #pragma directive is an instruction to the compiler
#pragma COPYRIGHT "JRT Software Ltd."
and is usually ignored during preprocessing. The syntax
of using a pragma directive can be given as The above pragma will place the following string in the
object code:
#pragma string
© Copyright JRT Software Ltd, 1999-2011. All rights
Here, string can be one of the instructions given to reserved. No part of this program may be photocopied,
the compiler with any required parameters. Table 10.1 reproduced, or transmitted without prior written consent
describes some pragma directives. of JRT Software Ltd.
felei-wlUime Pragma directives
pragma OPTIMIZE

The syntax of using the pragma OPTIMIZE can be given as


To specify a copyright string #pragma OPTIMIZE ON
COPYRIGHT_DATE | To specify a copyright date for #pragma OPTIMIZE OFF:
the copyright string The pragma optimize is basically used to turn on/off
HP_SHLIB VERSION | To create versions of a shared optimization in sections of a source program. However,
library routine when using this pragma you must specify one of the
LOCALITY To name a code subspace optimization options on the acc command (while giving
|
| OPTIMIZE To turn the optimization feature the command to compile the program), otherwise this
on or off pragma is ignored. Also remember that the pragma
OPT LEVEL | To set the level of optimization optimize cannot be used within a function.
For example,
To specify a version string
;
aCC +02 Prog.c // Set optimization to level
pragma COPYRIGHT Be Lor Progee
#pragma OPTIMIZE OFF
The syntax of pragma copyright can be given as: void Funci()
#pragma COPYRIGHT "string" { // Turn off optimization for
this function
Here, string specifies the set of characters included in
the copyright message in the object file.
Preprocessor Directives | 343 |
#pragma OPTIMIZE ON This pragma should be used only if incompatible changes
void Func2()
are made to a source file.
{ // Restore optimization to level 2

pragma LOCALITY
}
The syntax of pragma LOCALITY which is used to specify
pragma OPT LEVEL a name to be associated with the code that is written to a
re-locatable object module can be given as
The syntax for pragma OPT LEVEL which is used to set
the optimization level to 1,2,3, or 4 can be given as #pragma LOCALITY "string"

#pragma OPT LEVEL 1


oOo
Here, string specifies a name to be used for a code
#pragma OPT LEVEL 2 subspace. After this directive, all codes following the
#pragma OPT LEVEL 3 directive are associated with the name specified in string.
#pragma OPT LEVEL 4 The smallest scope of a unique LOCALITY pragma is a
Like the optimization pragma, even this pragma cannot function.
be used within a function. Finally, OPT LEVEL 3 and 4 are
pragma VERSIONID
allowed only at the beginning of a file.
For example, The syntax of pragma VERSIONID can be given as

ace -Onprog., € #pragma VERSIONID "string"


#pragma OPT LEVEL 1 Here, string is a string of characters that is placed in the
void Func ()
object file. For example, if we write,
{ // Optimize Funcl() at level 1.
#pragma VERSIONID "JRT Software Ltd.,

} Version 12345.A.01.10"
#pragma OPT LEVEL 2
Then this pragma places the characters JRT Software
void Func2()
Ltd., Version 12345.A.01.10 into the object file.
{ // Optimize Func2() at level 2.

pragma once

The pragma once specifies that the file, in which this


pragma directive is specified will be included (opened)
only once by the compiler in a building of a particular file.
Its syntax can be given as
#pragma once
pragma HP SHLIB VERSION
Conclusion: The pragma preprocessor directive is mainly
The syntax for pragma HP_SHLIB_ VERSION which is used used where each implementation of C supports some
to create different versions of a shared library routine can features unique to its host machine or operating system.
be given as For example, some programs may need to exercise precise
#pragma HP SHLIB VERSION ["]date[™“] control over the memory areas where data is placed or to
control the way certain functions receive parameters. In
Here, the date argument is of the form month/year,
such cases, #pragma directives provides machine- and
optionally enclosed in quotes. The month must be specified
operating system-specific features for each compiler while
using any number from 1 to 12. The year can be specified
retaining overall compatibility with the C language.
as either the last two digits of the year (99 for 1999) or
a full year specification (1999). Here the two-digit year
codes from 00 to 40 are used to represent the years from
2000 to 2040, respectively. A conditional directive is used to instruct the preprocessor
to select whether or not to include a chunk of code in the
final token stream passed to the compiler. The preprocessor
conditional directives can test arithmetic expressions, or
whether a name is defined as a macro, etc.
|344 | Introduction to C Programming

Although the conditional preprocessor directive #ifdef MACRO

resembles an if statement, it is important to understand controlled text

the difference between them. The condition in an if #tendif

statement is tested when the program is executed. So the This block is called a conditional group. The controlled
same C program may behave differently from run to run, text will be included in the output of the preprocessor if
depending on the data it is operating on. However, the and only if MACRO is defined. The #ifdef is said to be
condition in a preprocessing conditional directive is tested successful if the MACRO is defined. The controlled text will
when the program is being compiled. This facilitates the be executed only if the #ifdef succeeds.
programmer to allow different code to be included in the Even if the #ifdef directive fails, the controlled
program depending on the situation at compile time.
text inside it is still run through initial transformations
However, in today’s scenario the distinction is
and tokenization. So, the programmer must ensure that
becoming less clear. Modern compilers usually test if
the controlled text is lexically valid. For example, all
statements during program compilation in order to check
comments and string literals inside a failing conditional
if their conditions are known not to vary at run time, and
group must still end properly.
eliminate code which can never be executed. If you have
such a modern compiler then the use of an if statement Notey As the statements under the controlled
is recommended as the program becomes more readable if text of the #ifdef directive are not
you use if statements with constant conditions. enclosed in braces, the #endif directive
Conditional preprocessor directives can be used in the must be used to mark the end of the
following situations: #ifdef block.

e A program may need to use different code depending


The following example defines a stack array if MAX is
on the machine or operating system it is to run on.
defined for the preprocessor.
This may be because in certain situations, the code for
one operating system becomes erroneous on another #Hifdef MAX
operating system. For example, the program might int STACK [MAX] ;
refer to data types or constants that do not exist on #Hendif

the other system. When this happens, it is not enough In the above example, the stack array will not be created if
to avoid executing the invalid code; as even the MAX had not been initially defined.
presence of such data types and constants will make
the compiler reject the program. Therefore, in such
10.8.2 #ifndef
situations the conditional preprocessing primitive is
effective as with preprocessor the offending code The #ifndef directive is the opposite of #ifdef directive.
can be effectively exercised from the program when It checks whether the MACRO has not been defined or if
it is not valid. its definition has been removed with #undef. #ifndef is
e The conditional preprocessor directive is very useful successful and returns a non-zero value if the MACRO has not
when you want to compile the same source file into been defined. Otherwise in case of failure, that is when the
two different programs. While one program might MACRO has already been defined, #ifndef returns false (0).
make frequent time-consuming consistency checks Therefore, #ifndef directive is used to define code
on its intermediate data, or print the values of those that is to be executed when a particular macro name is not
data for debugging, the other program, on the other defined. The general format to use #ifndef is the same as
hand can avoid such checks. for #ifdef :
e The conditional preprocessor directives can be used
#ifndef MACRO
to exclude code from the program whose condition
controlled text
is always false but is needed to keep it as a sort of
#endif
comment for future reference.
Here, MACRO and controlled text have the same
meanings they have in case of #ifdef. Again, the #endif
10.8.1 #ifdef directive is needed to mark the end of the #ifndef block.
#ifdef is the simplest sort of conditional preprocessor You can also use #else directive with #ifdef and
directive and is used to check for the existence of macro #ifndef directives like
definitions. Its syntax can be given as
Preprocessor Directives | 345 |
#ifdef MACRO #endif directive. Any number of #elif directives can
controlled _text1l appear between the #if and #endif directives, but at
#else
most one #else directive is allowed. However, the #else
controlled text2
directive (if present) must be the last directive before
#endif
#endif.

10.8.3 #if£ Directive


10.8.4 #else Directive
The #if directive is used to control the compilation of
The #e1se directive can be used within the controlled text
portions ofa source file. If the specified condition (after the
of a #if directive to provide alternative text to be used
#if) has a non-zero value, the contrélled text immediately
if the condition is false. The general format of #else
following the #if directive is retained in the translation
directive can be given as
unit.
The #if directive in its simplest form consists of #if condition
Controlled text1
#if condition
#else
controlled text
Controlled text2
#endif
#endif
In the above syntax, condition is a C expression of integer
type, subject to stringent restrictions, i.e., the condition If condition evaluates to a non-zero value then
may contain the following: controlled text1 becomes active and the #else
directive acts like a failing conditional and the controlled
e Integer constants (which are all treated as either long
text2 is ignored. On similar grounds, if the condition
or unsigned long).
fails or evaluates to zero, then controlled text2 is
e Character constants considered included and controlled text1 is ignored.
e Arithmetic operators for addition, subtraction, The #el1se directive is usually used to delimit alternative
multiplication, division, bitwise operations, shifts, source text to be compiled if the condition tested for in
comparisons, and logical operations. the corresponding #if, #ifdef, or #ifndef directive is
e If an identifier used in the expression is not a macro false. However, a #else directive is optional.
and has not been currently defined, the compiler treats
the identifier as though it were the constant zero. 10.8.5 #e1if Directive
e Macros which are actually expanded before
The #e1if directive is used when there are more than two
computation of the expression’s value begins.
possible alternatives. The #e1if directive like the #else
e Defined operator can be used.
directive is embedded within the #if directive and has the
e The sizeof operator is not allowed in #if following syntax:
directives.
#if condition
e Typecast operator is not allowed.
Controlled text1
e Enumerated data types are not allowed. #elif new _condition
e The condition must not perform any environmental Controlled text2
inquiries and must remain insulated from #else
implementation details on the target computer. Controlled text3

e Increment, decrement, and address operator are not #endif

allowed. Here, when the if condition is non-zero then controlled


The controlled text inside the directive can include text1 becomes active and the #elif and #else directives
other preprocessing directives. However, any statement act like a failing conditional and the controlled text2
or any preprocessor directive in the controlled text will and controlled text3 are ignored. On similar grounds,
be executed if that branch of the conditional statement if the condition fails or evaluates to zero, then new_
succeeds. condition is evaluated. If it is true controlled text2
While using #if directive in your program, make sure is considered included and controlled text1 and
that each #if directive must be matched by a closing controlled text3 is ignored. Otherwise, if condition
|346 | Introduction to C Programming

and new_condition both are false then #else directive #endif directives that is required depends on whether the
becomes active and controlled text3 is included. elif or #else directive is used. For example, consider the
The #elif directive is same as the combined use of examples given below which although perform the same
the else-if statements. The #elif directive is used to task, requires different number of #endif directives.
delimit alternative source lines to be compiled if condition #i£ condition
in the corresponding #if, #ifdef, #ifndef, or another Controlled textl
#elif directive is false and if the newcondition in the #elif new condition
#elif line is true. An #elif directive is optional. Controlled text2
#endif
#define MAX 10
#if£ OPTION ==
OR
int STACK [MAX] ; #1£ condition
Controlled text1l
#eliz£ OPTION == 2
#else
float STACK [MAX] ;
#i£ new_condition
#elif OPTION == 3
Controlled text2
char STACK [MAX] ;
#endif
#else #endif
printf ("\n INVALID OPTION");
#endif
10.9 defined OPERATOR
We have seen that we can check the existence of a macro
by using #ifdef directive. However, there is another way
i”
directiveon a ndition to be |
to do the same. The alternative to #ifdef directive is to
_ tested. T he text following the ee is
use the defined unary operator. The defined operator
; proces: ed onlyifthe Hit conditio ails
has one of the following forms:
defined MACRO
In the above example, we have used more than one
#elif directives in the same #if-#endif group. The text or
after each #e1if is processed only if the #e1if condition
succeeds after the original #if and any previous #elif defined (MACRO)

directives within it have failed. The above expression evaluates to 1 if MACRO is defined
dition specified with Hit. and to 0 if it is not. The defined operator helps you to
Ise and if either no felit ~ check for macro definitions in one concise line without
- directives appear orno #elif condition having to use many #ifdef or #ifndef directives. For
a8 evaluated to true, then the preprocessor example, consider the following macro checks:
selects the text block after the #else #ifdef MACRO1
clause. If the Helse directive iis also #ifdef MACRO2
missing then no controlled text is Controlled text1
selected. #else
printf ("\n MACROS not defined") ;
#endif
10.8.6 #endif Directive
The general syntax of #endif preprocessor directive OR
which is used to end the conditional compilation directive
#1£ defined (MACRO1) && defined (MACRO2)
can be given as
Controlled text1,
#endif #else

The #endif directive ends the scope of the #if, #ifdef, printf ("\n MACROS not defined");
#endif
#ifndef, #else, or #elif directives. The number of
Preprocessor Directives | 347 |

As evident from the above example, the defined #warning string


operator can be combined in any logical expression using
Here, string is the warning message that has to be
the C logical operators. However, this operator can only
displayed. One important place where #warning directive
be used in the evaluated expression of an #if or #elif
can be used is in obsolete header files. You can display a
preprocessor directive.
message directing the user to the header file which should
be used instead.
10.10 #error DIRECTIVE
The #error directive is used to produce compiler time 10.11 PREDEFINED MACRO NAMES
error messages. The syntax of this directive is
There are certain predefined macros that are readily
#error string available for use by the C programmers. A list of such
The error messages include the argument string. The predefined macros is given in Table 10.2.
#error directive is usually used to detect programming Bc Cetey Predefined macros —
inconsistencies and violation of constraints during
preprocessing. When #error directive is encountered, the Value
compilation process terminates and the message specified
A decimal integer constant which
in string is printed to stderr. For example, consider
specifies the current line number in
the piece of codes given below which illustrates error the source file being compiled. We
processing during preprocessing: have already studied that the line
#ifndef SQUARE number can be altered with a #line
#error MACRO not defined. directive.
#endif A string literal which specifies
the name of the source file being
#ifndef VERSION compiled.
#error Version number is not specified.
Specifies the date of compilation of the
#endif
current source file. It is a string literal
of the form mm dd yyyy.
#ifdef WINDOWS
/* Windows specific code */ A string literal in the form "hh:mm:ss"
#else which is used to specify the time at
#error "This code works only on WINDOWS which the compilation process began.
operating system"
Specifies full conformance with ANSI C
#endif
standard.
The #error directive causes the preprocessor to report a _ TIMESTAMP _ A string literal in the form Ddd Mmm
fatal error. Date hh:mm:ss yyyy, where Ddd is the
Here the string need not be enclosed within double abbreviated day of the week and Date
quotes. It is a good programming practice to enclose the is an integer from 1 to 31. It is used to
string in double quotes. The #error directive is a very specify the date and time of the last
important directive mainly because of two reasons: modification of the current source file.

e First, it helps you to determine whether a given line


#include <stdio.h>
is being compiled or not. void main (void)
e Second, when used within a heavily parameterized {
body of code, it helps to ensure that a particular printf ("\n Current File’s Path Name:
MACRO has been defined. ts", FILE);
printf ("\n Line Number in the
Besides the #error directive, there is another
eibharaciqe, aealales ol), IenUNIE
directive—#warning, which causes the preprocessor to
printf ("\n Date of Compilation: 7s",
issue a warning and continue preprocessing. The syntax of
‘DATE 5
#warning directive is same as that of #error.
348 | Introduction to C Programming

printf ("\n Time of Compilation: %s", printf ("\n You C compiler


__TIME_); doesn’t conform with the ANSI C
#ifdef STDC _ standard") ;
printf ("\n YourRa C compiler #endif
conforms with the ANSI C standard") ;
#else

Lid e The preprocessor is a program that processes the The #pragma directive is used to control the —
fons source code before it passes through the compiler. actions of the compiler in a particular portion ©
2) e Preprocessor directives are lines included in the of a program without affecting the program as a
= whole. :
C program that are not program statements but
O
fam directives for the preprocessor. The preprocessor A conditional directive is used to instruct the —
2) directives are always preceded by a hash sign (3) preprocessor to select whether or not to include a _

and are executed before the actual compilation of chunk of code in the final token sabe eo to
é program code begins. the compiler.
2) e To define preprocessor macros, we use #define © #ifdef is used to check for the existence ofrmacro .
a.
directive. An object-like macro is a simple identifier definitions. The #ifndef directive is the opposite
which will be replaced by a code fragment. of #ifdef directive. It checks whether the MACRO
They are usually used to give symbolic names to has not been defined or if its definition has been
numeric constants. Function-like macros are used removed with #undef . The #if directive is used
to stimulate functions. to control the compilation of portions of a source
e The merge operator is used to concatenate two file.
tokens into a third valid token. The #el1se directive is used within the controlled
e The #include directive is used to inform the text of a #if directive in order to provide alterna-
preprocessor to treat the contents of a specified tive text to be used if the condition is false. The
file as if those contents had appeared in the source #el1if directive is used when there are more than
program at the point where the directive appears. two possible alternatives. The #e1i£ directive like
the #else directive is embedded within the #if£
e #undef directive removes a macro name previously
directive.
created with #define. The #1ine directive enables
the users to control the line numbers within the code ® The #error directive is used to cobgen compile:
files as well as the file name that appears when an error time error messages. —
takes place.

Function-like macro It is used to stimulate functions. Self-referential macro A macro whose name appears
Object-like macro It is a simple identifier which will be in its definition. one
replaced by a code fragment. They are usually used to Trailing arguments A function-like macro definition |
give symbolic names to numeric constants. declares the names of formal parameters within:
Preprocessor It is a program that processes the source parentheses, separated by commas. If the number of
GLOSSARY
code before it passes through the compiler. arguments in the invocation exceeds the number of
Preprocessor directives These are lines included in the C parameters in the definition, the excess elves are
program that are not program statements but directives called trailing arguments. eS
for the preprocessor. They are always preceded by a
hash sign (3).
Preprocessor Directives | 349 |

” Fill in the Blanks (a) * (b) &


i
vod 1. is a program that processes the source (d) #
O . In order to extend a preprocessor directive to
o code before it passes through the compiler.
rr operates under the control of
multiple lines; which character is placed as the last
x character of the line?
fr preprocessor directive.
. Before the source code is passed through the (a) \ (b) /
compiler, it is examined by the preprocessor for oe (d) :
any ; g . Which directive is used to control the line numbers
are lines included in the program that within the code files as well as the file name that
are not program statements but directives for the appears when an error takes place?
preprocessor. / (a) #pragma (b) #define
. the is also known as a macro. (c) #line (d) #£i1lename
. The #define directive is used to . Which directive is used to check for the existence
is used to give symbolic names to of macro definitions?
numeric constants. (a) #if (b) #define
; Trailing arguments are (c) #ifdef (d) #undef
preprocessor operator is used to convert . Choose the operator which can be used in the
the argument that follows it to a string literal. conditional expression of #if directive.
. The _____ Operator is used to concatenate two (a) defined (b) sizeof
tokens intoa third valid token. (c) typecast (d) address
. When we include a file using , a search . Which predefined macro is used to specify the date
is made for the file in a standard list of system
and time of the last modification of the current
directories. _ source file?
. File inclusion can be nested to levels.
(a) TIME (b) _DATE_
. The #undef directive removes a macro name
(c) (TIMESTAMP _ (J) Siu .
previously created with
. The directive is used to contro] the State True or False
actions of the compiler in a particular portion
of a program without affecting the program as a 1. Preprocessor directives are executable statements
whole. in aC program.

15. is used to instruct the preprocessor to . The preprocessor is executed before the actual
select whether or not to include a chunk of code in compilation of program code begins.
the final token stream passed to the compiler. . Preprocessor directives can only be one line long.
16. Each #if directive must be matched by the . Preprocessor directives can appear anywhere in
directive. the program.
17. The #e1if directive and the #else directive are . Object-like macros takes one argument.
embedded within the directive. . Amacro definition can include an expression.
18. When directive is encountered, the com- . It is compulsory to write macro names in
pilation process terminates. uppercase.
19 Z causes the preprocessor to issue a . The # preprocessor operator can be used onlyina
warning and continue preprocessing. function-like macro definition.
20. specifies full conformance with ANSI C . The conversion of an argument into a string literal
standard. occurs before macro expansion on that argument.
10. File inclusion cannot be nested.
Multiple Choice Questions
a While undefining a macro, you have to specify the
1, The preprocessor directives must be preceded by parameters, if any.
which symbol?
|350 | Introduction to C Programming

wn
Lu
=
Gc
ce
Lu
<or
"ANNEXURE 7
DUCTION TO DATA This statement declares an array marks that contains 10
‘STRUCTURES elements. In C, the array index starts from zero. This means
that the array marks will contain 10 elements in all. The
A data structure is nothing but an arrangement of data first element will be stored in marks [0], second element
either in computer’s memory or on the disk storage. Some in marks [1], and so on. Therefore, the last element, 1.e.,
common examples of data structure include arrays, linked the 10th element will be stored in marks [9]. In memory,
lists, queues, stacks, binary trees, and hash tables. Data the array will be stored as shown in Fig. A7.1.
structures are widely applied in areas “such as The limitations with arrays are as follows:
e Compiler design e Arrays are of fixed size.
e Operating system e Data elements are stored in continuous memory
e Statistical analysis package locations which may not be available always.
e Database Management System (DBMS) e Adding and removing of elements is difficult because
e Numerical analysis of shifting the elements from their positions.
e Simulation However, these limitations can be solved by using the
e Artificial intelligence linked list. We have already read about arrays in Chapter 5.
e Graphics Linked lists Linked list is a very flexible and dynamic data
While studying DBMS you will realize that the major structure in which elements can be added to or deleted
data structures used in the Network data model are graphs, from anywhere at will. In contrast to using static arrays,
Hierarchical data model are trees, and RDBMS are arrays. a programmer need not worry about how many elements
will be stored in the linked list. This feature enables the
programmers to write robust programs which require
N1 TYPES OF ATA much less maintenance.
STRUCTU RES. In a linked list, each element (called a node) is allocated
space as it is added to the list. Every node in the list points
There are a variety of data structures that we can have in C
to the next node in the list. Therefore, in a linked list every
language. In this section, we will just have an introduction
node contains two types of information:
to them and in further chapters we will learn about them
in detail. e The value of the node or any other data that
corresponds to that node.
Arrays An array is a collection of similar data elements.
These data elements have the same data type. The elements e A pointer or link to the next node in the list.
of the array are stored in consecutive memory locations and The last node in the list contains a NULL pointer to
are referenced by an index (also known as the subscript). indicate that it is the end or fail of the list. Since memory
Arrays are declared using the following syntax: for a node is dynamically allocated when it is added to
type name [size] ; the list, the total number of nodes that may be added to
a list is limited only by the amount of memory available.
For example
Figure A7.2 shows a linked list of seven nodes.
int marks [1];

ears marks[1] TET ET marks{4l markets mare market marist marks{9

Figure A7.1 Memory representation of an array of 10elements : ,


|352 | Introduction to C Programming

called the rear and removed from the other end called
front. Similar to stacks, queues can be implemented
using either arrays or linked lists.
iafitigsswars | A simple linked list
Every queue will have front and rear variables that
will point to the position from where deletions and insertions
Advantage: Provides quick insert and delete operations. can be done, respectively. Consider a queue as given in
Disadvantage: Slower search operation and requires more Fig. A7.4.
memory space.
We will read more about linked lists in Chapter 11.
Stacks In computer memory, stacks can be represented as
a linear array. Every stack has a variable TOP associated
Front=O1 2 3 5 Abul Tate soRear=9
with it. TOP is used to store the address of the topmost arauigawer | Queue
element of the stack. It is this position from where the
element will be added or deleted. There is another variable Here, front = 0 and rear = 5. If we want to add
MAX which will be used to store the maximum number of
one more value in the list say, if we want to add another
elements that the stack can store.
element with value 45, then rear would be incremented
If TOP = NULL, then it indicates that the stack is empty and
by | and the value would be stored at the position pointed
if TOP = MAX, then the stack is full.
by rear. The queue after addition would be as shown in
The stack in Fig. A7.3 shows that TOP = 4, so insertions
Fig. A7.5.
and deletions will be done at this position. Here, the stack
can store at most 10 elements where the indices range
from 0 to 9. In this stack, five more elements can be stored.

ne Ge ee ee ate
0 1 2 3 TOP=4 5 6 7 8 9 afattc-a/-Wacy | Queue after insertion of a new element

Figure A7.3 BSictes


Here, front = 0 and rear = 6. Every time anew element
A stack has three basic operations: push, pop, and has to be added, we will repeat the same procedure.
peek. The push operation adds an element to the top of Now, if we want to delete an element from the queue,
the stack. The pop operation removes the element from then the value of front will be incremented. Deletions
the top of the stack. Finally, the peek operation returns the are done from only this end of the queue. The queue after
value of the topmost element of the stack. deletion will be as shown in Fig. A7.6.
However, before inserting an element in the stack we
must check for overflow condition. An overflow will occur
when we will try to insert an element into a stack that is Foca Vice Bocelli ete
already full. 0. Front! to" 23. ean Mouepeat BG nye sey
Similarly, before deleting an element from the stack, atiey-VAcy| Queue after deletion of an element
we must check for underflow condition. An underflow
condition occurs when we try to delete an element from a
stack that is already empty. If TOP = -1, it indicates that However, before inserting an element in the queue we
there is no element in the stack. must check for overflow conditions. An overflow will
Advantage: Last-in, first-out access (LIFO) occur when we try to insert an element into a queue that
is already full. When rear = MAX - 1, where MAX is the
Disadvantage: Slow access to other elements
size of the queue, i.e., MAX specifies the maximum number
Queue A queue is a FIFO (First In First Out) data structure of elements in the queue. Note that we have written
in which the element that inserted first is the first one to be
MAX - 1, because the index starts from 0.
taken out. The elements in a queue are added at one end
Preprocessor Directives | 353 |

Similarly, before deleting an element from the queue, Graphs A graph is an abstract data structure that is used
we must check for underflow condition. An underflow to implement the graph concept in mathematics. A graph
condition occurs when we try to delete an element from a is basically a collection of vertices (also called nodes) and
queue that is already empty. If front = -1 and rear = edges that connect these vertices. A graph is often viewed
-1, this means there is no element in the queue. as a generalization of the tree structure, where instead of
Advantage: Provides first-in, first-out data access. having a purely parent-to-child relationship between the
tree nodes, any kind of complex relationships between the
Disadvantage: Slow access to other items.
nodes can be represented.
Trees A binary tree is a data structure which is defined as In trees, the nodes can have many children but only one
a collection of elements called nodes? Every node contains parent, a graph on the other hand doesn’t have such kinds
aleft pointer, a right pointer, and a data element. of restrictions. Figure A7.8 shows a graph with five nodes.
Every binary tree has a root element pointed by a root
pointer. The root element is the topmost node in the tree.
If root = NULL, then it means the tree is empty.
Figure A7.7 shows a binary tree. If the root node R is
not NULL, then the two trees T, and T, are called the left
and right subtrees 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.

Nw node
Every node in the graph may be considered to represent
a city and the edges connecting the nodes could represent
yy x me 2
2 32 the roads. A graph can also be used to represent a
computer network where the nodes are workstations and
the edges are the network connections. Graphs have so
many applications in computer science and mathematics
that several algorithms have been written to perform the
standard graph operations such as searching the graph and
finding the shortest path between nodes of a graph.

Unlike trees, graphs do not have any root


Figure A7.7 | Binary tree a node. . _

In Fig. A7.7, node 2 is the left successor and node Rather, every node in the graph can be connected with
3 is the right successor of the root node |. The left any other node in the graph. When two nodes are connected
subtree of the root node consists of the nodes 2, 4, 5, via an edge, the two nodes are known as neighbours. For
8, and 9. Similarly, the right subtree of the root node example, node A above has two neighbours: B and D.
consists of nodes 3, 6, 7, 10, 11, and 12. Advantages: Best models real-world situations.
Advantages: Provides quick search, insert, and delete Disadvantages: Some algorithms are slow and very
operations. complex.
Disadvantage: Complicated deletion algorithm.
CHAPTER

Linked Lists

Takeaways
e Linked List versus Arrays e Singly Linked List e Circular Linked List —
e Doubly Linked List e Circular Doubly Linked List e Header Linked List

the end of the list. In a linked list since every node contains
11.1 INTRODUCTION a pointer to another node which is of the same type, it is
A linked list, in simple terms, is a linear collection of data also called a self-referential data type.
elements. These data elements are called nodes. Linked A linked list contains a pointer variable, START, which
lists are data structures which can be used to implement stores the address of the first node in the list. We can
other data structures. Thus, they act as building blocks traverse the entire list using this single pointer variable. The
for other data structures such as stacks, queues, and START node will contain the address of the first node; the
their variations. A linked list can be perceived as a train next part of the first node will in turn store the address of its
or a sequence of nodes in which each node contains one succeeding node. Using this technique, the individual nodes
or more data fields and a pointer to the next node. In of the list form a chain of nodes. If START=NULL, this means
Fig. 11.1, we see a linked list in which every node contains that the linked list is empty and contains no nodes.
two parts—an integer and a pointer to the next node. In C, we implement a linked list using the following
code:
struct node

{
int data;
struct node *next;
afavig-eesle A simple linked list
ie
Let us see how a linked list is maintained in memory. In
The left part of the node which contains data may
order to form a linked list we need a structure called node
include a simple data type, an array, or a structure. The
that has two fields—DATA and NEXT, where DATA will store
right part of the node contains a pointer to the next node
(or the address of the next node in sequence). The last node the information part and NEXT will store the address of the
will have no next node connected to it, so it will store a next node in the sequence. Consider Fig. 11.2.
special value called NULL. In Fig. 11.1, the NULL pointer is From the figure we can see that the variable START is
represented by Xx. However, when we do programming we used to store the address of the first node. Here, in this
usually define NULL as —1. Hence, a NULL pointer denotes example, START=1, so the first data is stored at address
Linked Lists | 355 |

1, which is ‘H’. The corresponding variable NEXT stores Another advantage of a linked list over an array is that,
the address of the next node, which is 4. So, we will look we can add any number of elements in the list. This is not
at address 4 to fetch the next data item. The second data possible in case of an array. For example, if we declare an
element obtained from address 4 is ‘Ez’. Again, we see array aS int marks [10], then the array can store a maximum
the corresponding NEXT, to go to the next node. From the of ten data elements and not even one more than that. There
entry in the NEXT field, we get the next address, i.e., 7 and is no such restriction in the case of a linked list.
fetch “L’ as the data. We repeat this procedure until we Thus, linked lists provide an efficient way of storing
reach a position where the NEXT entry contains —1 or NULL, related data and perform basic operations such as insertion,
as this would denote the end of the linked list. When we deletion, and updating of information at the cost of the extra
traverse fields the DATA and NExT fields in this manner, space required for storing the address of the next node.
we will finally see that the linked list in this example
stores characters which when put together form the word
"HELLO" . 11.3 MEMORY ALLOCATIONAND _
_ DEALLOCATION FOR A LINKED LIST
START We have seen how a linked list is represented in memory.
If we want to add a node to an already existing linked list,
we will first find free space in the memory and then use it
to store the information. For example, consider the linked
list given in Figs 11.3(a) and (b). The linked list contains
the roll numbers of the students, marks obtained by them in
Biology, and finally a NEXT field which stores the address
of the next node in sequence. Now, if a new student joins
the class and is asked to appear for the same test that the
other students had given, then the new student’s marks
should also be recorded in the linked list. For this purpose,
we will find a free space and store the information there.
If, the grey shaded portions show free spaces, then we see
that we have 4 locations of memory available and we can
use any one of them to store our data.

START

(Biology)

DO
PP
OAN
FPWN

An array is linear collection of data elements and a linked


list is a linear collection of nodes. But unlike an array, a
linked list does not store its nodes in consecutive memory
locations. Another point of difference between an array and
PRPPrRPRPE
Evo
i)
Oo
es
a linked list is that a linked list does not allow random access
of data. Nodes in a linked list can be accessed only in a Figure 11. 3(a)_ ‘Memory representation of a linked list
sequential manner, but like an array, insertions and deletions _ . storing the marks obtained by students
can be done at any point in the list in constant time. _ in Biology
|356 | Introduction to C Programming

to store the desired information. After the insertion, the


START address of the next available free space is stored in AVAIL.
For example, in Fig. 11.4, when the first free memory
(Biology) space is utilized for inserting the new node, the AVAIL
pointer will be set to contain address 6.
This was all about inserting a new node in an already
existing linked list. Now we will talk about deleting a node
or the entire linked list. When we delete a particular node
from an existing linked list or delete the entire linked list
for some reason, the space occupied by it must be given
DMN
RP
OwoON
BWYN
back to the free pool so that the memory can be reused by
some other program that needs memory space.
The operating system does this task of adding the
freed memory to the free pool. The operating system will
PrPPrPPPR
oO
FP
BWN perform this operation whenever it finds the, CPU idle or
whenever programs fall short of memory. The operating
system scans through all the memory cells and marks the
cells being used by some other programs. Then, it collects
all those cells which are not being used and adds their
address to the free pool so that they can be reused by the
has been added
programs. This process is called garbage collection. The
whole process of collecting unused memory cells (garbage
Now the big question is who will take care of the
collection) is transparent to the programmer.
memory—which part of the memory is available and
which part is occupied. When we delete a node from a
linked list then who will change the status of the memory
occupied by it from occupied to available. The answer is
the operating system. Discussing the mechanism of how
(Biology)
the operating system does all this is out of the scope of this
book. So, in simple language, we can say that the computer
takes care of this without any intervention from the user or
the programmer. As a programmer, you just have to take ["
a
care of the code to perform insertions and deletions in the
list.
However, to have an overview of the mechanism, DO
PR
OON
BPWN

we will briefly discuss the basic concept. The computer


maintains a list of all free memory cells. This list of
available space is called the free pool.
We have seen that every linked list has a pointer variable
START which stores the address of the first node of the list.
Likewise, for the free pool (which is a linked list of all free
memory cells), we havea pointer variable AVAIL which
stores the address of the first free space. Let us revisit the
memory representation of the linked list storing the students’
marks in Biology. We have another pointer variable AVAIL
here which stores the address of the first free space. gratis eec Memory representation of a linked list with _
Now, when a new student’s record has to be added, | AVAIL and START pointers |
the memory address pointed by AVAIL is taken and used
Linked Lists | 357 |

11.4 DIFFERENT TYPES OF LINKED LISTS pointed by PTR. In Step 4, we move to the next node by
making the PTR variable point to the node whose address
There are different types of linked lists which we will is stored in the NEXT field.
discuss in the following sections. These are
e Singly linked list
e Doubly linked list “Step 1: [INITIALIZE] SET PTR =rrr
Step 2: Repeat Steps 3 and 4 while PTR Is NULL
e Circular linked list oe ae Apply process : PTR->DAT
e Circular doubly linked list : 4, —sSET PTR=ae NEXT
END OF LOOP] .
e Header linked list

11.5 SINGLY LINKED LIST Gti EO) Algorithm to traverse alinkedlist ==


A singly linked list is the simplest type of linked list in
which every node contains some data and a pointer 11.5.2 Searching a Linked List
Searching a linked list means to find a particular element in
to the next node of the same data type. By saying that
the linked list. As already discussed, a linked list consists of
the node contains a pointer to the next node we mean that
a node which is divided into two parts—the DATA part and
the node stores the address of the next node in sequence.
the NEXT part, where DATA stores the relevant information
Fig. 11.5 shows a singly linked list.
and NEXT stores the address of the next node in sequence.
So obviously, searching means finding whether a given
value is present in the information part of the node or not.
If it is present, the searching algorithm returns the address
of the node that contains that value.
There are two variants of the searching algorithm.
While one algorithm is used to search for a value in a
sorted linked list, the other works for an unsorted linked
A singly linked list allows traversal of data only in one list. Let us first have a look at the algorithm used to search
way. for a value in an unsorted linked list given in Fig. 11.7.

11.5.1 Traversing a Singly Linked List pee 1: [INITIALIZE] SET PTR = S91
_ ‘Step 2. Repeat Step 3 while PT
Traversing a linked list means accessing the nodes of -a IP VAL=PTRSDATA =
the list in order to perform some operations on them. - /SERPOS=POR .
Go To Step 5
Remember, a linked list always contains a pointer variable
Bice
START which stores the address of the first node of the list. SET PTR = PTR->NEXT
The end of the list is marked by storing NULL or -1 in the {ENDOF iF]. .
NEXT field of the last node. For traversing the linked list,
we also make use of another pointer variable PTR, which
will point to the node that is currently being accessed.
The algorithm to traverse a linked list is shown in Ogiati¢a«@ ly.) Algorithm to search an unsorted linked list
Fig. 11.6
In this algorithm, we first initialize PTR with the
In Step 1, we initialize a pointer variable PTR with
address of the START. So now, PTR points to the first node
START. In Step 2, a while loop is executed which will
of the linked list. Then in Step 2, a while loop is executed
compare every node’s DATA with the VAL for which the
which is repeated till PTR processes the last node, that search is being made. If the search is successful, that is,
is, until it encounters NULL. In Step 3, we apply the the VAL has been found, then the address of that node is
process (for ex, print) to the current node, i.e., the node stored in POS and the control jumps to the last statement of
|358 | Introduction to C Programming

the algorithm. However, if the search is unsuccessful, POS first node of the list. Then the following changes will be
is set to NULL, which indicates that the VAL is not present done in the linked list.
in the linked list.
Consider the linked list shown in Fig. 11.8. If we have
VAL = 4, then the flow of the algorithm can be explained
as shown in this figure.

PTR
Here, PTR->DATA = 1. Since PFR->DATA != 4, Wemoveto
the next node because PTR = PTR->NEXT.

Here, PTR—>DATA = 7. Since PTR—>DATA != 4, Wemoveto Add the new nodeas the first node ofthe list. Now
the next node because PTR = PTR->NEXT. the NEXT part of the new node contains the address
GiSTART

PTR
Here, PTR DATA = 3. Since PTR—DATA != 4, Wemoveto
the next node because PTR = PTR->NEXT.
ar-4Vig-ie wie] Insertingan element at the beginning ofa
linkediisn
PTR
Here, PTR->DATA = 4. Since PTR—DATA = 4, POS = PTR. POS Figure 11.10 shows the algorithm to insert a new node
Nowstores the address of the node that contains the VAL. at the beginning of a linked list. In Step 1, we first check
Figure 11.8 Searching. lin whether memory is available for the new node. If the free
memory has been exhausted then an OVERFLOW message
is printed. Otherwise, if a free memory cell is available
then we allocate space for the new node. Its DATA part is
11.5.3 Inserting a New Node in a Linked List set with the given VAL and its NEXT part is initialized with
In this section, we will see how a new node is added into an the address of the first node of the list, which is stored in
already existing linked list. To illustrate this, we will take START. Now, since the new node is added as the first node
five cases and see how the insertion is done in each case. of the list, it will now be known the START node, that is,
Case 1: The new node is inserted at the beginning of a the START pointer variable will now hold the address of the
linked list New Node.

Case 2: The new node is inserted at the end of a linked list


Case 3: The new node is inserted after a given node
“step 1:IF AVAIL = NULL, thenae
Case 4: The new node is inserted before a given node
Before we begin with the algorithms to do the insertion
in all these five cases, let us first discuss an important
term—OVERFLOW. Overflow is a condition that occurs
when AVAIL = NULL or no free memory space is present in
the system. This means that we want to add data to the data
structure, but there is no memory space available to do so.
When this condition prevails, the programmer must give
an appropriate message.
Figure 11.10 Algoritht nto
Case 1 Consider the linked list shown in Fig. 11.9.
beginning ifalinke:
Suppose we want to add a new node with data 9 that as the
Linked Lists | 359 |

Note the two steps— be done in the linked list; the algorithm to add the new
Step 2: SET New Node=AVAIL node is given in Fig. 11.14.
Step 3: SET AVAIL
= AVAIL—>NEXT

These steps allocate memory for the new node. In C,


functions such as malloc(), alloc(), and calloc() do
this automatically on behalf of the user.

Case 2 Consider the linked list shown in Fig. 11.11.


Suppose we want to add a new node with data 9 as the last
node of the list. Then the following“changes will be done
in the linked list.

START, PTR
We take a PTR which will initially point to START.
Figure 11.12 9

START
Take two pointer variables PTR and PREPTR and initialize
START . PTR
them with START so that START, PTR, and PREPTR all point
Add the new node after the node pointed by PTR. This is
to the first node of the list.
done by storing the address of the new node in the NEXT
part of the PTR.

Figure 11.11 i
START, PTR, PREPTR
Move PTR and PREPTR until the DATA part of PREPTR = value
of the node after which insertion has to be done. PREPTR
Figure 11.12 shows the algorithm to insert a new node will always point to the node just before PTR.
at the end of the linked list. In Step 1, we first check
whether memory is available for the new node. If the free
START, PRE EST Raed.
memory has been exhausted then an OVERFLOW message is
printed. Otherwise, if a free memory cell is available then
we allocate space for the new node. Its DATA part with START PREPTR PIR
the given VAL and its NEXT part is initialized with NULL
because this is the last node of the linked list.
START PREPTR PTR
In Step 6, we take a PTR and initialize it with START.
Add the new node in between the nodes pointed by PREPTR
That is, PTR now points to the first node of the linked list.
In the while loop, we traverse through the linked list to
reach the last node. Once we reach the last node, in Step
9, we change the NEXT pointer of the last node to store the
address of the new node. Remember that the NEXT field
of the new node contains NULL which signifies the end of
the linked list.
Case 3 Consider the linked list shown in Fig. 11.13. START
Suppose that we want to add a new node with value 9 after
the node containing data 3. Let us look at changes that will Figure 11.13 |
|360 |_Introduction to C Programming

the first node of the linked list. Then we take another


pointer variable PREPTR and initialize it with PTR. So
Step 1: IF AVAI
now, PTR, PREPTR, and START all point to the first node
of the linked list.
pecansg In the while loop, we traverse through the linked list
Step 3: to reach the node that has its value equal to NUM. We need
Step 4: to reach this node because the new node will be inserted
Step 5: before this node. Once we reach this node, in Step 10, we
Step
6: § F / i _
change the NEXT pointers in such a way that new node is
Step 7: Repeat steps 8and 9 wile PREPTR > DATA 1=NUM
Step 8: SED PEEPIR =P 2 7 inserted after the desired node.
Step 9: SET PIR = PIR->NEXT —
_[END OF LOOP] -
Step 10:‘PREPTR - NEXT- NewNode
| Step. al: SET New_No START

Step 12: EXIT

Figure 11.14 Algorithm to insert anew ‘node after a


nodethathasvalue NUM
START, PTR, PREPTR
In Step 1, we first check whether memory is available Move PTRand PREPTR until the DATA part of PTR = value
for the new node. If the free memory has been exhausted of the node before which insertion has to be done.
then an OVERFLOW message is printed. Otherwise, if a free PREPTR will always Bot tothe ey before PTR.
memory cell is available then we allocate space for the
new node and set its DATA part with the given VAL. START | PREPTR PTR
In Step 5, we take a PTR and initialize it with START.
That is, PTR now points to the first node of the linked list.
START 1 PREPTR PTR
Then we take another pointer variable PREPTR which will
Insert the new node in between the nodes pointed by PTR
be used to store the address of the node preceding PTR.
and PREPTR.
Initially, PREPTR is initialized to PTR. So now, PTR, PREPTR,
and START all point to the first node of the linked list.
In the while loop, we traverse through the linked list to
reach the node that has its value equal to NUM. We need to
reach this node because the new node will be inserted after
this node. Once we reach this node, in Step 10, we change
the NEXT pointers in such a way that a new node is inserted
after the desired node.
Figure 11.15 | Inserting an element before a given node ’:
Case 4 Consider the linked list shown in Fig. 11.15. in the linked list —
Suppose that we want to add a new node with value 9
before the node containing 3. Let us discuss the changes
Deleting a Node from a Linked List
that will be done in the linked list.
Figure 11.16 shows the algorithm to insert a new node In this section we will see how a new node is deleted from
before a given node. In Step 1, we first check whether an already existing linked list. To illustrate this we will
memory is available for the new node. If the free memory take five cases and see how the deletion is done in each
has been exhausted then an OVERFLOW message is printed. case.
Otherwise, if a free memory cell is available then we Case |: The first node is deleted
allocate space for the new node and set its DATA part with Case 2: The last node is deleted
the given VAL.
Case 3: The node after the given node is deleted
In Step 5, we take a pointer variable PTR, and
Before we begin with the algorithms to do the deletions
initialize it with START. That is, PTR now points to
in all these five cases, let us first discuss an important
Linked Lists | 361

term—UNDERFLOW. Underflow is a condition that Figure 11.18 shows the algorithm to delete the first node
occurs when we try to delete a node from a linked list that from the linked list. In Step 1 of the algorithm, we check if
is empty. This happens when START=NULL or when there the linked list exists. If START=NULL, then it signifies that
are no more nodes to delete. there are no nodes in the list and the control is transferred
to the last statement of the algorithm.

9 1:IF AVAIL = NULL, then


: Write OVERFLOW
. = Ch Step 12
» 2 END
Step2: SET ode =AVAIL
Step3: S VAIL->NEXT
Step 4: SET New_ ode->DATA= VAL
: SET PTR =START
pep 6:SET PREPTR=- PTR :
: Repeat Steps 8 and. 9 whi le
_ . SET PREPTR= Pr
Figure 11.18 7\fve rithm to delete |
the
e first node froma 7
_ SET PTR = PTR->NEXT
_ (ENDOF* LOOP}a _ ipkedlist

However, if there are nodes in the linked list, then we


use a pointer variable that is set to point to the first node of
the list. For this, we initiate PTR with START which stores
‘insert a new node before aa the address of the first node of the list. In Step 3, START is
s value NUM made to point to the next node in sequence and finally the
memory occupied by the node pointed by PTR (initially the
first node of the list) is freed and returned to the free pool.
Case 2 Consider the linked list shown in Fig. 11.19.
by that node. The memory Suppose we want to delete the last node from the linked
eturned back to the free pool so
list, then the following changes will be done in the list.
hat itcan be used to store other data.
ver be the case of deletion, we
a ways change the AVAIL pointer so that
it points |to the address which Le been
oo ‘recently freed. = We take two pointer variables PTR and PREPTR which
will initially point to START

Case1 Consider the linked list in Fig. 11.17. When we


want to delete a node from the beginning of the list, then START, PREPTR, LEAL.

the following changes will be done in the linked list. Move PTRand PREPTR in such a way that PTR points to
the last node and PREPTR points to the second last
node ofthe list.

START
Move the START pointer so that it now points to the second node of
the list. Delete the first node. Now the list begins from the node
with data 7 as it isthe node pointed by START.
The pointer variables will be moved to pointto the
last node of the list so that the memory occupied by
it can be freed. We also store NULLin the last node
(which was initially the second last node).
Figure 1147 Deleting
the first node of a linked list
Figure ‘Blsi]) Deleting the last node of a linked list
|362 | Introduction to C Programming

Figure 11.20 shows the algorithm to delete the first node


from a linked list. In Step 1 of the algorithm, we check if
the linked list exists. If START=NULL, then it signifies that START, PREPTR, PTR
there are no nodes in the list and the control is transferred We take pointer variables PTR and PREPTR which
to the last statement of the algorithm. initially point to START.

SESE PREPTR PTR |


Move PTRand PREPTR until the data of the node pointed
by PREPTR =the value of the node after which the
deletion has to be done. PREPTR should always pointto
the node just before the node pointed aie
PTR.

PREPTR PAR

The pointer variables will be moved to pointtothe


nodes that contain VAL and the node succeeding it.

In Step 2, we take a pointer variable, PTR and initialize


it to START. That is, PTR now points to the first node of
the linked list. In the while loop, we take another pointer
variable PREPTR such that it always points to on node
before PTR. Once we reach the last and the second last
nodes, we set the next pointer of the second last node to
NULL, so that it now becomes the (new) last node of the
linked list. The memory of the initial last node is freed and
returned back to the free pool.
Case 3 Consider the linked list shown in Fig. 11.21.
Suppose we want to delete the node that succeeds the node
which contains data value 4. Then the following changes
will be done in the linked list.
Re et Steps 5 and 6 whilePRETR -> DATA {= NUM
Figure 11.22 shows the algorithm to delete the node SEL PREPTR = - PTR .
after a given node from the linked list. SET ee PTR: Coe
In Step 1 of the algorithm, we check if the linked list
exists. If START=NULL, then it signifies that there are no
: SET PREPTR->NEXT = TEMP NEXT
nodes in the list and the control is transferred to the last
Step 9: FREE TEMP _
statement of the algorithm. Step 10: EXIT
In Step 2, we take a pointer variable PTR and initialize
it to START. That is, PTR now points to the first node of
Figure 11.= Algorithm to delete the node after a given |
the linked list. In the while loop, we take another pointer
node from the linked list
variable PREPTR such that it always points to one node
before PTR. Once we reach the node containing VAL and
the node succeeding it, we set the NEXT pointer of the 11.1 Write a program to create a linked list, perform
insertions of all cases, perform deletions in all cases,
node containing VAL to the address contained in NEXT
sort the linked list, and finally delete the entire list at
field of the node succeeding it. The memory of the node
once.
succeeding the given node is freed and returned back to #include <stdio.h>
the free pool. #include <conio.h>
Linked Lists | 363 |

struct node case 2:


{ start =display (start);

int data; break;


struct node *next; IIE
i. start=insert_beg(start);
break;
struct node *start=NULL;
case 4:
struct node *create_11(struct node *); start=insert end (start):
struct node *display(struct node *); break;
struct node *insert beg(struct node *); Casemor
struct node *insert_end(struct node *); start=insert_before (start);
struct node *insert before(struct node *start); break;
struct node *insert_after(struct node *start); Cee oe
struct node *insert_sorted(struct node *start); Ar egie ad eee EEL
break;
struct node *delete beg(struct node *);
a CASCH ies
struct node *delete end(struct node *);
= ( ogo) start=delete beg(start);
struct node *delete node(struct node *start);
break;
struct node *delete after(struct node *start); case 8:
struct node *delete sorted(struct node *start); start=delete end(start);
struct node *delete
list (struct node *start); break;
struct node *sort_list (struct node *start); case 9:
meters start=delete node(start);
{ break;
Casemloy:
LIME: COELHOMP
start=delete
after (start);
clrscr (); prea

do Caseriay:
{ start=delete list (start);
Prince (" \n\n <= ** [Link] +* * ™); printf ("\n List is EMPTY");
orsinateds GOI de Ciceatela last). break;
printf ("\n 2: Display the list"); case 12:
printf ("\n3:Addanode
( inthe beginning"); start=sort_list (start);
printf ("\n4:
( Addanode
at the end"); break;
(
printf ("\n5: Addanode before a given node"); }
while (option !=15);
printf (("\n6: Addafteragivennode"); ou
getch ();
printf ("\n7: Delete fromthe beginning"); ae
printf ("\n8: Delete fromthe end"); ;

pete e \noamelebe ag ivenriodsh); struct node *create _11l(struct node *start)


printf ("\n10: Deletebeforea givennode"); {
printf ("\n11: Delete the entire list"); struct node *new node;
print
(i aaeeISonemthe: dais) int num;
printf ("\n 13: EXIT"); printf ("\n Enter -1 to end");
printf ("\n FIO I IO IIR IO I I IA Ik Kk KM) printé("\n Enter the data: ");

printf ("\n\n Enter your option: "); scanf ("$d", &num);


scanf ("%d", &option); while (num! =—1)
switch (option) {
{ new_node= (struct node*)
case 1: malloc(sizeof (struct node*));
start=create 11 (start); new node—>data = num;
print£("\n LINKED LIST CREATED"); i€ (start == NULL)
break; {
|364 | Introduction to C Programming

new node—>next = NULL; ptr—>next


= new_node;
start =new_ node; new_node—>next
= NULL;

} return start;
else }
{ struct node *insert_before(struct node *start)
new _node—>next
= start;
start=new_node;
{
struct mode *new node; *ptr, “*preptxr;
} int num, val;
printf("\n Enter the data: ");
printf("\n Enter the data: ")y
scant ("%$d", &num);
scanf ("%d", &num);
} printf("\n Enter the value before which
weturn stark.
the data has to be inserted: ");
} scanf("%d", &val);
struct node *display(struct node *start)
new_node
= (struct node *);
{ malloc(sizeof (struct node *));
struct node *ptr;
new_node—>data
= num;
per =srEart;
ptr
= start;
joresbakese (Naw)
while (ptr—>data!
= val)
while (ptr! =NULL)
{
{ preptr
= ptr;
printf ("\t %d", ptr—data);
DEr=prEr— next,
ptr=ptr—-next;
}
} new _node—>next
= ptr;
return start;
preptr—>next
= new_node;
} Heer start;

struct node *insert_beg(struct node *start) }


{ struct node *insert_after(struct node *start)
struct node *new_node;
int num;
{
struct node *new_node, *ptr, *preptr;
printf("\n Enter the data: ");
int num, val;
scanf ("$d", &num);
printf("\n Enter the data: ");
new _node= (struct node *);malloc
scanf ("%d", &num);
(sizeof (struct node *));
printf ("\n Enter the value after which
new_node—>data
= num;
the data has to be inserted: ");
new_node-—>next
= start;
scanf ("%d", &val);
start =new_node;
new_node= (struct node *);
return start;
malloc (sizeof (struct node *));
} new_node—>data
= num;
struct node *insert_end(struct node *start) ptr = start;

{ while (preptr—>data != val)


SUC beNOE PEL new enodel, {
int num; preptr=ptr;
printf("\n Enter the data: "); ptr=ptr—>next;
scanf ("%$d", &num); }
new node= (struct node *); new _node—>next
= ptr;
malloc(sizeof (struct node *)); preptr—>next
= new_node;
new_node—>data
= num; return start;
pENn="staret; }
while (ptr—>next!
= NULL) struct node *delete beg(struct node *start)
ptr = ptr—>next; {
Linked Lists | 365 |

SELUCERNOGCe RADE iy, per = start;


ptr = start; while (preptr—data !=val)
start = start—>next; {
£ree (ptr) ; preptr= ptr;
return start; PEs PEL nexey

struct node *delete end(struct node *start) preptr—ne


= ptr—next;
xt
{ free (ptr);
struct node *ptr, *preptr; return start;
ptr = start; Z }
while (ptr—>next != NULL)
{ struct node *delete
list (struct node *start)

SOI ORES = oreier


Prep P struct node *ptr;
ptr = ptr—>next ;
DEG — stare,
} != NULL)
.
whil e (ptr—>next
DECDEGS
t .
NextiE uit ;
v2 ree (ptr); ° printf("\n %d is to be deleted next",
urn
retur start; ;
ptr—>data);
} start=delete beg (ptr);
struct node *delete node(struct node *start)
ptr=ptr—>next;

{ struct node *ptr, *preptr;


return start;
int val; }
printf ("\n Enter the value of the node
which has to be deleted: "); struct node *sort
list (struct node *start)

scanf("%d", &val); {
struct node *ptrl, *ptr2;
DEH
= SESEAE
Tf (ptr—>data == val) Act 0
{ ptri1 = start;
while (ptrl—>next != NULL)
Stange —idelerenbeg (start),
return start; {
PELZ = peri next:
} while (ptr2! = NULL)
else

{ {
if (ptr1—data
> ptr2—>data)
while (ptr—>data !=val)
{
{ temp = ptr1—>data;
preptr =peEr*
ptr1l—data
= ptr2—data;
DEL = pEr— next 7
ptr2—data
= temp;
}
}
preptr—Snext = per—=next;
PEL2 = ptr2——next;
£ Hee (ptr)
((p ;
return start;
}
ptril = ptril—next;

} return start;
struct node *delete after(struct node *start) }

Output
SerUCe NOden* pels DECDELT,
Kkkkk MAIN MENU kkk
int val;
printf ("\n Enter the value after which lan Create a list
the node has to deleted: "); 2: Display the list
scanf ("%d", &val); 3: Add a node in the beginning
|366 | Introduction to C Programming

4 : Add a node at the end

5 : Add a node before a given node


6: Add after a given node
7: Delete from the beginning
8: Delete from the end
artic weve Circular linked list
9: Delete a given node
10: Delete before a given node
11: Delete the entire list The only disadvantage of a circular linked list is the
iZ-eSone the Aust complexity of iterations. Note that there js no storing of
S37) EEE
NULL values in the list.
RK IRKK ERK KKRKRKEKKKKEKEKEKEKKE Circular linked lists are widely used in operating
Enter your option : 1 systems for task maintenance. Let us consider another
Pneen co end example where a circular linked list is used. When we are
Enter the data 1
surfing the Internet, we can use the Back and the Forward
Enter the data 2
buttons to move to the earlier visited previous and the
Enter the data : 3
next pages, respectively. How is this done? The answer
Enter the data a
is simple. A circular linked list is used to maintain the
Enter the data 5
sequence of the web pages visited. Traversing this circular
Enter the data : —l
linked list either in the forward or backward direction
Rae wae ay MAIN MENU Gabe
yahsey helps to revisit the pages again using the Forward and
Create a list
Back buttons. Actually this is done using either a circular
: Display the list
stack or a circular queue. We will read more about it in
: Add a node in the beginning
Chapter 12.
: Add a node at the end
Let us view how a linked list is maintained in
: Add a node before a given node
memory. In order to form a linked list we need a structure
: Add after a given node
called node that has two fields—DATA and NEXT. The DATA
: Delete from the beginning field will store the information part and the NEXT field
: Delete from the end
will store the address of the node in sequence. Consider
Pw
3Gy
OO
to
On Delete a node after a given node
Fig. 11.24.
10: Delete before a given node
11: Delete the entire list
2 weSOGtaathey slast
aes 1D
ak ede eke ase ee ee ee ie ee ee

Enter cour option’ > 72


543° 2) 1

11.6 CIRCULAR LINKED LIST


In a circular linked list, the last node contains a pointer
to the first node of the list. We can have a circular singly
listed list as well as a circular doubly linked list. While
aie eeL Memory representation of a circular linked
traversing a circular linked list, we can begin at any node it : a
and traverse the list in any direction forward or backward
until we reach the same node where we started. Thus, a In the figure, we see that a variable START is used to
circular linked list has no beginning and no end. Figure store the address of the first node. Here in this example,
11.23 shows a circular linked list. START=1, so the first data is stored at address 1, which is
Linked Lists | 367 |

‘H’. The corresponding NEXT stores the address of the next The prev field of the first node and the next field of
node, which is 3. So, we will look at address 3 to fetch the last node contain NULL. The prev field is used to store
the next data item. The second data element obtained from the address of the preceding node. This would enable one
address 3 is ‘E’ . Again we see the corresponding NEXT, to traverse the list in the backward direction as well.
to go to the next node. From the entry in the NEXT, we Thus, we see that a doubly linked list calls for more
get the next address, that is 7 and fetch ‘L’ as the data. space per node and for more expensive basic operations.
We repeat this procedure until we reach a position where However, a doubly linked list provides the ease to
the NEXT entry contains | or the address of the first node of manipulate the elements of the list as it maintains pointers
the list. This denotes the end of the linked list, that is, the to nodes in both the directions (forward and backward).
node that contains the address of the first node is actually The main advantage of using a doubly linked list is that
the last node of the list. When we traverse the DATA and it makes searches twice as efficient. Let us view how a
NEXT fields in this manner, we will finally see that the doubly linked list is maintained in memory. Consider
linked list in this example stores characters which when Fig. 11.26.
put together form the word "HELLO".

A doubly linked list or a two-way linked list is a more


complex type of linked list which contains a pointer to the
next as well as the previous node in sequence. Therefore,
it consists of three parts and not just two. The three parts In the figure, we see that a variable START is used to
are data, a pointer to the next node, and a pointer to the store the address of the first node. Here in this example,
previous node (refer Fig. 11.25). START=1, so the first data is stored at address 1, which
is ‘H’. Since this is the first node, it has no previous
node and hence stores NULL or —1 in the PREV field. The
corresponding NEXT stores the address of the next node,
which is 3. So, we will look at address 3 to fetch the next
data item. The prev field will contain the address of the
Figure 11.25 first node. The second data element obtained from address
3 is ‘E’. Again we see the corresponding NEXT, to go to
the next node. From the entry in the NEXT field, we get
In C, the structure of a doubly linked list is given as,
the next address, that is 7 and fetch ‘L’ as the data. We
struct node repeat this procedure until we reach a position where the
NEXT entry contains —1 or NULL. This denotes the end of
stmuct node *prevs; the linked list, that is, the node that contains the address
int data; of the first node is actually the last node of the list. When
struct node *next; we traverse the DATA and NEXT fields in this manner,
Li we will finally see that the linked list in this example
|368 | Introduction to C Programming

stores characters which when put together form the word is ‘H’. Since this is the first node, it stores the address
"HELLO" . of the last node of the list in its previous field. The
corresponding NEXT field stores the address of the next
The figure shows a chunk of memory
node, which is 3. So, we will look at address 3 to fetch the
locations whose addresses range from 1
next data item. The previous field will contain the address
_ to 10. The shaded portion contains
for other applications. Rem of the first node. The second data element obtained from
- the nodes of a linked list address 3 is ‘E’. Again we see the corresponding NEXT, to
not be in consecutive memory— go to the next node. From the entry in the NEXT field, we
. locations. In our example, the nodes for get the next address, that is 7 and fetch tL’ as the data.
the linked list »d at addresses 1, We repeat this procedure until we reach a position where
3, 7, 8, and 10. - the NEXT entry stores the address of the first element of
the list. This denotes the end of the linked list, that is, the
node that contains the address of the first node is actually

11.8 CIRCULAR DOUBLY LINKED LIST the last node of the list. When we traverse the DATA and
NEXT fields in this manner, we will finally see that the
A circular doubly linked list or a circular two-way linked linked list in the above example stores characters which
list is a more complex type of linked list which contains when put together form the word "HELLO".
a pointer to the next as well as the previous node in
sequence. The difference between a doubly linked and a START
circular doubly linked list is the same as that between a
singly linked list and a circular linked list. The circular
Bar| pREV [WET
doubly linked list does not contain NULL in the previous
field of the first node and the next field of the last node.
Rather, the next field of the last node stores the address
of the first node of the list, i.e., START. Similarly, the
previous field of the first field stores the address of the last
node. A circular doubly linked list is shown in Fig. 11.27.

Figure 11.28 | Memory representation ofa circular


doubly linked list
Sete eeera Circular doubly linked list

Since a circular doubly linked list contains three parts 11.9 HEADER LINKED LIST |
in its structure, it calls for more space per node and for A header linked list is a special type of linked list which
more expensive basic operations. However, a circular contains a header node at the beginning of the list. So, in a
doubly linked list provides the ease to manipulate the header linked list START will not point to the first node of the
elements of the list as it maintains pointers to nodes in list but START will contain the address of the header node.
both the directions (forward and backward). The main There are basically two variants of a header linked list:
advantage of using a circular doubly linked list is that it e grounded header linked list which stores NULL in the
makes searches twice as efficient. next field of the last node, and
Let us view how a circular doubly linked list is e circular header linked list which stores the address
maintained in memory. Consider Fig. 11.28. of the header node in the next field of the last node.
In the figure, we see that a variable START is used to Here, the header node will denote the end of the list.
store the address of the first node. Here in this example,
Look at Fig. 11.29 which shows both these types of
START=1, so the first data is stored at address 1, which
header linked lists.
Linked Lists | 369 |

contains —1 or NULL, as this would denote the end of the


linked list. When we traverse the DATA and NEXT in this
manner, we will finally see that the linked list in the above
example stores characters which when put together form
the word “HELLO”.
Header Hence, we see that the first node can be accessed by
node
writing first node = START-—>NEXT and not writing
START = first_node. Because START points to the header
node and the header node points to the first node of the
Figure 11.29 Header linked list header linked list.
Let us now see how a circular header linked list is
stored in memory. Look at Fig. 11.31.
Header Node
Similar to the other linked lists, if START=NULL, then this
denotes an empty header linked list. Let us see how a
grounded header linked list is stored in memory. In order
to form a grounded header linked list we need a structure START

called node that has two fields—DATA and NEXT. The DATA
field will store the information part and the NEXT field
will store the address of the node in sequence. Consider
Pigs 1°30.

Figure 11.31 tionofa circular — 2


START

START stores the address of the header node. The shaded


row denotes a header node. The NEXT field of the header
node stores the address of the first node of the list. This
node stores ‘H’. The corresponding NEXT field stores the
address of the next node, which is 3. So, we will look at
address 3 to fetch the next data item. The second data
element obtained from address 3 is ‘E’. Again we see the
Sete Ey Memory representation of aheade
corresponding NEXT, to go to the next node. From the
entry in the NEXT, we get the next address, that is 7 and
START stores the address of the header node. The fetch ‘L’ as the data. We repeat this procedure until we
reach a position where the NEXT entry contains 5 or the
shaded row denotes a header node. The NEXT field of
address of the header node as this would denote the end of
the header node stores the address of the first node of
the circular header linked list. When we traverse the DATA
the list. This node stores ‘H’. The corresponding NEXT
and NEXT fields in this manner, we will finally see that the
field stores the address of the next node, which is 3. So,
linked list in this example stores characters which when
we will look at address 3 to fetch the next data item.
put together form the word ‘HELLO’.
The second data element obtained from address 3 is ‘E’.
Hence, we see that the first node can be accessed by
Again we see the corresponding NEXT field, to go to the
writing first node = START-—>NEXT and not writing
next node. From the entry in the NEXT, we get the next START = first _node as START points to the header node
address, that is 7 and fetch ‘L’ as the data. We repeat this and the header node points to the first node of the header
procedure until we reach a position where the NEXT entry linked list.
|370 | Introduction to C Programming

Lad node. This would enable traversing the list in the


f~ ® A linked list is a data structure which in turn can
O be used to implement other data structures such backward direction as well.
2 as stacks, queues, and their variations. Linked lists e Thus, we see that a doubly linked list calls for more
O
peat
contain a pointer variable START, which stores the space per node and for more expensive basic
address of the first node in the list. operations. However, a doubly linked list provides
VW)
a e@ AVAIL stores the address of the first free space. the ease to manipulate the elements of the list as it
= e Before we insert a new node in a linked list, we maintains pointers to nodes in both the directions
O need to check for OVERFLOW condition, which (forward and backward). The main advantage of
a. using a doubly linked list is that it makes searches _
occurs when AVAIL=NULL or no free memory cell
is present in the system. twice as efficient. :
e A circular doubly linked list or a circular two-way
Before we delete a node from a linked list, we
linked list is a more complex type of linked list
must first check for the UNDERFLOW condition
which contains a pointer to the next as well as the
which occurs when we try to delete a node from
previous nodes in the sequence. The difference
a linked list that is empty. This happens when
between a doubly linked and a circular doubly
START = NULL or when there are no more nodes
linked list is the same as that which exists between
to delete when we attempt deletion.
a singly linked list and a circular linked list. The
Note that when we delete a node from the linked circular doubly linked list does not contain NULL
list, we have to actually free the memory occupied in the previous field of the first node and the next
by that node. The memory is returned to the free field of the last node. Rather, the next field of the
pool so that it can be used to store other useful last node stores the address of the first node of
programs and data. So whatever be the case of the list, i.e., START. Similarly, the previous field of
deletion, we always change the AVAIL pointer so the first field stores the address of the last node.
that it points to the address that has been recently
e A header linked list is a special type of linked list
vacated.
which contains a header node at the beginning of
e The PREV field of the first node and the NEXT the list. So, in a header linked list START will not
field of the last node will contain NULL. The PREV point to the first node of the list but will contain
field is used to store the address of the preceding the address of the header node.

Circular linked list A type of a linked list in which the address of next node in the list.
last node is linked to the head. The nodes of the list Linked list A list in which each node has a link to the
may be accessed starting at any item and following the next node.
links until one comes to the starting item again.
Searching a linked list Searching means to find a
Doubly linked list A type of a linked list in which each particular element in a linked list. The worst case
GLOSSARY
node has a link to the previous item as well as the next. complexity of searching an unsorted or a sorted linked
This enables ease of accessing the nodes backward as list is O(n).
well as forward and deleting any node.
Traversing a linked list Traversing means accessing the
Head The first node of the list. nodes of the list in order to perform some processing
Link A reference, pointer, or access handle to another on them.
part of the data structure. It usually stores the memory

Fill in the Blanks


1. is used to store the address of the first 2. The complexity to insert a node at the beginning of
free memory location. a linked list is
EXERCISES
Linked Lists | 371 |

2 The complexity to delete a node from the end of a State True or False
— linked list is :
. Alinked list is a linear collection of data elements.
4. Insertinga node in the beginning of a doubly linked
. A linked list can grow and shrink during run time.
list needs modification of pointers.
. Anodeina linked list can point to ony one node at
5. Inserting a node in the middle of a singly linked list
a time.
_ needs modification of pointers.
. Anode in the singly linked list canetenc: the.
6. Inserting a node at the end of a circular linked list
previous node.
needs modification of pointers.
. Alinked list can store onlyinteger values. 7
7. Inserting a node in the beginning of a circular
_ Linked list is a random access structure.
doubly linked list needs modification of
_ pointers. . Deleting a node from a doubly linked list is easier
_ than deleting itfrom a singly linked list.
8. Deleting a node for: the bestnnine of a singly
linked list needs modification of pointers. . Every node ina linked listcontains an ices part
anda pointer.
. Deleting a node from the middle of a doubly linked
list needs modification of ___ pointers. : START pointer stores theaddress of the firsnode 7
in the list.
. Deleting a node from the end of a circular ae
10. Underflow is a condition that occurs when we try
_ list needs modification of pointers.
a to delete a node from a linked listthat is empty.
Each elementina linked list is known asa :
. The first node in the linked list is called the Review Questions

i. Make a comparison betwen a linked list ae a


_ Data elements in a linked list are known as linear array. Which one will you as to use and
when?
verfl OW OCCUIS when
. Why is a doubly linked list mor : seful than S :
. In a circular linked list, the last node contains a
_ singly linked list?
pointerto the node of the list.
. Give the advantages and uses
oof a circular linked
list.
- Multiple Choice Questions _
Specify the use Ofe header node iina2 headerlinked
_ list.
a) random access structure Explain the aiffevence between a circular linked hee
(b) sequential access structure and a singly linked list.
Write a program that removes all nodes thathave
duplicate information.
. Write a program to print the total number of
occurrences of a given item in the linked list.
: ~_(b) cecuential access structure . Write a program to multiply every element o
(c) both linked list with 10.
(d) none of these . Write a program to print the number of non- zero
_ Linked list is used to implement data structures elements in the list.
_such as . Write a program that prints whether the given —
(a) Stacks (b) Queues linked list is sorted (in ascending order) or not.
(c) Trees (d) all of these . Write a program that copies a circular linked list.
. Which type of linked list contains a pointer to the . Write a program to merge two linked lists. |
next as well as the previous. nodes iin sequence?
. Write a program to sort the values stored in a
(a) singly linked list doubly circular linked list.
_ (b) circular linked list 14. Form a linked list to store student’s details.
(c) doubly linked list
15, Use the linked list of the above question to insert
(d) all of these the record of a new student in the list.
|372 | Introduction to C Programming

n . Delete the record of a student with a specified roll 32. Write a prograr i
uu number from the list maintained in question 14. point numbers. Disp 3)
=
Ss) . Write a program to merge two sorted linked lists. these numbers.
oe
ar The resultant list must also be sorted. 33. Witte a1 program to deletethe
<< . Write a program to delete the first, last and middle
WW
node of a header linked list. 34, Write a program to perf del
. Write a program to create a linked list from an cases of a circular header nked st
already given list. The new linked list must contain 35. Write a program 19multip|
every alternate element of the existing linked list. givennumber. _
. Given a linked list that contains alphabets. The 36. Write a program ‘to
can the
alphabets may be in upper case or in lower case. values in a circular linked list.
Create two linked lists—one which stores upper a progran _
37. Write
case alphabets and the other that stores lower stores the details of a stude
case characters. information storedHes a list
. Write a program to concatenate two doubly linked
lists.
. Write a program to delete the first element of a
doubly linked list. Add this node as the last node employees. Then 200 these. nar
of the list. the contents ofthe linked list.
. Write a program to 40. Write a program to create linked list w
(a) Delete the first occurrence of a given character the — = employee in a departm
in a linked list
(b) Delete the last occurrence of a given character
(c) Delete all the occurrences of a given character
. Write a program to reverse a linked list using —
recursion.
. Write a program to input an n digit number. Now
break this number into its individual digits and
then store every single digit in a separate node
thereby forming a linked list. For example, if you
enter 12345, now there will 5 nodes in the list
44. Write a program that prints the nth ele
containing nodes with values—1, 2, 3, 4, 5.
the end of a linked list in a aes
. Write a program to sum the values of the nodes of
a linked list and then calculate the mean.
. Write a program that prints minimum and
maximum value in a linked list that stores integer
values.
. Write a program to interchange the value of
the first element with the last element, second
element with second last element, so on and so
forth of a doubly linked list.
i
. Write a program to make the first element of singly
linked list, the last element of the list.
. Write a program to count the number of
occurrences of a given value in a linked list.
. Write a program that adds 10 to the values stored
in the nodes of a doubly linked list.
Linked Lists | 373 |

_ (a) PTR1->NEXT->NEXT->DATA = ? 54. Given the memory representation of a linked list of


>. e4 student shown below, give the changes that will _
_ © 6 - have to be done to the representation when a new
. linked list, set START= ? record is added. Also show the changes when the
« ee record of;so4 isdeleted.
EXERCISES ¢ START--NEXT —° ‘STa
mes of students in a class, show
epresentation of the linked list

fi
in memory provided that the names5 should be
sorted in alphabetical order.
NAMES= Mary, Joe, Adam, Nava, ios Karan,
Sehej, Riyansh, Priya
Hint: Set the START and NEXT vee
Case Study
for Chapters 8,9,and11

In Chapter 8, we have seen how related information Den next— NUL


rgSibhag) johwies
can be grouped and stored together using structures. In
Chapter 11 we have seen that a number of records that }
struct node *get_node()
are related to each other can be stored using a linked
{
list. Storing records using linked lists helps to preserve struct node *ptr;
memory space and is much more efficient. ptr = (struct node*)malloc(sizeof (struct
Finally to store the records on a persistent storage area node));
we can use files. The files are stored on the hard disk of printf ("\n Enter the phone number : ");
the computer and can be brought into the memory as and scanf ("%d", &ptr—>num);

when their need arises. printf("\n Enter the Name : ");


scanf ("%s", &ptr—>name);
1. Using all this information, write a program for imple-
ptr—next
= NULL;
menting a telephone directory. Write an application LECULHE DEL:
for storing the names and phone numbers in a file. }
Use a linked list to store and retrieve data. struct node *search record (int id,int *£llag)
include <conio.h> {
include <stdio.h> struct node *cur=start,*prev =NULL;
include <alloc.h> *flag=0;
+H
HH
HH include <string.h> if (start
== NULL)
return NULL;
struct node
while (start! =NULL)

int num;
{
if (cur—>num == id)
char name [15];
struct node *next;
{
cote
Chi—mlye
ie
break;
struct node *start; }
FILE *fp; prev
= cur;
Cur ='Cur——next;
struct node *get_record()
{
}
BECUPMmpIseva,
Struct node *ptxr;
ptr = (struct node*)malloc
(sizeof (struct }
node)); int insert_node(struct node *new_node)
fread(&ptr,
sizeof (struct node) ,1,fp); {
printf ("\n NUM = $d \t NAME = struct node *prev;
$s",ptr—>num, ptr—>name); int flag;
Case Study for Chapters 8, 9, and 11 | 375 |

prev = search record (new node-—>num,


&flag);
else
if (start
== NULL)
temp = prev—>next;
start =new_node; prev—>next
= temp—>next ;
return —1; free (temp);

ae (elle)
SS 2) return 0;

selsye hess 8p }
else Struct nodes querye record (intmud Charts
*flag,int option)
new_node—>next = prev—>next ;
{
prev —>next =new_node; struct node *cur, *prev =NULL;
} int x=0;
return 0; if (start
== NULL)
} return NULL;
void display() SUita=nsitec
ate
{ if (option)
struct node *ptr;
{
int. 1 = Oj. while (cur! =NULL)
if (start
== NULL) {
{ if (cur—>num == id)
johestinieas
(WN io) ieacetay! IES) jay
hebysll)\e {
TaShe bhgaye aS ILE
break;
}
preantf(\aeRECORDSE: i);
prev
= cur;
ptr=start;
CUR
CUE next:
while (ptr! =NULL)
{ }
jSieatiatene
(UH Wok 1kevclonael Fare), roll, aletal))y else
printf ("\n \t PHONE NUMBER:
{
$a",ptr—>num); while (cur! = NULL)
printf ("\n \t NAME {
$s",ptr—>name); if (!strcemp (cur—>name, flag) )
i++; {
PeB T= prs >Next; re=alip
break;
} }
prev =cur;
int delete node(int id)
Cur = cur—>next ;
{
struct node *prev,*ptr, *temp;
shine Ballets tO)

if (start==NULL)
return —l; printf ("\n The record does not
exist");
prev = search record (id, &flag);
return NULL;
Lt (Elag==0;) }
return —1; return cur;

if (prev==NULL) }
void backup()
{
ptr =start; {
FILE *fp;
start =start—next;
struct node *ptr;
free (ptr);
1E}O) fopen ("PHONE NUMBERS .TXT", "w");
|376 | Introduction to C Programming

ptr=start;
if (ptr==NULL) casem

{ new node = get_node();


printf ("The list is empty, nothing flag = insert_node (new_node);
to write back..."); if (Elag== —1)
return; printf ("\n Record already
} exists");
while (ptr! =NULL) else
{ printf ("\n Record Added");
Elonaaliahous
(Geyo), Cx break; i
$s",ptr—>num, ptr—name); case 2:

DER = pra next: printf ("\n Enter the phone


} no. to be deleted");
fclose (fp); scanf ("%d", &pno);
} flag = delete _node(pno);
void main () ane (GelleYo; = =AL)
{ printf ("\n Record .does not
THAME CYAN SO), joraioye exist");
inte flag
= OF ibe (Gelere; == 10)
chan str l15)7 searchiname 20); printf ("Record deleted !");
struct node *new_node; break;
Cilssea()is Caseas:
display
();
£p = open ("PHONE NUMBERS .TXT", "x"); break;

case 4:
aie (fp == NULL) printf ("\n Search by phone
{ no. or Name ? (1/2)");
printf ("File cant be opened!"); scanf ("%d", &option);
getch(); TE (OpeLon=—))
exit (1); {
} printf ("\n Enter the phone
while (!feof (fp) ) no. to be searched:");

{ scanf ("%d", &pno);


new_node=get_record(); new_node
= query _
if (insert_node (new_node) == —1) record (pno, &str,1);
printf ("\n The new node could }
not be inserted"); else
else {
printf ("\n Record Added."); printf("\n Enter the name
} to be searched : ");
getch(); scanf("%s",&str);
fclose (fp); new_node
= query _
do record (0,&str,0);
{ }
elrsen
(i; if (new_node)
jonemiajere (WU Nia ier xkkkk* MATIN MENU {
KKK KK KKM)
printf ("\n Enter the new
1, Add Record"); name : ");
2. Delete Record"); scanf ("%s", &new node—>name);
n 3. Display Records"); printf ("\n Enter new phone
4. Edit Record"); 1eveys LU)IS
Big losete,..))s scanf ("%d", &new_node—>num);
jouenliniene (Nish IDigleewe yoke Cjoieskesay 2 ))e printf ("\n Record modified
$d", &option); SUCCESS
Eu iy, Sl)
switch (option)
}
break;
Output
Sasemon
printf ("\n Copying the kKkkKKkK* MAIN MENU kkkkekKek

database to the file"); . Add Record


backup (); . Delete Record
getch(); . Display Records
free (start); Edit Record
exit (1); fF
Om
WN Bocate.
break; 3 Enter your option : 1
} Enter the phone number : 9871123456
getch (); Enter the Name : Goransh Bathla
}while (1); Record Added
Answers to
. Objective Questions

CHAPTER 1

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 utilities; 10. label, an operation
code, and one or more operands

Multiple Choice Questions

1. ROM; 2. FORTRAN; 3. assembly language; 4. all of these; 5. machine language; 6. linker;


7. anti-virus; 8. BIOS; 9. computer hardware; 10. operating system

True or False

1. true 2. true 3. true 4. false 5. false

6. true 7. false 8. true 9. false 10. true

CHAPTER 2

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. default case; 12. printf(); 13. abs() in math.h; 14. single quotes; 15. closing bracket;
16. math.h; 17. \n; 18. double; 19. const; 20. he sign of the first operand is positive; 21. the
direction in which the operator having the same precedence acts on the operands; 22. parenthesis;
23. sizeof; 24. Y%hd; 25. x; 26. —

Multiple Choice Questions

1. relational; 2. Logical AND and Logical OR; 3. 3; 4. Bitwise NOT; 5. comma; 6. %hd; 7. ‘bb’,
“A”; 8. ‘a’, “1”, pi; 9. Initial. Name, A+B, $amt, 1‘ row, Col Amt; 10. % 11. res =/4
Answers to Objective Questions | 379 |

State True or False

1. false 2. false 3. true 4. false 5. true


6. false Zire 8. false 9. false 10. false
11. true 12. true 13. false 14. false 15. false
16. true 17. true 18. false 19. false 20. false
21. false Daa true 23. false 24. false 25. true
26. true g

CHAPTER 3

Fill in the Blanks

1. there is no matching else; 2. integral; 3. n for every if statement; 4. break/continue; 5. infinite;


6. loop; 7. decision control; 8. integral; 9. iterative; 10. post test loops; 11. sentinel controlled;
12. goto; 13. goto
State True or False

. false
» true

CHAPTER 4

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. arguments; 17. local
variable

Multiple Choice Questions

1. called function; 2. all of these; 3. void; 4. defined; 5. static; 6. extern; 7. static; 8. auto

State True or False

1. false 2. true 3. true 4. true 5. true

6. false 7. true 8. false 9. true 10. true


11. true 12. false 13. true 14. false 15. false

16. true le true


|380 | Answers to Objective Questions

CHAPTER 5

Fill in the Blanks

1. collection of similar data elements; 2. subscript/index; 3. integral; 4. consecutive; 5. n;


6. pointer; 7. data type, name and size; 8. the element being referenced; 9. index; 10. array name;
11. the number of elements stored in it; 12. traversing; 13. sorted array; 14. O(n); 15. consecutive;
16. constant; 17. array of arrays; 18. fourth; 19. linear;

Multiple Choice Questions

1. 10; 2. 7; 3. 200; 4. 50; 5. 25; 6. greater; 7. O(log n); 8. best case; 9. all of these

State True or False

1. true : 3. true : 5. false


6. false : 8. false : 10. false
11. false : 13) true z 15. false
16. true : 18. true 2 20. true
21. false : 23. false : 25. false
26. false

CHAPTER 6

Fill in the Blanks

1. anull-terminated character array; 2. null character; 3.5; 4. zero; 5. consecutive; 6. 99; 7. scanf();
8. zero; 9. 65-91; 10. convert a character into upper case; 11. when in dictionary order S1 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 str2 to the end of the string pointed; 18. if str1 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. strcat(s,1(strcat(s2,s3))); 11. 23; 12. strcat();

State True or False

1. false = 3. false 4. true 5. false


6. false | ks 8. false 9. false 10. false
11. true : 13. false 14. true 15. false
16. false
Answers to Objective Questions | 381 |

CHAPTER 7

Fill in the Blanks

1. 1 byte; 2. dynamic memory allocation; 3. address, pointer; 4. null; 5. data type; 6. 2; 7. rvalue;
8. memory addresses; 9. pointers; 10. *; 11. main memory; 12. stack; 13. 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(), heap; 17. void pointer, null pointer; 18. to change the
memory size already allocated by calloc() and malloc(); 19. pointer-to-pointer-to-int; 20. garbage
value; 21. address of a pointer variable; 22. 0; 23. pointer-to-pointer-to-int; 24. pointers; 25. free();
26. arrays of varying sizes;

Multiple Choice Questions

1. Dereferencing operator; 2. num; 3. all of these; 4. address; 5. &; 6. stack; 7. heap; 8. stdlib.h;
9. calloc(); j

State True or False

. true
. false
. true

LEC

. false
2 (GUE

CHAPTER 8

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. true 5. true


6. false 7. false 8. true 9. true 10. true
11. false 12. false 13. 1me 14. false 15. false
16. true 17. false 18. true 19. false 20. true
Oe true
|382 | Answers to Objective Questions

CHAPTER 9

Fill in the Blanks

1. file; 2. 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. flushallQ); 13. stdout; 14. fseek() or
rewind(); 15. stdio.h, -1;

Multiple Choice Questions

1. ftellQ); 2. fwrite(Q); 3. all of these; 4. stderr; 5. buffer; 6. fopen(); 7. fgetc();


State True or False

1. false 2. false 3. true 4. true 5. false


6. false 7. false 8. false 9. true 10. false
11. false 12. true 13. true 14. true 15. true

CHAPTER 10

Fill in the blanks

1. 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 parameters in the definition; 9. #; 10. merge operator; 11.
angular brackets; 12. 10; 13. #define; 14. #pragma; 15. conditional directive; 16. a closing #endif;
17. #if directive; 18. #error directive; 19. #warning directive; 20. STDC_;

Multiple Choice Questions

1. #; 2. \; 3. #line; 4. #ifdef; 5. defined; 6. TIMESTAMP;

State True or False

1. false 2. true 3. false 4. true 5. false


6. true 7. false 8. true 9. true 10. false
11. false 12. true 13. false 14. true 15. false

CHAPTER I1

Fill in the Blanks

1. AVAIL; 2. O(1); 3. O(n); 4. two; 5. one; 6. two; 7. two; 8. one; 9. two; 10. one; 11. node; 12.
START; 13. node; 14. there is no memory that can be allocated for the new node to be inserted;
[Se first;

Multiple Choice Questions


1. Sequential access structure; 2. both; 3. all of these; 4. doubly linked list;

State True or False


1. true [Link] 3. false 4. false
6. false 7. true 8. false 9. true
Index

symbols binary file 303


binary search 163
& operator 258
BIOS 2
#define 337
Bit fields 299
#elif directive 345
break statement 93
#else directive 345
#endif directive 346
#error directive 347 Cle
#ifdef 344 characteristics 16
#if directive 345 uses 17
#ifndef 344 called function 117
#include 340 calling function 117
#line 341 character constant 26
#undef 341 circular doubly linked list 368
circular linked list 366
Cclearerr() 312
algorithm 107, 108, 109
comments 21
decision 107
compiler 4
repetition 107
compiling and executing C programs 20
sequence 107
computer software 1, 2
space complexity 108
classification 2
time complexity 108
system software 2
efficiency 109
conditional branching statements 62
application software 5
if—else-if statement 66
array of pointers 244
if-else statement 64
arrays 146, 351
conditional directives 343
accessing elements 147
constants 25
calculating the address of array elements 147
continue statement 93
calculating the length 149
declaration 146
deletion 158 dangling else problem 70
insertion 155 dangling pointer 257
operations 150 dependent quadratic loop 110
searching 162 device drivers 2
traversal 150 doubly linked list 367
assembly language 7 dynamic memory allocation 252

basic data types 23 enumerated data types 291


| 384 | Index

fgetc () 307 layered program 10


fgetpos () 330 linear loops 109
fgets () 306 linear search 162
file 301 linked lists 351, 354
file mode 304 linker 5
file pointer 303 linux 59
files used in a C program 19 loader 5
binary executable file 20 logarithmic loops 109
header files 19 logic-oriented programming 11
object files 20
source code file 19 machine language 6
floating point constant 26 memory allocation 252
fprintf () 308 automatic allocation 252
fputc () 310 dynamic allocation 252
fputs () 310 static allocation 252
fscanf() 305 memory corruption 257
fseek () 327 memory leak 257
fsetpos () 330 memory usage 252
ftell () 329 merging 160
function 115,117, 118 modular programming 9
call 118 multidimensional arrays 178
declaration 117
definition 118
nested loops 83, 109
prototype 117
nested structure 277
function-like macros 338
null pointer 233
function pointer 249, 250
array of 250
fwrite () 311 object 11
object-like macro 337
object-oriented paradigm 11
generic object 12
object-oriented programming 11
generic pointer 233
one-dimensional arrays 165
global memory 226
inter-function communication 165
goto statement 95
operating system 3
graphs 353
operations 173
inter-function communication 176
header linked list 368 two-dimensional arrays 173
heap 225 operator 40, 44
bitwise 41
identifiers 22 comma 44
input/output statement 27 conditional 40
formatting input/output 27 precedence chart 44
printf() 28 sizeof 44
scanf() 30 operators 35, 37, 38, 39, 42
streams 27 assignment 42
integer 25 equality 37
interpreter 5 logical 38
iterative statements 75 unary 39
while loop 75
passing parameters 121
keywords 22 call by reference 122
Index | 385 |

call by value 121 strcmp function 209


perror () 313 strcpy function 210
pointers 226, 251 strespn function 211
drawback 256 strlen function 210
pragma directives 342 strncat function 208
preprocessor directives 336 strncpy function 210
programming languages 5 strpbrk function 211
generation 6 strrchr function 209
strspn function 211
quadratic loop 110 strstr function 211
queue 352 strtod function 212
strtok function 212
strtol function 212
recursion 134
atoi () function 213
direct recursion 134
string operations 198 |
indirect recursion 134
strings 193
linear and tree recursion 135
reading 193
tail recursion 134
writing 193
recursive functions 131
string taxonomy 197
remove () 331
delimited string 197
return statement 120
fixed length string 197
rewind () 329
length-controlled string 197
robust C programming 97
variable length string 197
structure declaration 271
scanset 196 structured programming 9, 10
scope of variables 125 structure of aC program 17
block scope 125 structures 288
file scope 127 self-referential 288
function scope 126 system software 2
program scope 126
singly linked list 357
text file 302
slack byte 300
Tower of Hanoi 136
software re-use 107
treesw 353
sparse matrices 180
two-dimensional arrays 168
sscanf() 197
accessing the elements 171
stack 225 declaration of 169
standard error (stderr) 302 typecasting 48
standard input (stdin) 301 type conversion 48
standard output (stdout) 302
standard streams 302
UBUNTU 59
storage classes 127
union 289
auto 128
UNIX 59
extern 129
unstructured programming 9
register 128
utility software 4
static 130
string constant 26
string manipulation functions 208 variables 24
atof() function 213
atol() function 213 while loop 75
strcat function 208 do—while loop 78
strchr function 209 wild pointer 256
DATA STRUCTURES USING C (SECOND EDITION) DATA STRUCTURES USING C++
9780198099307 9780198066231
Reema Thareja, University of Delhi Varsha H. Patil, Matoshri College of Engineering, Nashik
The book starts off with a brief The book begins with a
overview of C programming discussion on the fundamentals ees
concepts, which is followed by the of data structures and
study of various data structures algorithms, and moves on to ' Data
such as arrays, linked lists, stacks, the concepts of linear data Structures
queues, trees, and graphs. structures, recursion, searching Vos
>.
.
Using
and sorting.
Key Features
e Provides a brief recapitulation Key Features
of C programming basics be- e Provides a thorough over-
fore delving into the analysis view of the fundamental con-
Reema Thareja
of data structures cepts
e Makes use of numerous algo- e Includes numerous algo-
rithms, programs, and illustra- rithms and program codes in
tions to explain the concepts C++ to illustrate the topics discussed
e Improved explanation of algorithms and a greater variety e Provides several illustrations and flowcharts to help
of in-text examples understand the subject effectively

PROGRAMMING WITH ANSI C++ (SECOND EDITION) PROGRAMMING IN JAVA (SECOND EDITION)
9780198083962 9780198094852

Bhushan Trivedi, GLS Institute of Computer Technology, Sachin Malhotra, JMS Ghaziabad and Saurabh Choudhary,
Ahmedabad IT Consultant and Corporate Trainer
This textbook provides a fine balance between theory and Thoroughly updated for Java
practice and an in-depth coverage of both elementary as well Standard Edition 7 (Java SE 7),
as advanced topics. this textbook provides greater
topical coverage and more
Key Features programming examples in
e Detailed discussion on every chapter.
advanced topics such as
RTTI, Casting operators, Key Features
MIL, Reference variables, e Provides a quick recap of
and Templates object-oriented program-
e Programs are followed by a ming concepts before get-
detailed analysis section that ting started with Java
decodes the logic behind the e Includes plenty of user-
BAUSHAN TRIVED!
programs friendly programs with line-by-line explanations and
e Accompanied with a CD comments in them to encourage self-study
that contains the codes of all e Contains a Lab Manual with useful program codes and a
the programs as well as case studies set of interview questions with answers as appendices

OTHER RELATED TITLES


9780198097402 Harsh Bhasin: Programming in C # e 9780198070887 Srimanta Pal: Systems Programming
9780198082163 B. M. Harwani: Unix and Shell Programming e¢ 9780198061847 Naresh Chauhan: Software Testing:
9780195696561 Subhajit Datta: Software Engineering Principles and Practices
9780198082873 Naresh Chauhan: Principles of Operating ¢ 9780198066774 Bhushan Trivedi: Computer Networks
Systems

Visit us at [Link] and [Link]


||

QA Thareja, Reema,
7673 author,
LO he Introduction to C
123 programming
INTRODUCTION TOcPROGRAMMING
SECOND EDITION ~
This second edition of Introduction io c Propanning
is designed to serve as a textbook for B Tech and MCA | Praise for the First Edition
students as well as those pursuing any basic course on C
Concepts are neatly explained with the required
programming. The book focuses on the fundamentals of C
programs.
programming to enable students write effective programs.
-~Harish G.,
Beginning with an introduction to programming in general,
the text delves into a complete analysis of the various Dr. Ambedkar Institute of Technology, Bengaluru
constructs of C such as decision control and looping It’s indeed a user friendly book.
statements, functions, arrays, strings, pointers, structures
and unions, file management, and pre-processor directives. A. Leelavathi,
It also presents a separate chapter on linked lists detailing Sri Vasavi Engineering College, Tadepalligudem
the various kinds of linked lists and how they are used
to allocate memory dynamically. The second edition also
features a new section on C programming with Unix, Linux, Reema Thareja is Assistant Professor at the Department
and Ubuntu as well as a detailed discussion on algorithms of Computer Science, Shyama Prasad Mukherji College for
and how they act as a blueprint for — effective | Women, University of Delhi. She specializes in programming
C programs. languages, OS, DMBS, multimedia, and web technologies
and is currently pursuing research in the area of improving
A strong pedagogical approach is followed throughout
the book, which includes plenty of examples, figures,
data warehouse quality.
programming tips, keywords, and end-chapter exercises. _ She is the author of Data Warehousing (OUP, 2009),
These features, augmented further in this new edition, will Programming in C (OUP, 2011), Computer Fundamentals
help students master the art of writing C programs. and Programming in C (OUP, 2012), Data Structures using
C, 2e (OUP, 2014), Fundamentals of Computers
Key Features (OUP, 2014), and Information Technology and its
Applications in Business (2015).
= Exhaustive coverage offundamental topics with moredion
200 program code examples with outputs
-@ Chapter on programming languages and the generations ONLINE
: through which these languages have. evolved, which -—
readers an insight intocomputer software — The following resources are available to support the faculty and students
using this text:
8 Chapter-wise case studies to enhance learning _
For Faculty For Students
More than 700ee type ‘questions, including fill
-in--the- S Solutions Manual Multiple Choice Questions
PowerPoint Slides Chapter-wise Programming Codes
Appendices on Library Functions, Type
Qualifiers and Inline Functions, Versions of C,
Graphics and Mouse Programming

ISBN 0-19-945205-9

Ras
anaeswe
mn
an

You might also like