Introduction To C Programming - Thareja, Reema, Author
Introduction To C Programming - Thareja, Reema, Author
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
Published in India by
Oxford University Press
YMCA Library Building, 1 Jai Singh Road, New Delhi 110001, India
ISBN-13: 978-0-19-945205-7
ISBN-10: 0-19-945205-7
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.
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
_ 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.
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.
.¥ Pulte Alone
wit» Ort)
« 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
Detailed Contents xi
. Introduction to C
. Functions
. Arrays 145
. Strings 19]
. Pointers pe
. Files 301
Index 383
Detailed Contents
Features of the Book iv Preface to First Edition ix
Preface to Second Edition vi Brief Contents x
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
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
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.
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.
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.
EXERCISES
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
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
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
_ 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
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.
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.
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
;
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
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
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:
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;
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
—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 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
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 _
:
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.
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 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") ;
(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
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);
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) ;
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
printf ("\n Enter two four digit numbers: "); %$1d \n MESSAGE = %s", num, amt, code, pi,
Cl = wel Mois }
return 0;
Output
} NUM i= 7,
}
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,
{
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;
(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. <
OR
(Ee) eeaeanne
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 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
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
{ 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
Bitwise AND
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 ()
=/ 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
a|qeluen
Introduction to C | 43
|
| 44 [ Introduction to C Programming
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 | ~~
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
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
{ }
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 |
#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
total amt “= num of 10\coins * 10 + num_ printf ("\n Discount: - %£", discount amt) ;
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
al aia.
Me
W/ = Bs
He SS A
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
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
{ 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
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.
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
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.
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);
}
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;
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 |
printé("\n C= | % Qu
\" Qs | ole e Q ee a@=a + 3*a++;
return 0; Prince (nh aq sa) ae
, | return 0,
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.
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
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
Takeaways
e Decision Control Statements — e Conditional Branching Statements e Iterative Statements
e Nested Loops e Break, Continue, and Goto Statements
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 —
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
The user has entered a digit DEINes ("\n) Enron sinedata srnput)s,
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
statement block 2;
}
Sitatbementsxc;
Figure 3.3
Decision Control and Looping Statements | 65 |
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
} }
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)
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
}
main () {
char ch;
printf ("\n Enter any printf("\n Enter the sex of the employee (m
number: "); ee Mig SAD))ic
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 " .
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) ;
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;
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 , ™
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
sae\eibhany (Oe }
}
Output
Output Enter any number from 1 to 10: 7
Enter any number from 1 to 7: 5 ODD
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 ()
Statement y
}
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
} AVERAGE = 16.25
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);
statement
y;
Condition
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()
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
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
For example, the following code produces no output and Lomi —0)~)
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 ()
} Statements executed
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 |
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++)
{ }
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
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)
: $a", primes) ;
} 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 ());
} while (octal_num != 0)
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
{ 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)
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
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 }
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 ()
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.
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 |
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
EXERCISES
scanf (“%d”, &num); FA
+
> &¢ *
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
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
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
- 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 |
_ 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) ~~ .
while (i==0) — _ oe
{ - - int x=-1;
(n<10)
thie cy)
Decision Control and Looping Statements | 105 |
}
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);
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):
} while (i<5); ee
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 ©
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
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
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
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
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>
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:
Functions
®
Takeaways
_¢@ Function Declaration
© Call-by-Value and Call-by-Referen
a .
-feburn; reuurn;
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.
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,
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
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
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
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);
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.
} \
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
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
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;
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);
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);
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,
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 */
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
}
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 ()
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
salto Bs
expression.
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 |
_ STORAGE CLASS
Veeccic
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
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 |
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)
{
Le (num <= 2)
return 1;
return (Fibonacci (num - 1) +
Fibonacci(num - 2));
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.
ete Tailrecursion
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.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
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
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
‘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. .
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 |
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;
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
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
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];
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
aerkeiG] Taare mare) Wsckela] Panel markets] marks(6] mmacks(7] Pattie} markst9)
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
Rest of the
elements are
filled with Os
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.
Solution
Show the memory representation of the array and calculate
its length.
Memory representation of the array Age is as given
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.
{
In Step 1, we initialize index to the lower bound of lia, sO), al, ease (2Ol|«
{ #include <conio.h>
Arr[5] = 5 }
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
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 ()
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);
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(()\
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):
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
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
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
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:
1
#include io.h
<stdio.h>
{ ;
“ae :
Beg) 4 a, SE eer
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++) {
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()-
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}
‘ {
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
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++)
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
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
#include <stdio.h>
Arrays | 161 |
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++;
{
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) ,
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
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
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
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
{
scant ("%d", &arr[i]);
}
printf ("\n Enter the number that has to
be searched: ");
scanf("%d", &num);
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()
} 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++;
5.23 Write a program to interchange the biggest and the for (i=0;i<n;1i++)
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.
the first row will occupy the first nth locations. This is OO Om toms So)
illustrated in Fig. 5.28. i] 1000 + 176 = 1176
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};
{
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 ();
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 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
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)
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
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)»
}
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 |
ies 95.627, 89 }
The elements of the matrix are
rows sum = rows1;
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)
}
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");
#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
();
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
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)
}
}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
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)»
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 ();
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]
il
5 3
4 1
2 vi 1
5 1
3 1 4 2
g il
g 2 8 1 i
2 2
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.
(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 |
{
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.
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
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
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.
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
The advantages of the selection sort algorithm are as slieie jokes = Ve, Ete lileweia
ied) a!
follows: for(i = k+1;1i < n;i++)
The disadvantage is that it is inefficient for large data sets. POs=— ai;
#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
a
Strings
T akeaways
ie Reading and Writing Strings Upprescing Input . « String Operations _
© Array of Strings [7+ ne ane Character Functions. -
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
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
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
|
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);
}
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:
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.
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.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: ");
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
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.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
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 |
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
}
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
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 |
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);
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>
}
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);
{
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 |
} 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 { ‘
#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);
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]
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) ;
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
Output
}
p
Sere |[sil| = ONO p
Enter * to end i=0;
KKK KK KK KKK KEKE while(str{i] != ‘\0’)
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> }
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
} linecount++;
joreubaese (UE, Sheae|fall|))2 printf ("sd \t", linecount) ;
i++; }
} }
gebhagh (la }
} else
Output Satins
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
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
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 |
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
- 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
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))
))§
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.
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, 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 = #
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;
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 = # {
printf ("\n Enter the number: "); int num, *pnuml, *pnum2;
scané ("td" , &num); pnuml = #
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
"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;
*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);
#include <stdio.h>
int num1l, num2, num3; #include <conio.h>
int *pnuml = &num1, *ponum2 = &num2,
int main()
*pnum3= &num3;
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
}
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 = #
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
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
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 |
printf ("\n Total = %d", total) ; void calculate area (float *b, float *h,
getch() ; float *a);
} {
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
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) ;
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]
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
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 *pn = &n, *parr = arr, *psum = ∑ 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);
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 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
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’)
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++;
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
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 |
} {
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
to be copied (from the end): "); Programming; is a book written by; Reema
scant ("3d", &n); Thareja.
|244 | Introduction to C Programming
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) ;
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
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.
{ 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
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);
{
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
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.
{ result = (*operate
fp) (num1, num2) ;
} {
float add(float x, float y) int result; 5
{ 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)
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 |
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)
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 ()
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) ;
{
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;
{
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;
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 |
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 |
EXERCISES
eS
{
Shor str [] ="ABCDEFGH ;
printi("s Sd", (estr[3)- -astr (01) ;
<a.
i. &k ksptr) pe
oy fooae
= *perssnum; -
a 3d", a mee. (*ptr) -
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
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"; |
m, “#ptr=num;
yee
, epED.
ANNEXURE 5
IPHERING POINTER ptr is array of 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
(Contd)
Pointers | 267 |
(Contd)
. Meaning /
char func()[](); func is a function returning array of array of function returning char
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
{ 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
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;
{
char title[20];
char author [20];
int pages;
float price;
int yr of publication;
struct inventory
{
char prod_name [20];
float price;
int stock;
Figure 8.1 ‘Memory allocation fora structure variable
Ve
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.
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]);
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; {
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
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
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]);
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;
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 ()
typedef struct {
igh 1godkibsineyy
{
int ddy char name[100];
}DATE; i
struct student studl;
typedef struct student Giese0).
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
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];
ROLLE No; = 2 }
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++)
stud
[i] . DOB);
Passing structures
to functions
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
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]);
}
#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
{
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; }
[Link]); {
break;
|284 | Introduction to C Programming
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 |
{
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;
} ROLL NUMBER = 01
{ int fees;
if (hl—inch < h2— inch) os
{
hi—>ineh += 12; : ;
void display(struct student *);
hi—ft--; ;
} main ()
{ 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: ™);
} display (ptr);
getch ();
Quiput return 0;
kKAKKKKKE MAIN MENU ********* }
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;
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
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)
{
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");
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;
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.
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
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
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
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
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.
-
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
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()
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
}
for decimal values
Output
eo
erecainunier Enter
NAME:
the
student:
Zubin
name
01
and
Zubin
ROLL
roll
NUMBER
number
= O1
of the
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
{
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
main () }
{ Output
FILE *fp;
Provide feedback on this book: good
char feedback [100] ;
fp = fopen("[Link]", Nw'l) >
if (fp==NULL)
{ ’
} 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 |
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
{ 5 gley atlas
fgets(str,
79, fp); fp = fopen("[Link]",
"w!');
- 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 |
{ 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
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’)
} {
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); ‘
} exit (1);
{ 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>
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: ");
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 |
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
{ 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[])
} 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
} FILE *fp;
sgope(Gl es Op ak << Sygaures)) ae struct student
[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
}
|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 |
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
Enter the name of employee: Tanya scanf ("$d $d $d", &.hra, &[Link], &[Link]);
#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 |
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;
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",
} 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
#include <conio.h> {
main () int emp code;
{ 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);
}
9.8.2 ftell () fclose (fp);
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)
if (fsetpos(fp,
&pos) != 0) *newname)
¢ 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.
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;
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
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.
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.
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.
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
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"
} 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
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.
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.
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 |
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 |
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];
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
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.
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
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.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.
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
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
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.
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
PREPTR PAR
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"); ;
} 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;
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
‘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".
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.
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 |
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.
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
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
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 |
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
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 |
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
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:");
CHAPTER 1
True or False
CHAPTER 2
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 |
CHAPTER 3
. false
» true
CHAPTER 4
1. called function; 2. all of these; 3. void; 4. defined; 5. static; 6. extern; 7. static; 8. auto
CHAPTER 5
1. 10; 2. 7; 3. 200; 4. 50; 5. 25; 6. greater; 7. O(log n); 8. best case; 9. all of these
CHAPTER 6
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();
CHAPTER 7
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;
1. Dereferencing operator; 2. num; 3. all of these; 4. address; 5. &; 6. stack; 7. heap; 8. stdlib.h;
9. calloc(); j
. true
. false
. true
LEC
. false
2 (GUE
CHAPTER 8
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;
CHAPTER 9
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;
CHAPTER 10
CHAPTER I1
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;
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
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