0% found this document useful (0 votes)
1 views

Introduction To Programming C Chopra Rajiv download

Ebook download

Uploaded by

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

Introduction To Programming C Chopra Rajiv download

Ebook download

Uploaded by

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

Introduction To Programming C Chopra Rajiv

download

https://ebookbell.com/product/introduction-to-programming-c-
chopra-rajiv-56597050

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Introduction To Programming With C 3rd International Edition 3rd Y


Daniel Liang

https://ebookbell.com/product/introduction-to-programming-with-c-3rd-
international-edition-3rd-y-daniel-liang-55234740

Introduction To Programming With C For Engineers 1st Edition Boguslaw


Cyganek

https://ebookbell.com/product/introduction-to-programming-with-c-for-
engineers-1st-edition-boguslaw-cyganek-22898364

Introduction To Programming In C Language C Programming Best C


Programming Language Book For Beginners Khachane

https://ebookbell.com/product/introduction-to-programming-in-c-
language-c-programming-best-c-programming-language-book-for-beginners-
khachane-23917738

Introduction To Programming With C 1st Edition Nhce

https://ebookbell.com/product/introduction-to-programming-with-c-1st-
edition-nhce-23436930
Introduction To Programming With C For Engineers Cyganek Boguslaw
Cyganek

https://ebookbell.com/product/introduction-to-programming-with-c-for-
engineers-cyganek-boguslaw-cyganek-23549354

Introduction To Programming In C Language C Programming Best C


Programming Language Book For Beginners Khachane

https://ebookbell.com/product/introduction-to-programming-in-c-
language-c-programming-best-c-programming-language-book-for-beginners-
khachane-23917736

Introduction To Programming Languages Programming In C C Scheme Prolog


C And Soa Fifth Edition Yinong

https://ebookbell.com/product/introduction-to-programming-languages-
programming-in-c-c-scheme-prolog-c-and-soa-fifth-edition-
yinong-21889502

An Introduction To Programming With C 6th Edition 6th Diane Zak

https://ebookbell.com/product/an-introduction-to-programming-
with-c-6th-edition-6th-diane-zak-2427428

An Introduction To Programming With C 8th Edition Diane Zak

https://ebookbell.com/product/an-introduction-to-programming-
with-c-8th-edition-diane-zak-38548024
C
Programming
LICENSE, DISCLAIMER OF LIABILITY, AND LIMITED WARRANTY

By purchasing or using this book (the “Work”), you agree that this license
grants permission to use the contents contained herein, but does not give you
the right of ownership to any of the textual content in the book or ownership
to any of the information or products contained in it. This license does not
permit uploading of the Work onto the Internet or on a network (of any kind)
without the written consent of the Publisher. Duplication or dissemination
of any text, code, simulations, images, etc. contained herein is limited to and
subject to licensing terms for the respective products, and permission must
be obtained from the Publisher or the owner of the content, etc., in order to
reproduce or network any portion of the textual material (in any media) that is
contained in the Work.

Mercury Learning and Information (“MLI” or “the Publisher”) and anyone


involved in the creation, writing, production, accompanying algorithms,
code, or computer programs (“the software”), and any accompanying Web
site or software of the Work, cannot and do not warrant the performance or
results that might be obtained by using the contents of the Work. The author,
developers, and the Publisher have used their best efforts to insure the
accuracy and functionality of the textual material and/or programs contained in
this package; we, however, make no warranty of any kind, express or implied,
regarding the performance of these contents or programs. The Work is sold “as
is” without warranty (except for defective materials used in manufacturing the
book or due to faulty workmanship).

The author, developers, and the publisher of any accompanying content, and
anyone involved in the composition, production, and manufacturing of this
work will not be liable for damages of any kind arising out of the use of (or the
inability to use) the algorithms, source code, computer programs, or textual
material contained in this publication. This includes, but is not limited to, loss
of revenue or profit, or other incidental, physical, or consequential damages
arising out of the use of this Work.

The sole remedy in the event of a claim of any kind is expressly limited to
replacement of the book and only at the discretion of the Publisher. The use
of “implied warranty” and certain “exclusions” vary from state to state, and
might not apply to the purchaser of this product.
C
Programming
A Self-Teaching Introduction

By
RAJIV CHOPRA, PhD

Mercury Learning and Information


Dulles, Virginia
Boston, Massachusetts
New Delhi
Copyright ©2018 by Mercury Learning and Information. All rights reserved .
Reprinted and revised with permission.

Original title and copyright: Introduction to Programming (C)


Copyright © 2017 by New Age International (P) Ltd. Publishers. All rights reserved.
ISBN : 978-93-86070-20-3

This publication, portions of it, or any accompanying software may not be reproduced in
any way, stored in a retrieval system of any type, or transmitted by any means, media,
electronic display or mechanical display, including, but not limited to, photocopy, record-
ing, Internet postings, or scanning, without prior permission in writing from the publisher.

Publisher: David Pallai

Mercury Learning and Information


22841 Quicksilver Drive
Dulles, VA 20166
info@merclearning.com
www.merclearning.com
1-800-232-0223

R. Chopra. C Programming: A Self-Teaching Introduction.


ISBN: 978-1-68392-090-8

The publisher recognizes and respects all marks used by companies, manufacturers, and
developers as a means to distinguish their products. All brand names and product names
mentioned in this book are trademarks or service marks of their respective companies. Any
omission or misuse (of any kind) of service marks or trademarks, etc. is not an attempt to
infringe on the property of others.

Library of Congress Control Number: 2017934665

171819321 Printed in the USA on acid-free paper.

Our titles are available for adoption, license, or bulk purchase by institutions, corporations,
etc. For additional information, please contact the Customer Service Dept. at 800-232-
0223(toll free).

All of our titles are available in digital format at authorcloudware.com and other digital
vendors. The sole obligation of Mercury Learning and Information to the purchaser is to
replace the book, based on defective materials or faulty workmanship, but not based on the
operation or functionality of the product.
Contents

Preface viii

Acknowledgments x

Chapter 1: C Overview 1
1.0 Introduction 1
1.1 The Concept of Algorithms and Pseudocodes 2
1.2 Flowcharts 8
1.3 Compiler Overview 15
1.4 Assembler, Linker, and Loader 19
1.5 Structure of a Simple “Hello World” Program in C 22
1.6 Overview of the Compilation and Execution
Process in an Integrated Development Environment
(preferably CodeBlock) 30
Summary 32
Exercises 32

Chapter 2: Programming Using C 35


2.0 Introduction 35
2.1 Preprocessor Directives/Compiler Directives/C Preprocessor 35
2.2 C Primitive Input-Output using getchar and putchar 40
2.3 Simple Input/Output 42
2.4 Function Calls from a Library 44
2.5 Data Types in C 44
2.6 Enumeration 47
2.7 Operators 51
2.8 Type Casting (or Coercion) in C 62
vi • Contents

2.9 Conditional Executing Using If-Else 63


2.10 Switch and Break 68
2.11 The Concept of Loops—While Loop, Do-While
Loop, For Loop, Nested Loops, Break Statement,
Continue Statement 73
2.12 Storage Classes: Auto, Static, Extern, and Register 119
Summary 135
Exercises 135

Chapter 3: Arrays And Pointers 141


3.0 Introduction 141
3.1 1D, 2D, and 3D Arrays 142
3.2 The Concept of Subprogramming 212
3.3 Functions 213
3.4 Parameter Transmission Techniques—Call by Value
and Call by Reference 228
3.5 Pointers 234
3.6 Relationship between Array and Pointer 239
3.7 Argument Passing Using Pointers 241
3.8 Array of Pointers 243
3.9 Passing Arrays as Arguments 244
Summary 269
Exercises 269

Chapter 4: Structures And Unions 275


4.0 Introduction 275
4.1 Structures versus Unions 296
4.2 Structures and Pointers 298
Summary 312
Exercise Questions 313

Chapter 5: File Handling In C 317


5.0 Introduction 317
5.1 File Pointers 317
5.2 Character Input / Output with Files 320
5.3 String I/O Functions 321
5.4 Integer I/O Functions 321
5.5 Formatted I/O Functions 322
5.6 Block (or Record) I/O Functions 323
Summary 338
Exercises 338
Contents • vii

Appendices 341

A: C Programming Lab Projects 341

B: Keywords in C 343

C: Escape Sequences in C 344

D: Operator Precedence and Associativity 345

E: Standard Library String Functions 346

References 347

Index 349
Preface

The right temperament required for research originates from the right expo-
sure and environment that a student receives during study. And good books
help in this direction.
Programming is an art. You have to learn this art, as only then will you learn
how to write good programs.
This book is an outcome of lecture notes prepared during my long years of
teaching Introduction to Programming (C), augmented by consulting a large
number of books available on the subject. I thank my students, colleagues, and
teachers, as well as all the authors who have helped in shaping my approach to
this knowledge.
Acknowledgments

A dream is visualized by a pair of eyes; however, many pairs of hands join to-
gether and work hard toward its realization. This book has been a similar en-
terprise.
I next thank my college staff, director, and HOD for their contributions to
this book on the C programming language.
I would also like to thank the entire staff of Mercury Learning for bringing
the book to a new market.
Finally, I would like to thank my wife, Mrs. Shakti, my twin kids, Arjessh
and Arshitha Chopra, as well as my parents who cooperated with me in all terms
in order to write this book.
Dr. Rajiv Chopra
CHAPTER

1
C Overview

1.0 INTRODUCTION

T
he C programming language was developed by Dennis Ritchie at AT&T
Bell Laboratories in the early 1970s. Soon after, Bell Laboratories devel-
oped a new operating system, called UNIX. About 90% of the code for
the Unix operating system (OS) was exclusively in C. As C gained popularity,
more and more vendors joined the race and developed their own compilers.
This was necessary because until the late 1970s, only Bell Laboratories had a C
compiler.
In the early 1980s, realizing the need to standardize the C language, the
American Standards Institute (ANSI), an organization that handles such mat-
ters, began the task. In 1990, the first official ANSI standard definition of C was
published. Soon C became omnipresent and thus there was a need of further
standardization. The International Standards Organization (ISO) adopted a
standard called ISO/IEC 9899:1990. After 1990, many additional changes were
made in the C language. In 1993, an ANSI C committee (known as X3J11), was
formed to standardize C. The most recent standard was adopted in 1999. It is
known as ANSI C99 or ISO/IEC 9899:1999. Since then, ANSI C has been im-
plemented on a wide variety of computers, including IBM-compatible personal
computers (PCs), mainframes, minicomputers, and workstations.
C is a higher-level language that nevertheless allows the programmer to deal
with hardware at a much lower level. Please note that although C is a general-
purpose programming language, it was designed with systems program-
ming applications in mind. So it provides a lot of power and flexibility.
2 • C Programming

This chapter discusses some basic terminology related to C and also ex-
plains the process of compiling a program written in the C language.

1.1 THE CONCEPT OF ALGORITHMS AND


PSEUDOCODES

A computer is a dead piece of hardware if it is not loaded with software. It may


be application software, system software, embedded software, or other types
of software. The basic operations of a computer system form the com-
puter’s instruction set. Now in order to solve a problem using a computer,
you will have to express the solution to the problem in terms of the instructions
for the particular computer. So we define a computer program as a collection of
instructions necessary to solve a specific problem. The approach or method
that is used to solve the problem is known as an algorithm. For ex-
ample, if you want to find the factorial of a number, then the set of statements
that solves the problem becomes a program. You first express the solution to
the problem in terms of an algorithm and then develop a program that imple-
ments that algorithm. A program may be written in any programming language
of your choice, such as C/C++, JAVA2, Visual Basic 9, and so on.
An algorithm is a formal step-by-step method for solving problems. Let us
now look at some of the characteristics of algorithms:

1. An algorithm consists of an ordered sequence of instructions.


2. Each step of the algorithm should be unambiguous—that is, it should
not have many meanings.
3. It should have a finite number of steps.
4. It should terminate/stop after this finite number of steps.
5. It should have some input and may or may not produce any output.
Algorithms should be concise and compact to facilitate verification of their
correctness. Verification involves observing the performance of an algorithm
with a good quality set of test cases.
For example, we might want to write an algorithm to find the maximum
from a set of n positive numbers. We assume that the numbers are stored in an
array X.
C Overview • 3

