Programming in Objective C 1st Edition by Stephen Kochan 067248420X 9780672484209 download
Programming in Objective C 1st Edition by Stephen Kochan 067248420X 9780672484209 download
https://ebookball.com/product/programming-in-objective-c-1st-
edition-by-stephen-kochan-067248420x-9780672484209-15258/
https://ebookball.com/product/programming-in-c-4th-edition-by-
stephen-kochan-9780132781190-0132781190-15230/
https://ebookball.com/product/c-common-knowledge-essential-
intermediate-programming-1st-edition-by-stephen-dewhurst-
isbn-0321321928-9780321321923-12370/
https://ebookball.com/product/learn-objective-c-for-java-
deve-1st-edition-by-james-bucanek-9781430223702-1430223707-8822/
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/
https://ebookball.com/product/memory-as-a-programming-concept-in-
c-and-c-1st-edition-by-frantisek-franek-
isbn-051183862x-9780511838620-14982/
https://ebookball.com/product/functional-programming-in-c-1st-
edition-by-enrico-buonanno-isbn-9781638354048-1638354049-15788/
https://ebookball.com/product/object-oriented-programming-
in-c-1st-edition-by-nabajyoti-
barkakati-0672228009-9780672228001-15280/
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
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
. ., .
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
• 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
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
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");
",
..•.
• '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"
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
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);
}
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;
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;
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 ()
,-
"
: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
Main ()
-::
1* Declare variables *1
j.nt v~~luelt val~Je2t S\JM;
E x E R c s E s
• • • • • • • • •
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);
:::-
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.
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
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
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.
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);
)
integer_val' = 100
floating_val' = 331.789978
double_val' 8.~~0000E+ll
char_val' = 101
22 o PROGRAMMING IN C 0
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.
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
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;
,lt = a + b
res •.. 'II. c;
printf ("a + b
* c = 7.d\n", result);
" Variables, Constants, Data Types, and Arithmetic Expressions " 25
a - b 98
b c
)I( 50
a / c 4
a + b c)I( 150
a )I( b + c )I( d = 300
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
*
(a b) + (c d) * or
(100 * 2) + (25 * 4)
Program 4.3
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
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
Program 4.4
Maira ()
{
irat a = 25, b = 5, c = 10, d = 7;
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
will be evaluated as
Program 4-5
/* Basic conversions in C */
",ain ()
{
float fl = 123.125. f2:
int i1. i2 = -150:
char c = ., a' :
fl =
i2 / 100: /* integer divided b~ integer */
printf ("Xd divided b~ 100 prodLlces i::f\n".i2. f1):
E x E R c s E s
• • • • • • • •
Int char
calloc X;.:
floati.ng _.1312
ReIni.ti.ali.ze A$
32 o PROGRAMMING IN C 0
OXab05 OL -597.25
4. Write a program that converts 27° from degrees Fahrenheit (F) to degrees
Celsius (C) using the formula
c= (F- 32)/1.8
c = 'd';
d = c;
print.f (lid = :Y.c\n", d);
::-
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.)
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
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;
• 34 •
o Program Looping 0 35
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;
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
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.
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
a = 2
n <= 200
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
Main ()
-::
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
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
--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).
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;
triangular_nUMber = 0;
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.
Fig. lxix.
FIGURA Sexagesimanona.
Deformatio vestigii figuræ sexagesimæseptimæ, & præparatio
tertia ad figuram septuagesimamprimam.
Fig. lxx.
FIGURA SEPTUAGESIMA.
Deformatio elevationis figuræ sexagesimæoctavæ, & præparatio
quarta ad figuram septuagesimamprimam.
Fig. lxxi.
FIGURA Septuagesimaprima.
Theatrum repræsentans Nuptias Canæ Galilææ, constructum
Romæ, anno 1685. in expositione Ven. Sacramenti in Templo
Farnesiano Societatis JESU.
Fig. lxxiii.
FIGURA Septuagesimatertia.
Aliud vestigium theatri, ubi de modo inveniendi ejus punctum.
ebookball.com