100% found this document useful (8 votes)
16 views

Programming in Objective C 1st Edition by Stephen Kochan 067248420X 9780672484209 download

The document provides information about various programming books available for download, including titles by Stephen Kochan and others. It highlights the importance of learning programming through examples and emphasizes the structured approach to teaching the C programming language. Additionally, it discusses the evolution of the C language and its relationship with UNIX operating systems.

Uploaded by

sanyabasma5b
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
100% found this document useful (8 votes)
16 views

Programming in Objective C 1st Edition by Stephen Kochan 067248420X 9780672484209 download

The document provides information about various programming books available for download, including titles by Stephen Kochan and others. It highlights the importance of learning programming through examples and emphasizes the structured approach to teaching the C programming language. Additionally, it discusses the evolution of the C language and its relationship with UNIX operating systems.

Uploaded by

sanyabasma5b
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/ 77

Programming in Objective C 1st Edition by

Stephen Kochan 067248420X 9780672484209 pdf


download

https://ebookball.com/product/programming-in-objective-c-1st-
edition-by-stephen-kochan-067248420x-9780672484209-15258/

Explore and download more ebooks or textbooks


at ebookball.com
Get Your Digital Files Instantly: PDF, ePub, MOBI and More
Quick Digital Downloads: PDF, ePub, MOBI and Other Formats

Programming in C 4th edition by Stephen Kochan 9780132781190


0132781190

https://ebookball.com/product/programming-in-c-4th-edition-by-
stephen-kochan-9780132781190-0132781190-15230/

C++ Common Knowledge Essential Intermediate Programming 1st Edition by


Stephen Dewhurst ISBN 0321321928 9780321321923

https://ebookball.com/product/c-common-knowledge-essential-
intermediate-programming-1st-edition-by-stephen-dewhurst-
isbn-0321321928-9780321321923-12370/

Learn Objective C for Java Deve 1st edition by James Bucanek


9781430223702, 1430223707

https://ebookball.com/product/learn-objective-c-for-java-
deve-1st-edition-by-james-bucanek-9781430223702-1430223707-8822/

C Programming in Linux 1st Edition by David Haskins 9788776814724

https://ebookball.com/product/c-programming-in-linux-1st-edition-
by-david-haskins-9788776814724-15294/
Memory as a Programming Concept in C and C 1st Edition by Frantisek
Franek isbn 0521520436 9780521520430

https://ebookball.com/product/memory-as-a-programming-concept-in-
c-and-c-1st-edition-by-frantisek-franek-
isbn-0521520436-9780521520430-12552/

Memory as a Programming Concept in C and C 1st Edition by Frantisek


Franek ISBN 051183862X 9780511838620

https://ebookball.com/product/memory-as-a-programming-concept-in-
c-and-c-1st-edition-by-frantisek-franek-
isbn-051183862x-9780511838620-14982/

Functional Programming in C 1st Edition by Enrico Buonanno ISBN


9781638354048 1638354049

https://ebookball.com/product/functional-programming-in-c-1st-
edition-by-enrico-buonanno-isbn-9781638354048-1638354049-15788/

Object oriented programming in C 1st Edition by Nabajyoti Barkakati


0672228009 9780672228001

https://ebookball.com/product/object-oriented-programming-
in-c-1st-edition-by-nabajyoti-
barkakati-0672228009-9780672228001-15280/

Object Oriented Programming in C 4th Edition by Robert Lafore


0672323087 9780672323089

https://ebookball.com/product/object-oriented-programming-
in-c-4th-edition-by-robert-lafore-0672323087-9780672323089-16228/
PROGRAMMING IN

STEPHEN G.KOCHAN