Algorithm to Find the Maximum from an Array X


INPUT: An array X with n elements.
OUTPUT: Finding the largest element, MAX, from the array X.
Step 1: Set MAX=0/* Initial value of MAX */
Step 2: for j=1 to n do
Step 3: if(X[j] > MAX) then MAX = X[j]
end for
Step 4: Stop
As a problem-solving tool, programmers usually introduce at least one in-
termediate step between the English-like problem definition and C. This inter-
mediate step is known as a pseudocode (pseudo=false). Pseudocode is a
restatement of the problem as a list of steps, in an English-like format,
describing what must be done to solve it. Using the pseudocode, a pro-
grammer then writes the actual program. In a nutshell we can say that pseudo-
code consists of statements which are a combination of English and C,
in which pseudocode is not quite C code but can be easily translated.
It can be refined and gradually made more precise. The practicality of this ap-
proach is that the pseudocode used at one stage of the development process will
often be a comment at the next stage.
For example, for the preceding algorithm, Max, we now write its
pseudocode as follows:
Initialize a variable, MAX, to 0.
Check through the entire set of elements.
If any element from the set is greater than the Max then max is that element.
Print the MAX number.
Before further discussion, let us solve some examples.
Example 1: Write an algorithm to find the greatest of three numbers
and then validate your algorithm by giving it dry runs.
Solution 1: The algorithm to find the greatest of three numbers (a, b, and c) is
as follows:
Step 1: Input three numbers from the user: a, b, c.
Step 2: Check,
4 • C Programming

if (a > b)
Step 3: do if (a > c)
Step 4: then Print ‘a’ and go to step-12.
Step 5: else
Step 6: Print ‘c’ and go to step-12.
Step 7: else
Step 8: do if (b > c)
Step 9: then Print ‘b’ and go to step-12.
Step 10: else
Step 11: Print ‘c’ and go to step-12.
Step 12: Stop

Now let us validate this algorithm.


Dry Run 1:
Input: a = 10
b = 20
c = 30
Expected Output: 30
Process: Is (a > b) ?
Is (10 > 20) → false
Is (b > c) ?
Is (20 > 30) → false
Observed Output: 30
Dry Run 2:
Input: a = 10
b = 20
c = 30
Expected Output: 30
Process: Is (a > b) ?
Is (10 > -20)→ true
Is (a > c) ?
Is (10 > 30) → false
Observed Output: 30
Example 2: Write an algorithm to read a, b, and c as the coefficients of
a quadratic equation and to find its roots; then validate your algorithm
by giving it dry runs.
C Overview • 5

Solution 2: The algorithm to find the roots of a given quadratic equation is as


follows:
Quad_equation (a, b, c)
Step 1: Input three numbers: a, b, c.
Step 2: if (a= =0)
Step 3: 
Then Print ‘Not a quadratic equation’ and go to
step-12
Step 4: else
Step 5: put D = b2 – 4 a c
Step 6: check if (D > 0 or D < 0)
Step 7: then ROOTS = (-b + sqrt (b2 – 4ac)) / 2a
Step 8: and Print ‘ROOTS’ and go to step 12.
Step 9: else do ROOTS = -b/2a
Step 10: and Print ‘ROOTS’ and go to step 12.
Step 11: Stop.

Now let us validate this algorithm.


Dry Run 1:
Input: a = 1
b = 2
c = 3
Expected output: ROOTS = -1 + sqrt(2) / 1
Process:
Is a= =0 ?
Is 1 = = 0 → false
D = b2 – 4ac
D = -8
Is D > 0 or D < 0 ?
D < 0 → true
ROOTS = (-b ± sqrt(b2 – 4ac)) /2a
Observed Output:
-1 ± sqrt(2) / 1
Dry Run 2:
Input: a = 4
b = 2
c = 1
6 • C Programming

Expected output: ROOTS = -1 ± sqrt(3) / 4


Process:
Is a= =0 ?
Is 4 = = 0 → false
D = b2 – 4ac
D = -12
Is D > 0 or D < 0 ?
D < 0 → true
ROOTS = (-b + sqrt(b2 – 4ac)) /2a
Observed Output:
-1 ± sqrt(3) / 4
Dry Run 3:
Input: a = 0
b = 2
c = 1
Expected output: Not a quadratic equation.
Process:
Is a= =0 ?
Is 0 = = 0 → true
Observed Output:
Not a quadratic equation.

In all of the preceding dry runs, the expected output equals the
NOTE observed output.

Example 3: Write an algorithm to read x, y, and z as the three sides of


a triangle and to check the type of triangle formed; then validate your
algorithm by giving it dry runs.
Solution 3: The algorithm to check for the triangle type is as follows:
Triangle_type (x, y, z)
Step 1: Input three sides of triangle: x, y, z.
Step 2: check if (x + y > z) && (y + z > x) && (x + z >y)
Step 3: then do if (x= y && y = z)
Step 4: then Print: ‘Equilateral triangle’ and go to step 17.
C Overview • 7

