Professional Documents
Culture Documents
C Programmimg Book PDF
C Programmimg Book PDF
Second Edition
ss
re
yP
sit
Reema Thareja
er
Assistant Professor
iv
Published in India by
Oxford University Press
YMCA Library Building, 1 Jai Singh Road, New Delhi 110001, India
ss
by law, by licence, or under terms agreed with the appropriate reprographics
rights organization. Enquiries concerning reproduction outside the scope of the
re
above should be sent to the Rights Department, Oxford University Press, at the
address above.
yP
You must not circulate this work in any other form
and you must impose this same condition on any acquirer.
sit
ISBN-13: 978-0-19-945614-7
ISBN-10: 0-19-945614-3
er
Typeset in Times New Roman
by Pee-Gee Graphics, New Delhi
iv
Comprehensive Coverage
Introduction to Linked Lists
Programming The book provides comprehensive cov-
Introduction to C Stacks and Queues erage of topics ranging from fundamen-
Decision Control and Trees
tal concepts of C programming to data
Looping Statements structures
Functions Graphs
ss
re
Notes Note
yP
These elements highlight the important The printf and return statements have been indented
terms and concepts discussed in each or moved away from the left side. This is done to make the
code more readable.
chapter
sit
er
iv
#include <stdio.h>
int main()
As many as 260 C programs are
{ included, which demonstrate the
d
%d", a, b);
return 0;
O
Output
Enter two four digit numbers : 1234 5678
The two numbers are : 12 and 34
Points to Remember
POINTS TO REMEMBER
A list of key topics at the end of each
chapter helps readers to revise all the ∑ A computer has two parts—computer hardware which called programming.
important concepts explained in the does all the physical work and computer software which
∑ Computer software is written by computer
tells the hardware what to do and how to do it.
chapter ∑ A program is a set of instructions that are arranged in
programmers using a programming language.
a sequence to guide a computer to find a solution for a ∑ Application software is designed to solve a
given problem. The process of writing a program is particular problem for users.
C Case Study 1:
ss
Chapters 2 and 3 Case Studies
re
Select chapters are followed by case
yP
We have learnt the basics of programming in C language Roman Numeral Table studies that show how C can be used
and concepts to write decision-making programs, let us
now apply our learning to write some useful programs. 1 I 14 XIV 27 XXVII 150 CL to create programs demonstrating
2 II 15 XV 28 XXVIII 200 CC
real-life applications
ROMAN NUMERALS
3 III 16 XVI 29 XXIX
sit
300 CCC
4 IV 17 XVII 30 XXX 400 CD
Roman numerals are written as combinations of the seven 5 V 18 XVIII 31 XXXI 500 D
letters. These letters include:
er
6 VI 19 XIX 40 XL 600 DC
I=1 C = 100 7 VII 20 XX 50 L 700 DCC
8 VIII 21 XXI 60 LX 800 DCCC
V=5 D = 500
iv
Programming Tips
Programming Tip:
These elements educate readers about
xf
Programming Exercises
1. Write a program which deletes all duplicate elements from Programming Exercises
the array.
Numerous exercises at the end
2. Write a program that tests the equality of two one-
of every chapter test the readers’
dimensional arrays. understanding of the concepts
3. Write a program that reads an array of 100 integers. Display learned.
all pairs of elements whose sum is 50.
ss
5. Computer Science and IT
6. Economics Member Login
7. Electrical Engineering ∑ Projects
6
Student/Instructor having username and
re
8. Electronics
∑ Model Question
password canPapers
login from here
9. Engineering General Online Resources available for the following users:
10. Hospitality ∑ Supplementary Reading Material on
Instructors Students 5
yP
11. Life sciences Graphics/Mouse Programming
New Instructor Registration:
12. Mechanical Engineering PowerPoint Presentation Web links Sign Up for Instructors
13. Media Studies
Solutions Manual Projects
Teaching Notes Multiple Choice Questions
3
sit 6 New Student Registration:
Recent Solutions to Case Studies Scholastic Capability Test
Newly Released titles for which and more... and more... Sign Up for Students
online resources are available
er
to download. Resources are book specific and may vary from title to title.
iv
Steps to Register
Un
Step 1: Getting Started Step 7: Registration Form Step 10: Visit us again after validation
• Go to www.oupinheonline.com Please fill correct details and *marked fields are mandatory • Go to www.oupinheonline.com
• Login from Member Login
Username should
• BASIC SEARCH be email ID
Author
or
Title
ISBN
xf
• ADVANCED SEARCH
w Subjects
Please fill correct Mobile no.
w Recent titles to get SMS after verification
O
Click here
ss
re
C is one of the most popular and successful programming The salient features of the book include:
yP
languages of all time and considered to be the origin of ∑ Lucid style of presentation that makes the concepts
all modern-day computer languages. Many of the popular sit easy to understand
cross-platform programming languages, such as C++, ∑ Plenty of illustrations to support the explanations,
Java, Python, Objective-C, Perl, and Ruby, and scripting which help clarify the concepts in a clear manner
er
languages, such as PHP, Lua, and Bash, borrow syntaxes ∑ Programming tips in between the text educating
and functions from C. readers about common programming errors and how
iv
many applications including interface to hardware. ∑ Glossary of important terms at the end of each
or
Thus, studying C provides a good foundation to learn chapter for recapitulation of the important concepts
learnt
advanced programming skills such as object-oriented
xf
ss
as well as special statements such as break statement,
control statement, and jump statement. Asa linked list is a preferred data structure when memory
re
needs to be allocated dynamically for the data, the chapter
Case Study 1 includes two programs which harness the
gives the techniques to insert and delete data from the
concepts learnt in Chapters 2 and 3.
yP
linked list.
Chapter 4 deals with declaring, defining, and calling
functions. The chapter also discusses the storage classes Case Study 4 shows how a telephone directory can be
sit
as well as variable scope in C. The chapter ends with the implemented using C.
important concept of recursive functions and a discussion Chapter 12 introduces data structures—stacks and queues.
er
on the Tower of Hanoi problem. Annexure 2 discusses In this chapter, these data structures are implemented
how to create user-defined header files. using arrays. The chapter also provides the operations
iv
Chapter 5 focuses on the concept of arrays, including and applications of stacks and queues in the world of
programming.
Un
Case Study 2 provides an introduction to sorting and Chapter 13 focuses on binary trees, their traversal schemes
or
various sorting techniques such as bubble sort, insertion and representation in memory.
sort, and selection sort. The chapter also discusses expression trees which is a
xf
Chapter 6 discusses the concept of strings which are also variant of simple binary trees.
known as character arrays. The chapter not only focuses on
O
ACKNOWLEDGMENTS
ONLINE RESOURCES
I would like to gratefully acknowledge the feedback and
The following resources are available at Oxford University suggestions given by various faculty members for the
Press India’s Higher Education Companion Site (http://
improvement of the book. I am obliged to the editorial
oupinheonline.com) to support the faculty and students
team of Oxford University Press India for all their support
using this text:
ss
towards revising this book. Suggestions for improving the
For Faculty presentation and contents can be sent to the publishers
re
∑ Solutions Manual through their website www.oup.com or to the author at
reemathareja@gmail.com.
yP
∑ PowerPoint Slides
∑ Projects sit ReemaThareja
er
iv
Un
d
or
xf
O
ss
re
C is the most popular and widely used language for constructs in C, such as ‘if’ statements, ‘for’ and ‘while’
yP
developing computer programs. Programmers all over loops and the types of variables used can be found in many
the world embrace the C language as it provides them modern languages, therefore the ideas expressed in C are
sit
maximum control and efficiency. One of the major benefits well understood by program developers. Moreover, unlike
of learning C is its user friendliness that allows the user most of these modern-day languages that apply object-
er
to read and write codes for a wide range of platforms, oriented design, C applies a procedural style of design,
ranging from embedded micro controllers to advanced i.e., it uses procedures such as functions, methods, or
iv
scientific systems. The versatility of C is apparent from routines to call itself or other procedures. However, many
the fact that many modern operating systems have used C
Un
ss
objective, subjective, and programming exercises at the Oxford University Press, India, for their help and support.
end of each chapter. Reema Thareja
re
yP
sit
er
iv
Un
d
or
xf
O
Brief Contents
ss
re
Features of the Book iv
yP
Companion Online Resources for Instructors and Students vi
Preface to the Second Edition vii
Preface to the First Edition xi
sit
Detailed Contents xv
er
1. Introduction to Programming 1
2. Introduction to C 12
iv
4. Functions 105
5. Arrays 134
6. Strings 180
d
7. Pointers 213
or
9. Files 290
O
ss
re
Features of the Book iv Preface to the Second Edition vii
Companion Online Resources for Preface to the First Edition xi
yP
Instructors and Students vi Brief Contents xiii
sit
1. Introduction to Programming 1 2.4.3 Object Files 17
2.4.4 Binary Executable Files 17
er
1.1 Introduction to Computer Software 1 2.5 Compiling and Executing C Programs 17
1.2 Classification of Computer Software 2 2.6 Using Comments 18
iv
2.12 Variables 22
Languages 7 2.12.1 Numeric Variables 22
O
ss
Annexure 1 56 4.10.2 Finding Exponents 122
4.10.3 Fibonacci Series 123
re
4.11 Types of Recursion 123
3. Decision Control and Looping 4.11.1 Direct Recursion 123
yP
Statements 57 4.11.2 Indirect Recursion 123
4.11.3 Tail Recursion 123
3.1 Introduction to Decision Control Statements 57 4.11.4 Linear and Tree Recursion 124
sit
3.2 Conditional Branching Statements 57 4.12 Tower of Hanoi 124
3.2.1 if Statement 57 4.13 Recursion Versus Iteration 126
er
3.2.2 if–else Statement 59 Annexure 2 133
3.2.3 if–else–if Statement 61
iv
ss
7.13 Pointers and 2D Arrays 234
6.1.1 Reading Strings 182
7.14 Pointers and 3D Arrays 236
6.1.2 Writing Strings 182
re
7.15 Function Pointers 237
6.1.3 Summary of Functions Used to
7.15.1 Initializing a Function Pointer 237
yP
Read and Write Characters 183
7.15.2 Calling a Function Using a Function
6.2 Suppressing Input 184
Pointer 237
6.2.1 Using a Scanset 184 7.15.3 Comparing Function Pointers 238
sit
6.3 String Taxonomy 185 7.15.4 Passing a Function Pointer as an Argument
6.4 Operations on Strings 186 to a Function 238
er
6.4.1 Finding the Length of a String 186 7.16 Array of Function Pointers 238
6.4.2 Converting Characters of a String into 7.17 Pointers to Pointers 239
iv
6.4.5 Appending a String to Another String 189 7.20.3 Releasing the Used Space 242
6.4.6 Comparing Two Strings 189 7.20.4 To Alter the Size of Allocated
xf
ss
8.10.3 Assigning Values to Enumerated 10.3.4 Rules for Using Macros 328
Variables 281 10.3.5 Operators Related to Macros 328
re
8.10.4 Enumeration Type Conversion 281 10.4 #include 329
8.10.5 Comparing Enumerated Types 281 10.5 #undef 330
yP
8.10.6 Input/Output Operations on Enumerated 10.6 #line 330
Types 281 10.7 Pragma Directives 331
sit
Annexure 4 288 10.8 Conditional Directives 333
10.8.1 #ifdef 333
er
10.8.2 #ifndef 333
9. Files 290 10.8.3 #if Directive 334
iv
9.1.2 Buffer Associated with File Stream 291 10.8.6 #endif Directive 335
9.1.3 Types of Files 291 10.9 Defined Operator 335
9.2 Using Files in C 292 10.10 #error directive 336
d
ss
12.7 Operations on Queues 380
15. Developing Efficient Programs 426
re
12.8 Applications of Queues 382
Case Study 5: Chapters 11 and 12 366
15.1 Modularization 426
yP
15.2 Design and Implementation of Efficient
13. Trees 391 sit Programs 427
15.2.1 Requirements Analysis 428
13.1 Binary Trees 391
13.1.1 Key Terms 392 15.2.2 Design 428
er
13.1.2 Complete Binary Trees 393 15.2.3 Implementation 428
13.1.3 Extended Binary Trees 393 15.2.4 Testing 428
iv
Memory 394
13.2 Expression Trees 395 15.2.6 Maintenance 428
13.3 Traversing a Binary Tree 396 15.3 Program Design Tools: Algorithms, Flowcharts,
Pseudocodes 429
d
ss
Takeaways
re
∑ Hardware ∑ System software ∑ Compiler, interpreter, linker, loader
∑ Application software ∑ Generation of programming languages ∑ Machine language
yP
∑ Assembly language ∑ Procedural and non-procedural languages
sit
er
∑ First is the computer hardware that does all the physical The computer hardware cannot think and make
or
work computers are known for. decisions on its own. So, it cannot be used to analyse
∑ Second is the computer software that commands the a given set of data and find a solution on its own. The
xf
hardware what to do and how to do it. hardware needs a software (a set of programs) to instruct
what has to be done. A program is a set of instructions that
O
∑ Driver software which allows a computer to interact others. Simply put, application software represents
with hardware devices such as printers, scanners, and programs that allow users to do something besides
video cards. simply running the hardware.
∑ Educational software which includes programs and
User 1 User 2 User N
games that help in teaching and providing drills to help
memorize facts. Educational software can be diversely
used—from teaching computer-related activities like Application programs (games, spreadsheets,
typing to higher education subjects like Chemistry. word processors, database, web browsers)
∑ Media players and media development software that are
specifically designed to play and/or edit digital media
files such as music and videos. System Software (operating system)
ss
(printer, mouse, scanner, keyboard, CPU, disk)
include word processors, database management utilities,
re
and presentation software. Figure 1.2 Relationship between hardware, system
∑ Operating system software which helps in coordinating software, and application software
yP
system resources and allows execution of other
programs. Some popular operating systems are
1.2.1 System Software
Windows Vista, Mac OS X, and Linux.
sit
System software is software designed to operate the
er
computer hardware and to provide and maintain a platform
1.2 CLASSIFICATION OF COMPUTER for running application software.
iv
ss
re
yP
sit
er
iv
Un
d
To summarize, BIOS performs the following functions: From users’ point of view the primary consideration
∑ Initializes the system hardware is always the convenience. Users should find it easy to
O
For example, there may be many service requests on a web ∑ System profilers can be used to provide detailed
server and each user request needs to be serviced. Moreover, information about the software installed and hardware
there may be many programs residing in the main memory. attached to the computer.
Therefore, the system needs to determine which programs ∑ Anti-virus utilities are used to scan for computer viruses.
are currently being executed and which programs need to
∑ Data compression utilities can be used to output a file
wait for some I/O operation. This information is necessary
with reduced file size.
because the programs that need to wait can be suspended
temporarily from engaging the processor. Hence, it is ∑ Cryptographic utilities can be used to encrypt and
important for an operating system to have a control policy decrypt files.
and algorithm to allocate the system resources. ∑ Launcher applications can be used as a convenient
access point for application software.
Utility Software ∑ Registry cleaners can be used to clean and optimize the
Utility software is used to analyse, configure, optimize, and Windows operating system registry by deleting the old
maintain the computer system. Utility programs may be registry keys that are no longer in use.
ss
requested by application programs during their execution ∑ Network utilities can be used to analyse the computer’s
for multiple purposes. Some of them are as follows: network connectivity, configure network settings, check
re
∑ Disk defragmenters can be used to detect computer files data transfer, or log events.
whose contents are broken across several locations on
yP
∑ Command line interface (CLI) and Graphical user
the hard disk, and move the fragments to one location in interface (GUI) can be used to make changes to the
order to increase efficiency. operating system.
sit
∑ Disk checkers can be used to scan the contents of a hard
disk to find files or areas that are either corrupted in some Compiler, Interpreter, Linker, and Loader
er
way, or were not correctly saved, and eliminate them in
Compiler It is a special type of program that transforms
order to make the hard drive operate more efficiently.
iv
∑ Disk partitions utilities are used to divide an individual from a high-level programming language to a lower level
language (e.g., assembly language or machine code).
O
drive into multiple logical drives, each with its own file
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 resulting
∑ Backup utilities can be used to make a copy of all from the code not conforming to the syntax of the
information stored on a disk. In case a disk failure programming language are called syntax errors. Syntax
occurs, backup utilities can be used to restore the entire errors may be spelling mistakes, typing mistakes, etc.
disk. Even if a file gets deleted accidentally, the backup Another type of error is logical error which occurs when
utility can be used to restore the deleted file. the program does not function accurately. Logical errors
∑ Disk compression utilities can be used to enhance the are much harder to locate and correct.
capacity of the disk by compressing/decompressing the The work of a compiler is simply to translate human
contents of a disk. readable source code into computer executable machine
∑ File managers can be used to provide a convenient code. It can locate syntax errors in the program (if any)
method of performing routine data management but cannot fix it. Until and unless the syntactical errors
tasks such as deleting, renaming, cataloguing, moving, are rectified the source code cannot be converted into the
copying, merging, generating, and modifying data sets. object code.
ss
interpreted program. However, the big advantage of an and operational research software. Multiple applications
interpreted program is that it does not need to go through bundled together as a package are sometimes referred to as
re
the compilation stage during which machine instructions an application suite.
are generated. This process can be time consuming if the
yP
program is long. Moreover, the interpreter can immediately
1.3 PROGRAMMING LANGUAGES
execute high-level programs.
sit
A programming language is a language specifically
All in all, compilers and interpreters both achieve
similar purposes, but inherently different as to how they designed to express computations that can be performed
er
achieve that purpose. by the computer. Programming languages are used to
create programs that control the behaviour of a system,
iv
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. Gener- communication.
Un
ally, in case of a large program, the programmers prefer Usually, programming languages have a vocabulary
to break a code into smaller modules as this simplifies the of syntax and semantics for instructing a computer to
programming task. Eventually, when the source code of all
d
to put all the modules together. This is the job of the linker. C, C++, COBOL, FORTRAN, Ada, and Pascal to name a
Usually, the compiler automatically invokes the linker as
xf
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
∑ The type of computer on which the program has to be each of the machine languages, a computer could not
executed understand programs written in another machine language
(Figure 1.4).
∑ The type of program
∑ The expertise of the programmer MACHINE LANGUAGE
For example, FORTRAN is a particularly good This is an example of a machine language program that will add
two numbers and find their average. It is in hexadecimal
language for processing numerical data, but it does not notation instead of binary notation because this is how the
lend itself very well to organizing large programs. Pascal computer presented the code to the programmer.
can be used for writing well-structured and readable
D000000A D000
programs, but it is not as flexible as the C programming
language. C++ goes one step ahead of C by incorporating D000000F D009
ss
powerful object-oriented features, but it is complex and D000000B D009
difficult to learn.
re
D009
D009
yP
D0Q0
1.4 GENERATION OF PROGRAMMING
LANGUAGES FF55 CF FF54 CF FF53 CF C1 DOD0
sit FF24 CF FF27 CF D2 C7 D00C
We now know that programming languages are the
D0E4
primary tools for creating software. As of now, hundreds
er
Dd0D
of programming languages exist in the market, some
iv
more used than others, and each claiming to be the best. Dd3D
However, back in the 1940s when computers were being
Un
developed there was just one language—the machine Figure 1.4 A machine language program
language.
The concept of generations of programming languages In machine language, all instructions, memory locations,
d
(also known as levels) is closely connected to the advances numbers, and characters are represented in strings of
or
in technology that brought about computer generations. 1s and 0s. Although machine-language programs are
The four generations of programming languages include: typically displayed with the binary numbers represented
xf
ss
critical, such as video games but most programmers today
Assembly language developed in the mid 1950s have switched to third or fourth generation programming
re
was a great leap forward. It used symbolic codes also languages.
known as mnemonic codes that are easy-to-remember
yP
abbreviations, rather than numbers. Examples of these
1.4.3 Third Generation Programming
codes include ADD for add, CMP for compare, MUL for
Languages
multiply, etc.
sit
Assembly language programs consist of a series of A third generation programming language (3GL) is
a refinement of the second-generation programming
er
individual statements or instructions that instruct the
computer what to do. Basically, an assembly language language. The 2GL languages brought logical structure to
iv
statement consists of a label, an operation code, and one software. The third generation was introduced to make the
or more operands. languages more programmer friendly.
Un
Labels are used to identify and reference instructions in Third Generation Programming Languages spurred the
the program. The operation code (opcode) is a mnemonic great increase in data processing that occurred in the 1960s
and 1970s. In these languages, the program statements
d
to be processed is located.
Generally, a statement written in a high-level program-
However, like the machine language, the statement
ming language will expand into several machine language
O
statements like English language statements, making them only what they want the computer to do, without supplying
more convenient to use and giving the programmer more all the details of how it has to be done.
time to address a client’s problems. There is no standard rule that defines what a 4GL is but
Although 3GLs relieve the programmer of demanding certain characteristics of such languages include:
details, they do not provide the flexibility available in low- ∑ the code comprising instructions are written in English-
level languages. However, a few high-level languages like sentences;
like C and FORTRAN combine some of the flexibility
∑ they are non-procedural, so users concentrate on ‘what’
of assembly language with the power of high-level
instead of the ‘how’ aspect of the task;
languages, but these languages are not well suited to an
amateur programmer. ∑ the code is easier to maintain;
While some high-level languages were designed to serve ∑ the code enhances the productivity of the programmers
a specific purpose (such as controlling industrial robots as they have to type fewer lines of code to get something
or creating graphics), other languages were flexible and done. It is said that a programmer becomes 10 times
considered to be general-purpose languages. Most of the more productive when he writes the code using a 4GL
programmers preferred to use general-purpose high-level than using a 3GL.
ss
languages like BASIC (Beginners’ All-purpose Symbolic A typical example of a 4GL is the query language
re
Instruction Code), FORTRAN, PASCAL, COBOL, C++, or that allows a user to request information from a database
Java to write the code for their applications. with precisely worded English-like sentences. A query
yP
Again, a translator is needed to translate the instructions language is used as a database user interface and hides the
written in high-level language into computer-executable specific details of the database from the user. For example,
machine language. Such translators are commonly known
sit
when working with structured query language (SQL),
as interpreters and compilers. Each high-level language the programmer just needs to remember a few rules of
has many compilers. syntax and logic, and it is easier to learn than COBOL
er
For example, the machine language generated by one or C.
computer’s C compiler is not the same as the machine
iv
to have a C compiler for each type of computer on which enrolled in each class and in each semester. Using a 4GL,
the C program has to be executed. the request would look similar to one that follows:
Third generation programming languages have made
d
programmers more time to think about its overall logic. SUM STUDENTS BY SEMESTER BY CLASS
The programs written in such languages are portable So we see that a 4GL is much simpler to learn and work
xf
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
O
ss
Generally, 5GLs were built upon Lisp, many originating as a possible level of computer language. Software vendors
on the Lisp machine, such as ICAD. Then, there are many across the globe currently claim that their software meets
re
frame languages such as KL-ONE. the visual ‘programming’ requirements of the 5GL concept.
yP
POINTS TO REMEMBER sit
∑ A computer has two parts—computer hardware which just two digits—1s and 0s (the target language). The
er
does all the physical work and computer software which resultant code in 1s and 0s is known as the object code.
tells the hardware what to do and how to do it.
iv
a sequence to guide a computer to find a solution for a ∑ A loader is a special type of program that copies programs
given problem. The process of writing a program is called
from a storage device to main memory, where they can be
programming.
d
executed.
∑ Computer software is written by computer programmers
or
Exercises
ss
(a) operating system
7. ________ helps in coordinating system resources and (b) computer hardware
re
allows other programs to execute.
(c) firmware
8. ________ provides a platform for running application
(d) device drivers
yP
software.
9. ________ can be used to encrypt and decrypt files.
State True or False
10. An assembly language statement consists of a ________,
sit
an ________, and ________. 1. Computer hardware does all the physical work.
2. The computer hardware cannot think and make
er
Multiple Choice Questions decisions on its own.
1. BIOS is stored in 3. A software is a set of instructions that are arranged in a
iv
(a) RAM (b) ROM sequence to guide a computer to find a solution for the
Un
(c) COBOL (d) FORTRAN 7. Pascal cannot be used for writing well-structured
programs.
3. Which language is a symbolic language?
xf
ss
re
yP
sit
er
iv
Un
d
or
xf
O