[(]
HAYDEN BOOK COMPAN'(, INC.
Hasbrouck Heights, New Jersey

- --~
.- .".
- .-
r

AcquisUions Editor: DOUGLAS McCORMICK


Production Editor: MAUREEN CONNELLY
Art Director: JIM BERNARD
Cover Design: JEANNETTE JACOBS
Compositor: McFARLAND GRAPHICS & DESIGN INC.
Printed and bound by: HAMILTON PRINTING Co.

Copyright @ 1983 by Stephen G. Kochan. All rights reserved. No part of this


book may be reprinted, or reproduced, or utilized in any form or by any
electronic, mechanical, or other means, now known or hereafter invented,
including photocopying and recording, or in any information storage and
retrieval system, without permission in writing from the Publisher.
Printed in the United States of America

2 3 4 5 6 7 8 9 PRINTING
83 84 85 86 87 88 89 90 91 YEAR
To my mother

I
r~--------"""""'-------"""""'--------"""""'----------
;"1

I wish to thank the following people for their help in the preparation of
this book: Doug McCormick and Maureen Connelly of Hayden Book Com-
pany, Jim Scharf, Tony lannino, Henry Tabickman, and especially Ken
Brown. Ken and I spent many hours discussing various approaches and
ideas, and he was also kind enough to edit the entire text. For this I am
sincerely grateful.
I also wish to thank Henry Mullish of New York University for getting me
started in the publishing business.
Undertaking a project such as this places an equal if not greater burden
on the people closest to you. My wife, Leela, provided her patience and under-
standing. But above all she provided her love.

Stephen G. Kochan
(
c 0 N T E N TS
• • • • };
• • • •
1
,
J
{~
.

1 Introduction • 1
2 Some Fundamentals • 4
3 Writing a Program in C • 10
4 Variables. Constants, Data Types, and Arithmetic
Expressions • 17
5 Program Looping • 34
6 Making Decisions • 53
7 Arrays • 80
B Functions • 99
9 Structures • 138
10 Character Strings • 162
11 Pointers • 196 j
12 Operations on Bits • 234
13 The Preprocessor • 254
14 More on Data Types • ;271
15 Working with Larger Programs • 279
16 Input and Output • 285
17 Miscellaneous Features ~nd Advanced Topics • 308
Appendix A Language Summary • 321
AppendixB Common Programming Mistakes • 351
AppendixC The UNIXC Library • 355
AppendixD Compiling Programs un~er UNIX • 363
AppendixE The Program LINT • 367
AppendixF The ASCn Character Set e. 368
Index • 369
r
c H A p T E R
• • • • • •
1

INTRODUCTION

The "C" programming language evolved from a succession of programming


languages developed at Bell Laboratories in the early 1970s. It was not until the
late 1970s, however, that this programming language began to gain
widespread popularity and support. This was because until that time C
compilers were not readily available for commercial use outside of Bell
Laboratories. Furthermore, C's growth in popularity has been spurred in
part by the equal, if not faster, growth in popularity of the UNIX! operating
system. This operating system, which was also developed at Bell Laboratories,
has C as its "standard" programming language. In fact, well over 90 percent of
the operating system itself is written in the C language!
C is a so-called "higher-level language," yet it provides capabilities that
enable the user to "get in close" with the hardware and deal with the computer
on a much lower level. This is because, while the C language is a general
purpose structured programming language, it was designed with systems
programming applications in mind and, as such, provides the user with an
enormous amount of power and flexibility. In fact, programming applications
exist that could be easily handled by the C language but that would be difficult,
if not impossible, to develop in other languages such as Pascal, FORTRAN, or
BASIC.
This book proposes to teach you how to program in C. It assumes no
previous exposure to the language whatsoever and was designed to appeal to
both the novice and experienced programmer alike. If you have previous
programming experience, then you will find that C has a unique way of doing
things that will probably differ significantly from any language you have used.
Even if you are coming from a Pascal background-a language that C
superficially resembles-you will quickly discover that there are many
features that are unique to this language, such as pointers, character strings,
and bit operations.
Every feature of the C language is treated in this text. As each new feature
is presented, a small complete program example is usually provided to

I UNIX is a registered trademark of Bell Laboratories.

. ., .
2 o PROGRAMMING IN C 0

illustrate the feature. This reflects the overriding philosophy that has been
used in writing this book: to teach by example. Just as a picture is worth a
thousand words, so is a properly chosen program example. If you have access
to a computer facility that supports the C programming language, then you are
strongly encouraged to enter and run each program that is presented in this
book, and to compare the results obtained on your system to those shown in
the text. By doing so not only will you learn the language and its syntax, but you
will also become familiar with the process of typing in, compiling, and running
C programs.
The style that is used for teaching the C language is one of posing a
particular problem for solution on a computer and then proceeding to develop
a program in C to solve the problem. In this manner, new language constructs
are introduced as they are needed to solve a particular problem.
You will find that program readability has been stressed throughout the
book. This is because I strongly believe that programs should be written so that
they may be easily read-either by the author himself or by somebody else.
Through experience and common sense you will find that such programs are
almost always easier to write, debug, and modify. Furthermore, developing
programs that are readable is a natural result of a true adherence to a
structured programming discipline.
Because this book was written as a tutorial, the material covered in
each chapter is based on previously presented material. Therefore, maximum
benefit will be derived from this book by reading each chapter in succession,
and you are highly discouraged from "skipping around." You should also work
through the exercises that are presented at the end of each chapter before
proceeding to the next chapter.
Chapter 2, which covers some fundamental terminology about higher-
level programming languages and the process of compiling programs, has
been included to make sure that we are speaking the same language
throughout the remainder of the text. From Chapter 3 on, you will be slowly
introduced to the C language. By the time Chapter 16 rolls around, all of the
essential features of the language will have been covered. Chapter 16 goes into
more depth about input! output (I/O) operations in C. Finally, Chapter 17
includes those features of the language that are of a more advanced or esoteric
nature.
Appendix A provides a summary of the syntax of the language, among
other things, and is provided for reference purposes. A comprehensive index is
also provided so that you may quickly find explanations and program
examples of particular C language features.
This book makes no assumptions about a particular computer system or
operating system on which the C language is implemented. However, since C is
most often found running under the UNIX operating system, special attention
is given to using C under UNIX. The text describes how to compile and execute
programs under UNIX, and the Appendix provides a summary of many of the
UNIX runtime library routines, as well as a description of the cc command and
the program lint.
o Introduction 0 3

If you are using a C compiler under an operating system other than UNIX,
then you may find slight anomalies exist between the C language at your
installation and the language described in the text. This is because as of this
writing there exists no standard definition for the C language.
c H A p T E R
• • • • • •
2

SOME FUNDAMENTALS

This chapter describes some fundamental terms that you must understand
before you learn how to program in C. A general overview of the nature of
programming in a higher-level language is provided, as is a discussion of the
process of compiling a program developed in such a language.

• Programming •
Computers are really very dumb machines indeed, since they do only what
they are told to do. Most computer systems perform their operations on a very
primitive level. For example, most computers know how to add 1to a number,
or how to test if a number is equal to zero or not. The sophistication of these
basic operations usually does not go much further than that. The basic
operations of a computer system form what is known as the computer's
instruction set. Some computers have very limited instruction sets. For
example, the DEC PDP-8 computer has just a handful of instructions, while the
DEC VAX machines contain instruction sets consisting of hundreds of basic
operations.
In order to solve a problem using a computer, we must express the
solution to the problem in terms of the instructions of the particular
computer. A computer program is actually just a collection of the instructions
necessary to solve a specific problem. The approach or method that is used to
solve the problem is known as an algorithm For example, if we wish to develop
a program that tests if a number is odd or even, then the set of statements
that solves the problem becomes the program. The method that is used to test
if the number is even or odd is the algorithm. Normally, to develop a program
to solve a particular problem, we first express the solution to the problem in
terms of an algorithm and then develop a program that implements that
algorithm. So the algorithm for solving the even! odd problem might be
expressed as follows: "First divide the number by two. If the remainder of the
division is zero then the number is even; otherwise the number is odd." With
the algorithm in hand, we can then proceed to write the instructions necessary

• 4 •
o Some Fundamentals 0 5

to implement the algorithm on a particular computer system. These


instructions would be expressed in the statements of a particular computer
language, such as BASIC, Pascal, or C.

• Higher-Level Languages •
When computers were first developed, the only way they could be
programmed was in terms of binary numbers that corresponded directly to
specific machine instructions and locations in the computer's memory. The
next technological software advance occurred in the development of
assembly languages, which enabled the programmer to work with the
machine on a slightly higher level. Instead of having to specify sequences of
binary numbers to carry out particular tasks, the assembly language permits
the programmer to use symbolic names to perform various operations and to
refer to specific memory locations. A special program, known as an assembler,
translates the assembly language program from its symbolic format into the
specific machine instructions of the computer system.
Because there still exists a one-to-one correspondence between each
assembly language statement and a specific machine instruction, assembly
languages are regarded as low-level languages. The programmer must still
learn the instruction set of the particular computer system in order to write a
program in assembly language, and the resulting program is not transportable;
that is, the program will not run on a different computer model without being
rewritten. This is because different computer systems have different
instruction sets, and since assembly language programs are written in terms of
these instruction sets, they are machine dependent.
Then, along came the so-called higher-level languages, of which
FORTRAN was one of the first. Programmers developing programs in
FORTRAN no longer had to concern themselves with the architecture of the
particular computer, and operations performed in FORTRAN were of a much
more sophisticated or "higher level," far removed from the instruction set of
the particular machine. One FORTRAN instruction or statement would result
in many different machine instructions being executed, unlike the one-to-one
correspondence found between assembly language statements and machine
instructions.
Standardization of the syntax of a higher-level language meant that a
program could be written in the language to be machine independent. That is, a
program could be run on any machine that supported the language with little
or no changes.
In order to support a higher-level language, a special computer program
must be developed that translates the statements of the program developed in
the higher-level language into a form that the computer can understand-in
other words, into the particular instructions of the computer. Such a program
is known as a compiler.
6 o PROGRAMMING IN C 0

· Operating Systems ·
Before we proceed with our discussion of compilers, it is worthwhile
discussing the role that is played by a computer program known as an
operating system. An operating system is a program that controls the entire
operation of a computer system. All 110 operations that are performed on a
computer system are channeled through the operating system. The operating
system must also manage the computer system's resources, and must handle
the execution of programs.
One of the most popular operating systems today is the UNIX operating
system, which was developed at Bell Laboratories. UNIX is a rather unusual
operating system in that it can be found on many different types of computer
systems. Historically, operating systems were typically associated with only
one type of computer system. But because UNIX is written primarily in the C
language and makes very few assumptions about the architecture of the
computer, it has been successfully transported to many different computer
systems with a relatively small amount of effort.

· Compiling Programs ·
A compiler is a software program that is in principle no different from the ones
you will be seeing in this book, although it is certainly much more
complex. A compiler 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.
Figure 2-1 shows the steps that are involved in entering, compiling,
and executing a computer program developed in the C programming
language.
The program that is to be compiled is first typed into a file on the
computer system. Computer installations have various conventions that are
used for naming files, but in general, the choice of the name is up to you. Under
UNIX, C programs can be given any name provided the last two characters are
'.c'. So the name program.c would be a valid file name for a C program running
under UNIX.
To enter the C program into a file, the use of a text editor is usually
required. The editor ed is most commonly used for entering programs under
UNIX. In order to be able to try the programs presented in this book, you will
first have to learn how to use such an editor. Check with someone at your
installation for getting help and the appropriate documentation for using the
locally available text editor.
The program that is entered into the file is known as the source program,
since it represents the original form of the program expressed in the C
language. Once the source program has been entered into a file, we can then
have it compiled.
o Some Fundamentals 0 7

UNIX
COMMAND

ed

cc

a.out

Done

Fig. 2-1. The process of entering, compiling, and executing a C program


(showing typical UNIXcommands).
B o PROGRAMMING IN C 0

The compilation process is initiated by typing in 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, under UNIX, the
command to initiate program compilation is called cc. Typing the line
cc prograM.c

would have the effect of initiating the compilation process with the source
program contained in program.c.
In the first step of the compilation process, the compiler examines each
program statement contained in the source program and checks it to ensure
that it conforms to the syntax and semantics of the language. If any mistakes
are discovered by the compiler during this phase, then they will be reported to
the user and the compilation process will end right there. The errors will then
have to be corrected in the source program (with the use of the text editor), and
the compilation process restarted. Typical errors reported during this phase of
compilation might be due to an expression that has unbalanced parentheses
(syntactic error) or due to the use of a variable that is not "defined" (semantic
error).
When all of the syntactic and semantic errors have been removed from
the program, the compiler will then take each statement of the program and
translate it into a "lower" form. On most machines, this means that each
statement will be translated by the compiler into the equivalent statement or
statements in assembly language to perform the identical 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 may
or may not involve the execution of a separate program known as an
assembler. Under UNIX, a separate assembler is executed automatically
whenever the cc command is used to compile a program. Other operating
systems may require that you issue another command at this point to have the
assembly language program translated.
The assembler takes each assembly language statement and converts it
into a binary format known as object code, which is then written into another
file on the system. This file will have the same name as the source file under
UNIX, with the last letter an '0' instead of a 'c.'
After the program has been translated into object code, it is then ready to
be linked. This process is once again performed automatically whenever the cc
command is issued under UNIX. Other operating systems may require
issuance of another command to perform this task. The purpose of the linking
phase is to get the program into a final form for execution on the computer. If
the program uses other programs that were previously 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 lin~dfogether with
the object program during this phase....
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
o Some Fundamentals 0
9

is called a.out by default. To subsequently execute this program, all we have to


do under UNIX is to type in the name of the executable object file. So the
command '

a.out

would have the effect of loading the program~called a.out into the computer's
memory and initiating its execution. ;
When the program is executed, each of the statements of the program is
sequentially ex~cuted in tum. If the program requests any data from the user.
known as input, then the program will temporarily suspend its execution so
that the input may be entered. Results that are displayed by the program,
known as output, will normally appear at the terminal from which the program
was executed. ;
If all goes well (and it probably won't' the first time the program is
executed), then the program will perform its intended functions. If the
program does not produce the desired results, then it will be 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 of the known problems or bugs
from the program. In order to do so, it will most likely be necessary to make
changes in the original source program. In that case, the entire process of
compiling, linking, and executing the program must be repeated until the
desired results are obtained.
Before leaving this discussion of the compilation process, we should point
out that there is another method used for analyzing and executing programs
developed in a higher-level language. With this method, programs are not
compiled but are interpreted. An interpreter analyzes and executes the
statements of a program at the same time. The BASIC programming language
is the primary example of a language in which programs are interpreted and
not compiled. But since programs developed in C are compiled, we will not go
into any further detail here about the interpretive process.
I

c H A T 'E R
• • • • • •
3
\I\IRITING A PROGRAM IN C

In this chapter you will be introduced to the C language so that you can get a
feeling as to what programming in C is all about. But what better way to gain an
appreciation for this language than by taking a look at an actual program
written in C?
To begin with, let's pick a rather simple example-a program that displays
the phrase "Programming is fun." at the terminal. Without further ado, then,
here is a C program to accomplish this task.

Program 3"1
Main ()
-::
printf ("F'rOgraMMing is fun.\ro");
",
..•.

In the C programming language, lower-case and upper-case letters are distinct.


In most other programming languages, such as FORTRAN, COBOL, PL/I, or
BASIC, upper-case letters are used exclusively. If you are used to programming
in any of these languages the use of lower-case letters may take some getting
used to. \
Also unlike many other programming languages, C does not particularly
care where on the line you begin typing. Some languages such as FORTRAN
and COBOL are very fussy about such things, but in C you may begin typing
your statement at any position, on the line. This fact can be used to advantage in
developing programs that are easier to read.
Returning to our first C program, if we were to type this program into the
computer, issue the proper commands to the system to have it compiled, and
then execute it, we could expect the following results or output to appear at the
terminal (minus the "Program 3-1 Output,", of course).

Program 3-1 Output

• '10 •
o Writing A Program In C 0 11

Let's take a closer look at our first program. The first line of the program
informs the system that the name of the program is main. main is a special
name used by the C system that indicates precisely where the program is to
begin execution.
The open and closed parentheses immediately following main specify
that no "arguments" or parameters are expected by this routine. (This concept
will be explained in more detail in Chapter 8 when we discuss functions.)
Now that we have told the system that the name of our program is main,
we are ready to specify precisely what function this routine is to perform. This
is done by enclosing all program statements of the routine within a pair of
braces. (For those readers who are familiar with Pascal, the braces in Care
somewhat analogous to the BEGIN and END block declarators of that
language.) All program statements included between the braces will be taken
as part of the main routine by the system. In Program 3-1, we have only one
such statement. This statement specifies that a routine named printf is to be
invoked or called The parameter or argument to be passed or handed to the
printf routine is the string of characters

IIPr-D<:.l,~aMM:i.n~:.l
i.s fun.\n"

The printf routine is a function in the C system that simply prints or


displays its argument (or arguments as you will see shortly) at the terminal or
on the CRT screen. The last two characters in the string, namely the backs lash
\ and the letter n, are known collectively as the newline character. A newline
character tells the C system to do precisely what its name implies-that is, go to
a new line. Any characters to be printed after the newline character will then
appear on the next line of the terminal or display. In fact, the newline character
is really very similar in concept to the carriage return key on a typewriter.
"Allprogram statements in C must be terminated by a semicolon. This is
the reason for the semicolon that appears immediately following the closed
parenthesis of the printf call.
Now that we have finished discussing our first program, why don't we
modify it to also display the phrase "And programming in C is even more fun."
This can be done by the simple addition of another call to the printf routine, as
shown below. Remember that each and every C program statement must be
terminated by a semicolon.

Program 3-2
Main ()
-::
p"i.ntf ("P,'o'3I'aMMing is fun.\n~');
Pl'intf ("And pl'c)gl'aMMin~l in Cis f,)VE!n MDl'f! fun.\n");

If we type in Program 3-2 and then compile and execute it, we can expect
the following output at our terminal.
12 o PROGRAMMING IN C 0

Program 3-2 Output


PrograMMing is fun.
And prograMMing in C is even More fun.

As you will see from the next program example, it is not necessary to
make a separate call to the printf routine for each line of output. Study the
program listed below and try to predict the results before examining the
output (no cheating now!).

Program 3-3
Main ()
-(
printf (OITesting•••\n ••l\n •••2\n •••• 3\nOl);
}

Program 3-3 Output


Testing •••
• • :1.
•• • 2
•••• 3

The printf routine is the most commonly used routine in this book. This is
because it provides an easy and convenient means to display program results.
Not only can simple phrases be displayed, but the values of variables and the
results of computations as well. In fact, the next program uses the printf
routine to display the results of adding two numbers, namely 50 and 25.

Program 3-4
Main ()
-::
int SUM;

SUM = 50 .•. 25;