Step 5: else
Step 6: do if (x = y && y! =z) || (x = z && z!=y) || (y=z &&x!=z)
Step 7: then do if (x = sqrt( z2 /2) || (x = sqrt(y2 /2) || (y = sqrt(x2 /2))
Step 8: Print: ‘Right Angled Isosceles Triangle’ and go to step 17.
Step 9: else
Step 10: Print: ‘Isosceles Triangle’ and go to step 17.
Step 11: else
Step 12: do if (x = sqrt(z2 + y2 )) || (y = sqrt(z2 + x2 )) || (x = sqrt(x2 + y2 ))
Step 13: then Print: ‘Right Angled Scalene Triangle’ and go to step 17.
Step 14: else Print: ‘Scalene Triangle’ and go to step 17.
Step 15: else
Step 16: Print: ‘Not a triangle’ and go to step 17.
Step 17: Stop.

Let us validate this algorithm now.


Dry Run 1:
Input: x = 1
y = 1
z = 2
Expected output: Not a triangle
Process:
Is (x + y > z) ?
Is (1 + 1 > 2) → false
Observed Output: Not a triangle
Dry Run 2:
Input: x = 3
y = 4
z = 5
Expected output: Right Angled Scalene Triangle
8 • C Programming

Process:
Is (x + y > z) && (y + z > x) && (x + z > y)?
True
Is x = y && y = z?
False
Is (x =y && y!=z) || (x=z && z!=y) ||(y=z && z!=x)?
True
Is (32 + 42 = 52) → True
Observed Output: Right Angled Scalene Triangle
Dry Run 3:
Input: x = 6
y = 6
z = 6
Expected output: Equilateral Triangle
Process:
Is (6 + 6 > 6) ? → True
Is (6 = 6 = 6) → True
Observed Output: Equilateral Triangle

In all of the preceding dry runs, it is seen that the expected output
NOTE equals the observed output.

1.2 FLOWCHARTS

A flowchart is defined as a pictorial representation of an algorithm. It


serves as a means of recording, analyzing, and communicating problem infor-
mation. Programmers often use a flowchart before writing a program, although
this is not always mandatory. Practically speaking, sometimes drawing of
the flowchart and writing of the code in a high-level language go side
by side. Flowcharts are of two types.

(a) Program flowchart


(b) System flowchart

A program flowchart (or simply a flowchart) shows the detailed pro-


cessing steps within one computer program and the sequence in which
those steps must be executed. Different notations are used in a flowchart to
denote the different operations that take place in a program.
C Overview • 9

On the other hand, system flowcharts show the procedures involved


in converting data on input media to data in output form. Here, the focus
is on the data flow into or out of a program, the forms of input, and the forms of
the output. Please understand that a system flowchart makes no attempt
to depict the function-oriented processing steps within a program. A
system flowchart may be constructed by the system analyst as part of problem
definition. Note that algorithms in data structures are always expressed
in the form of flowcharts.
This difference is clear from Figures 1.1a and 1.1b.

Quantity, Unit price

Monthly billing program

Amount due

Figure 1.1a A System Flowchart Example

Contrast this with a program flowchart.

Start

Read
quantity,
price

Multiply quantity
by price

Write
amount bill

Stop

Figure 1.1b A Program Flowchart Example


10 • C Programming

A flowchart is a tool to show the logic flow of a program. Programmers use


flowcharts to design a complete program. The primary purpose of a flowchart
is to show the design of an algorithm. The flowchart frees a programmer from
the syntax and details of a programming language while allowing focus on the
details of the problem to be solved.
A flowchart is a combination of symbols. Symbols enhance the readability
of the flowchart. They do not directly show instructions (or commands). They
show the start and stop points, the order and sequence of actions, and how one
part of a flowchart is connected to another.
Golden Rule

1. Each algorithm should have only one entry point and one exit point.
2. A null statement is shown by a flow line; there is no symbol for null.

Some of the notations used are shown in Figure 1.2.


An oval shows the beginning or ending of an algorithm.
Flow lines show the order or sequence of actions in a program.
A connector is used when we reach the end of a page. It is also used when
we need to show the logic details that do not fit in the flow.
Assignment statements are shown using a rectangle, as in the following:

Variable ← Expression

A parallelogram shows any input read or output produced. A rectangle


with two vertical bars inside represents a module call.
Selection statements (Decisions) may be two-way or multi-way se-
lections. In both cases, the statement ends with a connector where the true
and false flows join. In this case, the connector has nothing in it. This is ap-
plicable to switch statements or even for, while, and do-while loops of C (to be
discussed later).
C Overview • 11

Start/Stop

Input (Read)/ Output (Write)

Initializations and calculations

Decisions

C Connector

Flow of control

Module call

Figure 1.2 Flow Chart Notations

Both flowcharts and algorithms are isomorphic—that is, one can be


converted to another form without the loss of data (although there are
some differences).
12 • C Programming

Let us now distinguish between a flowchart and an algorithm.


Flowchart Algorithm
1. The graphical or pictorial rep- 1. Step-by-step finite procedure of
resentation of the logic of the solving the problem in hand
problem in hand
2. Use of different shapes that are 2. Written step by step
joined by flow lines
3. Use of flow lines 3. Flow control moves from top
to bottom
4. The task to be performed written 4. All instructions written in English
within boxes in English
5. Easily converted into algorithm or 5. Easily converted into flowchart or
program in high-level language program in high-level language
6. Drawn after writing algorithm. 6. Normally written before flowchart

We are in a position to solve some examples now.


Example 1: Draw a flowchart to find the greatest of three numbers.
Solution 1: The flowchart is as follows:

start

Input
a,b,c

Y
Is a>b? Is a>c? Print a

N N

Y
Is b>c ? Print c

Print c Print b

Stop
C Overview • 13

Example 2: Draw a flowchart that finds the roots of a given quadratic


equation, using a, b, and c as its coefficients.
Solution 2: The flowchart is drawn as follows:

Start

Input
a, b, c

Print 'Not
a
Is a=0?
quadratic
equation'

D = b2 – 4ac

Is D>0
OR roots=(-b+ sqrt(D))/2a
D<0?

ROOTS=-b /2a

Print
ROOTS

STOP

Example 3: What is the difference between a flowchart and a dataflow


diagram?
Example 4: 
Define flowchart. Write are the advantages of and the
symbols used in a flowchart. Draw a flowchart to find the
smallest of three numbers.
Example 5: (a) 
What is the difference between a flowchart and an
algorithm?
(b) Differentiate between a linker and a loader.
14 • C Programming

Example 6: It is desired to add n numbers. Write the following for this
problem:

(a) Plain English


(b) Structured English
(c) Pseudocode
(d) C code

Hint: (a) Plain English: First, read n numbers to be added. Initialize a re-
sultant value to 0. Then add these numbers to this resultant value one by one.
When all the numbers have been added, display the result.
(b) Structured English:
Step 1: Start
Step 2: Initialize sum and number of elements to add to 0.
Step 3: Read the number of elements to add—that is, read n.
Step 4: Read a number to be added and let it be a.
Step 5: s=s+a and i=i+1
Step 6: If i<n, go to step 4, else go to step 7.
Step 7: Display (output) the value of sum.
Step 8: Stop.
(c) Pseudocode:
Algo_ add(a, n)
{
s:= 0.0;
for i:=1 to n do
s:= s + a [i]; S + a [i];
return s;
}
(d) C Code:
int add(int a[ ] , int n)
{
int i, s=0;
for(i=0; i <n ; i++)
s=s + a[i];
return s;
}
C Overview • 15

1.3 COMPILER OVERVIEW

A compiler is a software program that analyzes a program developed


in a particular computer language and then translates it into a form
that is suitable for execution on your particular computer system. The
GNU C compiler gcc is the best compiler available for the C language. In
fact, it is a suite of compilers, as the package contains g++ (a compiler for
C++) and facilitates compiling other languages like Objective-C and Objec-
tive-C++, Fortran in both fixed form and free form, ADA, and JAVA2. It can
handle different dialects of C. It is also able to generate executable code for
CPU families like ARC, AVR, ARM, Darwin, DEC Alpha, HPPA, i386 and
x86-64, IA-64, MIPS, PDP-11, POWERPC, SPARC, and so on. When you in-
voke gcc, it normally does preprocessing, compilation, assembly, and linking.
The overall options allow one to stop this process at an intermediate stage.
For example,
-c Compile or assemble the source files but do not link. The linking stage
is not done. The output is in the form of an object file for each source file.
-S Stop after the stage of compilation proper; do not assemble. The out-
put is in the form of an assembler code file for each nonassembler input file
specified.
-E Stop after the preprocessing stage; do not run the compiler proper.
The output is in the form of preprocessed source code, which is then sent to
the standard output.
-o Place output in file file.
- wall A warning option—displays all possible warnings and is very useful
during initial debugging of a code.
Actually, gcc has a large complement of options for warnings, debugging,
optimization, preprocessor, linker, assembler, and the target machine or lan-
guage—for example, a C compiler, a C++ compiler, etc.
The steps involved in entering, compiling, and executing a computer pro-
gram developed in the C programming language are shown in Figure 1.3.
16 • C Programming

Start
Source
program
Edit
(file.c)

Compile
and
assemble

yes Object
Errors program
? (file.o)
no

Link

Libraries
and other Execute Executable
object object
program (a.out)

Results
no OK?
yes

Finish

Figure 1.3 Basic Steps for Entering, Compiling, and Executing C Programs

Explanation: The program that is to be compiled is first typed and saved into
a file. C programs are saved with a .c extension. Thus, program1.c might be a
valid filename for a C program. A C program is typed, saved, and edited in a
text editor. For example, vi is a popular text editor used on Unix systems. The
program that is entered into the file is known as the source program
because it represents the original form of the program expressed in the
C language. After the source program is entered into a file, you can then pro-
ceed to have it compiled. The compilation process is initiated by typing a special
command on the system. When this command is entered, the name of the file
that contains the source program must also be specified. For example, on Unix
systems, the command to initiate program compilation is called cc.
But please remember that if you are using the popular GNU C compiler,
the command you use is gcc. So typing the line
gcc program1.c
has the effect of initiating the compilation process with the source program
contained in program1.c.
C Overview • 17

In the first step of the compilation process, the compiler examines each
of the program statements contained in the source program and checks to en-
sure that each conforms to the syntax and semantics (meaning) of the language.
Practically speaking, the C compiler normally makes a prepass of the program
looking for special statements. This is also known as a preprocessing phase. If
any mistakes are discovered by the compiler during this phase, they are report-
ed to the user and the compilation process ends right there. Then the errors
have to be corrected in the source program using an editor and the compilation
process must be restarted. Typical errors reported during this phase of compi-
lation might be due to an expression that has unbalanced parentheses (syntax
error) or due to the use of a variable that is not defined (i.e., semantic error).
When all the syntactic and semantic errors have been removed from the
program, the compiler then proceeds to take each statement of the program
and translate it into lower form. This means that each statement is trans-
lated by the compiler into the equivalent statement or statements in
assembly language needed to perform the task.
After the program has been translated into an equivalent assembly language
program, the next step in the compilation process is to translate the assembly
language statements into actual machine instructions. This step might or might
not involve the execution of a separate program known as an assembler. On
most systems, the assembler is executed automatically as part of the compila-
tion process. The assembler takes each assembly language statement and con-
verts it into a binary format known as object code which is then written into
another file on the system. This file typically has the same name as the source
file under Unix, with the last letter as “o” (for object) instead of a “c”. In Win-
dows, the suffix letters “obj” typically replace the “c” in the filename.
After the program has been translated into object code, it is ready to be
linked. This process is once again performed automatically whenever the cc
or gcc command is issued under Unix. Also understand that the purpose
of the linking phase is to get the program into a final form for execu-
tion on the computer. If the program uses other programs that were previ-
ously processed by the compiler, then during this phase the programs are linked
together. Programs that are used from the system’s program library are also
searched and linked together with the object program during this phase. The
process of compiling and linking a program is known as building. The
final linked file, which is in an executable object code format, is stored in
another file on the system, ready to be run or executed.
Under Unix, this file is called a.out (by default).
18 • C Programming

Under Windows, the executable file usually has the same name as the
source file, with the c extension replaced by an exe extension.
The command a.out is used to execute the program. This command will
load the program called a.out into the computer’s memory and initiate its ex-
ecution. When the program is executed, each of the statements of the program
is sequentially executed in turn. If the program requests any data from the
user (called input), the program temporarily suspends its execution so that the
input can be entered. Or the program might simply wait for an event, such
as a mouse being clicked, to occur. Results that are displayed by the program
(called outputs) appear in a window (also called console). Or the output might
be directly written to a file on the system.
If the program works correctly, there is no problem, but this does not of-
ten happen on the first attempt. If the program does not produce the desired
results, it is necessary to go back and reanalyze the program’s logic. This is
known as the debugging phase, during which an attempt is made to remove
all known problems or bugs from the program. Doing this requires making
changes to the original source program. Please note that in such a case, the
entire process of compiling, linking, and executing the program must
be repeated until the desired results are obtained. Also note that in
general, gcc follows the following processing steps:
Step 1: Preprocessing (invokes cpp)
Step 2: Compilation
Step 3: Assembly (invoke as)
Step 4: Linking (invokes ld).
This can also be shown graphically, as in Figures 1.4 and 1.5.

gcc
Myprog.c Myprog.s
8086 m/c code

Assembler as
Myprog.s Myprog.o
(x86 m/c code)

Figure 1.4 gcc Converting from C to obj Using Assembler


C Overview • 19

gcc
Myprog.c Myprog.o
8086 m/c code

Linker ld
Myprog.o Myprog
(x86 m/c code)

Figure 1.5 gcc: The Linker Converts an obj File to an Executable

In gcc, the level of attempted optimization is controlled by -0 and other


switches but one has to be very careful for embedded and device driver codes.

1.4 ASSEMBLER, LINKER, AND LOADER

If we look at the history of programming languages we find the following:

(a) In the 1940s, machine languages were used.


(b) In the 1950s, symbolic languages were used.
(c) In the 1960s, high-level languages were used.

Each computer has its own machine language that is made of streams of
0s and 1s. This is so because computers are made up of switches, transistors,
and other electronic devices that can be either in 1 (logic high) or 0 (logic low)
states. These are also named as 0 (off state) and 1 (on state).

The only language understood by computer hardware is machine


NOTE language.

In the 1950s, Admiral Grace Hopper, a mathematician, developed the con-


cept of a special computer program that would convert programs into machine
language. It used symbols (also called mnemonics), which is why the languages
used in these programs were known as symbolic languages. Because a com-
puter cannot understand this symbolic language, it must be translated
20 • C Programming

into machine language. The program that translates symbolic code into
machine language is known as an assembler.
Then in the 1960s came the introduction of high-level languages that re-
lieved the programmer of the tedious task of writing programs in assembly
language. Both symbolic and higher-level languages share one thing in com-
mon—both must be converted into machine language. And this process of
converting them is known as compilation.
For example, the first high-level language was FORTRAN (FORmula
TRANslation). It was created by John Backus and an IBM team in 1957. C is
also a high-level language used for developing system software and new appli-
cations.
Often a program is so large that it is convenient to break it down into small-
er units. Each of these units is stored in a separate file. After these separate
program files are compiled, they must somehow be linked together to form a
single program. This linking is usually accomplished by a program called
a linkage editor, which is often run automatically when a program is
compiled. This linker assembles all of the functions (both user-defined
as well as system functions) into a final executable program.
Once a program has been linked, it is ready for execution. To execute a
program, we use an operating system command like the run command. This
command will load the program into primary memory and execute it. And get-
ting the program into memory is the function of an operating system
program known as the loader. It locates the executable program and
reads it into memory. When everything is loaded, the program takes
control and it begins execution.
We are in a position to solve some examples now.
Example 1: Compare a compiler and an interpreter.
Solution 1: The following chart compares a compiler and an interpreter:
Compiler Interpreter
1. Converts the whole program into 1. Converts the program into ma-
machine code and then executes chine code one step at a time and
the entire program. then runs only
that step.
2. Lists all errors after compilation. 2. Immediately displays any error in
any line of the program after the
translation of that line.
C Overview • 21

3. Requires less execution time. 3. Requires more execution time.


4. Not especially efficient for 4. Efficient for debugging.
debugging.
5. Creates only one .exe file (for 5. Does not create .exe file (for
example, C/C++ compilers, TC example, V. B. 6.0
compiler, etc.). interpreter).

Example 2: Compare a linker and linkage editor in a tabular form.


Solution 2: The comparison is shown in the following chart:
Linker Linkage Editor
1. Linking of object modules and 1. Linking of object modules and nec-
necessary libraries are done and essary libraries are done and stored
immediately loaded into main in a file or library called a linked
memory. program.
2. Used only once. 2. Can be used many times.
3. A library search and the resolution of 3. Library search and resolution of ex-
external reference is done each time. ternal reference must be done only
once.
4. Not suitable for a program which is 4. Suitable for a program which is ex-
executed repeatedly. ecuted repeatedly.

Example 3: Compare machine language, assembly language, and high-


level languages in tabular form.
Solution 3: The comparison is shown in the following chart:

Machine Assembly High-Level


Language Language Language
1. Programs written in 1. Programs in assem- 1. Programs in high-
machine language are bly language are less level language are
difficult to write, de- difficult than machine easy to write, debug,
bug, and understand. language. and understand.
2. Programs are not 2. Programs are not 2. Programs are
portable. portable. portable.
22 • C Programming

3. Programmer has to 3. Programmer has to 3. No need to keep


keep track of memory keep track of memory track of memory ad-
addresses. addresses. dresses.
4. No translator is re- 4. No translator is re- 4. Compiler or inter-
quired to convert into quired to convert into preter is required.
machine code. machine code.
5. The execution of 5. The execution of pro- 5. The execution of pro-
programs is very fast. grams is slower than grams is slower than
machine language assembly language
programs. programs.

Example 4: Name some commonly used assemblers.


Solution 4:

(a) Intel 8086 macro assembler (ASM 86)


(b) Borland Turbo Assembler (TASM)
(c) IBM Macro Assembler (MASM)

Example 5: Explain briefly the compilation and execution process of a


C program.

1.5 STRUCTURE OF A SIMPLE “HELLO WORLD”


PROGRAM IN C

In general, any C program comprises one or more preprocessor commands,


a global declaration section, and one or more functions. That is,

Preprocessor Directives

Global declarations

Main function

Other functions (if needed)


C Overview • 23

Every C program starts with some preprocessor directives or commands.


These are special instructions to the preprocessor that tell it how to prepare a
program for compilation. In every C program, we use a preprocessor directive
named include. This include command tells the preprocessor that we
need information from selected libraries known as header files. By the
time we type our C program (in some editors), all the preprocessor al-
locations will have taken place automatically. This means that the prepro-
cessor actually analyzes these statements before the analysis of the C program
itself takes place.
Preprocessor statements are identified by the presence of a pound sign, #,
which must be the first nonspace character on the line.
In C, a programmer inserts a directive #include<stdio.h> that tells the pre-
processor to include the header file stdio.h at this point in the program.
Then a programmer can give global declarations (if any). Global declara-
tions are those that are visible to all parts of the program. We shall study these
a bit later.
Then comes the main where the actual execution of the program starts. We
know that the actual work of the program is carried out by its functions, which
are blocks of code that accomplish tasks within a program. Only one function
can be a main function in any program. All functions in a program (also
the main) are subdivided into two sections—the declaration section and the
statement section.
The declaration section is at the beginning of the function. It speci-
fies the data that you will be using in the function. Declarations in a function
are known as local declarations because they are visible only to the function that
contains them.
The statement section follows the declaration section. This section
contains some instructions that cause something to be performed, such as di-
viding two numbers.
Let us consider the simplest C program that explains its structure.
/* My first C program */
1. #include<stdio.h>
2. int main (void)
3. {
4. printf(“Hello World! \n”);
5. return 0;
6. }
24 • C Programming

This program has only one preprocessor directive. There are no global
declarations and no local definitions. It simply displays “Hello World!” on the
screen. Then there are two statements, one to print the message and the other
to stop the program.
Let us learn about these parts now.

I. Preprocessor Directive/Command
As discussed earlier, a preprocessor is a part of the C compilation process that
recognizes special statements that might be interspread throughout a C pro-
gram. It actually analyzes these statements before analysis of the C program
starts. The preprocessor is a section of the compiler which looks over the C
program before it is compiled.

Working of Preprocessor
When you issue the command to compile a C program, the program is run au-
tomatically through the preprocessor. The preprocessor is a program that modi-
fies the C source program according to the directives supplied in the program.
An original source program is usually stored in a file. The preprocessor does not
modify this program file but creates a new file that contains the processed ver-
sion of the program. This new file is then submitted to the compiler.
When we compile this program, the compiler shows the number of lines
compiled to be greater than 6. This is because during the preprocessing stage,
the include preprocessor directive (line 1) searches the file stdio.h in the pre-
scribed list of directories and if the header file is found, the include directive
is replaced by the entire content of the header file. If the included header file
contains another include directive, it will also be processed. This processing
is carried out recursively till either no include directive remains or till
the maximum translation limit is achieved (ISO specifies a maximum of
15 nested levels of include files). Thus, one line of source code gets replaced
by multiple lines of the header file. During the compilation stage, these added
lines will also be compiled. Thus, the compiler shows the number of lines to be
greater than 6.

Some compilers enable the programmer to run only the


NOTE preprocessor on the source program and to view the results of the
preprocessor stage.
C Overview • 25

Please remember the following points regarding preprocessor


directives:

1. They are placed at the beginning of the program.


2. They start with a pound/hash (#) sign. This is its syntax (rule).
3. There is no semicolon at the end of these directives.
4. They can start in any column but usually they start in column
number 1.
5. They tell the compiler to include the standard input/output library
file in the program. This library file prints a message on to the screen.
Actually, printing is one of the input/output processes identified in this
library.
6. The syntax of this command as shown in line 1 must be exact.
7. There is no space between the pound/hash sign and the reserved
keyword include.
8. It tells the preprocessor that you want the library file in the
angular brackets (< >) to be included in your program. The
name of this header file is stdio.h. It stands for “Standard input/
output header file”.
9. The angular brackets tell the preprocessor to search for the file in
one or more standard directories. These directories contain header files
that are provided by the system and those commonly used by several
programmers (if the computer is a multiple-user machine).
10. Sometimes the brackets are replaced with double quotation marks as in
the following:
#include “stdio.h”
In this case the preprocessor will first look in the programmer’s own
directory or the same one that contains the program file. If it is NOT
found there, then the standard directories are searched.

11. The preprocessor can also add or delete C program statements.


12. A preprocessor symbol is never replaced if it occurs within single or
double quotation marks.
26 • C Programming

13. Header files also provide consistency among several program files.
Often a program is large and thus it is possible to break it into smaller
units, each of which is stored in a separate file. After these separate
program files are compiled, they must somehow be linked together to
form a single program. This linking is usually done by a program called
the linkage editor (which is run automatically when a program is
compiled).
14. A header file can contain other #include directives. Please note that
it cannot include itself because this would result in an infinite
recursion. Also note that it cannot include another file that
includes the first file as this would also result in an infinite
recursion.
15. Header files can contain any text at all. They may also contain C code
to define structure templates, global variables, or function definitions.
However, header files usually do not contain function definitions, as it is
more efficient to store these in the function libraries set up by the user.
But global variables are sometimes included.
16. If stdio.h is included in the program, the macro versions (to be discussed
later) are used. On the other hand, if the programmer wishes to use the
function versions they can be undefined after the #include<stdio.h>
directive.
17. A preprocessor directive is terminated by the end of the line it oc-
cupies but if necessary it can be continued onto one or more lines by
ending all but the last line with backslashes.

II. Main Function


Here starts the executable portion of your program (i.e., the code for which
object and .exe files are generated). Main is a special C function. The program
execution starts from main and there can be only one main in every program.
The int preceding this keyword main says that the function main (here) will re-
turn an integer value to the operating system. The keyword void shows that the
function main has no parameters (i.e., the parameter list is void). Following the
main are two braces that show that main is a function. Please note here that
there is no punctuation after the function header.

If there are no parentheses following the main, it is not a function


but is instead a variable. For example, sum is a variable but sum( )
NOTE
is a function. This function may or may not return a value. We
shall study this a bit later.
C Overview • 27

After identifying the main( ) to the system, we must now specify what this
routine must do. And this is done by enclosing all program statements of the
routine within a pair of curly braces (line 3). Also note that all program
statements included between the braces are taken as part of the main
routine by the system. In the Hello World! program, we have only two such
statements. The first statement tells that a routine named printf is to be
invoked or called. The string of characters “hello world! \n” is the pa-
rameter or argument to be passed to the printf routine.
Just remember that the printf routine is a function in the C library. It simply
prints or displays its arguments on your screen in between double quotation
marks. Also note that a blank space in a string counts as a character.
Also seen in line 4 are two special characters—the backslash (\) and the
letter n—that are together known as the newline character. This newline
character tells the system to do precisely what its name implies—that
is, go to a new line (next line).

Any characters to be printed after the newline character then ap-


NOTE pear on the next line of the display. This concept of newline char-
acter is similar to that of the carriage return key on a typewriter.

Another rule in C may be stated as follows: “All program statements in


C must be terminated by a semicolon. That is why a semicolon appears
immediately after the closing braces of the printf( ) statement. How-
ever, there are some exceptions; for example, after main( ) there are no
semicolons!”
Line 5 is the last statement (return 0); it tells the compiler to finish the ex-
ecution of main and return to the system a status value of 0. Please note that
you can use any integer here. Also note that zero is used here by con-
vention to show that the program completed successfully (i.e., without
any errors). Different numbers can be used to indicate different types of error
conditions that occur, such as divide by zero, file not found, and so on.

This exit status can be tested by other programs like the UNIX
NOTE shell to see whether the program ran successfully.

The end of the program is marked off by a closing brace. Remember the
following programming tips:

1. The number of opening braces and closing braces must be the same.
2. These braces line up with the letter ‘m’ of the main( ).
28 • C Programming

3. This is not mandatory but will improve the program’s readability.


4. The body of the function is indented within the braces. This also
improves the program’s readability.
5. The function name like main is given parentheses—that is, ( ). On
the other hand, the body starts and ends with two delimiters—
that is, { and }. One cannot interchange them. They are design
features of the C compiler.
Now we are left with one more nonexecutable statement (see the “Hello
World!” program again) called a comment. Comments are written within the
code to make it more understandable and readable. These comments are inter-
nal program documentations. C supports two types of comments:

(a) Block comments


(b) Line comments

A block comment is used when the comment spans several lines of


code. It uses an opening token (/* ) and a closing token ( */). Anything
that is enclosed within these is simply ignored by the compiler. The tokens can
start in any column and they do not have to be on the same line. For example,
/* a block comment can go to
More than one line also */
On the other hand, a line comment uses two slashes (//) to identify a
comment. There is no need for an end-of-line token here. This type of com-
ment format is very much preferred by programmers as it is easier to write. It
can also start anywhere on the line.
However, note another programming rule: “Comments cannot be nested.”
We cannot have comments inside comments. This results in an error.
This is the complete anatomy of a C program.
Before further discussion, let us solve some questions now.
Q1. W
 hat delimiters are used to specify the start and end of a character string
in C?
A1. Double quotation marks.
Q2. What is the character string in a printf statement called?
A2. The control string.
C Overview • 29

Q3. C is derived from which of the following languages:


(a) FORTRAN
(b) PASCAL
(c) C++
(d) B language
A3. (d) B language.
Q4. Give the output of the following statement:
printf(“alpha\n\nbeta\n\ngamma\n”);
A4. It prints three lines that are double spaced as follows:
alpha
beta
gamma
Q5. Give the errors in the following:
mane{ } /* this is a main …/*
(
print(‘ that’s great. /n’)
A5. The following errors are noticed in this program:
(a) The word main is not spelled correctly.
(b) Parentheses should be used instead of braces after the word main.
(c) The wrong slash symbol is used in the first comment symbol.
(d) The characters in the terminating comment symbol are reversed.
(e) T
 he body of the program should commence with a left brace, not a left
parenthesis.
(f) The function should be spelled as printf and not print.
(g) T
 he literal should be delimited by double instead of single quotation
marks.
(h) The newline character has an incorrect type of slash.
(i) The semicolon is missing from the printf statement.
(j) The final right brace is missing.
30 • C Programming

1.6 OVERVIEW OF THE COMPILATION AND


EXECUTION PROCESS IN AN INTEGRATED
DEVELOPMENT ENVIRONMENT (PREFERABLY
CODEBLOCK)

IDE stands for Integrated Development Environment. An IDE is a window-


based program that allows you to easily manage large software programs, edit
files in windows, and compile, link, run, and debug your programs. This pro-
cess of editing, compiling, running, and debugging programs is man-
aged by a single integrated application known as an IDE.
For example,
(a) On the Mac OS, CodeWarrior and Xcode are two IDEs.
(b) Under Windows, MS Visual Studio is an IDE.
(c) Under Linux, Kylix is a popular IDE.

All IDE applications greatly simplify the entire process of program


NOTE development. CodeWarrior (by Metrowerks) can run on Linux,
Solaris, and Windows, too. Kylix is sold by Borland.

All of the tools like text editor, preprocessor, compiler, and linker that are
required for developing programs are integrated into one package known as an
IDE.
Codeblocks is an open source, cross-platform IDE. A global variable or a
function defined in one source file can be used in another source file in a mul-
tifile program. Let us see how.
Consider a program that consists of two source files, t1.c and t2.c. The
source file t2.c contains the definition of a variable var1 and a function fun1.
These definitions are used in another source file t1.c of the program. Because
the global variables and the function have external linkage, this usage is al-
lowed. And this can be done with CodeBlock as follows:
Say, file t1.c has the following code:
#include<stdio.h>
main( )
{
C Overview • 31

extern int var1;


printf(“The value of var1 defined in other source file is
%d\n”, var1);
fun( );
}
And t2.c has the following code:-
int var1 = 95;
fun( )
{
printf(“Function fun is defined in other source file”);
}
Then after running these files in CodeBlock we get the following output:
The value of var1 defined in the other source file is 95.
The function fun1 is defined in the other source file.
We are in a position to answer some questions now.
Q1. What are the advantages of writing an algorithm over the C program?
[Hint: a) It is simple, clear, and unambiguous and thus can be debugged
by any programmer having no prior knowledge of any programming lan-
guage.
(b) It is easier to understand the logic in an algorithm.]
Q2. Why don’t we translate directly from the statement of the problem to C?
Q3. Which two lines will be used in all of our C programs?
Q4. “C is often described as a middle level language.” Explain.
[Hint: C permits programs to be written in much the same style as that
of most modern high-level languages like Fortran, Cobol, Basic, and Pas-
cal. Where it differs is that C permits very close interaction with the in-
ner workings of the computer. It is analogous to a car that has a luxury of
automatic gears but at the option of the driver permits the manual shifting
of gears. It is possible in C to deal with the machine at a fairly low level.
Nevertheless, C is a general purpose structured programming language
that has much in common with the best of the high-level languages. C is
concise but at the same time it is a very powerful language, too.]
Q5. What is a preprocessor directive?
or
Q6. Distinguish between function and preprocessor directives.
32 • C Programming

[Hint: Preprocessor directives are the lines to be executed before the ac-
tual compilation of the code starts. And wherever in the program code the
macros are called, the code of that macro is inserted. On the other hand,
in a function call, the body of the function is executed at runtime. And
wherever in a code the functions are called, the execution of the program
jumps to the body of the function. Code is not copied as in the case of
preprocessor directives.]
Q7. Name some popular C language IDEs.
[Hint: There are various IDEs on the market today targeted toward differ-
ent operating systems. For example, Turbo C and Turbo C++ are popular
compilers that work under MS-DOS, Visual Studio and Visual Studio Ex-
press Edition are compilers that work under Windows, whereas the gcc
compiler works under Linux. Please note here that the Turbo C, Turbo
C++, and gcc compilers can also be installed on machines running Win-
dows. Both the Visual Studio Express Edition and gcc compilers are free
of cost and can be downloaded easily.]

Summary
In this chapter, we have studied what an algorithm is. We have defined terms
like flowcharts, pseudocode, and structured English. Also we have seen how a
C program is compiled and run. The roles of assemblers, linkers, and loaders
have also been examined. We have specifically focused on the gcc compiler.
The chapter also shows the basic structure of any C program. It also discusses
the IDEs that are used to compile and run C programs like CodeBlocks.

Exercises
Q1. What is a C preprocessor? Explain each of them.
Q2. How do you debug a C program? Discuss the purpose of preprocessor
directive statements and macros as used in the C language?
Q3. What is an interactive debugger?
Q4. Distinguish between the following with examples:
(a) Syntactic errors and semantic errors
(b) Runtime errors and logical errors
(c) Debugging and testing
Q5. What is the scope of a preprocessor directive within a program file?
C Overview • 33

Q6. Draw a flowchart to find the sum of the following series:


Sum = 1+3+5+7+ … up to 25 terms.
Q7. Write an algorithm to find the roots of a given quadratic equation ax2 +
bx +c =0, where ‘a’ is nonzero.
Q8. Draw a flowchart to determine whether a year entered through a key-
board is a leap year or not?
Q9. Explain the various stages in program development.
Q10. Describe in detail syntax errors, logic errors, and runtime errors.
Q11. Write an algorithm and draw flowcharts for the following:
(a) To generate the first n Fibonacci numbers
(b) To sum the first 80 even numbers
(c) To check whether a given number is prime or not
(d) To check whether a given number is even or odd
Q12. Define a bug and debugging.
Q13. What are the characteristics of a good algorithm?
Q14. What are the advantages of flowcharts?
[Hint: Better communication, effective analysis, proper documentation,
efficient coding, proper debugging, and better program maintenance].
Q15. How will you test your program? What are dry runs?
Q16. What is top-down design? How is it done?
Q17. What is modular design? Should it be used or not?
Q18. Explain Wirth’s equation:
Program = Algorithm + Data-Structure or Program-Algorithm =
Data Structure
Q19. What is meant by program documentation? Explain.
Q20. Suppose you have a C program whose main function is in main.c and has
other functions in the files input.c and output.c:
(a) What commands would you use on your system to compile and link
this program?
(b) How would you modify the above commands to link a library called
process1 stored in the standard system library directory?
34 • C Programming

(c) How would you modify the above commands to link a library called
process2 stored in the home directory?
(d) Some header files need to be read and have been found in a header
subdirectory of your home directory and also in the current work-
ing directory. How would you modify the compiler commands to ac-
count for this?
Q21. Suppose you have a C program composed of several separate files and
they include one another as shown in the following chart:
File Name Include Files
main.c stdio.h, process1.h
input.c stdio.h, list.h
output.c stdio.h
process1.c stdio.h, process1.h
process2.c stdio.h, list.h

(a) Which files have to recompile after you make changes to process1.c?


(b) Which files have to recompile after you make changes to process1.h?
(c) Which files have to recompile after you make changes to list.h?
CHAPTER

2
Programming Using C

2.0 INTRODUCTION

C
is a general purpose, block-structured, procedural, case-
sensitive, freeflow, portable, powerful high-level programming
language. This language is so powerful that an operating system like
UNIX is itself coded in C. It is said that programming languages are born,
age, and eventually die but the C programming language has only matured
from the time it was born. It has the same relevance today as it had when it
was developed by Dennis Ritchie at Bell Telephone Laboratories in 1972. The
importance of the language can be easily fathomed from the fact that C is a
prerequisite in any software industry today.

2.1 REVIEW OF PREPROCESSOR DIRECTIVES/


COMPILER DIRECTIVES/C PREPROCESSOR

As discussed earlier, a preprocessor is a part of the C compilation process that


recognizes special statements that might be interspread throughout a C pro-
gram. It actually analyzes these statements before analysis of the C program
starts. The preprocessor is a section of the compiler which looks over the C
program before it is compiled.

Working of the Preprocessor


When you issue the command to compile a C program, the program is run
automatically through the preprocessor. The preprocessor is a program that
36 • C Programming

modifies the C source program according to the directives supplied in the pro-
gram. An original source program is usually stored in a file. The preprocessor
does not modify this program file but creates a new file that contains the pro-
cessed version of the program. This new file is then submitted to the compiler.
When we compile this program, the compiler shows the number of lines
compiled to be greater than 6. This is because during the preprocessing stage,
the include preprocessor directive searches the file iostream.h in the pre-
scribed list of directories and if the header file is found, the include directive
is replaced by the entire content of the header file. If the included header file
contains another include directive, it will also be processed. This processing
is carried out recursively till either no include directive remains or till
the maximum translation limit is achieved (ISO specifies a maximum of
15 nested levels of include files). Thus, one line of source code gets replaced
by multiple lines of the header file. During the compilation stage, these added
lines will also be compiled. Thus, the compiler shows the number of lines to be
greater than 6.

Some compilers enable the programmer to run only the preproces-


NOTE sor on the source program and to view the results of the preproces-
sor stage.

Please remember the following points regarding preprocessor


directives:

1. They are placed at the beginning of the program.


2. They start with a pound/hash (#) sign. This is its syntax (rule).
3. There is no semicolon at the end of these directives.
4. They can start in any column but usually start in column 1.
5. They tell the compiler to include the standard input/output library
file in the program. This library file prints a message onto the screen.
Printing is one of the input/output processes identified in this library.
6. The syntax of this command must be exact.
7. There is no space between the pound/hash sign and the reserved
keyword include.
Programming Using C • 37

8. It tells the preprocessor that you want the library file in angular
brackets (< >) to be included in your program. The name of this
header file is iostream.h. It stands for “Standard input/output header
stream file.”
9. The angular brackets tell the preprocessor to search for the file in
one or more standard directories. These directories contain header files
that are provided by the system and those commonly used by several
programmers (if the computer is a multiple-user machine).
10. Sometimes the brackets are replaced with double quotation marks as in
the following:
#include “iostream.h”
In this case the preprocessor will first look in the program-
mer’s own directory or the same one that contains the program
file. If it is NOT found there, then the standard directories are
searched.

11. The preprocessor can also add or delete C program statements.


12. A preprocessor symbol is never replaced if it occurs within single or
double quotation marks.
13. Header files also provide consistency among several program files.
Often a program is large and thus it is possible to break it into smaller
units, each of which is stored in a separate file. After these separate
program files are compiled, they must somehow be linked together to
form a single program. This linking is usually done by a program called
the linkage editor (which is run automatically when a program is
compiled).
14. A header file can contain other #include directives. Please note that
it cannot include itself because this would result in an infinite
recursion. Also note that it cannot include another file that
includes the first file as this would also result in an infinite
recursion.
15. Header files can contain any text at all. They may also contain C code
to define structure templates, global variables, or function definitions.
However, header files usually do not contain function definitions as it is
more efficient to store these in the function libraries set up by the user.
But global variables are sometimes included.
38 • C Programming

16. If iostream.h is included in the program, the macro versions (to be


discussed later) are used. On the other hand, if the programmer
wishes to use the function versions they can be undefined after the
#include<iostream.h> directive.
17. A preprocessor directive is terminated by the end of the line it oc-
cupies but if necessary it can be continued onto one or more lines by
ending all but the last line with backslashes.

Definition Section
In this section, we define a variable with some value in it. This is also known as a
special constant section. Here, a define statement is used. The general syntax
of a symbolic preprocessor or symbolic compiler directive can be defined using
the following #define statement:
#define name value
For example,
#define PI 3.1417
This initializes a variable PI with a value of 3.1417. But please remember
the following points regarding a #define preprocessor directive:

1. #define cannot be placed anywhere in a program.


2. The variables defined in these statements are symbolic constants and
therefore must be written in uppercase, preferably.
3. There is no semicolon at the end of a #define statement.
4. No spaces are allowed between # and define.
5. define should be written as define only and not as Define.
6. If PI is a symbolic name, as in our example, then we cannot make it a
variable also.
7. There is no equals (=) sign between PI and 3.1417.
8. Do not use special characters in these symbolic names.
9. You cannot concatenate these symbolic statements together (i.e., each
symbolic name must be declared on a separate line).
Random documents with unrelated
content Scribd suggests to you:
Friedel. (Boy of nine.) Very ragged coat and trousers. Bare feet. No
hat. (Should be a thin little fellow whose appearance may give the
touch of pathos.)
Old Marta. (May be taken by a boy, if preferred.) Poorly dressed, in
old shawl and hood, carrying a bundle of fagots. Face deeply
wrinkled and lined, with an ill-tempered expression.
Rich Johann. Velvet coat, flowered vest, full knee-breeches, shoes
with silver buckles. Broad-brimmed felt hat. Silver-headed cane. Is
very pompous.
Cross Jacob. Rough farm clothes, heavy boots.
Woodcutter. Fur cap, warm gloves, high boots. Carries an ax. Is
young, wholesome, rosy with work, and happy.
Star Child. (Child of seven or eight, who can sing.) White gown,
hanging straight from neck to ground, with flowing sleeves. Carries a
gold wand with a star on the end, and wears a star on the forehead.
If taken by a boy, he should wear a short white sleeveless tunic,
white stockings, and sandals.
Fritz and his sisters and brothers, children from twelve years down
to six, are dressed in ordinary outdoor winter costumes, with as
much as possible of bright color about them.
St. Nicholas differs somewhat from the accepted idea of Santa Claus,
being dignified, benign, and kindly, rather than lively and jolly.
Costume about the same,—long coat, high boots, fur cap, flowing
white beard.
Note for Snow Scene. If not feasible to have a winter scene for the
back drop, cover the back wall with white, and fasten drooping
branches of evergreen at sides, to suggest the limbs of trees just out
of sight. The wings may be treated in the same way,—or screens, if
given in home or schoolroom. Cover the floor with white, piling with
cushions beneath in some places to give an irregular surface, and to
make the bank (R. Center), where Friedel lies down. Four or five
evergreen trees will make an effective forest, and if quite small, they
should be raised to different heights, and banked about with white.
Leave opening between them (Back Center), in which the Star Child
should appear, coming and going very silently and slowly. Cotton
snow upon the little trees and "diamond-dust" over all, help to make
this a very pretty scene.
For chimes, play the music of the carol "Oh, Happy Night" on a
xylophone, behind the scenes.
TOINETTE AND THE ELVES
IN TWO ACTS

CHARACTERS

Mother.
Toinette, girl of twelve or fourteen.
Marie, girl of eleven.
Jeannette, little girl of five or six.
Pierre }
Boys of ten or eleven.
Marc }
The Elves:
Hollyberry }
Mistletoe }
Little boys of five or six.
Evergreen }
Icicle }
Hollyberry
TOINETTE AND THE ELVES
From the story by Susan Coolidge, St. Nicholas for January, 1876.

ACT I
Time: Christmas Eve.
Scene: The kitchen of a peasant cottage. Open fireplace[7] (R.) with
large pot, hung from a crane, or standing directly upon the logs. On
the shelf above, small bowls and spoons. Beside fireplace, a narrow
exit leading to Toinette's room: opposite, door to other rooms.
Outside door, R. Back. L. window. Down stage L. a low table with
small chairs, where the children sit for their supper, used later by the
Elves. Before the fire, a large old-fashioned wooden rocker.
Mother bends over sewing, near window, from time to time glancing
at Toinette, who sits dreamily gazing into the fire.

Mother. Toinette! [Toinette, absorbed in thought, apparently hears


nothing.] Toinette! Bless the child, is she asleep? Toinette!
Toinette [absently]. Yes, Mother.
Mother. Come, Toinette, it is time to brush the hearth and set the
kettle on to boil.
Toinette [without moving]. Yes'm, in a minute.
Mother [sharply]. Toinette, the dusk is coming. It is nearly supper-
time, and the candle must be lit. Come, brush the floor quickly, child.
Toinette [flinging impatiently out of her chair]. I hate to work!
[Sweeps slowly and absently, stopping to lean on her broom. Enter
Marie and Jeannette, with sewing and book, and sit down on low
chairs.]
Marie. Toinette, will you show me how to fasten this off?
Toinette [who has been leaning on her broom, begins suddenly to
sweep]. No, I won't. I'm busy sweeping.
Marie. Oh, I didn't know you were busy.
Toinette. What are your eyes for? Don't you see me sweeping?
Marie. Well, you were standing still, and I just thought——
Toinette [sweeping furiously]. You're always "just thinking" things.
Jeannette. I'm hungry, Mother.
Mother. Are you, dear?
Toinette [crossly, leaning on her broom]. She's always hungry. I
never saw such a little pig.
Marie [putting her arms indignantly around Jeannette]. No, she isn't at
all. You're very unkind, Toinette.
Mother. Hush, children. Don't quarrel. [Shakes her head sadly and
looks perplexed.]
[Enter Pierre and Marc, the latter with
knife and bits of wood. Marc sits down
against the fireplace, whittling. Pierre
lies at full length before the fire.
Jeannette. Will you tell us a story, Toinette?
Marie [gently]. Sh, dear, Toinette's busy, but I wish she would. She
can tell such lovely fairy stories when she likes to. And this is
Christmas Eve, Jeannette. Perhaps the fairies are out, looking for
good children. Fairies are always helping St. Nicholas; Toinette says
so. I wish she would get done sweeping.
Jeannette. When you get done, can't you tell just one story, Toinette?
Toinette. Oh, it's so hard to keep thinking up stories all the time.
There now, Marc, you horrid boy, just see how you've scattered
chips all over my clean floor. And, Pierre, your old shoes are just as
dirty as they can be. What's the use of my sweeping, Mother, when
the boys are so careless?
Mother. Try to remember to brush your shoes next time, Pierre. And,
Marc, it's better not to bring the whittling into the house.
Toinette. I should think as much.
Pierre [getting up]. I'm sorry I forgot, Mother. Come along, Marc,
we'll go out in the woodshed.
Marc [giving the chips a brush towards the fireplace with his cap and
then following Pierre]. It's pretty cold in the woodshed. [Looking
resentfully at Toinette.] I'd rather be cold than get scolded all the
time. [Exeunt boys.]
Mother [rises, lights candle, puts saucepan over the fire]. Now,
Toinette, I have other work to do. Finish brushing up [Toinette puts
down broom], and set the table. The porridge is over the fire and
will be done soon. If you would put your mind on it, daughter, and
work quickly, you would get done quickly, and the work would not
seem so hard. [Exit.]
Toinette [seizes a tablecloth and approaches the table]. Work
quickly! Marie, how ever can I set the table with you and Jeannette
in the way, I'd like to know?
Marie. We'll go in Mother's room, Toinette. [Takes Jeannette by the
hand. Exeunt.]
Toinette [covering table and slapping bowls and spoons pettishly
down upon it]. Work quickly! Don't I work and work all the time?
And I'm never done. The work seems hard because it is hard, that's
why. Oh, if we weren't so poor, and didn't have to work so hard!
[Relaxes her efforts and stands before the fire, dish in hand.] And if
we could have beautiful Christmas presents to-morrow, instead of
just—anything. [A very gentle knock at the door.] Oh, what was
that? [Opens.] The boys must be playing tricks on me. [Knocks
again.] Surely, there is someone there. [Opens door and steps
outside. Hollyberry slips in behind her and hides behind the door. Re-
enter Toinette.] It must be the fairies, I think. [Stands looking out.]
This is Christmas Eve and of course it's the right time for good fairies
to be about. How I wish I could see one!
Hollyberry. Do you, Toinette? Just open your eyes and you will, then.
Toinette [jumping, rubs her eyes and looks about]. Where? Oh,
where?
[Hollyberry comes from behind the door
and makes a low bow.
Toinette [clasping her hands with delight]. Oh, are you really a fairy?
Hollyberry [hands on hips]. Yes, I think I'm a pretty real sort of a
fairy. We elves have heard you talking about us and you always tell
what's true, so we like you.
Toinette. Oh, I'm so glad, because I love fairies. The children do too,
and they are always teasing me to tell them fairy tales.
Hollyberry. I am the leader of the band of elves. My name is
Hollyberry, and I've come with a message to you. I told you the
elves and fairies all like you. So we are going to give you a
Christmas present.
Toinette. Oh, oh! how kind you are.
Hollyberry [arms folded, nodding his head]. Yes, we are. Very kind.
But people don't always think so. Toinette, how would you like to be
invisible?
Toinette. Invisible? Oh, do you mean to go around wherever I like
without being seen? Oh, what fun!
Hollyberry. That's exactly what I mean. We can do it, at any time,
because we know how. But mortals like you can only do it on
Christmas Eve, and then only when we help them.
Toinette. Do you mean you are going to show me how?
Hollyberry. That's it. There are two things you must do. First you
must put fern seed in your shoes.
Toinette. Fern seed? Why, I didn't even know ferns had seeds. I
never saw any.
Hollyberry. Of course not. The elves take very good care of that.
Toinette. Where shall I get any?
Hollyberry. I'll attend to that. The second thing is to put on the Cloak
of Darkness.
Toinette. The Cloak of Darkness! What is that?
Hollyberry. Don't be impatient, Toinette. [Waves his holly wand and
snaps his fingers above his head. The door opens and the other
elves enter, carrying between them the gray cloak and a tiny bag.]
Elves [kneeling before Toinette and presenting bag and cloak]. Hail,
Toinette!
Hollyberry [touching the kneeling elves as he names them].
Evergreen and Mistletoe, present the magic Cloak of Darkness.
Icicle, yield the fairy fern seed. Now, Toinette, put a pinch of fern
seed in each shoe, wrap the cloak around you, and then,—well,
nobody but an elf can find you.
Mistletoe. The charm is only for to-night.
Hollyberry. And if you get tired of it before bedtime——
Evergreen. Take off the cloak——
Icicle. And empty your shoes——
Hollyberry. And, presto! Toinette is herself again. Now, farewell. [All
bow low and go to door.]
Icicle. Good-by.
Mistletoe. We'll take care of the cloak when you're done with it.
Evergreen. We hope you'll like our Christmas present.
[Exeunt elves, laughing mischievously.
Toinette [looking after them]. What cunning little fellows! Oh, what
fun. [Examines cloak.] I'll put it on right away. [Exit (R.).]
[Enter Mother (L.), going at once to the fire.
Mother. Why, where is Toinette? The porridge is almost boiling over.
Come, children,—Marie, Jeannette, boys. Supper is ready.
[Enter children and take their places at table.
Mother fills bowls from saucepan while
they talk.
Mother [calls]. Toinette, come to supper, daughter.
[Enter Toinette in cloak. All are unconscious
of her presence.
Mother [giving bread to children, who eat hungrily]. Where can
Toinette be? Boys, have you seen her?
Marc. No, Mother, she lets us alone when we keep out of her way.
Mother. For shame, Marc. Pierre, go call her,—she may be in her
room. [Pierre crosses the room, almost bumping into Toinette, who
stands in the way.]
Pierre [at door]. Toinette! Toinette! We're at supper. [A moment's
silence. Toinette giggles.] She isn't here, Mother.
Marie. I'm sure I heard her laughing.
Mother. Listen. [Toinette covers her mouth to stifle a laugh. Pierre
sits down again and eats.]
Toinette [aside]. This is such fun. But I'm hungry,—how am I going
to get anything to eat? [Goes close to the table and, watching her
chance, slips Marc's bread off the table and eats.]
Marc. Where's my bread? You took it, Pierre.
Pierre. I did not. Here's my own.
Marie. You must have dropped it on the floor.
Marc [looking under chair]. No, I didn't.
Marie. Well, you ate it, then.
Marc. I never. [Toinette laughs silently.]
Mother. Here's another piece. Never mind where that is gone. I only
wish Toinette had it. [Toinette nearly chokes.] The child must have
gone out. I will go to the gate and look down the road. [Exit.]
Jeannette. Poor Toinette's all gone.
Marc. Perhaps a bear has eaten her up.
Pierre. If he has, I mean to ask Mother if I can't have her room.
Marie. Marc, don't talk so, you'll frighten Jeannette.
Marc. Well, perhaps it's true.
Marie. Well, you know you'd be sorry if it was.
Pierre. I wouldn't be very sorry.
Marie [horrified]. Oh, you bad boy.
Pierre. Well, of course I don't want her to be hurt.
Marc. But we wouldn't care much if she didn't come back.
Marie. Boys, how can you be so naughty?
Pierre. But, Marie, Toinette never does a thing but scold us when
she's around.
Marie. She tells us beautiful fairy stories sometimes.
Marc. That's just it—"sometimes." You don't catch her doing it unless
she wants to.
Pierre. And she's just a regular old spoil-sport.
Marc. Oh, bother about Toinette. She'll come back a good deal
sooner than we want her. Can't you talk about anything else?
Marie [doubtfully]. Well, it is pleasanter when she isn't here, I know.
Pierre. Of course it is.
Marie. But I hope she's having a good time somewhere else.
[Throughout this conversation Toinette listens,
horrified at first, then angry, then
distressed; at one moment about to exclaim,
then starting forward to strike one
of the boys, and at last covering her face
with her hands and crying. Enter Mother.
Mother [anxiously]. Not a trace can I see of her. Children, have you
eaten your porridge? Marie, take Jeannette to bed. [Exeunt Marie
and Jeannette.] Boys, go out and cut some wood for our Christmas
fire. [Exeunt boys.] There will be no Christmas in this house unless
Toinette comes back soon. [Sits down in the rocker to warm herself.]
Dear, dear, she is a good girl, and a clever girl, but she is a sore
puzzle to me. What can make her so thoughtless and careless and
full of discontent? Why, even little Marie is a greater help to me than
she is.
[Exit Toinette in great distress. Mother
sits in silence. Enter Toinette without
cloak, throwing herself on her knees at her
mother's feet.
Toinette. Oh, Mother, Mother! [Buries her face in her mother's lap.]
Mother [trying to raise her]. Toinette, my child! Where have you
been all this time?
Toinette [with great excitement, half crying]. Oh, I've been here—
right here—all the time, only you couldn't see me.
Mother. Toinette!
Toinette. Yes, Mother, it's all true. I'll tell you. A fairy came and lent
me the Cloak of Darkness—and—and—I thought it would be such
fun, but it was horrid. And then the children—they said such cruel
things. Mother, don't they love me at all?
Mother. Mercy, mercy, what is all this about? Fairies—cloak of
darkness—the child must have a fever. [Feels Toinette's forehead and
takes her hand as if to count her pulse.]
Toinette. No, no! I'm not sick at all. But, Mother, don't you love me?
Mother [puts her arm about Toinette]. Love you, my child? Mother
always loves you.
Toinette. But you said I didn't help you. Oh, I wish the fairy had
never given me the cloak.
Mother. Fairies again! [Anxiously.] I must put the child to bed at
once. Stay by the fire, Toinette. I will get your bed ready. [Rises,
leaving Toinette seated on the floor by chair. Exit Mother.]
Toinette [slowly]. Mother thinks I dreamed it—or that I'm sick. But
I'm not. It's all true, it's all true. [Covers her face with her hands.]
How could the children be so unkind?... But perhaps I'm not always
kind to the children. The boys are so provoking—but then I needn't
scold them even if they are. And Marie must care a little, for she
hoped I was happy somewhere. Happy! How can I be happy? [Gazes
at the fire.] Perhaps if I began now, and tried and tried every day, I
could be kinder—to the children—and then they would love me more
—and I could try to help Mother—and then she needn't be so tired
all the time—— And surely, then I would be happy. [Brightly, facing
audience, hands clasped on one knee.] Yes, that's just what I'll do.
And now, perhaps I can help Mother this very minute—— I'll take
the candle up to her. [Jumps up, takes candle from table, pauses in
center of the stage.] It is Christmas—I do think that if I begin to-
morrow to try to be kind, I will surely succeed. Because Christmas is
the very best and happiest day in all the whole year. It was on
Christmas Day the angels first sang about Peace on earth, good will
to men.
CURTAIN

ACT II
Time: One year later. Christmas Eve.
Scene: Curtain rises showing Toinette and Marie seated, sewing;
Jeannette sits upon the floor, leaning against Toinette's knee; Marc
leans over the back of her chair; Pierre sits in the big chair rocking
and looking on. All are singing a Christmas carol. Enter Mother,
pausing a moment in doorway to watch and smile at the group.

Mother. Come, chickabiddies, it is time to stop work.


Marie [going to Mother]. Oh, Mother, must we stop now? Toinette
was just going to tell us the Christmas story about the Shepherds
and the Star in the East.
Mother. It is supper-time now, and Toinette must set the table.
[Exit.]
Pierre. And after supper comes bedtime. Oh, dear.
Toinette [cheerfully folding her work]. Never mind, Pierre, I'll tell it to
you to-morrow.
Marc. That'll be Christmas day, Toinette. I wish you could tell it on
Christmas Eve.
Toinette. Oh, I think I can tell it better on Christmas day, Marc. Now
we all have something to do,—let's get to work. Who will fetch water
for me to-night?
Marc and Pierre [springing for the pitcher]. I will, I will.
Marc. It's my turn, Pierre.
Pierre. No, you nearly always get water for Toinette. I'm going to.
Toinette. Let Pierre get the water, Marc, and you go and cut the
wood.
Marc and Pierre. All right, Toinette. [Exeunt.]
Marie. What can we do for you, Toinette, dear?
Toinette. Nothing just now, I think. [Toinette is spreading the cloth
and setting the bowls and spoons.]
Jeannette. But we want to help, too, dear Toinette. [Clings to her
skirt.]
Toinette. I'll tell you what. I'd rather send my two little helpers in to
see what they can do for poor busy Mother. She needs them more
than I do. [Exit Jeannette.]
Marie [following]. Won't that be helping you too, Toinette?
Toinette. Yes, dear. [Exit Marie.] How good the children are to-night!
I do think they are the best brothers and sisters a girl ever had.
[Lighting the candle.] And I think they love me more than they ever
used to. Oh, I'm so glad! [Tap at the door.] There is someone
knocking. [Goes to the door.]
Hollyberry [bowing low]. How do you do, Toinette? A Merry
Christmas to you.
Toinette. Oh, how wonderful. It's Hollyberry again, and I was just
thinking about you. Won't you come in?
Hollyberry. Just for a moment. [Enter Hollyberry. Toinette closes the
door.] I've brought you a Christmas present, Toinette. [Holds out
cloak and fern-seed bag.]
Toinette [retreating, hands behind her]. Oh, no, no, no! I know what
those are, and I don't want them. Oh! Hollyberry, they made me so
unhappy last year.
Hollyberry. You didn't like the elves' gift, then?
Toinette. Oh, it was horrid—I hated it.
Hollyberry [severely]. Do you call that being grateful?
Toinette [confused]. Oh, no—I mean, yes—that is, it was very kind of
you—but I didn't like it. Oh, dear!
Hollyberry [kindly]. Never mind, Toinette, I'm only teasing you now.
And I advise you to take the fern seed. You will like it better this
year, I'm sure.
Toinette [anxiously]. Truly?
Hollyberry. Truly. [Toinette takes bag and cloak.] And if you like it we
are going to ask a favor of you. We want you to make us some fern-
seed broth.
Toinette. Fern-seed broth?
Hollyberry. Yes, elves are very fond of it, but they don't get any very
often, because it has to be made over a fire, and you see we're
afraid of fire. We're so little and light, we might be blown in and
burned up.
Toinette. But how shall I make it?
Hollyberry. It's very easy. We'll show you how. And now, good-by.
We'll come in by and by when the children are in bed. [Exit with a
bow.]
Toinette [looking gravely at cloak and bag]. Oh, do I dare use them?
I have tried to be kinder—I know the children love me more—— Yes,
I will. [Runs out. Boys singing carol in the distance. Enter boys
singing, with pitcher and wood. Enter Mother, Marie, and Jeannette.]
Mother. Why, the supper is all ready, but where is that busy bee of
ours, Toinette? [Goes to door as if to call.]
Pierre [catches her arm]. Oh, Mother, wait a moment; don't call her
yet! You know we've made her some Christmas gifts, and we want
to put them on her plate and surprise her.
Mother. Run and get them.
Marc [under his breath]. Hurry, quick, everybody.
[Exit children in haste. Mother takes saucepan
from fire and fills bowls. Enter children
singing carol, each bearing a homemade
gift. They place the presents about
Toinette's place, and all take their places
at the table, sitting with folded hands until
hymn is ended. During the singing Toinette
enters, dressed in cloak, and stands
near door (R.), her hands clasped in
pleasure at the sight.
Marc [looking towards the door]. Oh, I wish Toinette would hurry.
Marie. Won't she be surprised?
Pierre. And won't she look jolly surprised, too? I love to see Toinette
when she's surprised. Her eyes get so big and shiny, and she just
stares.
Marc. Andrew, the blacksmith's son, thinks his sister is prettier than
our Toinette, but I don't.
Pierre [in great scorn]. Aw! I should think not. Our Toinette is just
the prettiest girl in the village.
Marie. And the very nicest, too!
Mother [smiling]. And Toinette is Mother's right hand. We all love
Toinette! Don't we?
Toinette [softly]. Oh, the dear little things! I can't wait a minute
longer. [Exit quickly.]
Children [calling]. Toinette! Toinette! [Enter Toinette without cloak.
Shows great surprise.]
Children. Merry Christmas, Merry Christmas, Toinette!
Toinette. Oh, oh! what do I see? [Sits down in her place.] Oh, did
you make these lovely things, children?
Pierre. Yes, mademoiselle, we did!
Marc. Every one of them.
Marie. Nobody helped us.
Jeannette. All for you, Toinette, all for you! [Leaves her chair and
throws her arms around Toinette.]
Toinette [kissing her]. Oh, thank you, thank you! How beautifully
these are made. [Looks them over one at a time.] How good
everyone is. I'm so happy I don't know what to do.
Pierre. And to-morrow's Christmas! Hurrah!
Mother. Yes, dear, but if you don't go to bed and to sleep, Christmas
won't come. [Takes Jeannette by the hand.] We will leave you to
finish, Toinette.
Children. Good-night, Toinette!
Toinette. Good-night, everyone! [Marie and Jeannette throw their arms
about Toinette.]
Marie. Good-night again, dear Toinette! [Exeunt all but Toinette, who
clears the table, shakes off crumbs, and sets fresh bowls and
spoons. The children are heard singing carol. When all is ready and
the song is done, Toinette goes to outer door and looks out. After a
moment the elves rush in.]
Elves. Here we are, Toinette, here we are!
Hollyberry. Now let's proceed to business. Where is the saucepan,
Toinette! Icicle, give me the honey-dew; Mistletoe, you have the fern
seed.
[Toinette produces the saucepan and the
elves crowd around her and hand her the
articles named. The honey-dew is supposed
to be in a jar—or pitcher—or anything
curious or unusual in appearance;
the fern seed in a quaint box.
Hollyberry. Now, Evergreen, give me the holly stick she must stir it
with.
[Toinette puts it on the fire, the elves watching
with great interest.
Hollyberry. It's very simple, but it must be made with great care.
Mistletoe. You must always stir it the same way!
Evergreen. Or else it will curdle.
Icicle. And you must never let it scorch!
[Toinette bends over fire, stirring broth. A
very gay waltz in very quick time is played
softly outside, and the four elves dance and
tumble about, coming up one at a time to
peep over Toinette's shoulder. They
show great fear of the fire, however.
Toinette. Now, little Elves, the feast is ready!
Elves. Oh, joy! Oh, joy! [All seat themselves at table, Toinette pours
out broth, and they eat. Music continues, Toinette refills bowls, and
elves drink from them, tipping their heads far back and making
grotesque motions. Music grows fainter. Elves rise and bow to
Toinette.]
Elves. Thank you, Toinette! Thank you!
Evergreen. We've had a merry feast.
Mistletoe. And fairies are never ungrateful.
Icicle. When you need us, you'll find us ready.
[Evergreen, Mistletoe, and Icicle go outside
and stand about door. Hollyberry
remains within.
Toinette. But I haven't thanked you at all!
Hollyberry. No need of that, Toinette. [He brushes door-post with his
holly wand.] Be lucky, house! We are the luck-bringers, and we have
feasted here! [Touches Toinette on the head and hands.] Be lucky,
Toinette! Good temper, and kindness, and unselfishness are the very
best good luck, after all. Now, good-by!
Elves. Good-by, good-by! Merry Christmas to all!
[Exeunt. Toinette closes the door and goes
slowly to hearth, where she sits down on
floor, resting her arm on a chair and her
head on her hand.
Toinette [softly]. The fairies have been here, and they have taught
me a lesson.... After all, it isn't the fairies who make the children
love me, or me love the children.... I think—yes, I'm sure—that it is
Christmas that makes us all love each other!
[Her head drops, and she falls asleep. The
children's voices are heard, singing, very
softly and distinctly, the last verse of the carol:

"Thank God on Christmas morning!


Thank God, O children dear."

CURTAIN

NOTES ON COSTUME AND SETTING


The children are dressed in peasant costumes, the girls in bright
skirts and stockings, white guimpes, black velvet bodices, and
Normandy caps; the boys in full trousers, bright stockings, vests of
green or blue, fastening in the back, white shirts with full sleeves,
and toboggan caps. Toinette wears shoes with buckles; the others
may wear the same, or sabots.
Mother. Plain dark dress, with full skirt; kerchief on her shoulders,
and a white cap.
The magic "Cloak of Darkness" brought by the Elves for Toinette, is a
long cape, with hood attached, made of light gray canton flannel.
The Fern-seed Bag may be made of a bit of the same material, or of
the colors of Hollyberry's costume.
The Elves wear harlequin costumes in two shades of the same color,
with tall pointed hoods, and long shoes with toes turned up. Gilt
bells on all points of collar, jacket, and hood. See illustration. Sateen
is perhaps the best material for these little suits, as it comes in a
great variety of rich shades, but cheaper goods may be found.
Hollyberry. Dark red and scarlet. He carries a holly branch in lieu of a
wand.
Mistletoe. Brown and yellow. In Act II he carries an odd box
supposed to be full of fern seed.
Evergreen. Dark and light green. In Act II he produces the holly stick
for stirring the broth.
Icicle. Dark and light blue. In Act II he carries a small jar or pitcher,
—something curious or unusual in appearance,—which is supposed
to contain the honey-dew.
Instead of the gilt bells, the points of these suits may be trimmed
with bits of holly, mistletoe, evergreen, and glass icicles, as indicated
by the names.
In setting the stage, it is effective to make small windows, with
diamond-shaped panes, and white sash-curtains, placing small pots
of scarlet geraniums on the sills.
The song is "Good News on Christmas Morning," from St. Nicholas
Songs (Century Company).
Where music is indicated through the play, any part of the carol is
sung, except the last verse, which is used only once, just before the
last curtain. For the Elves' dance, the Pizzicato from the ballet
"Sylvia" by Delibes, Dvorak's "Humoresque," or a waltz, very lightly
played, may be used.
TOM’S PLAN
IN TWO ACTS

CHARACTERS

Father Wright.
Mother Wright.
Phil }
Daisy }
Charlie } The little Wrights.
Tom }
Dot }
Sarah, the nurse.
Santa Claus.
TOM’S PLAN
ACT I
Time: Christmas Eve.
Scene: Nursery or sitting-room, children sitting about, each working
upon a Christmas gift. Nurse at one side with her work-basket. All
singing a Christmas carol.[8]

Daisy. I just can't believe that to-morrow really will be Christmas!...


What do you think of that for a book-mark? [Holds it up.] Don't you
suppose Papa will be pleased?
Phil [driving a last nail into a bootjack]. Papa says he can't get his
new boots off. If he can't do it now, with this, I'm sure he never will
be able to. Isn't that fine?
Sarah. Sure, Master Phil, he'll be wantin' a new house to kape that
big thing in!
Daisy. Now, Sarah, you mustn't say that! You know Papa always likes
the things we make for him.
Dot [crossing to Sarah]. Sarah, please fasten my thread.... Now, my
spectacle-wiper is done. Oh, boys, don't you wish it was to-morrow
morning!
Tom. You bet! I'm going to do Papa's knife up in a great big bundle,
so he'll think it's a pair of slippers or a book, anyway, and see how
surprised he'll be.
Charlie [clapping his hands]. What fun! Say, Tom, don't you wish we
could see Santa Claus?
Phil. Let's try and stay awake all night.
Dot. No! you bad boys! Santa Claus doesn't like to have children see
him when he comes to put things in the stockings.
Daisy. No, of course he doesn't. And, besides, Mamma has a better
way. She told me to ask you all whether you would rather hang your
stockings this year, or get Santa Claus to come and bring us a tree.
Charlie. Oh, jolly! But how is Santa Claus going to know in time?
Phil. That's what I'd like to know.
Daisy. I asked Papa that, and he said, Oh, he guessed he could
telegraph.
Tom. Then do let's have him come here!
Children. Oh, yes, let's!
Dot. I want to thank him for my dolly's bed that he brought last year.
Daisy. Well, I'll go tell Mamma. [Exit.]
Sarah. Ye'd all better come down and wrap up yer things now.
Phil. All right. Come along. [Exeunt all but Tom.]
Tom. I'll be along in a minute. [Looks up chimney.] I'm so glad Santa
Claus is coming this year. [Crosses to front of stage and sits astride a
small chair with its back to audience.] There are so many things I
want to know about him. I'm just going to count. [Checks off on his
fingers.] First, I want to know where he lives. Daisy says he lives at
the North Pole, and she's got a picture of his house, with icicles and
snow all over it. But then he always brings us oranges and bananas
and nuts and figs, and I know they don't grow at the North Pole. I
wish I could find out. Next, what he feeds the reindeer on. Next,
how he ever gets all the things into the sleigh. How fast the reindeer
can go. And whether they ever get balky. He'd be late all the time if
they did. Horses do, but perhaps reindeer are different. But the one
thing I'd rather know than all the others put together, is just this:
Sarah said, the other day when I took a bite out of one of her hot
pies, that Santa Claus [very slowly and impressively] would put a
whip in my stocking! Now I wonder if he would do that? [Thinks
awhile, then shakes his head.] No, no! I don't believe he would. He's
always smiling in his pictures, and he looks so jolly. And then, if
anybody wanted to spend all his time giving presents, like Santa
Claus, I don't believe he would ever put ashes or whips in anybody's
stocking, just because he forgot the pie was for company.... Oh,
dear! I wish I did know. [Jumps up suddenly, puts one knee on the
chair, and holds on to the back with both hands.] Oh! Oh! I've got
such a splendid plan! It'll be easy enough to find out, after all. I
don't really want anything for Christmas this year ... 'cept maybe a
sled, and ... well, I guess Phil will let me coast on his sled. Now, I'm
going to be just as cross, as cross as a bear, to-night and see if
Santa Claus will give me a whip. I don't care—I know he won't!
Anyway, Mamma never lets anybody whip me—only Papa—and if
Santa Claus wants me whipped he'll have to give the whip to Papa.
There! I hear somebody coming. I'm just going to begin right off.
Charlie [calling, without]. Tom, Tom! Aren't you coming to wrap up
your things?
Tom [very crossly]. No!
Charlie [much surprised]. Why not?
Tom. Don't want to. [Chuckles.] He sounded rather surprised. I guess
they won't know what to make of it. It'll be such fun! [Sits astride
chair again.] Here comes somebody else. I won't look around. [Puts
his head down on his arms. Enter Dot.]
Dot. Tom!
Tom. What do you want?
Dot [timidly]. What's the matter, Tom?
Tom. Ain't nothing the matter.
Dot [aside]. Oh, dear! Tom, do you want me to wrap up the knife for
you?
Tom. Can if you want to. Here. [Takes it from his pocket and hands it
to her without looking up.]
Dot [aside]. What can be the matter? We can't any of us be happy if
Tom isn't. [Exit, putting her handkerchief to her eyes.]
Tom [looking after her]. 'Tisn't so much fun as I thought. [Puts his
head down. Enter Sarah.]
Sarah [hands on hips, looking at Tom]. Well, what 'ud be the trouble
here? [Goes about, putting things to rights. Dusts chair, giving Tom a
brush.]
Tom [hits out at her]. Go 'way!
Sarah. Oh, is that yerself?
Tom. Yes, it's meself.
Sarah. Well, what's the matter wid yerself?
Tom. Never you mind what! [The other children run in.]
Daisy. Oh, Sarah, Sarah, give us our coats, quick! Papa says he'll
take us along Fourth Street, to see the shop windows lighted up!
Charlie. Do hurry, Sarah!
Daisy. I can't find my mittens!
Dot [softly, nudging Phil]. Phil, tell Tom to come.
Phil. Come along, Tom, and be quick!
Tom. Won't.
Phil. You won't?
Charlie. Why not?
Tom. Don't want to.
Charlie. Well, then, don't! Come on, Dot! [Takes her by the arm, and
leads her out. Phil and Daisy look at Tom.]
Daisy. Please come, Tom.
Tom. I tell you I won't.
Daisy. We'll have such fun.
Tom. Well, you can have it for all me.
Phil. See here, Tom, don't be a donkey! Come along! [Takes him by
the arm.]
Tom [shakes him off]. Get out!
Daisy. Well, I suppose we'll have to go without him. Papa is waiting.
[They start.] Phil, what is the matter with Tom?
Phil. I don't know. Dot said he was cross——
[Exeunt.
Sarah. Ye'd betther remember what I was a-tellin' ye, Master Tom. Ye
gettin' ready for the stick?
Tom. You be still and clear out, Sarah!
Sarah. Oh, I'm a-goin'—I'm a-goin'! Shall I tell Santa Claus to make it
out of rattan, Master Tom?
Tom. Go on out, I say! [Chases her out.] Well, it's some fun to be
cross to Sarah, but I really don't like to be cross to Dot and the
others. Oh, dear! I wish I didn't have to. [Sees Sarah's dust-cloth,
which he rolls into a wad and tucks into a cap lying on one of the
chairs.] He-he! that'll fix her. Now she can't find it. [Enter Sarah. Tom
sits down by the fire, holding his knee.] What do you want?
Sarah. Oh, my clearin'-up's not done yet! I declare, if I've redd up
this room once, I've done it forty times this day. [Straightens things,
then looks for her duster. Tom watches slyly.] Did I take that cloth
downstairs wid me? Sure, I know I didn't. Where did I put it, then?
'Tain't here annywheres. Maybe that little squirrel hid it. Seen my
duster, Tom?
Tom. No, I don't see your duster.
Sarah. Did I ax ye if ye saw it now? I said, have ye sane it?
Tom. And I said I didn't see it.
Sarah. Well, ye little fox, I know yer tricks, and I'll find it yet. Them
as hides, finds, but sometimes other folks can find, too, when they
know who did the hiding. Ah! what did I tell ye! I've got it at last. I
knew ye put it somewheres. Now I can get my work done.
Tom. Well, don't you bother me.
Sarah [stands with hands on hips, looking at Tom, who scowls at
her]. If I were you, I wouldn't scowl like that, Master Tom; yer
furhead might stay that way.
Tom. If I were you, I wouldn't either.
Sarah. Ye don't look a bit pretty, Master Tom.
Tom. You don't have to look at me.
Sarah. See, this is what ye look like. [Makes a face and hunches up
her shoulders. Tom refuses to look.] Do ye think that's rale
handsome? [Aside.] Well, since I can't t'ase ye into a good humor,
I'll go on down.
[Exit.
Tom. I did want to laugh at her awfully. If she comes in again, I think
I'll just have to.
[Enter Daisy and Phil.
Daisy. We didn't go far, because it was so late. Phil, did you ever see
anything so perfectly grand as that last window? [Taking off things.]
Phil. Never! Don't I wish I had that air-rifle!
Daisy. I'd rather have the doll's piano than anything else.
[Enter Sarah with Dot and Charlie.
Sarah takes children's coats, etc.
Sarah. Here, give me yer coats. Now just sit down and get warm for
a minute, and then ye've got to go to bed. Yer Ma said so.
Daisy. Let's sing while we're here. We don't know our new carol very
well. [All begin to sing a carol. Tom claps, stamps, whistles, and
bangs his chair up and down, to put them out. They stop.]
Charlie. See here, Tom, if you don't want to sing, you don't have to,
but you shan't stop us!
Sarah. No, sir! That ye shall not. Ye can't stay here makin'
disturbances, so just be off with ye to bed. [Pushes him out.
Children sing a carol, and curtain falls during last verse.]
CURTAIN

ACT II
Time: Christmas morning.
Scene: Sitting-room with open fire [back Center] in fireplace through
which Santa Claus may enter. Father and Mother sitting by fire, Father
with paper, Mother sewing. Phil and Charlie in one corner [R. Front],
reading together. Daisy and Dot [L. Front] with dolls.
Daisy. And I caught Mamma! I hid behind the door, and jumped out
and shouted "Merry Christmas!" before she saw me at all.
Dot [leaning towards Daisy]. Daisy, let's say it to Santa Claus.
Daisy. Oh, do you suppose he would like it?
Dot. Why not?
Daisy. Yes, I guess he would. Dear Santa Claus, nobody ever thinks
of saying "Merry Christmas" to him.
Dot. Poor man! Well, Daisy, his little boys and girls might say it to
him.
Daisy. Oh, Dot! He hasn't any little boys and girls to say it. Don't you
know he's an old man, oh, hundreds of years old? And if he ever did
have any little boys and girls, they're all grown up by this time.
Dot. Maybe he's got some grandchildren.
Daisy. No, I don't believe he has, for then why do they let him do all
the work? Nobody ever fills stockings but Santa Claus.
Dot. Poor Santa Claus! He must get very tired.
Daisy. I wonder ... I wonder who keeps house for Santa Claus?
Dot. Maybe nobody does.
Daisy. Oh, yes! He must have somebody to make his fires, and cook
his meals, and darn his socks.
Dot. Why, he doesn't wear socks. Don't you know, he's all dressed in
fur in the pictures. But perhaps fur wears out and has to be mended.
I'd like to help her do it.
Daisy. Perhaps she's a real cross, ugly woman, and scolds him when
he stays out too long filling stockings, and doesn't give him enough
sugar in his tea, and never lets him have but one cup!
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like