printf (OIThe SUM of 50 and 25 is %d\nOl, sut'll;
-,
-,"

Program 3-4 Output


The SUM of 50 and 25 is 75

A bit of explanation is in order with respect to the above program. The


first C program statement declares the variable sum to be of type integer. C,
like Pascal-and unlike FORTRAN or BASIC-requires that all program
variables be declared before they are used in a program. The declaration of a
variable specifies to the C compiler how a particular variable will be used by
the program. This information is needed by the compiler in order to generate
the correct instructions to store and retrieve values into and out of the
o Writing A Program In C 0 13

variable. A variable declared as type int can only be used to hold integral
values, that is, values without decimal places. Examples of integral values are 3,
5, -20, and O.Numbers with decimal places, such as 3.14, 2.455, and 27.0, for
example, are known as floating point numbers.
The integer variable sum will be used to store the result of the addition of
the two integers 50 and 25. We have intentionally left a blank line following the
declaration of this variable. This is done to visually separate the variable
declarations of the routine from the program statements, and is strictly a
matter of style. Sometimes the addition of a single blank line in a program can
help to make the program more readable.
The program statement
SUM :::: ~:;o -+- 25;

reads as it would in most other programming languages: the number 50 is


added (as indicated by the plus sign) to the number 25 and the result is stored
(as indicated by the assignment operator, the equals sign) into the variable sum.
The printf routine call in Program 3-3 now has two items or arguments
enclosed within the parentheses. These arguments are separated by a comma.
The first argument to the printf routine is always the character string to be
displayed. However, along with the display of the character string we may
frequently wish to have the value of certain program variables displayed as
well. In our case, we would like to have the value of the variable sum displayed
at the terminal after the characters
The SUM Df 50 and 25 is

are displayed. The percent character inside the first argument is a special
character recognized by the printf function. The character that immediately
follows the percent sign specifies what type of value is to be displayed at that
point. In the above program, the letter "d" is recognized by the system as
signIfying that it is an integer value that is to be displayed.
Whenever the printf routine finds the %d characters inside a character
string, it will automatically display the value of the next argument to the printf
routine. Since sum is the next argument to printf, its value is automatically
displayed after the characters "The sum of 50 and 25 is" are displayed.
Now try to predict the output from the following program.

Program 3.5

Mai.n ()
,-
"

int valuel, value2, SUM;

valuf.~:I. :::: :iO;


valuf.~2 :::: 25;
S~JM = vi~].ue1 + vall_1eZ;
printf ("The S'-'M Df %d and %d is %d\n", valuel, value2, S'-'M);
::-
14 a PROGRAMMING IN C a

Program 3.5 Output

The SUM of 50 and 25 is 75

The first program statement declares three. variables called value!,


value2, and sum all to be of type Int. This statement could have equivalently
been expressed using three separate declaratory statements as follows:

:i.nt vall.,l(.~:1.;
int vall.JE-~2;
int SUM;

After the three variables have been declared, the program assigns the
value 50 to the variable value! and then the value 25 to value2. The sum of
these two variables is then computed and the result assigned to the variable
sum.
The call to the prlntf routine now contains four arguments. Once again,
the first argument, commonly called the format string, describes to the system
how the remaining arguments are to be displayed. The valueof value! is to be
displayed immediately following the display of the characters liThe sum of" are
displayed. Similarly, the values of value2 and sum are to be displayed at the
appropriate points as indicated by the next two occurrences of the %d
characters in the format string.
The last program in this chapter introduces the concept of the comment.
A comment statement is used in a program to document a program and to
enhance its readability. As you will see from the following example, comments
serve to tell the reader of the program-be it the programmer himself or
someone else whose responsibility it is to maintain the program-just what the
programmer had in mind when he or she wrote a particular program or a
particular sequence of statements.

Program 3.6

1* This prograM adds two integer values and displa~s


the results *1

Main ()
-::
1* Declare variables *1
j.nt v~~luelt val~Je2t S\JM;

1* Ass;ign val~le5 and CaMF)~lte the result ~/


\!aluf::-~:1. ~:.:iO;

1* Displa~ the results *1


PT~:i.ntf ("Th(.:.~ r:;UM of %ci an(~ %ci :i.s %d\n11t vall..le:tt vcJll.Je~!.t SUM);
o Writing A Program In C 0 15

Program 3.6 Output

Acomment statement is initiated by the two characters / and *. These two


characters must be written without any intervening spaces. To end a comment
statement, the characters * and / are used, once again without any embedded
spaces. All characters included between the opening / * and the closing */ are
treated as part of the comment statement and are ignored by the C system. In
Program 3-6, four separate comment statements were used. This program is
otherwise identical to Program 3-5. Even with such a simple example as this, a
comparison of the two programs will confirm that the added comment
statements vastly improve the program's readability and help to clarify its
function and operation.
The generous use of comment statements inside a program cannot be
overemphasized. Many times a programmer will return to a program that he
had coded perhaps only 6 months before only to discover to his dismay that he
cannot remember the purpose of a particular routine or of a particular group
of statements. A simple comment statement judiciously inserted at that
particular point in the program might have saved a significant amount of time
otherwise wasted on rethinking the logic of the particular routine or set of
statements.
It is a good idea to get into the habit of inserting comment statements into
the program as the program is being written or typed into the computer. There
are three good reasons for this. First, it is far easier to document the program
while the particular program logic is still fresh in one's mind than it is to go back
and rethink the logic after the program has been completed. Second, by
inserting comments into the program at such an early stage of the game, the
programmer gets to reap the benefits of the comments during the debug
phase, when program logic errors are being isolated and debugged. A
comment can not only help the programmer read through the program, but it
can also help to point the way to the source of the logic mistake. Finally, it has
yet to be my experience to discover a programmer who actually enjoyed
documenting a program. In fact, once you have finished debugging your
program you will probably not relish the idea of going back to the program to
insert comments. Inserting comments while developing the program will make
this sometimes tedious task a bit easier to swallow.
This discussion concludes this introductory chapter on developing
programs in C. By now you should have a good feel as to what is involved in
writing a program in C and you should be able to develop a small program on
your own. In the next chapter, we will begin to examine some of the finer
intricacies of this wonderfully powerful and flexible programming language.
But first, try your hand at the exercises that follow to make sure that you
understand the concepts presented in this chapter.
16 o PROGRAMMING IN C 0

E x E R c s E s
• • • • • • • • •

1. If you have access to a computer facility that supports the C programming


language, type in and run the six programs presented in this chapter.
Compare the output produced by each program with the output presented
after each program.
2. Write a program that prints the following text at the terminal.
a. In C, lower-case letters are significant.
b. main is where program execution begins.
c. Open and closed braces enclose program statements in a routine.
d. All program statements must be terminated by a semicolon.
3. What output would you expect from the following program?
Main ()
{
pr:i.ntf ( ••Testing ••••• );
P T' i fit..f (II + ••• 1. II ) ;
PT'intf (11, •• 2");
PI':i.ntf ( •••• 3");
printf ("\n");

4. Write a program that subtracts the value 15 from 87 and displays the
result, together with an appropriate message, at the terminal.
5. Identify five syntactic errors in the following program. Then type in and run
the corrected program to make sure that you have correctly identified all of
the mistakes.
Main ()

INT SUM;

I~ COMPUTE RESULT
SUM = 25 + 37 - 19

1* DISPLAY RESULTS *1
PI':i.rotf ("Thf.! anSWf.H'is %d\ro" SI.IM);
:::-

6. What output might you expect from the following program?


Main ()
{

:i.nt answer, result:

anSW(':.~T' :::: 1. 0 0 ;
T'es~Jlt ::::
answer - 10;
.,
Pl'intf ("Thf.! rE~sult is %d\n", result + 5);
..,'
c H A T E R
• • • • • •
4
VARIABLES. CONSTANTS.
DATA TVPES. AND
ARITHMETIC
EXPRESSIONS

In this chapter we will discuss the formation of variable names and constants,
take a look at the basic data types, and describe some fundamental rules for
forming arithmetic expressions in C.

· Variables ·
Early computer programmers had the onerous task of having to write their
programs in the binary language of the machine they were programming. This
meant that computer instructions had to be hand-encoded into binary
numbers by the programmer before they could be entered into the machine.
Furthermore, the programmer had to explicitly assign and reference any
storage locations inside the computer's memory by a specific number or
memory address.
Modem-day programming languages allow the programmer to concen-
trate more on solving the particular problem at hand than on worrying about
specific machine codes or memory locations. They enable us to assign
symbolic names, known as variable names for storing program computa-
tions and results. A variable name can be chosen by the programmer in a
meaningful way so as to reflect the type of value that is to be stored in that
variable.
In Chapter 3 we used several variables to store integer values. For
example, we used the variable sum in Program 3-4 to store the result of the
addition of the two integers 50 and 25.
The C language allows data types other than just integers to be stored in
variables as well, provided the proper declaration for the variable is made
before it is used in the program. Variables can be used to store floating point
numbers, characters, and even pointers to locations inside the computer's
memory.
The rules for forming variable names are quite simple: they must begin
with a letter or underscore (_) and may be followed by any combination of
letters (upper- or lower-case), underscores, or the digits 0 - 9. The following is a
list of valid variable names.

• 17 •
18 o PROGRAMMING IN C 0

SUM
piece_flag
i
J5:.:7
N'-'Mber_of _Moves
_s~sflag

On the other hand, the following variable names are not valid:
s'-'M$value
piece flag
3Spencer
int

The name sum$value is not valid because the dollar sign is not a valid
variable name character. In the second case, embedded blank spaces are not
permitted. The name 3Spencer is not valid, since the name does not begin with
a letter or an underscore. Finally, int cannot be used as a variable name, since
its use has a special meaning to the C compiler. This name is known as a
reserved name. In general, any name that has a special significance to the C
compiler cannot be used as a variable name. Appendix A provides a complete
list of such reserved names.
You should always remember that upper- and lower-case letters are
distinct in C. Therefore, the variable names sum, Sum, and SUM each refer to a
different variable.
While there is no real restriction on the total number of characters that
can be used in a variable name, on many systems only the first eight characters
are significant. This means, for example, that the two variables categoryl and
category2 would not be distinguishable on such a system, since their first eight
characters are the same. With the DEC VAX-II VMS compiler, variable name
length rarely becomes a problem, since this compiler distinguishes such names
to 31 characters.
When deciding on the choice of a variable name, keep one recommenda-
tion in mind-don't be lazy. Pick names that reflect the intended use of the
variable. The reasons are obvious. Just as with the comment statement,
meaningful variable names can dramatically increase the readability of a
program and will payoff in the debug and documentation phases. In fact, the
documentation task will probably be greatly reduced, since the program will
be more self-explanatory. Just remember the point discussed above: only the
first eight characters may be significant on your system. So, for example, if you
have two variables, one that you would like to call average_temperature, and
another average_time, then you might have to change their names .to
something like av~temperature and av~time or temperature...average and
time...average to avoid the eight-character name conflict.

Data Types and Constants •


You have already been exposed to the C basic data type intoAs you will recall, a
variable declared to be of type int can be used to contain integral values
only-that is, values that do not contain decimal places.
o Variables. Constants. Data Types. and Arithmetic Expressions 0 19

The C programming language provides the user with three other basic
data types: float, double, and char. A variable declared to be of type float can be
used for storing floating point numbers (values containing decimal places).
The double type is the same as type float only with roughly twice the accuracy.
Finally, the char data type can be used to store a single character, such as the
letter 'a', the digit character '6', or a semicolon.
In C, any literal number, single character, or character string is known as
a constant. For example, the number 58 represents a constant integer value.
The character string "Programming in C is fun. \n" is an example of a constant
character string. Expressions consisting entirely of constant values are called
constant expressions. So the expression
12~1 .•. 7 ... 17

is a constant expression because each of the terms of the expression is a


constant value. But if i were declared to be an integer variable, then the
expression
128 + 7 _. i.

would not represent a constant expression.


It is important to understand the concept of constants in order to fully
understand data types and operations in C.

Type Int
In C, an integer constant consists of a sequence of one or more digits. A minus
sign preceding the sequence indicates that the value is negative. The values
158, -10, and 0 are all valid examples of integer constants. No embedded
spaces are permitted between the digits, and values larger than 999 cannot be
expressed using commas. (So the value 12,000 is not a valid integer constant,
and must be written as 12000.)
There are two special formats in C that enable integer constants to be
expressed in a base other than decimal (base 10). If the first digit of the integer
value is a zero, then the integer is taken as expressed in octal notation, that is, in
base 8. In that case, the remaining digits of the value must be valid base-8 digits
and therefore must be from 0 through 7. So, for example, to express the value
octal 50 in C, the notation 050 is used. Similarly, the C octal constant 0177
represents the decimal value 127 (1 X 64 + 7 X 8 + 7). An integer value can be
displayed at the terminal in octal notation by using the format characters %0 in
theformat string of a printf statement. In such a case, it is noted that the value
will be displayed in octal without a leading zero.
If an integer constant is preceded by a 0 and the letter x (either lower-case
or upper-case), then the value is taken as expressed in hexadecimal (base 16)
notation. Immediately following the letter x are the digits of the hexadecimal
value, which can be composed of the digits 0 through 9 and the letters a
through f (or A through F). The letters represent the values 10 through 15,
respectively. So to assign the hexadecimal value 5EB (= 162 X 5 + 16 X 14 +
11 = 1,515 decimal) to an integer variable called type-lllask, the statement
20 a PROGRAMMING IN C a

can be used. To display an integer value in hexadecimal format at the terminal,


use the format characters %x. So the statement
printf ("Value == :Y.:<\n", t'jpe._Mask>;

would display the value of type_mask in hexadecimal format, without the


leading Ox.
Octal and hexadecimal constants frequently find their way into systems
programs and more advanced programming applications. As such, this
notation will not be used again until much later in this book.

Type float
A variable declared to be of type float can be used for storing values containing
decimal places. A floating point constant is distinguished by the presence of a
decimal point. It is permissable to omit digits before the decimal point, or digits
after the decimal point, but obviously not to omit both. The values 3., 125.8,
and -.0001 are all valid examples of floating point constants. To display a
floating point value at the terminal, the printf conversion characters %f are
used.
Floating point constants can also be expressed in so-called scientific
notation. The value 1.7e4 is a floating point value expressed in this notation and
represents the value 1.7 X 104• The value before the letter e is known as the
mantissa, while the value that follows is called the exponent. This exponent,
which may be preceded by an optional plus or minus sign, represents the
power of 10 that the mantissa is to be multiplied by. So in the constant 2.25e- 3,
2.25 is the value of the mantissa and -3 is the value of the exponent. This
constant represents the value 2.25 X 10-3 or 0.00225. Incidentally, the letter e
separating the mantissa from the exponent can be written in either lower or
upper case.
In order to display a value in scientific notation, the format characters %e
should be specified in the printf format string.

Type double
The type double is very similar to type float. It is used whenever the accuracy
provided by a float variable is not sufficient. Variables declared to be of type
double can store roughly twice as many significant digits as can a variable of
type float. The precise number of digits that can be stored in either a float or
double variable depends on the particular computer system you are using. On
the DEC VAX machines, a float variable can contain approximately seven
decimal digits, while a variable of type double has a precision of approximately
16 decimal digits.
There is no special distinction made between a constant of type float or
one of type double. In fact, all floating point constants are taken as double
o Variables, Constants, Data Types, and Arithmetic Expressions 0 21

values by the C compiler. To display a double float value at the terminal, the
format characters %f or %e, which are the same format characters used to
display a float value, can be used.

A char variable can be used to contain a single character. A character constant


is formed by enclosing the character within a pair of single quote marks. So 'a',
';', and '0' are all valid examples of character constants. The first constant
represents the letter a, the second a semicolon, and the third the character
zero-which is not the same as the number zero. Do not confuse a character
constant, which is a single character enclosed in single quotes, with a character
string, which is any number of characters enclosed in double quotes. We will
learn more about this distinction in the chapter on character strings.
The character constant '\n' -the newline character-is a valid character
constant even though it seems to contradict the rule cited above. The reason
for this is that the backslash character is a special character in the C system and
does not actually count as a character. In other words, the C compiler treats the
character '\n' as a single character, even though it is actually formed by two
characters. In Chapter 10 you will find that the backslash character can be
used for purposes other than just for advancing to the next line.
The format characters %c can be used in a printf call to display the value
of a char variable at the terminal.
In Program 4-1 that follows, the basic C data types are used. Note how a
value can be assigned to a variable at the time that the variable is declared.

Program 4.1

Main ()
{
int integer_val' = 100;
float floating_val' = 331.79;
dOl,ble double_val' = 8.~~e+ll;
char char_val' = '101';

printf ("integer_val' =
:r.d\n",integer_var);
printf ("floating_val' = :r.f\n",floating_var);
printf ("double_val' = :r.e\n",double_var);
printf ("char_val' = :r.c\n",char_var);
)

Program 4-1 Output

integer_val' = 100
floating_val' = 331.789978
double_val' 8.~~0000E+ll
char_val' = 101
22 o PROGRAMMING IN C 0

The first statement of Program 4-1 declares the variable integer_var to be


an integer variable and also assigns to it an initial value of 100, as if the following
two statements had been used instead:
int integer_var;
integer_var = 100;

In the second line of the program's output, you will notice that the value
of 331.79 that we assigned to floating.-var is actually displayed as 331.789978. In
fact, the actual value that is displayed is quite dependent on the particular
computer system you are using. (The reason for this inaccuracy is due to the
particular way that numbers are internally represented inside the computer
system. You have probably come across the same type of inaccuracy when
dealing with numbers on your pocket calculator. If you divide 1 by 3 on your
calculator, you will get the result .33333333-with perhaps some additional3s
tacked on at the end. The string of 3s is the calculator's approximation to
one-third. Theoretically, ~here should be an infinite number of threes. But the
calculator can only hold so many digits, thus the inherent inaccuracy of the
machine. The same type of inaccuracy applies to your computer system.
Certain floating point values cannot be exactly represented inside the
computer's memory.)
When displaying the values of float or double variables, you have the
choice of two different formats. The %f characters are used to display values in
a standard manner. Unless told otherwise, the printf routine will always display
a float or double value to six decimal places. We will see later in this book
how to select the number of decimal places that are displayed.
The %e characters are used to display the value of a float or double
variable in scientific notation. Once again, six decimal places are automatically
displayed by the system.
In the last printf statement, the %c characters are used to display the
single character 'W' that we assigned to char_var when the variable was
declared. Remember, that while a character string (such as the first argument
to printf) is enclosed within a pair of double quotes, a character constant must
always be enclosed within a pair of single quotes.

Qualifiers long, short, and unsigned


Just as it is possible to extend the accuracy of a variable containing a floating
point number by declaring it to be of type double, so is it possible to extend the
accuracy of an integer variable. If the qualifier long is placed directly before
the int declaration, then the declared integer variable will be of extended
accuracy on many computer systems. An example of a long int declaration
might be

long int factorial;


o Variables, Constants, Data Types, and Arithmetic Expressions 0 23

which would declare the variable factorial to be a long integer variable. As with
floats and doubles, the particular accuracy of a long variable depends on the
particular computer system. On the PDP-II, for example, the maximum
positive value that can be stored inside a variable of type int is 32,767.
Declaring a variable to be of type long int permits values up to 231 - 1 or
2,147,483,647 to be stored in the variable. On the VAX-II, an int and a long int
both have the same accuracy (which is the same as that for a long int on the
PDP-ll) and therefore both can be used to store integer values up to
2,147,483,647.
A constant value of type long is formed by optionally appending the letter
L (upper- or lower-case) onto the end of an integer constant. No spaces are
permitted between the number and the L. So, the declaration

long int MeMor~_address = 131071L;

declares the variable memory_address to be of type long int with an initial


value of 131,071. If the letter L is not specified, the compiler will treat any
constant larger than the largest allowable integer constant as a long integer
constant.
To display the value of a long int variable at the terminal, the letter I is
used as a modifier before the integer format characters d, 0, or x. This means
that the format characters %ld can be used to display the value of a long int in
decimal format, the characters %10to display the value in octal format, and the
characters %lx to display the value in hexadecimal format.
The qualifier short, when placed in front of the int declaration, tells the C
system that the particular variable being declared will be used to store fairly
small integer values. The motivation for using short variables is primarily one
of conserving the computer's memory space, which may be an issue in cases
in which the amount of memory available to a program is limited. On many
machines, a short int will take up half the amount of storage as a regular int
variable will. On the VAX-II, a short int can be used to store integer values in
the range of -32,768 to 32,767.
The final qualifier that may be placed in front of an int variable is used
when an integer variable will be used only to store positive numbers. The
declaration

unsigned int counter;

declares to the C system that the variable counter will be used only to contain
positive values. By restricting the use of an integer variable to the exclusive
storage of positive integers, the accuracy of the integer variable is extended.
On the PDP-II, for example, a normalint variable can assume values from

°
- 32,768 through 32,767. The same variable declared to be of type unsigned int
can assume values from through 65,535.
When declaring variables to be of type long int, short int, or unsigned int,
it is permitted to omit the keyword int. So the unsigned variable counter could
have been equivalently declared as
24 0 PROGRAMMING IN C 0

ur)signed counter;

Don't worry if the discussions of the types long int, short int, and unsigned
int seem a bit esoteric to you at this point. The discussion was included here
mainly for the sake of completeness. In later sections of this book, we will
illustrate the use of many of these different types with actual program
examples.

· Arithmetic Expressions
In C, just as in virtually all programming languages, the plus sign (+) is used to
add two values; the minus sign (-) to subtract two values; the asterisk (*) to
multiply two values; and the slash (/) to divide two values. These operators are
known as binary arithmetic operators, since they operate on two values or
terms.
We have seen how a simple operation like addition can be performed in C.
The following program further illustrates the operations of subtraction,
multiplication, and div.ision. The last two operations performed in the program
introduce the notion that one operator can have a higher priority or
precedence over another operator. In fact, each operator in C has a precedence
associated with it. This precedence is used to determine how an expression
that has more than one operator is evaluated: The operator with the higher
precedence is evaluated first. Expressions containing operators of the same
precedence are either evaluated from left to right or from right to left,
depending on the operator. This is known as the associative property of an
operator. Appendix A provides a complete list of operator precedences and
their rules of association. .

Program 4-2
I'll. Illustrate the use of various arithMetic operators *1

Main ()
(
int a 100;
int b 2;
int c = 25;
int d 4;
int result;

result = a - b; I'll. subtraction *1


printf ("a - b = 7.d\n", result);

res'.Jlt= b c; I'll. M,jltip'1icat.ion *1


printf ("b * c = 7.d\n", .result) ;
*
,lt = a I
res •.. c; I'll. division '11.1
printf ("a I c 7.d\n", result) ;

,lt = a + b
res •.. 'II. c;
printf ("a + b
* c = 7.d\n", result);
" Variables, Constants, Data Types, and Arithmetic Expressions " 25

printf ("a )I( b + c )I( d 7.d\n", a )I( b + c )I( d);

Program 4.2 Output

a - b 98
b c
)I( 50
a / c 4
a + b c)I( 150
a )I( b + c )I( d = 300

After declaring the integer variables a, b, C, d, and result, the program


assigns the result of subtracting b from a to result and then proceeds to display
its value with an appropriate prlntf call.
The next statement
result = b )I( c;

has the effect of multiplying the value of b by the value of C and storing the
product in result. The result of the multiplication is then displayed using a
prlntf call that should be very familiar to you by now.
The next program statement introduces the division operator-the slash.
The result of 4 as obtained by dividing 100 by 25 is displayed by the prlntf
statement immediately following the division of a by c.
In mathematics, the result of dividing any number by zero is infinity (00).
On most computer systems, attempting to divide a number by zero will result
in abnormal termination of the program. Even if the program does not
terminate abnormally, the results obtained by such a division will be
meaningless. In Chapter 6 we will see how division by zero can be checked for
before the division operation is performed. If it is determined that the divisor is
zero, then an appropriate action (such as displaying a message at the terminal)
can be taken and the division operation averted.
The expression
a + b )I( C

does not produce the result of 2550 (102 • 25) as might be expected; rather, the
result as displayed by the corresponding prlntf statement is shown as 150. This
is because C, like most other programming languages, has rules for the order of
evaluating multiple operations or terms in an expression. Evaluation of an
expression generally proceeds from left to right. However, the operations of
multiplication and division are given higher precedence over the operations of
addition and subtraction. Therefore, the expression

is evaluated as

a + (b )I( c)
26 o PROGRAMMING IN C 0

by the C system. (This is the same way that this expression would be evaluated
if we were to apply the basic rules of algebra.)
If we wish to alter the order of evaluation of terms inside an expression,
then parentheses can be used. In fact, the last expression listed above is a
perfectly valid C expression. Thus, the statement

result = a + (b * e);

could have been substituted in Program 4-2 to achieve identical results; but if
the expression

result = (a + bl * e;

were used instead, then the value assigned to result would be 2550, since the
value of a (100) would be added to the value of b (2) before multiplication by the
value of c (25) would take place. Parentheses may be nested, and evaluation of
the expression will proceed outward from the innermost set of parentheses.
Just be sure to have as many closed parentheses as there are open.
You will notice from the last statement in Program 4-2 that it is perfectly
valid to give an expression as an argument to the printf statement without
having to first assign the result of the expression evaluation to a variable. The
expression
-a * b + e * d

is evaluated according to the rules stated above as

*
(a b) + (c d) * or
(100 * 2) + (25 * 4)

and the result of 300 "handed" to the printf routine.

Integer Arithmetic and the Unary


Minus Operator
The next program reinforces what we have just discussed and introduces the
concept of integer arithmetic.

Program 4.3

1* More arithMetic expressions *1

Main ()
-(
int a = 25;
ir,t b =
2;
int res,-,lt;
float c 25.0;
float d = 2.0;
o Variables. Constants. Data Types. and Arithmetic Expressions 0 27

printf ("6 + a / 5 )I( b = :Y.d\n". 6 + a / 5 )I( b);


printf ("a / b )I( b = :Y.d\n". a / b )I( b>;
printf ("c / d )I( d = :Y.f\n", c / d )I( d>;
printf ("-a = :Y.d\n". -a>;
)

Program 4-3 Output

6 + a / 5 )I( b 16 =
a / b )I( b 2"t
c / d )I( d = 25.000000
-a -25=
We inserted extra blank spaces between int and the declaration of a, b,
and result in the first three statements to align the declaration of each variable.
This helps to make the program more readable. You also may have noticed in
each program presented thus far that a blank space was placed around each
operator. This too is not required and is done solely for esthetic reasons. In
general, you may add extra blank spaces just about anywhere that a single
blank space is allowed. A few extra presses of the space bar will prove
worthwhile if the resulting program is easier to read.
The expression in the first printf call of Program 4-3 reinforces the notion
of operator precedence. Evaluation of this expression proceeds as follows:
1. Since division has higher precedence than addition, the value of a (25) is
divided by 5 first. This gives the intermediate result of 5.
2. Since multiplication also has higher precedence than addition, the
intermediate result of 5 is next multiplied by 2, the value of b, giving a new
intermediate result of 10.
3. Finally, the addition of 6 and 10 is performed, giving a final result of 16.
The second printf statement introduces a new twist. We would expect
that dividing a by b and then multiplying by b would return to us the value of a,
which we have set to 25. But this does not seem to be the case, as shown by the
output display of 24. Did the computer lose a bit somewhere along the way?
Very unlikely. The fact of the matter is that this expression was evaluated using
integer arithmetic.
If you glance back at the declarations for the variables a and b, you will
recall that they were both declared to be of type int. Now, whenever a term to
be evaluated in an expression consists of two integers, the C system performs
the operation using integer arithmetic. In such a case, all decimal portions of
numbers are lost. Therefore, when the value of a is divided by the value of b, or
25 is divided by 2, we get an intermediate result of 12 and not 12.5 as you might
expect. Multiplying this intermediate result by 2 gives us the final result of 24,
thus explaining the "lost" digit.
As can be seen from the next-to-Iast printf statement in Program 4-3, if we
perform the same operation using floating point values instead of integers, we
obtain the expected result.
--- ~---,;--------------------------------

28 o PROGRAMMING IN C 0

The decision of whether to use a float variable or an Int variable should be


made based on the variable's intended use. If you don't need any decimal
places, then use an integer variable. The resulting program will be more
efficient-that is, it will execute faster on most computers. On the other hand, if
you need the decimal place accuracy, then the choice is clear. The only
question that you then must decide is whether to use a float or double. The
answer to this question will depend on the desired accuracy of the numbers
you are dealing with, as well as their magnitude.
In the last prlntf statement, the value of the variable a is negated by use of
the unary minus operator. A unary operator is one that operates on a single
value, as opposed to a binary operator, which operates on two values. The
minus sign actually has a dual role: as a binary operator it is used for
subtracting two values. As a unary operator, it is used to negate a value.
The unary minus operator has higher precedence than all other
arithmetic operators, so the expression
c = -a lK b;

will result in the multiplication of -a by b. Once again, in Appendix A you will


find a table summarizing the various operators and their precedences.

The Modulus Operator


The last operator to be presented in this chapter is the modulus operator, which
is symbolized by the percent sign (%). Try to determine how this operator
works by analyzing the output from the following program.

Program 4.4

IlK The Modulus operator lKl

Maira ()
{
irat a = 25, b = 5, c = 10, d = 7;

prirat~f ("a 7.7.b = 7.d\ra", a 7. b);


priratf ("a 7.7.c =
7.d\ra", a 7. c);
priratf ("a 7.7.d = 7.d\ra", a 7. d);
priratf ("a I d lK d + a 7.7.d = 7.d\ra",
a / d lK d + a 7. d);
}

Program 4-4 Output

a 7.b 0
a 7. c 5
a "d
a I d lK
"I

d + a "d 25
o Variables. Constants. Data Types. and Arithmetic Expressions 0 29

The first statement inside main declares and initializes the variables a, h,
c, and d in a single statement.
In the first printf call, you will notice that we used two percent signs in the
format string; yet, if you examine the program's output, you will notice that
only a single percent sign was printed. The reason for this is due to the special
significance of the % sign to the printf routine. As you know, the printf routine
uses the character that immediately follows the percent sign to determine how
to print the next argument. However, if it is another percent sign that follows,
then the printf routine takes this as an indication that you really intend to
display a percent sign, and inserts one at the appropriate place in the program's
output.
You are correct if you concluded that the function of the modulus
operator % is to give the remainder of the first value divided by the second
value. In the first example, the remainder after 25 is divided by 5 is displayed as
O.If we divide 25 by 10, we get a remainder of 5, as verified by the second line of
output. Dividing 25 by 7 gives a remainder of 4, as shown in the third output
line.
The last line of output in Program 4-4 requires a bit of explanation. First,
you will notice that the program statement has been written on two lines. This
is perfectly valid in C. In fact, a program statement may be continued onto the
next line at any point where a blank space could be used. (An exception to this is
when dealing with character strings-a topic to be discussed in Chapter to.) At
times, it may not only be desirable, but perhaps even necessary, to continue a
program statement onto the next line. The continuation of the printf call in
Program 4-4 was indented to visually show that it is a continuation of the
preceding program statement.
Let us now turn our attention to the expression that is evaluated in this
last statement. You will recall that any operations between two integer values
in C are performed with integer arithmetic. Therefore, any remainder
resulting from the division of two integer values will simply be discarded.
Dividing 25 by 7, as indicated by the expression a / d, gives an intermediate
result of 3. Multiplying this value by the value of d, which is 7, produces the
intermediate result of 21. Finally, adding in the remainder of dividing a by d, as
indicated by the expression a % d, leads to the final result of 25. It is no
coincidence that this value is the same as the value of the variable a. In general,
the expression

a I b * b + a Z b

will always equal the value of a, assuming of course that a and h are both
integer values. (In fact, the modulus operator % is defined to work only with
integer values.)
As far as precedence is concerned, the modulus operator has equal
precedence to the multiplication and division operators. This implies, of
course, that an expression such as

table + value Z TABLE_SIZE


30 o PROGRAMMING IN C 0

will be evaluated as

table + (value % TABLE_SIZE)

Integer and Floating Point Conversions


In order to effectively develop C programs, it will be necessary for you to
understand the rules that are used for the implicit conversion of floating point
and integer values in C. In Chapter 14, the rules that are followed for
conversion between other data types are described in detail.

Program 4-5
/* Basic conversions in C */

",ain ()
{
float fl = 123.125. f2:
int i1. i2 = -150:
char c = ., a' :

il = fl: /* floating to integer conversion */


printf ("Xf assigned to an int prodL1ces i::d\n".fl. il>:

fl = i2: /* integer to floating conversion */


printf ("Xd assigned to a float produces i::f\n".i2. fl):

fl =
i2 / 100: /* integer divided b~ integer */
printf ("Xd divided b~ 100 prodLlces i::f\n".i2. f1):

f2 = i2 / 100.0: ;* integer divided b~ a float */


printf ("Xd divided b~ 100.0 produces i::f\n".i2. f2);
)

Program 4-5 Output


123.125000 assigned to an int produces 123
-150 assigned to a float prbduces -150.003000
-150 divided b~ 100 produces -1.000000
-150 divided b~ 100~0 produces -1.500000

Whenever a floating point value is assigned to an integer variable in C, the


decimal portion of the number gets truncated. So when the value of f1 .is
assigned to 11in the above program, the number 123.125 gets truncated, which
means that only its integer portion, or 123, is stored into 11.The first line of the
program's output verifies that this is the case.
Assigning an integer variable to a floating variable does not cause any
change in the value of the number. The value is simply converted by the system
and stored into the floating variable. The second line of the program's output
verifies that the value of 12, -150, was correctly converted and stored into
the float variable £1. .
The next two lines of the program's output illustrate two points that must
be remembered when forming arithmetic expressions. The first has to do with
o Variables, Constants, Data Types, and Arithmetic Expressions 0 31

integer arithmetic, which we have already discussed in this chapter. Whenever


two operands in an expression are integers (and this applies to short, unsigned,
and long integers as well), the operation is carried out under the rules of integer
aIithmetic. Therefore, any decimal portion resulting from a division operation
will be discarded, even if the result is assigned to a floating variable (as we did
in the program). So when the integer variable i2 is divided by the integer
constant 100, the system performs the division as an integer division. The result
of dividing -150 by 1DO,which is -I, is therefore the value that is stored into the
float variable £1.
The next division that is performed in the above program involves an
integer variable and a floating point constant. Any operation between two
values in C will be performed as a floating point operation if either value is a
floating point variable or constant. Therefore, when the value of i2 is divided by
100.0, the system treats the division as a floating point division and produces
the result of -1.5, which is assigned to the float vaIiable £1.
We have reached the end of our discussions on variables, data types, and
expressions. If you are familiar with other programming languages, you may
have noticed that there is no operator for raising a number to a power
(exponentiation). Many computer systems provide a function in the program
library for performing exponentiation, or you can always compute the value
yourself (for raising a number to an integer power by simply multiplying the
number by itself the required number of times).
Try your hand at the exercises presented on the following pages before
proceeding to the next chapter, which introduces the concept of program
looping.

E x E R c s E s
• • • • • • • •

1. If you have access to a computer facility that supports the C programming


language, type in and run the five programs presented in this chapter.
Compare the output produced by each program with the output presented
after each program.
2. Which of the following are invalid variable names? Why?

Int char

calloc X;.:

floati.ng _.1312

ReIni.ti.ali.ze A$
32 o PROGRAMMING IN C 0

3. Which of the following are invalid constants. Why?

123."t56 0).:10.5 OXOG1

0001 OJ.:FFFF 123L

OXab05 OL -597.25

123.5e2 .0001 +12.5

0996 -12E-12 07777

4. Write a program that converts 27° from degrees Fahrenheit (F) to degrees
Celsius (C) using the formula

c= (F- 32)/1.8

5. What output would you expect from the following program?


Main ()
-(
char c, d;

c = 'd';
d = c;
print.f (lid = :Y.c\n", d);
::-

6. Write a program to evaluate the polynomial

3x3 - 5x1 +6
for x = 2.55.

7. Write a program that evaluates the following expression and displays the
result. (Remember to use exponential format to display the result.)

(3.31 X 10-8 + 2.10 X 10-7) / (7.16 X 106 + 2.01 X 108)

8. To round off an integer i to the next largest even multiple of another integer
j, the following formula can be used:

Next-multiple =i +j - i %j

For example, to round off 256 days to the next largest number of days
evenly divisible by a week, values of i= 256 and j= 7 can be substituted into
the above formula as follows.
Next-multiple = 256 + 7 - 256 % 7
= 256 + 7 - 4
= 259
[J Variables, Constants, Data Types, and Arithmetic Expressions [J 33

:;

Write a program to find the next largest even multiple for the following
values of i and j. 1

365 7
12,258 23
996 4
c H A p T E R
• • • • • •
5

PROGRAM LOOPING

The for Statement •


If we were to arrange 15 dots into the shape of a triangle, we would end up with
an arrangement that might look something like this:
o

o 0

o o o

o o o o

o o o o o

The first row of the triangle contains one dot, the second row two dots, and so
on. In general, the number of dots it would take to form a triangle containing n
rows would be the sum of the integers from 1through n. This sum is known as a
triangular number. If we start at 1, then the fourth triangular number would
be the sum of the consecutive integers 1 through 4 (1 + 2 + 3 + 4), or 10.
Suppose we wished to write a program that calculated and displayed the
value of the eighth triangular number at the terminal. Obviously, we could
easily calculate this number in our heads, but for the sake of argument, let us
assume that we wanted to write a program in C to perform this task. Such a
program is shown below.

Program 5-1
/* PrograM to calculate'the eighth triangular nUMber */

Main ()
{

triangular_nUMber = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8;

printf ("The eight.h t.riangular n'.IMberis %d\n",


t.riangular_nuMber);
}

• 34 •
o Program Looping 0 35

Program 5.1 Output

The eighth triangular nUMber is 36

The above technique works fine for calculating relatively small triangular
numbers. But what would happen if we needed to find the value of the 200th
triangular number, for example? It certainly would be a bit tedious to have to
modify the above program to explicitly add up all of the integers from 1to 200.
Luckily, there is an easier way.
One of the fundamental properties of a computer is its ability to
repetitively execute a set of statements. These looping capabilities enable
programmers to develop concise programs containing repetitive processes
that could otherwise require thousands or even millions of program
statements to perform. The C programming language contains three different
program statements for program looping. They are known as the for
statement, the while statement, and the do statement. Each of these
statements will be described in detail in this chapter.
Why don't we dive right in and take a look at a program that uses the for
statement. The purpose of this program is to calculate the 200th triangular
number. See if you can determine how the for statement works.

Program 5-2
1* PrograM to calculate the ZUOth triangular nUMber *1
1* Introduction of the for stateMent *1

Main ()
{

for ( n = 1; n (= ZOO; n = n + 1 )
triangular_nuMber = triangular_nuMb,r + n;

printf ("The ZOOth triang'.Ilar nUMber is rod\n",


triangular_nuMber);
-,
..•.

Program 5-2 Output

The ZOOth triangular nUMber is Z0100

Some explanation is owed for the above program. The method employed
to calculate the 200th triangular number is really the same as that used to
calculate the 8th triangular number in the previous program-the integers
from 1 up to 200 are summed. The for statement provides the mechanism that
enables us to avoid having to explicitly write out each integer from 1to 200. In a
sense, this statement is used to "generate" these numbers for us.
The general format of the for statement is as follows:
36 o PROGRAMMING IN C 0

for ( iniLexpression; loop_condition; loop_expression)


program statement;

The three expressions enclosed within parentheses-iniLexpression, loop_con-


dition, and loop_express ion-set up the environment for the program loop.
The program statement that immediately follows can be any valid C program
statement and constitutes the body of the loop. This statement will be executed
as many times as specified by the parameters set up in the for statement.
The first component of the for, labeled iniLexpression, is used to set the
initial values before the loop begins. In Program 5-2, this portion of the for
statement is used to set the initial value of n to 1.As you can see, an assignment
is a valid form of an expression.
The second component of the for statement specifies the condition or
conditions that are necessary in order for the loop to continue. In other words,
looping continues as long as this condition is satisfied. Once again referring to
Program 5-2, we find that the loop_condition of the for is specified by the
relational expression
n <= zoo:
This expression can be read as "n less than or equal to 200." The "less than or
equal to" operator (which is the less-than character '<' followed immediately
by the equals sign '=') is only one of several relational operators provided in the
C programming language. These operators are used to test specific conditions.
The answer to the test will be "yes" or, more commonly, TRUE if the condition
is satisfied and "no" or FALSE if the condition is not satisfied.
Table 5-1 lists all of the relational operators that are available in C.
The relational operators have lower precedence than all arithmetic
operators. This means, for example, that an expression such as
• < b + c

will be evaluated as
• < (b + c)

as you would expect, and would be TRUE if the value of a was less than the
value of b + c, and FALSE otherwise.

TABLE 5.1. RELATIONAL OPERATORS

OPERATOR MEANING EXAMPLE

equal to count == 10
!= not equal to flag!= DONE
< less than a<b
<= less than or equal to low<= high
> greater than pointer> end_oLlist
>= greater than or equal to i>=O
o Program Looping 0 37

Pay particular attention to the "is equal to" operator "==" and do not
confuse its use with the assignment operator "=." The expression
a == 2

tests if the value of a is equal to 2, whereas the expression

a = 2

assigns the value 2 to the variable a.


The choice of which relational operator to use will obviously depend on
the particular test beinJ made and in some instances on your particular
preferences. For example, the relational expression

n <= 200

can be equivalently expressed as

n < 201

Returning to our example, the program statement that forms the body of
the for loop:

will be repetitively executed as long as the result of the relational test is TRUE,
or in this case, as long as the value of n is less than or equal to 200. This program
statement has the effect of adding the value of triangular-llumber to the value
of n and storing the result back into the value of triangular-llumber.
When the loop_condition is no longer satisfied, execution of the program
will continue with the program statement immediately following the for loop.
In our program, execution will continue with the printf statement once the
loop has terminated.
The final component of the for statement contains an expression that is
evaluated each time afterthe body of the loop is executed. In Program 5-2, this
loop_expression adds 1 to the value of n. Therefore, the value of n will be
incremented by 1 each time after its value has been added into the value of
triangular-llumber, and will range in value from 1 through 201.
It is worth noting that the last value that n attains, namely 201, is not
added into the value of triangular-llumber, since the loop is terminated as soon
as the looping condition is no longer satisfied, or as soon as n equals 201.
In summary, then, execution of the for statement proceeds as follows:
1. The initial expression is evaluated first. This expression usually sets a
variable that will be used inside the loop, generally referred to as an index
variable, to some initial value such as 0 or 1.
2. The looping condition is evaluated. If the condition is not satisfied (the
expression is FALSE), then the loop is immediately terminated. Execution
continues with the program statement that immediately follows the loop.
38 o PROGRAMMING IN C 0

3. The program statement that constitutes the body of the loop is executed.
4. The looping expression is evaluated. This expression is generally used to
change the vaiue of the index variable, frequently by adding 1 to it or
subtracting 1 from it.
5. Return to Step 2.
Since Program 5-2 actually generates all of the first 200 triangular
numbers on its way to its final goal, it might be nice to generate a table of these
numbers. To save space, however, we will assume that we just want to print a
table of the first 10 triangular numbers. Program 5-3 performs precisely this
task!

Program 5-3

1* Pro~raM to Generate a Table of Trian~ular NUMbers ./

Main ()
-::

printf ("TABLE OF TRIANGULAR NUMBERS\n\n")~


prir.tf (" n SUM froM 1 to n\n");
printf ("___ ---------------\n");

for ( n = 1; n <= 10; ++n)


,"
'-
triangular_nUMber = triangular_nuMber + n;
printf (" "d "d\n", r., triangular_nuMber>;
)
)

Program 5.3 Output


TABLE OF TRIANGULAR NUMBERS

n SUM froM 1 to n

1 1
2 3
3 6
"I 10
5 15
6 21
7 28
8 36
9 "15
10 55

It is always a good idea to add some extra printf statements to a program


in order to provide more meaning to the output. In Program 5-3, thepurpose of
the first three printf statements is simply to provide a general heading and to
o Program Looping 0 39

label the columns of the output. You will notice that the first printf statement
contains two newline characters. As you would expect, this has the effect of
not only advancing to the next line but also inserting an extra blank line into the
display.
After the appropriate headings have been displayed, the program
proceeds to calculate the first 10 triangular numbers. The variable n is used to
count the current number whose "sum from 1 to n" we are computing, while
the variable triangular_number is used to store the value of triangular number
n.
Execution of the for statement commences by setting the value of the
variable n to 1. You will recall that we mentioned earlier that the program
statement immediately following the for statement constitutes the body of the
program loop. But what happens if we wish to repetitively execute not just a
single program statement but a group of program statements? This can be
accomplished by enclosing all such program statements within a pair of
braces. The system will then treat this group or block of statements as a single
entity. In general, any place in a C program that a single statement is permitted,
a block of statements can be used, provided that you remember to enclose the
block within a pair of braces.
Therefore, in Program 5-3, both the expression that adds n into the value
of triangular_number and the printf statement that immediately follows
constitute the body of the program loop. Pay particular attention to the way
the program statements are indented. At a quick glance, it is easy to determine
which statements form part of the for loop.
The next triangular number is calculated by simply adding the value of n
to the previous triangular number. The first time through the for loop, the
"previous" triangular number is zero, so the new value of triangular_number
when n is equal to 1 is simply the value of n, or 1. The values of nand
triangular_number are then displayed, with an appropriate number of blank
spaces inserted in the format string to ensure that the values of the two
variables line up under the appropriate column headings.
Since the body of the loop has now been executed, the looping expression
is evaluated next. The expression in this for statement appears a bit strange,
however. Surely we must have made a typographical mistake and meant to
insert the expression
n = n + 1

instead of the funny-looking expression


++n

The fact of the matter is that ++n is actually a perfectly valid C


expression. It introduces us to a new (and rather unusual) operator in the C
programming language-the increment operator. The function of the double
plus sign-or the increment operator-is to add 1 to its operand. Since addition
by 1 is such a common operation in programs, a special operator was created
solely for this purpose. Therefore, the expression ++n is equivalent to the
40 o PROGRAMMING IN C 0

expression n = n + I. While at first glance it might appear that n = n + 1 is more


readable, you will very soon get used to the function of this operator and will
even learn to appreciate its succinctness.
Of course, no programming language that offered an increment operator
to add 1 would be complete without a corresponding operator to subtract 1.
And as you would guess, the name of this operator is the decrement operator
and is symbolized by the double minus sign. So, an expression in C that reads

can be equivalently expressed using the decrement operator as

--bean_counterJ

One slightly disturbing thing that you may have noticed in Program 5-3's
output is the fact that the 10th triangular number does not quite line up under
the previous triangular numbers. This is because the number 10 takes up two
print positions, whereas the previous values of n, 1through 9, took up only one
print position. Therefore, the value 55 is effectively "pushed over" one extra
position in the display.
This minor annoyance can be corrected if we substitute the following
prlntf statement in place of the corresponding statement from Program 5-3.

l'rintf ("X2d

To verify that this change will do the trick, here is the output from the
modified program (we'll call it Program 5-3A).

Program 5-3A Output

1 1
2 3
3 6
1 10
5 15
6 21
7 28
8 36
9 15
10 55

The primary change made to the prlntf statement was the inclusion of a
field width specification. The characters %2d tell the prlntf routine that not
only do we wish to display the value of an integer at that particular point, but
also that the size of the integer to be displayed should take up 2 columns in the
display. Any integer that would normally take up less than 2 columns (that is,
the integers 0 through 9) will be displayed with a leading space. This is known
as right justification.
Thus, by using a field width specification of %2d we guarantee that at
o Program Looping 0 41

least two coiumns will be used for displaying the value of n, and therefore
ensure that the values of triangular_number will be lined up.
If the value that is to be displayed requires more columns than are
specified by the field width, then the prlntf routine simply ignores the field
width specification and uses as many columns as are necessary to display the
value.
Field width specifications can be used for displaying values other than
integers as well. We will see some examples of this in programs that will be
coming up shortly.

• Program Input •
Program 5-2 calculates the 200th triangular number-and nothing more. What
if we wanted to calculate the 50th or the 100th triangular number instead?
Well, if that were the case, then we would have to go back and change the
program so that the for loop would be executed the correct number of times.
We would also have to change the prlntf statement to contain the correct
message.
An easier solution might be if we could somehow have the program ask us
which triangular number we wished to calculate. Then, once we had given our
answer, the program could calculate the desired triangular number for us.
Such a solution can be effected in C by use of a routine called scanf. The scanf
routine is very similar in concept to the prlntf routine. Whereas the latter
routine is used to display values at the terminal, the function of the former
routine is to enable the programmer to type values intothe program. Program
5-4 below asks the user which triangular number he would like to have
calculated, proceeds to calculate that number, and then displays the results.

Program 5.4
Main ()
{
int n. nUMber. triangular_nUMber;

printf ("What triangular nUMber do ~ou want?\n");


sear,f ("Xd". &nL'Mber);

triangular_nUMber = 0;

for ( n = 1; n <= nUMber; ++n)


triangular_nuMber = triangular_nuMber + n;

printf ("Triar.gular nUMber Xd is Xd\n". nUMber.


triangular_nuMber);
)

In the program output that follows, the number as typed in by the user
(l00) is set in bolder type to distinguish it from the results displayed by the
program.
Another Random Scribd Document
with Unrelated Content
FIGURA Sexagesimaseptima.
Vestigium geometricum, ac prima præparatio ad figuram
septuagesimamprimam.

GREGIAM adeò speciem præsetulit, atque oculis


adeò imposuit machina quam construxi anno
1685, pro supplicatione quadraginta horarum, in
Templo Urbis Farnesiano, ut decreverim satisfacere
Studiosis, publici juris faciendo non modò
imaginem totius ædificii, sed etiam illius vestigia &
elevationes: quæ omnia eâ diligentiâ
delineavimus, veluti Opus ipsum non pennicillo colorandum, sed
lapidibus extruendum fuisset. Spatia nigrantia soliditatem designant
parietum & columnarum. Cæteræ lineæ sunt crepidines
stylobatarum & coronicum. Initium delineationis fiet ab iis membris,
ex quibus oriuntur lineæ occultæ positæ in A, (quæ autem dicuntur
de hac medietate, intelligi debent de aliâ) ne multitudo linearum
confusionem pariat. In B lineæ curvæ occultæ sunt vestigium tholi
qui complet summitatem ædificii. Vestigium C exhibet ambulacrum
interius. Omisimus autem vestigium theatri, quia paginæ angustia
illud non capit.
The Sixty-seventh FIGURE.
The Geometrical Plan, and first Preparation to the Seventy-first
Figure.

HE Machine which I erected in the Year 1685, in


the Church Farneze, or Jesuits Church at Rome,
for the Devotions of the Forty Hours; had so
admirable an Effect, and so pleasantly deceiv’d the
Eye, that I resolv’d to gratify the Studious, not
only with a general View, but with the Plan and
Elevation thereof; all which was perform’d with
such Exactness, that the Work itself seem’d rather to consist of solid
Stones, than to be wrought by the Painter’s Hand. The hatch’d Part
denotes the Solidity of the Walls and Columns. The other shews the
Breaks and Projectures of the Pedestals and Cornices. Lest many
Lines should cause Confusion, begin with those Members, which
produce the occult Lines on the Side A; understanding the same also
of the other half. In B the occult curv’d Lines are the Plan of the
Cupola which crowns this Structure. The Plan C is that of the inner
Vestibule, but that of the Theater is here omitted, through Want of
Room in the Page.
FIG. LXVIII.
FIGURA Sexagesimaoctava.
Elevatio geometrica vestigii præcedentis, & secunda præparatio ad
figuram septuagesimamprimam.

N hoc schemate habes elevationem ædificii sectam


in longum, quam figurâ septuagesimâ opticè
projiciemus: eisdemque membris constare videbis
elevationem deformatam, quibus constat elevatio
geometrica. Hinc disces ad excogitandas
hujusmodi machinas, eandem Architecturæ
scientiam in Pictore necessariam esse, quæ ad
construenda solida ædificia exigitur in Architecto.
The Sixty-eighth FIGURE.
The Geometrical Elevation of the foregoing Plan, and second
Preparation to the Seventy-first Figure.

N this Figure you have the Elevation of the


aforesaid Structure dissected lengthwise; the
Perspective thereof is describ’d in the Seventieth
Figure; and you may observe that both of them
consist of the same Members: whence you may
perceive, that for designing things of this kind, the
Painter ought to have no less Skill in Architecture,
than is requir’d for the Execution of solid Works.

Fig. lxix.
FIGURA Sexagesimanona.
Deformatio vestigii figuræ sexagesimæseptimæ, & præparatio
tertia ad figuram septuagesimamprimam.

RTIFICIUM projectionis vestigii hujus, explicatum à


nobis est figurâ quadragesimasecundâ. Nimirum,
ut parallelæ sint invicem distantiores, lineam plani
deorsum protraximus, ut ex intuitu figuræ statim
cognosces.
The Sixty-ninth FIGURE.
The Plan of the Sixty-seventh Figure in Perspective, and third
Preparation to the Seventy-first Figure.

HE Artifice us’d in projecting the Perspective of this


Plan, has been already shewn in the Forty-second
Figure; namely, that for giving the greater
Distance between the Parallels, the Ground-line is
drawn much lower than its true Place; as is
manifest on Inspection of the Figure.

Fig. lxx.
FIGURA SEPTUAGESIMA.
Deformatio elevationis figuræ sexagesimæoctavæ, & præparatio
quarta ad figuram septuagesimamprimam.

UÆ dicta sunt de projectione vestigii nostri ædificii,


habent locum in elevatione. Nimirum, ut parallelæ
invicem notabiliter distarent, usi sumus industriâ
quam declaravimus figurâ quadragesimasecundâ.
The Seventieth FIGURE.
The Perspective of the Elevation of the Sixty-eighth Figure, and
the fourth Preparation to the Seventy-first Figure.

HAT has been said of the Perspective-Plan of this


Structure, is also here practis’d in the Elevation;
namely, that the Parallels might be sufficiently
distinct, the Perpendiculars are drawn more
remote from the Point of Sight, as was shewn in
the Forty-second Figure.

Fig. lxxi.
FIGURA Septuagesimaprima.
Theatrum repræsentans Nuptias Canæ Galilææ, constructum
Romæ, anno 1685. in expositione Ven. Sacramenti in Templo
Farnesiano Societatis JESU.

X antecedentibus præparationibus eruimus


projectionem nobilis hujus Architecturæ, quæ
oculos implebat tum ad lucem solis diurnam, tum
præcipuè ad lumen candelarum; ex quibus multæ
palam erant expositæ, aliæ omnino latebant, ut
illuminarent sex diversos ordines telariorum quibus
tota machina constabat, non computando in hoc
numero telaria, quæ in medio arcûs maximi exprimebant nubes
refertas Angelis adorantibus Venerabile Sacramentum. Nubes istas
omisimus, ne absconderentur partes interiorum ædificiorum. In
disponendis autem ordinibus telariorum, servatus est modus quem
declaravi figurâ sexagesimaprima & sexagesimasecunda; ac
præterea in eligenda eorum distantia curatum fuit, ut candelæ in
parte postica telariorum collocatæ, illuminarent faciem telariorum
interiorum. Porrò quot membra præcipua in duabus faciebus
majoribus, totidem distincta telaria numerabantur, quorum proinde
connexiones discerni vix poterant; eorumque aliquot paria ferreis
hamulis copulata erant, ut explicari ac replicari possent, ad faciliorem
tractationem diuturnioremque conservationem.
Qui hucusque sequuti me fuerint, nihil dubito quin suum iter
felicissimè sint prosequuturi; atque Opera his nostris majora
melioraque inventuri.
The Seventy-first FIGURE.
A Theater representing the Marriage of Cana in Galilee, erected in
the Jesuits Church at Rome, in the Year 1685; for the Solemnity of
exposing the Holy Sacrament.

ROM the foregoing Preparations, is drawn the


Perspective of this noble Piece of Architecture;
which struck the Eye when seen by Day-light, but
was more especially surprizing by Candle-light;
many of the Candles being expos’d to Sight, and
others altogether hidden, to illuminate the six
different Ranges of Scenes, of which the whole
Work consisted, without reckoning that in the midst of the great
Arch, representing Clouds fill’d with Angels adoring the blessed
Sacrament. Those Clouds are here omitted, that the inner Parts of
the Work might be the better seen. In disposing the several Ranges
of Scenes, the same Method was observ’d, which was deliver’d in
the Sixty-first and Sixty-second Figures; and great Care was also
taken in their Distances, that the Candles plac’d on the Back of one
of them might illuminate the Face of the other behind it. Moreover,
each Scene consisted of as many parts, as there were principal
Members in the two greater Façades; so that the Joints were
scarcely discernible: and some Pairs of them being coupl’d with
Hinges, folded and unfolded, for the more easy managing and
preserving them.
I doubt not but those who have follow’d me thus far, will be
encourag’d so to prosecute their Studies, as to be able to design
even greater and more noble Works, than these of mine.
Fig. lxxii.
FIGURA Septuagesimasecunda.
De theatris scenicis.

HEATRIS quæ jam delineavimus affinia sunt


theatra scenica: in his tamen non adeò facilè
reperitur punctum oculi seu perspectivæ.
Præterea, quia ex obliquitate canalium intra quos
moventur scenæ, oritur ut lineæ rectæ quæ videri
debent parallelæ ad lineam plani, non debeant
esse parallelæ sed obliquæ, harum delineatio
difficultate non caret. Incommodum istud vitari posset adhibendo
canales parallelos ad poscenium, ut alicubi fieri solet, præsertim in
Germaniâ. Nihilominus usus Italicus affert hoc adjumentum, ut illi
quibus incumbit suggerere actoribus, vel scenas movere, aliisque
similibus præesse, facilius lateant & liberius fungantur munere suo.
Ut brevem summam habeas eorum quæ deinde latius declaraturi
sumus, hanc figuram contemplare. 1, 2, 3, 4, est vestigium aulæ
quæ habet in longitudine centumviginti palmos Romanos, in
latitudine sexaginta palmos; ut ostendit scala S triginta palmorum.
Medietatem loci occupat theatrum, medietatem obtinent podia &
loca spectatorum. O punctum in quo uniuntur lineæ visuales, D locus
pro apparentiis rerum magis ac magis distantium. BC locus poscenii.
HH sunt canales obliqui, quorum latitudo est dupla latitudinis
scenarum. FG frons & facies theatri. AO ejus profunditas aut
longitudo. E locus pro psaltibus, tibicinibus, & fistulatoribus. K
spatium pro spectatoribus. I vestigium podiorum. L scalæ podiorum.
N ipsorum elevatio. M declivitas tabulati, cum sectione & elevatione
theatri, & scenis ex latere inspectis, quæ cum suis canalibus
congruunt, ut demonstrant lineæ occultæ. OO linea normalis ad
lineam horizontalem. P & Q elevatio scenarum coram inspectarum,
quæ introrsum flectuntur; & in latitudine congruunt cum canalibus
vestigii B, in altitudine cum sectionibus elevationis M; ut constat ex
lineis occultis. In eâdem elevatione M pars altitudinis tribuenda est
scenis, pars laquearibus R, per quæ jungitur unumquodque par
telariorum. VV lineæ ad explorandum an detur vacuum inter scenas
& laquearia, vel inter scenas, vel inter laquearia. In quibusdam
autem scenis, loco laquearium pinguntur nubes & aer.
The Seventy-second FIGURE.
Of Scenes for the Stage.

CENES for the Stage have very much Affinity with


those lately describ’d, but the Point of Sight is not
so easily found in these; and from the Obliquity of
the Grooves in which the Scenes run, it comes to
pass, that the right Lines which ought to appear
parallel to the Line of the Plan, must not be drawn
parallel thereto, but oblique; which is a Work of
some Difficulty. This indeed may be avoided, by fixing the Grooves
parallel to the Poscene; as is usual in some Places, especially in
Germany. Nevertheless, the Italian Manner has this Advantage; That
those who are employ’d to prompt the Actors, and shift the Scenes,
&c. are less expos’d to Sight, in the Performance of their Business.
In this Figure I have given you an Abridgment of those things,
which shall hereafter be more enlarg’d on. The Numbers 1, 2, 3, 4,
denote the Area of a Hall an hundred and twenty Roman Palms in
Length, and sixty in Breadth; as is manifest from the Scale of thirty
Palms mark’d S. Half this Space is taken up by the Stage, the other
half by the Spectators. O is the Point in which the visual Lines
concenter. D is the Place of those things that are to appear most
remote. BC is the Place of the Poscene. HH are the oblique Grooves,
whose Lengths are double the Breadth of the Scenes. FG is the Front
of the Stage. AO is its Depth or Length. E is the Place for the Musick.
K is the Room for Spectators. I is the Plan of the Galleries. L the
Stairs to the same. N is the Elevation of the Galleries. M shews the
Declivity of the Floor, with the Section and Elevation of the Stage
and Scenes view’d on the Side; answering their respective Grooves,
as the occult Lines demonstrate. OO is a Line perpendicular to that
of the Horizon. P and Q are the Elevation of the Scenes view’d in
Front, turning inwards, in Breadth agreeing with the Length of the
Grooves of the Plan B; and in Height answering that of the Sections
of the Elevation M; as is evident from the occult Lines. In this Profile
M, part of the Height belongs to the Scenes, and part to their
Soffites, or Ceilings, R; where each Pair of these Frames are join’d.
VV are the Lines by which is espy’d what Vacancy there is either
between the Scenes and their Ceilings, between the Scenes
themselves, or between their respective Ceilings; though in some
Scenes the Place of these last is supply’d by painting therein the Air
with Clouds, &c.

Fig. lxxiii.
FIGURA Septuagesimatertia.
Aliud vestigium theatri, ubi de modo inveniendi ejus punctum.

I pingendæ sint scenæ theatri alicujus antea


constructi, delineare oportebit vestigium
geometricum ex ipso erutum, (ad formam vestigii
quod cernis in hac paginâ) ut inveniatur longitudo
theatri, seu distantia quam ejus punctum habet à
puncto A: id autem nullo negotio fiet, accipiendo
distantias BC inter primos canales, & DE inter
ultimos, ac ducendo visuales MO, NO: nam theatrum habebit
longitudinem AO, ac punctum perspectivæ in vestigio theatri erit O.
Præterea scire oportebit longitudinem & latitudinem canalium,
eorumque numerum, distantias, & flexus; ac præcipuè curandum
est, ut licet sint obliqui ad lineam MN, sint invicem paralleli in
unoquoque latere, ac singuli tangant lineas MO, NO. Jam si rectæ
AO fiat æqualis recta FA, in F erit punctum distantiæ: adeoque si
theatrum juxta methodum à nobis tradendam depictum fuerit,
spectatori qui consistat in F apparebit veluti tabula picta juxta leges
perspectivæ, posita in A.
The Seventy-third FIGURE.
Another Plan of a Theater, with the Method of finding the Point of
Sight therein.

F it be requir’d to paint the Scenes of some Theater


already built, the Geometrical Plan thereof must
first be carefully drawn, (as you see, for Example,
in this Plate) that the Length of the Theater may
be found; or the Distance of its Point from that of
A; which is easily done, by taking the Interval BC
of the first Grooves, and DE of the latter; and
drawing the Visuals MO, NO: for AO is the Length of the Theater,
and the Point of Sight, or Perspective, therein, is O. Moreover the
Length and Breadth of the Grooves must be known, as also their
Numbers, Distance, and Obliquity; and especial Care must be taken,
that though they be oblique to the Line MN, that on each Side they
be Parallels between themselves, and that they all touch the Lines
MO, NO. If you then make AO equal to FA, the Point of Distance will
be F; and if the Theater be painted according to the Rules hereafter
given, it will appear to him that views it from F, as a regular Piece of
Perspective plac’d in A.
Fig. lxxiv.
Figura Septuages. quarta.
Sectio Scenarum Theatri.

RÆTER vestigium Theatri delineanda est sectio


scenarum. Itaque si acceptis mensuris altitudinis,
quam punctum A unde incipit tabulatum, ac
punctum D poscenii, habent supra planum
horizontale FV, fiant ex perpendiculo NV tum recta
ADO ex qua innotescit declivitas tabulati, tum
recta NO, quæ sit parallela ad FV & æqualis rectæ
AO figuræ septuagesimætertiæ; punctum theatri in elevatione est O;
in poscenio verò punctum theatri est Q. Si maxima scenarum
altitudo sit EB, recta OE dat altitudinem omnium reliquarum. Vera
tamen altitudo cujuslibet scenæ est illa quam habet linea major, ex
minori autem dignoscitur quantum obliquitas cujusque scenæ
apparenter minuat altitudinem extremæ illius lineæ. Porro excessus
quo linea major superat minorem tum in summo tum in imo,
diligenter notandus est, hinc enim pendet intelligentia figuræ
septuagesimæquintæ. Punctum M quod est remotum ab N quantum
in figura septuagesimatertia punctum F est remotum ab A, designat
locum unde Theatrum spectari oporteat, ut ibidem notavimus.
In construendo tabulato solet servari hæc regula, ut altitudo
puncti O sit æqualis altitudini oculi, & elevatio ex A usque ad D sit
nona circiter vel decima pars ipsius longitudinis AD. Expediret autem
ad scenas facilius movendas, pavimentum F esse profundius
pavimento G, ut erecto corpore sub tabulato ambulari possit.
Seventy-fourth Figure.
The Section or Profile of Scenes for Theaters.

ESIDES the Plan of the Theater, the Section of the


Scenes is also to be delineated, for finding the
Point of the Theater in the Elevation. Wherefore,
setting the Measures of the Heights which the
Point A, where the Floor of the Stage begins, and
the Point D of the Poscene, have above the Level
of the Horizontal FV; from the Perpendicular NV
draw the right Line ADO, which gives the Declivity of the Stage; then
make NO parallel to FV, and equal to AO of the Seventy-third Figure:
The Point of the Theater in Elevation is O; the Point of the same on
the Poscene is Q. If EB be the greatest Height of the first Scene, the
Line OE determines the Height of all the others. The longest of the
two Lines gives the true Height of each Scene; and the shorter
discovers how much of that Height the Sight loses on the Out-line,
by the oblique Position of the Scenes. Moreover, the Excess of the
longer Line above the shorter, as well at top as at bottom, is to be
well observ’d; for on this depends the right Understanding of the
Seventy-fifth Figure. The Point M, which is as far distant from N, as
that of F is from A in the Seventy-third Figure, denotes the Place
from whence the Stage ought to be view’d; as is there mention’d.
In laying the Floor of the Stage, this Rule is commonly observ’d,
That the Height of the Point O be made equal to the Height of the
Eye, and that the Rise of the Floor from A to D, be about a Ninth or
Tenth Part of the Length AD. ’Tis also requisite, for the better
shifting the Scenes, that the Pavement F be sunk lower than that of
G, that a Man may walk upright under the Floor thereof.
Fig. lxxv.
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!

ebookball.com

You might also like