Chapter 1 - 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 133

1

C Fundamentals

9 chapter objectives
1.1 Understand the components of a C program
1.2 Create and compile a program

r]
1.3 Declare variables and assign values
1.4 Input numbers from the keyboard
1.5 Perform calculations using arithmetic
expressions
1.6 Add comments to a program
1.7 Write your own functions
1.8 Use functions to return values
1.9 Use function arguments
1.10 Remember the C keywords
2 TEAcH YOURSELF
V

..aival elements of a computer language such as C do


not stand alone, but rather in conjunction with one another.

.T Therefore, it is necessary to understand several key aspects


of C before examining each element of the language in detail,
To this end, this chapter presents a quick overview of the C
language. Its goal is to give you sufficient working knowledge of C so
that you can understand the examples in later chapters.
As you work through this chapter, don't worry if a few points are
not entirely clear. The main thing you need to understand is how andY
why the example programs execute as they do. Keep in mind that
most of the topics introduced in this chapter will be discussed in
greater detail later in this hook. In this chapter, you will learn about
the basic structure of a C program; what a C statement is; and what
variables, constants, and functions are. You will learn how tc display
text on the screen and input information from the keyboard.
To use this book to the fullest, you must have a computer, a C
compiler, and a text editor. (You may also use a C++ compiler. C++
compilers can also compile C programs.) Your compiler may include
its own text editor, in which case you won't need a separate one. For
the best results, you should work along with the examples and try the
exercises.


NOERSTAND THE IPONENTS OF A
C PROGRAM
All Cprograrns share certain essential components and traits. All C
programs consist of one or more functions, each of which contains one
or more statements. In C, a function is a named subroutine that can be
called by other parts of the program. Functions are the building blocks
of C. A statement specifies an action to be performed by the program.
In other words, statements are the parts of your program that actually
perform operations.
All C statements end with a semicolon. C does not recognize the
e na_o-nre Iffie as terminator. This mea'hs There are no constraints on
the position of statements within a line. Also, you may place two or
more statements on one line.
C FUNDAMENTALS 3
1.1 UNDERSTAND THE COMPONENIS OFA C PROORAM

The general form - of. a C ftinction is shown here:


--ret-type function-name(ParamItSO

statement sequence

Here et-!ye specifies the type of data returned by the function.)


As you willee,
s it is 'ora fur fintoitUThaVaIUe. The
rnctton-name is the name of the function. Information can be passed
^6 _a function through its parameters, which are specified in the
function's parameter list, pa ram-list. The statement sequence may be
one or more statements. (Technically, a function can contain no
statements, but since this means the function performs no action, it is
a degenerative case.) If return types and parameters are new concepts,
don't worry, they will be explained later in this chapter.
With few exceptions, you can call a function by any name you like.
It must be composed of only the upper- and lowercase letters of the
alphabet, the digits 0-9, and the underscore. A digit cannot start a
function name however. C is case-sensitive, which means that C
recognizes the difference between upper- and lowercase letters.
Thus, as far as C is concerned, Myfunc and inyfunc are entirely
different names.
Although a C program may contain several functions, the only
function that it must have is main( ). The main( ) function is where
execution of your program begins. That is, when your program begins
running, it starts executing the statements inside main( ), beginning
with the first statement after the opening curly brace. Your program
ends when main( )'s closing curly brace is reached. Of course, the
curly brace does not actually exist in the compiled version of your
program, but it is helpful to think of it in this way.
Throughout this book, when a function is referred to in text, it will
be prir ed in bold and followed by parentheses. This way, you can see
immeIiately that the name refers to a function, not some other part
of the program.
Another important component of all C programs is library functions.
The ANSI C standard specifies a set of library functions to be supplied
by all C compilers, which your program may use. This collection of
4 TEACH YOURSELF
V

IUflCtiOflS is usuall y rcferred to as the C standard library. The standard


library contains functions to perform disk I/O (input/ output), string
manipulations, mathematical computations, and much more. When
your program is compiled, the code for each librar y function used by
y our program is automatically included. This differs from the way
some other computer languages work. For example, in BASIC or
Pascal, operations such as writing to a file or computing a cosine are
performed using keywords that are built into the language. The
advantage C gains b y having them as library functions is increased
flexibility. Library functions can be enhanced and expanded as needed
to accommodate changing circumstances. The C language itself does
not need to change. As you will see, virtually all C programs you
create will use functions from the C standard library.
(Qjc of the most common library functions is called printf( ). This
is C I S CMI-])Lirpose out pit jfujnc .tionqThc printf — ftTrct1on is quite
verstiThTaflowing many variations. Its simplest form is shown here:
printI( "string-to-output"):
The printf( ) function outputs the characters that are contained
between the beginning and ending double quotes to the screen. (The
double quotes are not displayed on the screen.) In C, one or more
characters enclosed between double quotes is called a string. The
quoted string between printf( )'s parentheses is said to be an argument
to printf( ). Ingc lie raijnformation passed to a function is called an
argument. In C, calting a library function is a stat terefore, it
must end w)thsemicolon.
To call a function, you specify its name followed by a parenthesized
list of arguments that you will be passing to it. If the function does
not require any arguments, no arguments will be specified—and the
parenthesized list will be empty. If there is more than one argument,
the arguments must be separated by commas.
Another component common to most C programs is the header file.
In C, information about the standard library functions is found in
various files supplied with your compiler. These files all end with a
.H extension. The C compiler uses the information in these files to
handle the library functions properly. You add these files to your
program using the #include All C compilers use
as their first phase of compilation a preprocessor, which performs
various manipulations on your source file before it is compiled.
C FUNDAMENTALS 5
I.? UNDERSTAND THE COMPONENTS OFA C PROGRAM 'V

Preprocessor directives are not actually part of the C language, but


rather instructions from you to the compiler. The #include directive
tells the preprocessor to read in another file and include it with your
program. You will learn more about the preprocessor later in this book.
The most commonly required header file is called STDIO.H. Here is
the directive that includesFiifile: -

*include <stdio.h>
-
You can specify the fl.'c name in either upper- or lowercase, but
lowercase is the trauonal method. The STDIO.H header file
contains, among other things, information related to the printf()
library function. Notice that the # include directive does not end with
a semicolon. The reason for this is that # include is not a C keyword
that can define a statement, Instead, it is an instruction to the C
compiler itself.
One last point: With few exceptions, C ignores spaces. That is, it
doesn't care where on a line a statement, curly brace, or function
name occurs. If you like, you can even put two or more of these items
on the sand line. The examples you will see in this book reflect the
way C code is normally written; it is a form you should follow. The
actual positioning of statements, functions, and braces is a stylistic,
not a programming, decision.

1. Since all C programs share certain common traits,


understanding one program will help you understand many
others. One of the simplest C programs is shown here:
inc1ue <stdio.h>

int main(void)

printf("Thl.s is a short C program.);

return 0;
6 TEACH YIMJRSELF

When compiled and executed, this program displays the message


This is a short C program. on the screen of your computer.
Even though this program is only six lines long, it illustrates
those aspects common to all C programs. Lets examine it line
by line.
The first line of the program is
#include <stdio.h>

It causes the file STDIO.H to be read by the C compiler and to


be included with the program. This file contains information
related to printf( ).
The second line,
mt main(void)
begins the main( ) function. As stated earlier, all C programs
must have a main() function. This is where program execution
begins. The mt specifies that main( ) returns an integer value.
The void tells the compiler that main( ) does not have any
parameters.
After main( ) is an opening curly brace. This marks the
beginning of statements that make up the function.
The next line in the program is
printf(Thjs is a short C program.");

This is a C statement. It calls the standard library function,


printf( ), which causes the string to be displayed.
The following line causes maifjp return the value zero. In
this case, the value is returned to the calling process, which is
usually the operating system.
return 0;

By convention, a return value of zero from main( ) indicates


normal program termination. Any other value represents an
error. The operating system can test this value to determine
whether the program ran successfully or experienced an error.
return is one of C's keywords and is examined more closely
later in this chapter.
Finally, the program is formally concluded when main( )'s
closing curly brace is encountered.
C FUNDAMEHTP.1.S 7
2 CREATE AND COMPILE PROGRAM

2. Here is another simple C program:


*include <stdjo.h>

mt main (void)

printfY' This is );
printf("another C •');
prinet ( progrant. ')

return 0;

This program displays This is another C program. on the


screen. The key point to this program is that statements are
executed sequentially, beginning with the opening curly brace
and ending with the closing curly brace.

rREATE AND COMPILE A PROGRAM


How you will create and compile a program is determined to a very
large extent by the compiler y ou are using and the operating system
under which it is running. If you are using a PC or compatible, you
have your choice of a number of excellent compilers, such as those by
Borland and Microsoft, that contain integrated program-development
environments. If you are using such an environment, you can edit,
compile, and run your programs directly inside this environment.
This is an excellent option for beginners—just follow the instructions
supplied with your compiler.
If you are using a traditional command-line compiler, then you
need to follow these steps to create and compile a program:

1. Create your program using an editor.


2. Compile the program.
3. Execute your program.
The exact method to accomplish these steps will be explained in the
user's manual for your compiler.
I EACH YOURSELF
V

Nearly all modern C compilers are also C++ compilers. As you


maykuow, C++ is the object-oriented extension to C. Most likelyyou
will he using a C++ compiler to compile your C code. Don't won-v. This
is perfectly acceptable because all C++ compilers are capable of
compiling C programs. For example, ifyou arc using Borland C++ or
Microsoft Visual C++, then everything will workjust fine. However,
there is one thing about which you must be very careful: the extension
you give your files.
When naming your program's file, you must give it a C—not
.CPP—extension. This is important. If you are using a C++ compiler,
then it will automatically assume that a file using the .0 extension
contains a C program and will compile it as a C program. But, if the file
uses a .CPP extension, then the compiler will assume that the program is
written in C++ and compile it as such. The problem is that while C is the
foundation for C++, not all C programs are valid C++ prograruis.Trying
to compile a C program as if it were a C++ program will cause error- in a
few cases. Since the programs in thisbook are C programs, they should ie
compiled as C programs. Using the .0 extension ensures this.

Remember Your program must be compiled as a C program—not a C++ program. To


ensure this, make sure that your programs use the ,C, not the .CPP, extension.

The file that contains the C program that you create is called the
source file. The file that contains the compiled form of your program
that the computer executes is called the object file, or, sometimes, the
executable file.
If you enter something into your program incorrectly, the compiler
will report syntax error messages when it attempts to compile it. Most
C compilers attempt to make sense out of your source code no matter
what you have written. For this reason, the error that gets reported
may not always reflect the actual cause of the error. For example,
accidentally forgetting the opening curly brace to the main( )
function in the preceding sample programs will cause some compilers
to report the printf( ) statement as an incorrect identifier. So, when
You receive a syntax error message, be prepared to look at the last few
lines of code in your program before the point at which the error is
reported to find its cause.
Many compilcr 'port not only actual errors but also warning
errors. The C la g. 'e was designed to be very forgiving and to allow
C FUNDAMENTALS 9
1.2 CREATE AND COMPILE APROGRAM 'V

virtually anything that is syntactically correct to be compiled. However,


some things, even though syntactically correct, are highly suspicious.
When the compiler encounters one of these situa:u. is it prints a
warning. You, as the programmer, then decide whether its suspicions
are justified. Frankly, some compilers are a hit too helpful and flag
warnings on perfectly correct C statements. More important, some
compilers allow you to enable various options that simply report
information about your program that you might like to know. Sometimes
this type of information is reported in the form of a warning message,
even though there is nothing to be 'warned' about. The programs in
this book are in compliance with the ANSI standard for C and will not
generate any warning messages about which you need he concerned.

1. If you are using Borland C++, you can create and compile your
program using the integrated environment. Online instructions
are provided. If you are using the command-line version of
Borland C++, you will use a command line such as this
(assuming that the name of your program is called TEST.C)
to compile the program once you have used a text editor to
create it.
BCC TEST.0
2. If you are using Microsoft Visual C++, you can use the
integrated environment to create and compile your program.
Online instructions are provided. When using the command line
compiler, this command line will compile your program after
using a text file to create it. (Again, assume that the program is
called TEST.C.)
CL TEST.0
3. If you are using another brand of compiler, refer to your user's
manual for details on compiling your programs.
10 TEACH YOURSELF
V

EXERCM
1. Enter into your computer the example programs from Section
I.I. Compile them and run them.

ECLARE VAJ NIABLES AND ASSIGN


VALUES
'A variable is a named memory location that can hold various values.)
Only the most trivial C programs do not include variables. In C, unlike
some computer languages, all variables must be declared before they
can be used. A variables declaration serves one important purposei It
tells the compiler what type of variable is being used. C supports five
different basic data types, as shown in Table 1-1 along with the C
keywords that represent them. Don't be confused by void. This is a
special-purpose data type that we will later examine closely.
A variable of type char is8bits long and is most commonly used to
hold a single character. Because C is very flexible, a variable of type
char can also be used as a little integer if desired.
Integer variables (int) may hold signed whole numbers (numbers
with no fractional part). For 16-bit environments, such as DOS or
Windows 3.1, integers are usually 16 bits long and may hold values in
the range 7to 32,767. In 32-bit environments, such as Windo
NT or Windows 95, integers are typically 32 bits in length. In this c,
they may store values in the range -2,147,433,648 to 2,147,483,647.

Type Keyword
character data char
signed whole numbers mt
floating-point numbers float
double-precision floating-point numbers double
valueless void
iiTnl u C's Five Basic Data Types V
C RJ*JAMU4TALS
DECLARE VARIABLES AND ASSIGN VALUES

Variables of types float and double hold signed floating-point


values, which may have fractional components. One difference
between float and double is that double provides about twice the
precision (number of significant digits) as does float. Also, for most
uses of C, a variable of type double is capable of storing values with
absolute magnitudes larger than those stored by variables of type
float. Of course, in all cases, variables of types float and double can
holdyery large values.
o declare a variable, use this general form:

/ type var-name;
where type is a C data type and var-name is the name of the variable.
For example, this declares counter to be of type int:
mt counter;

In C, a variable declaration is a statement and it must end in a


semicolon.
There are two places where variables are declared: inside a function
or outside all functions. Variables declared outside all functions are
called,global variables and they may he accessed by any function in
your program. Globl variables exist the entire time ypurprogram
is executing.
Variables declared inside a function are called local variables. A local
variable is known to—and may be accessed by—only the function in
which it is declared. It is common practice to declare all local variables
used by a function at the start of the function, after the opening curly
brace. There are two important points you need to know about local
variables at this time. First, the local variables in one function have
no relationship to the local variables in another function. That is, if
a variable called count is declared in one function, another variable
called count may also be declared in a second function—the two
variables are completely separate from and unrelated to each other.
The second thing you need to know is that local variables are created
when a function is called, and they are destroyed when the function is
exited. Therefore, local variables do not maintain their values between
function calls. The examples in this and the next few chapters will use
only local variables. Chapter 4 discusses more thoroughly the issues
and implications of global and local variables.-
12 TEACH YOURSELF

You can declare more than one variable of the same type by using a
comma-separated list. For example, this declares three floating-point
variables x, y, and z:
float x, y, z;

Like function names, variable names in C can consist of the letters


of the alphabet, the digits 0 through 9, and the underscore. (But a digit
may not start a variable's name.) Remember, C is case-sensitive;
count and COUNT are two completely different variable names.
To assign a value to a variable, put its name to the left of an equal
sign. Put the value you want to give the variable to the right of the
equal sign. In C, an assignment operation is a statement; therefore, it
must be terminated by a semicolon. The general form of an
assignment statement is: -
variable-name = value;

For example, to assign an integer variable named num the value 100,
you can use this statement:
- nun = 100;

In the preceding assignment, 100 is a constant. Just as there are


different types of variables, there are different types of constants. A
constant is a fixed value used in your program. Constants are often
used to initialize variables at the beginning of a program's execution.
A character constant is specified by placing the character between
single quotes. For example, to specify the letter you would use
W. Integers are specified as whole numbers. Floating-point values
must include a decimal point. For example, to specify 100, 1, you
would use 100.1. If the floating-paint value you wish to specify does
not have any digits to the right of the decimal point, then you must
use 0. For example, to tell the compiler that 100 is a floating-point
number, use 100.0.
You can use printf( ) to display values of characters, integers, and
floating-point values. To do so, however, requires that you know more
about the printf( ) function. Let's look first at an example. This
statement:
printf("This prints the number %d, 99);
CFUNDAMENTAI& 13
1.3 DECLARE VARIABLES AND ASSIGN VALUES

displays This prints the number 99 on the screen. As you can see,
this call to printf( ) contains not one, but two arguments. The first
is the quoted string and the other is the constant 99. Notice that the
arguments ard separated from each other by a comma. In general,
when there is moie than one argument to a function, the arguments
are separated from each other by commas. The operation of the
printf( ) function is as follows. The first argument is a quoted string
that may contain either normal characters or format specifiers that
begin with the percent sign. Normal characters are simply displayed
as-is on the screen in the order in which they are encountered in the
string (reading left to right). A format specifier, also called a format
code, informs printf( ) that a different type item is to be displayed. In
this case, the %d means that an integer is to be output in decimal
, format. The value to hedi l 'edi found iniTic second argument.
This value is then output to the screen at the point where the format
specifier is found in the string. To understand the relationship
between the normal characters and the format codes, examine this
statement:
printf('This displays %d, 99);

Now the call to printf() displays This displays 99, too. The key
point is that the value associated with a format code is displayed at the
point where that format code is encountered in the string.
If you want to specify a character value, the format specifier is %c.
To specify a floating-point value, use %f. The %f works for both float
and double. As you will see, prin&f has many more capabilities.
Keep in mind that the values matched with the format specifier
need not be constants; they may he variables, too.

Th program shown here illustrates the three new concepts


introduced in this section. First, it declares a variable named
num. Second, it assigns this variable the value 100. Finally, it
uses printf( ) to display The value is 100 on the screen.
Examine this program closely:
14 TEACH YOURSELF
V

cl:de oh>

i-t main(void)

mt num;

riuin = 100;
printf("The value is %d num);

return 0;

The statement
mt nuin;

declares num to be an integer variable.


To display the value of num, the program uses this statement:
pr, intf("The value is %d". nun);

2 This program creates variables of types char, float, and double;


assigns each a value; and outputs these values to the screen.
#include <stdio.h>

mt main(void)

char ch;
float f;
double d;

ch =
f = 100.123;
d = 123.009;

printf(ch is %c, , ch);


printf(f is %f. ,
printfVd is %f, dl;

return 0;
C FUNDAMENTALS 15
7.4 INPUr NUMBERS FROM THE KEYBOARD

EKERCUM
1.En3compile, and run the example programs in this section.
num.
^ rite a program that declares one integer variable called
Give this variable the value 1000 and then, using one printf( )
statement, display the value on the screen like this:
Izz-
1000 is the value of nwn

NUMBERS FROM THE KEYBOARD


1though there are actually several ways to input numeric values from
the keyboard, one of the easiest is to use another of C's standard
library functions called scanf( ). Although it possesses considerable
versatility, wewill use it in this chapter to read only integers and
floatii-point numbers entered from the keyboard.
To use scanf( ) to read an integer value from the keyboard, call it
using the gene1TOrtf

nfC%d" &in f-var-name);

where mt-var-name is the name of the integer variable you wish to


receive the value. The first argument to scanf( ) is a string that
determines how the second argument will be treated. In this case, the
%d specifies that the second argument will be receiving an integer
value entered in-decimal format. This fragment, for example, reads an
integer entered from the keyboard.
mt nuin;
scanf("%d', &num);

The & preceding the variable name is essential to the operation


of scanf( ). Although a detailed explanation will have to wait until
later, loosely, the & allows a function to place a value into one of
its arguments.
16 TEACH YOURSELF
C

It is important to understand one key point: When you enter a


number at the keyboard, you are simply typing a string of digits. The
scanf() function waits until you have pressed ENTER before it
converts the string into the internal binary format used by the
computer.
To read a floating-point number from the keyboard, call scanf()
using the general-form
/ scanfC%f', & float-var-name;
were float-var-name is the name of a variable that is declared as being
of type float. If you want to input to a double variable, use the %lf
specifier.
Notice that the format specifiers for scanf( ) are similar to those
used for printf( ) for the corresponding data type except that %lf is
used to read a double. This is no coincidence—prinff( ) and scanf()
are complementary functions.

/L/ his program asks you to input an integer and a floating-point


/ number. It then displays the values you enter.
#include <stdio.h>

t main(void)

) mt nun;
/ float f;

printf(Enter an integer:
scanf("%d", &num);

printf('Enter a floating point number:


scanf(%f', &f);

printf("%d •, nun);
prmntf(*%f, f);

return 0;

C FUNDAMENTALS 17
5 PERFORM CAL CULA flOWS USING ARITHMETIC EXPRESSIONS'

F.XERCISES

Enter, compile, and run the example program.


2. Write a program that inputs two floating-point, numbers (use t y pe float)
and then dispLivs their sutn. -

CALCULATIONS USING
/
/ 44ffHMErIC EXPRESSIONS
/ -1n C, the exprcssion plays a much more important role than it does
most other programming languages. Part of the reason for this is the
detjiies nianv more perators than do most other languages. An
is a eoiuibin,iron of operators id operands. C expressions
follow the rules ut ah'hri. so, for the most part, the y will he familiar.
in this section we will k,ok onl y at arithmetic expressions.
C defines these five uitluinetic: operators:

Operator Meaning
additi
adci I ti ott
on

so Lit r a u: t On
iou ltipliett on
division
mod oh ii S

be + , - I, .uuud (peralo! :av he used with our of the bask, dat.


types. F however, the % ma y be used with integer t y pes only. I he
modulus operator i duces the remainder of an integer division.
This has no mean! ig when applied to floating-point types.
'lhe - has two meanings. First; it is the subtraction operator
wcoiid, it can he used is a unary minus to reverse the sign Of .1
riuniber. A unuiry osrator uses only one operand
An expressi'i iiuu . ' u : ii n the right side of an .issir1rII'n
I u ' fliS prugrani II'Liflerut .issi.
.insi hi ii lu ' v,11i I1H1
18 TEACH YOURSELF
V

answer;
arwer = 100 * 31;

The * I, and % are higher in precedence than the + and the -.


F{owevc r. von can use parentheses to alter the order of evaluation. For
example, this expression produces the value zero,

10-2 * 5
but th ill mm produces the value 40.

(10-2) * 5
AC expression ma y contain variables, constants, or both. For
example, assuming that answer and count are variables, this
expression is perfectly valid:
answer = count - 100:

Finally, you may use spaces liberally within an expression.

stated earlier, the modulus operator returns the remainder of


an integer division. The remainder of 10 % 3 equals 1, for
example. This program shows the outcome of some integer
divisions and their remainders:
#nc1udo <stdio.h>

mt main(void)

printf("%d". 5/2);
printf(' %d, 5%2);
printf(' %d', 4/2);
printf (" %d", 4%2);

return 0;

[his program displays 2 1 2 0 on the screen.


C FUNDAMENTALS. 19
1.5 PERFORM C4L COLA TIONS USING ARITHMETIC EXPRESSIONS

2. long expressions, the use of parentheses and SdCCS can add


clarity, even if the y are not necessary . For example, examine
this expression:
count nurn-58'va1--19%count.

This expression po dtices the same r(!sult, hut is much easier


to read:
rout * nun) + (CS / val) (19 % count)

S program computes the area of a rectangle, given its


,,If, nsi1 ns. It first prompts the user for the length and width of
- the rectangle and then displays the area.
51r,c1uo <stdio,h>

1: min(void)

mt Ion, width;

priritf("Enter length:
Scant C "%d" ,
print.f("Enrer wath:
scanf("%d", &wi;It)-;);

p1 let f("Area '.-:11, h)

return 0;

t As stated rue; Oir - ( dO he used as a nn;irv operator to


reverse the sign of its operant!. To see how this works, try
this po 1,41 ani
i nclu..ie rd o

jet rn1flCV3td)

let

rrr;L1)This is 1: %d", ii:


20 TEACH YOURSELF
V

return 0;

EXERCISES

1 Write a program that computes the volume of a cube. Have tile


jirogra mu prompt the user for each dimension.
2. Write a progranl that computes the number of seconds in a year.

DO COMMENTS TO A PROGRAM
A
A comwmmenl is a note to yourself (or others) that y ou put into your
oU1CC code. All comments are ignored b y the compiler. The y exist
solel y for your benefit. Comments are used primaril y to document the
miieimn i ng and purpose of your source code, so that you can remember
later how it functions and how to use it.
In C. the start of a comment is signaled b y the /* character pair.
.\ comiuiwnt is ended b y 1. For example, this is a s y ntactically correct
C C(mnloleflt:
Tn;n is a comment. I /
Comments can extend over s(\'er,nl lines, lot cxLinlplc, this is comptetel'
valid in C:

Tn;s is a [anger comment


that extends over
tiv-: lincs.
-I
In C, a comment can go an y where except in thr middle of any C
vu (>rd, function name, or variable name.
C FUNDAMUALS 21
16 ADO COMMENTS TOA PROGRAM

You can use a comment to temporarily remove a line of code.


Simply surround the line with the comment symbols
Although not currently defined by ANSI C standard, you may see
, It begins with
another style of comment, called a single-low comment.
a II acil stops at the end of the line. The single-line comment was
created b y C++. its use in a C program is technically invalid, but
most compilers will accept it. Assuch, many programmers have hcgufl to
USC it in thcirC programs. Since the single-line comment is not detiiiedby
the current ANSI C standard, thisbook will not use it. However, don't he
surprised ifvou sec it in commercially written
Cprograills.
One final point: In C. y ou can't have one comment within another
comment. That is, cornnients may not he nested For exaiiiplc, C will
not accept this:
1* this is a comment .' this is another comment
nested inside the first - which will cause
i with a nested comment
a syntax error

I A year on Jupiter (the time it takes for Jupiter to make one


full circuit around the Sun) takes about 12 Earth years.
following program allows Vol' to convert Earth da ys to Jovi,111
years. Simpl y specif' the number of Earth da y s, and it computes
tlw equivalent number of Jovian y ears. Notice the use
i:omlllents throughout the rogra 01.

/
This prograsn converts Earth days into Jovian years.
iincudc <stdio.h>

tnt main(void)

float e_days: / number of Earth days


float j ..years; 1 equivalent number of Jovian years

/ get number of Earth days 1


22 TEACH YOURSELF
V

printf(Enter number of Earth days:


scanf(%f" &e-days)

/ • now, compute Jovian years


i_years r e_days / (365.0 * 12.0);

/. display the answer -/


princE ("Equivalent Jovian years: %f, i_years);

return 0;

Notice that comments can appear on the same line as other C


prograill state in(,
(UflhIfl(iits are often used to help describe chat the program
is doing. Aith ioth this program is eas y to unit rstanct even without
the comments, niariv programs are ver y ditheolt to understand
even with the liberal use of comments. For more cotuplex
programs, the grutcr;il approault is the same as used here:
simpl y describe the actions of the program Also, Onto c the
conirne nt at the start Of he program. in general, it IS it idea

to ide ntify the purpose of it at the top of its to )urcc file.


2 'iou cannot place a comment inside the ilame of a function or
variable name. For example, this is an incorrect statement:
pcI i wrong */ntf(this won't work" ) ;

EXERCISES

• Go back anti add comments to the programs developed in


ous sections.
2. Is this comment correct?
1**!
3. Is this comment correct?
/" primittVthis is a test"); "1
C FUNDAMENTALS- 23
17 WRITE YOUR OWN FUNCTIONS

YOUR OWN FUNCTIONS

:ticns are the building blocks of C. SC) far, the programs you have
seen included only one function: main( ) Most real-world programs,
however, will contain many tUflCtiOflS. In this section y ou will begin to
learn how to write programs that contain multiple functions.
The general form of a C program that has multiple functions is
shown here:

/ include header files here V

/ function prototypes here V

mt main(void)

I. .. 'I

ret- type f (pararn- list)

I. ...

ret- type f21param-list

I.

ret-type IN(param-list)

I. .. •1

)f course, you can call y our functions b y difterent names Here,


cHype spec ites the tYpe of data returned h the function. If a
to nctioii clues nut return a value, then its return t y pe should be void.
It a function does not use paranieters, then its parwn-list should
tintain the keyword void.
24 TEACH YOURSELF
'V

rxuticc the comment about protot y pes. A (iirietiori prototype declares


a In nctiofl before it is uSed and por to its definition. :\ prototype
consists of a functions name, its return t y pe, and its parameter list.
It is ternunated 1w a semicolon. The compiler needs to know this
Information in order for it to properl y execute a tall to the tiinctioti
1-or example, given this simple function:

ryfunc vc.d)

f This is a test

Its prototype is

jh' univ fi.i flttiOil that does not nerd a prototype is main( ) 510cr
it is preilefitied h' the C language.
l'rotutvpes are an important part of progiarmuiilg, but von will
ned to learn more about C before von can full y LinderStand their
pi I poso 1111d value. For the next floe chapters we will be using prototypes
withoutan y further explanation. They will he included as needed in
all ol the (Nainpie progrtlnls shown in this book. You should also
include them ill programs that y ou write. A full explanation ot
protot y pes is foti rid in Chapter 7.
\\linra hi netion is called, execution transfers to that hinction
the end iii that function is reached, execution returns to a point
imnuiiatelv after the place at enteh the function was called. Put
ditterentiv. when a function ends, execution resumes at the point in
your po ' ram immediatel y following tIle call to the function. Any
Lu nct ion inside a program ma y call an y other function within the salle
program Traditionall y , main( ) is not (-ailed by any other function,
but there is no technical restriction to this effect.
ii the examples that follow, you will learn to create the simplest
tv rn of ( 1, functions: those that that do not return values and do not U5(
1)aranleters. The skeletal form of such a function is shown here.

void Fur.CNarnClVoid) I
body of motion here */
C FUNDAMENTALS 25
1.7 WRITE YOUR OWN FUNCTIONS

Of course, the name of the function will vary. Because the function
does not return a value, its return type is void. Because the function
does not have parameters, its parameter list is vo

Pie following program contains two functions: rnain( ) and funcl( ). Try to
determine what it displays on the screen before reading the description that
follows it.

/I A program with two functions */

include <stdio.h>

void funcl(void); i prototype for funclti

Int main(void)

pri.ritf("I
fund 1 C
prntf("C.");

return 0;

void ftnc1vo:d

prntfCiike

This n ogram displays I like C. on the screen. Here is how it


works. In main( ). the First call to printf( ) executes, printing
the I. Next, fund ( ) is called. This causes the printf( ) inside
fund ( ) to execute, displaying like. Since this is the oily
statement inside fund ( ), the function returns. This caLlSeS
execution to resume inside main( ) and the C. is printed.
Notice that the statenirnt that calls funel ( ) ends with a
semicolon (Remember a function call is a statement.)
26 TEACH YOURSELF
I,

A ke y point to understand about writing 'uur own functions is


that when the closing curl y brace is reached the function wifl
return, and execution resumes one line after the point at which
the fu riction was called.
Notice the prototype for find ( ). As you can see, it consists
of its name, return t y pe, and parameters list, but no bod y . It is
terminated by a semicolon.
2 '[his program prints 1 2 3 on the screen:
* This program has three functions.

#include <stdio.h'

void funcl(void); 1* prototypes


void func2(void);

jOt main(void)

func2 ()
print

return 0;

void func2 (void)

funvi. (1
printL(.

void funcl(vo_d)

pr jot f ( 1 . ")

In this program, main( ) first tills func2 ( ). which then calls


fu ticl ( ). Next. func ( ) displa y s I and titcit returns to func2( ),
which prints 2 and then returns to main( ), which prints 3.
C FUNDAMENTALS - 27
18 USE FUNCTIONS TO RETURN VALUES

EXERCES

1. Enter, compile, and run the two example programs in this


section.1
2. Write a program that contailis at least two Functions and prints
the message The summer soldier, the sunshine patriot.
3. Remove the prototypt , from tim first example prograill and then
compile it. What happens?

USE FUNCTIONS To RETURN VALUES


In C, a function ma y return a value to the calling routine. For
example, another of Cs standard I ibrarv functions is sqrt( ) which
returns the squ,irc, root of its argunietit. ['or y our progr.I ni to obtain
the return value, y ou must put the tu nctuoii on the right side of an
gflh1ueflt statement. For exuiiple, this program prints the square
root of 10:
Lr:cude <ctdio.h>
8include <math.h> / I needed by sqrt()

ier_ rnin(void

dub1e answer;

dnswer = sqrt(10.0);
print.f("%f", anser);

return 0;

[his programil calls sqrt( ) and assigns its return value to answer.
Notice that sqrt( ) US;S the M :\[E 1.11 header file
28 TEACH YOURSELF
'V

Actuall y , the assignment statement in the precedin g prngra Ifl is net


technicall y necessa iv because stlrt( ) could siuLpl y be used as an
argument to printf( ). as shown here:
#include <stdio.h'
$inc1ude <rnath.h> / needed b y sqitt)

mt main(void)

prin:f('%f, sqrt.(100));

return 0;

The reason this works is that C will automaticall y call sclrt( ) and
obtain its return value before calling printf( ) The return value then
becomes the second argument to printf( ). 11 this scents strange,
don't worry ; you Will understand this sort of situation better as ou
learn more about C.
The sqrt( ) function requires a floating-point value for its
arqu ment, and the value it returns is of t y pe double. YOU mLiSt match
the t y pe of value a function returns with the variable that the value
will be assigned to. As y ou learn more about C, you will see wh y this is
important. It is also important that y ou match the types of a funct;on's
arguments to the t y pes it requires.
When writing vuni own I nnctioflS, y ou can return a value to the
cahhine, routine using the return statement. The rcturn staement
takes the general firm

return vaIue
where P(LINC is the value to be returned. For example, this program
prints 10 on the screen.
tinc1ude <s:dio.h'

I
act. fuc('-od) ; ' :rctctype

mt

ir.t nurn;

nunt = func;
C FUNDAMENTALS
29
1. 8 USE FUNCTIONS TO RETURN VALUES

printf(%d, purn);

return 0;

mt func(void)

return 10;

In this example, func( ) returns an integer value and its return type
is specified as mt Although y ou can create functions that return any
t y pe of data, functions that return values of type mt are quite common.
Later in this book, y ou will see man y examples of lunctiuns that return
other t y pes. Functions that are declared as void mav not return values
If a titriction does not explicitly specif y a return t y pe, it is assumed
to return an integer b y default. For example, func( ) could have been
coded like this:
func (void)

return 10:

In this case, the mt is implied. The use of the dcfault to int' riile is
very common in older C code. However, recentl y there has been a
move awa y from using the integer defaLilt. Whether this trend will
c(ntitlue is unknown. In an y event, to avoid misunderstandings, this
book will alwa y s exphcit[v specify mt.
One important potti t: When the return statement is encountered,
the function returns im niecliitelv. No state Inc nts after it will he
executed. Thus, a return statement causes a function to return before
its closing curly brace is reached.
The value associated with the return statement need not he a
constant. It can he an y valid C expression.
A return statement can also be used b y itself, without a return
value. This k>rrn of return looks like this:
retr

It is used mosth' b y void fuii(ri as ( j r., tuticijuits thu have a void


return tvpi' ) ttise the f'uiil ton u t.;rii intmediat'lv. bell
It ti'

him 'ti 'n's ' hasin cmlv lira a-; reel i'd \\'hilt' lint 11, emniended,
1
30 TEACH YOURSELF
V

), oil also use this form of return in functions that are supposed
return values. 1-lowc'er, cluing so makes the returned value tindcfin d
There can he more than one return in a function You will see
examples of this later in this hook
Even though a function returns a value, you clout nccesSaril have
to assign that valuc to an y thing, lithe return value of a fWutioil is not
used it is lost, but no harm is done.

T EXAMPLES
This prograill displays the square of a number cii tcrecl from the
keyboard. The squareis computed using the geLsqr()
function. Its operation should be clear.
r. c7 '. ,I r1>

mt getsqr(vad);

..it rnOifl(VOC

mt sqr;

sqi m cjt_i r )
pr a nt f squ. sqz

reLurr C;

j ot . qetSqr(VOiCi)

nL nurn;

printf("FnPr a number:
scan f( '%c1 &nurn);
reLurr, nur,0Um; / squre

' uned edFII(i, \O)I tall 051; 1( till Il ,)til()lit


5})((iVI

valto- lids -s a !tlnt:lioil to returil before ic closing curl


1

brace is rt'a lod I or example, in the tollowing progrilli, iii'


C FUNDAMENTALS 3
1.8 USE FUNCTIONS TO RETURN VALUES

include <stdio.h>

void funcl(void);

mt main (void)

fund ();

return 0;

void funcl(void)

printf("This is printed.');
return; / return with no value
printf("This is never printed.");

EXCISES
1. Enter, compile, and run the example programs in this section.
2. Write a program that USC5 a function called convcrt( ), which
prompts the user for an amount in dollars and returns this value
converted into pounds. (Use an exchange rate of $2.00 per
1)011 lid.) Displa y the conversion.

3. What is wrong with this program?


#includ <stdio.h>

mt 11 (void)

mt main (void),

double answer;

answer = fl();
prirtf%f", answer);

return 0

TEACH YOURSELF
32
C

mt f (void

return 100;

is wrong with this function?

void func(void)

mt 1;

printfVEr.ter a number:
scanf &i)

return i;

S(E FUNCTION ARGUMENTS


*stad earlier, a tuticttiis it ttt11flt is a value that is passed to the

tunctioti when the lun(;ti( did A lunetiun in C in have from


zero to several ajuifleuts - tipper bout is detetnuned b y the
compiler you are uSing 11 at ti ANSI C standard specifieS that a
tuncuon must he able to Like at i1LtiflefltS.) Fot a function
to he able to take arguments, sp&:i 1,11 irii,ic to receive aigurnent
values must be declared. Thesc art' called the to oai 1 irontcteis of tb;
(unction 'The parameters arc decLireil between titi; parentheses that
follow the luilettoilS name I or s,tnple, tire fitni ti 111 listed below
pilots the sum of the tSVf) intlgt;r at ii inents used t o ( .all it.
t;,.17 x, irt Y)

1)1 tnt! C :'


C FUN(AME*1g 33
1.9 USE FUNCTION ARGUMENTS "

Each time sum() is called, it will sum the value passed to x with the
value passed to y. Remember, however, that x and y are simply the
function's operational variables, which receive the values you use
when calling the function. Consider the following short program,
which illustrates how to call sum().
/ A simple program that demonstrates sum)). *1

#include <stdio,h>

void sum(jnt x, mt y);

mt main (void)

sum(l, 20);
suITl(9,,.6);
sum(81, 9);

return 0;

void sum(int x, mt y)

printf("%d ", x +

This program will print 21, 15, and 90 on the screen. When sum()
is called, the value of each argument is copied into its matching
parameter. That is, in the first call to sumQ, 1 is copied into x and 20
is copied into y. In the second call, 9 is copied into x and 6 into y. In
th€ thfrd tall, At l& dd litfo t And 9 jfjft
If you have never worked with a language that allows parameterized
functions, the preceding process may seem strange. Don't worry—as
you see more examples of C programs, the concept of arguments,
parameters, and functions will become clear.
It is important to keep two terms straight. First, argument refers to
the value that is passed to a function. The variable that receives the
value of the argument Inside the function is the formal parameter of
the function. Functions that take arguments are called parameterized
34 TEACH YOtIRSW
V

fimctions. Remember, if a variable is used as an argument in a function, it


has nothing to do with the formal parameter that receives its value.
In C functions, arguments are always separated by commas. In this
book, the term argument list will refer to comma-separated arguments.
All function parameters are declared in a fashion similar to that
used by sum( ). You must specify the type and name of each
parameter and, if there is more than one parameter, you must use a
comma to separate them. Functions that do not have parameters
should use the keyword void in their parameter list.

An argument to a function can consist of an expression. For


\.X" example, it is perfectly valid to call sum( ) as shown here:
su.m(10-2, 9*7).

2. This program uses the outchar( ) function to output characters


to the screen. The program prints ABC.
Itinc1iide <stdio.h>
void outchar(ctiar cli);

mt main(void)

outchart 'A');
outchar( 'B');
outchar( 'C');
return 0;

void outchar(char ch)

printf('%c ch);
C FUNDAMENTALS 35
7.10 REMEMBER THE C KE'WORDS

EXERCISES

1. Write a program that uses a function called outnum( ) that


takes one integer argument and displays it on the screen.
2. What is wrong with this program?
#inciude <stdio.h>

void sqr_it(int num);

mt main(void)

sqr_it(10.0)

return 0;

void sqr , it(int num)

printf("%(_T", nuni * nun);

I
REMM8 THE C KEYWORDS
Before concluding this chapter, you should familiarize yourself with
the keywords that make up the C language. ANSI C standard has 32
ke.iju.ords that may not be used as variable or function names. These
words, combined with the formal C syntax, form the C programming
language. They are listed in Table 1-2.
Many C compilers have added several additional keywords that arc
used to take better advantage of the environment in which the
compiler is used, and that give support for interlanguage program-
ming, interrupts, and mcmory organization. Some commonly used
extended keywords are shown in Table 1-3.
The lowercase lettering of the keywords is significant. C requires
that all keywords be in lowercase form. For example, RETURN will
not be recognized as the ke yword return. Also, no keyword may he
used as a variable or function name.
36 TEACH YOURSELF

auto double mt struct


break else long switch
case enum register typedef
char extem return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while

•i1:1 . The 32 Keywords as Defined by the ANSI C Standard V

es
asm cs As

ss cdecl far huge
interrupt near pascal

Some Common C Extended Keywords V

Mastery
Skills Check

I. The moon's gravity is about 17 percent of Earth's. Write a


program that allows you to enter your weight and computes
your effective weight on the moon.
2. What is wrong with this program fragment?
I this inputs a number
scanf(%d, &nwm);

3. There are 8 ounces in a cup. Write a program that converts


ounces to cups. Use a function called 0_to_co to perform the
conversion. Call it with the number of ounces and have it return
the number of cups.
4. What are the five basic data types in C?
C FUNDAMENTA1S 37
110 RLMEM1ER THE CKEYWORDS

S What is wrong with each of these variable names?


a) short-fall
b) $halancc
c) last -4- name
d) 9times
-0
Introducing C's
Program Control
Statements

chapter obIeclivea
2.1 Become familiar with the if
2.2 Add the else

2.3 Create blocks of code


2.4 Use the for loop

2.5 Substitute C's increment and decrement


operators

2.6 Expand printf( )'s capabilities


2.7 Program with C's relational and logical
operators

39
V
40 TEACH VOtJRSEL
C

N this chapter you will learn about two of C's most important
program control statements: if and for. In genera], program
control statements determine your programs flow of execution.
As such, they form the backbone of your programs. In addition to
I these, you will also learn about blocks of code, the relational and
logical operators, and more about the printf( ) function.

•Review
Skills Check

Before proccedilig, you should he able to correctly answer these


questions and do these exercises:

1. All C programs are composed of one or more functions. What is


the name of the function that all programs must have? Further,
what special purpose does it perform?
2. The printf() function is used to output information to the
screen. Write a program that displays This is the number 100.
(Output the 100 as number, not as a string.)
3. Header files Contain information used by the standard library
functions. flow do y ou tell the compiler to include one in your
program'..' Give an example.
4. C supports five basic types of data. Name them.
5. Which of these variable names are invalid in C?
a. _count
h. 123count
c. $test
d. This_is_ajongnan-ie
e. new-word
6. What is scanf( ) used for?
7. Write a program that inputs an integer froni the keyboard and
displays its square.
8. [low are comments entered into a C program? Give an example.
9. flow does a function return a value to the routine that called it?
tNIROOUCING C'S PROGRAM CONTROL STATEMENTS 41
21 BECOME FAMILIAR 4?7H THE If

10. A function called Myfunc( ) has these three parameters: an mt


called count, a float called balance, and a char called ch. The
function does not return a value. Show how this function is
prototyped.

E FAMILIAR WITH THE if

The if statement is one of C's selection statements (sometimes called


conditional statements). Its operation is governed by the outcome of a
conditional test that evaluates to either true or false. Simply put,
selection statements make decisions based upon the outcome of some
condition.
In its simplest form, the if statement allows your program In
conditionally execute a statement. This tbrniof the if is shown here:

if(expression) statement;

The expression may be any valid C expression. If the expression


evaluates as true, the statement will he executed. If it does nut the
statement is bypassed, and the line of code fbllowing the if is executed.
In C, an expression is true if it evaluates to any nonzero value. If it
evaluates to zero, it is false. The statement that follows an if is usually
referred to as the target of the if statement.
Commonly, the expression inside the if compares one value with
another using a relational operator. Although you will learn about all
the relational operators later in this chapter, three are introduced here
SO that we can create some example programs. A relational operator

tests how one value relates to another. For example, to see it one value
is greater than another, C uses the > relational operator. The outcome
of this comparison is either true or false. For example, 10 > 9 is true,
but 9 > 10 is false. Therefore, the following if will cause the message
true to be displayed.

if(10 > 9) printf(true');

however, because the expression in the following statement is false,


the if does not execute its target statement.
if(5 > 9) printf('this will not print")
42 TEACH YOURSELF
V

C uses < as its less than operator. For example, 10 < 11 is true. To
test for equality, C provides the operator. (There can he no space
between the two equal signs.) Therefore, 10 == 10 is true, but 10 ==
11 is not.
01 course, the expression inside the if may involve variables- For
example, the following program tells whether an integer entered from
the keyboard is negative or non-negative
include <stdio.h>

mt main (void)

mt num;

prirmt.f VEnter an integer:


scanf C %d", &nurn

if(num < 0) printf("NUmbet is negative.')


if(num > -1) printf('Number is non-negative.");

return 0;

Remember, in C, true is any nonzero value and false is zero.


Therefore, it is perfectly valid to have an if statement such as the one
shown here:
if (cuuflt+l) printf ("Not Zero")

1. This program forms the basis for an addition drill. U displays


two numbers and asks the user what the answer is. The
program then tells the user if the answer is right or wrong.
#include <stdio.Ii>

mt main(void)

mt answer;
INTRODUCING CS PROGRAM CONTROL STATEMENTS 43
21 BECOME FAMILIAR WITH THE If

printf(What is 10 + 14? );
scanf("%d, &answer);
if (answer == 10+14) printf("RightV);

return 0;

2. This program converts either feet to meters or meters to feet,


depending upon what the user requests.
#tinclude <stdio.h>

mt main(void)

float num;
mt choice;

printf (Enter value:


scanf("%f", &rium);

printfV'l: Feet to Meters, 2: Meters to Feet.


printf("Enter choice:
scant ("%d", &choice)

if (choice == 1> printf("%f", nurn / 3.'28)


if(choice 2) printf(%f', num * 3.28);

return 0;

EXERCISES

1 . Which of these expressions are truer


a. 0
h. 1
c. 10 9 < 9()
d. 1==1
C. -1
44 TIACH YOURSELF
V

2. Write aprogram that asks the user for an integer and then tells
the user if that number is even or odd. (Hint, use C's modulus
operator %.)

You tan add an else statement to the if. When this is done, the if
statement looks like this:
if(expression) statement 1;
ease statement2,
If the expression is true, then the target of the if will execute, and the
else portion will be skipped. However, if the expression is tjlse, then
the target of the if is bypassed, and the target of the else will execute.
Under no circumstances will both statements execute. Thus, the
addition of the else provides a two-way decision path.

I EXAMPLES]
1. You can use the else to create more efficient code in some
cases. For example, here the else is used in place of a second if
in the program from the preceding section, which determines
whether a number is negative or non-negative.
#include <stdio.h>

mt main(void)

irn; nun;

priritf{Enter an integer: ):
scanf("%d", &num);

if(num 0) printf("Number is negative);


else prirLtf("Number is non-negative);
tNTROOUCINO CS PROGRAM CONTROL STATE&KTS 45
2.2 ADO THEeb.e

return 0;

Recall that the original version of this program explicitly tested


for non-negative numbers by comparing num to -1 using a
second if statement. But since there are only two possibilities-
num is either negative or non-negative—there is no reason for
this second test. Because of the way a C compiler generates
code, the cisc requires far fewer machine instructions than an
additional if and is, therefore, more efficient.
2. This program prompts the user for two numbers, divides the
first by the second, and displays the result. However, division by
zero is undefined, so the program uses an if and an else
statement to prevent division by zero from occurring.
#include <stdio.h>

mt main(void)

mt nuinl, num2;

printf(Enter first number:


scanf(%d &nwnl);

printf('Enter second number: );


scanf("%d', &num2);

if(nujn2 == 0) printf(Carrnot divide by zercI.);


else printf("Answer is: %d, nurul I nwn2);

return 0;

EXERCISES
1. Write a program that requests two numbers and then displays
either their sum or product, depending on what the user selects.
46 TEACH YOURSEIJ
V

2, Rewrite Exercise 2 from Section 2.1 SO that it uses an else


statement.

BLOCKS OF CODE

In C, you can link two or more statements together. This is called a


block of code or a code block To create a block of code, you surround
the statements in the block with opening and closing curly braces.
Once this is done, the statements form one logical unit, which may
be used anywhere that a single statement may.
For example, the general form of the if using blocks of code is

if (expression)
statement!;
statement2;

statement W

else
statement!;
statement2;

statement N;

If the expression evaluates to true, then all the statemelits in the block
of code associated with the if will he executed. If the expression is Iilse,
then all the statements in the else block will be executed (Remember,
the else is optional and need not he present.) For example, this
fragment prints the message This is an example of a code block.
if the user enters any positive number.
INTRODUCING C5 PROGRAM CONTROL STATEMENTS 47
23 CREATE LOCV.SOFCOOE

scanf("%d', &num);

if(num > 0) {
printfvThis is
printf('ari example of •');
printf(a code block.");

Keep in mind that a block of code represents one indivisible logical


unit. This r)eans that under no circumstances could one of the
prinff( ) statements in this fragment execute without the others
also executing.
In the example shown, the statements that appear within the block
of code are indented. Although C does not care where a statement
appears on a line, it is common practice to indent one level at the
start of a block. Indenting makes the structure of a program easier
to understand. Also, the placement of the curly braces is arbitrary.
However, the way they are shown in the example is a common
method and will he used by the examples in this hook.
In C, as wou will see, you can use a block of code anywhere you can
use a single statement.

1. This program is an improved version of the feet-to-meters,


meters-to-feet conversion program. Notice how the use otcode
blocks allows the program to prompt specifically fhr each unit.
include <stdio.h>

mt main(void)

float num;
mt choice;

printf(1: Feet to Meters, 2: Meters to Feet.


priritf(Enter choice:
scanf('%d, &choice);

if (choice = 1)
printf("Enter number of feet: ');
48 ifACH YoURSaF
V

scanf('%f, &flUini;
printf( 'Meters: %f, nuxn / 3.28);

else C
printf(Enter number of meters:
scanf('%f', &nuir);
printf(Feet: %f", nuin * 3.28);

return 0;

2. Using code blocks, we can improve the addition drill program


so that it also prints the correct answer when the user makes
a mistake.
#include <stdio.h>

mt main(void)

mt answer;

printf("What is 10 + 14? );
scarif(*%d, &answer);

if (answer == 10+14) printf("Right!");


else
printf{Sorry, you're wrong.
printf(The answer is 24.);

return 0

This example illustrates an important point: it is not necessary


for targets of both the if and the else statements to be blocks of
code. in this case, the target of if is a single statement, while the
target of else is a block. Remember, you are free to use either a
single statement or a code block at either place.
INTRODUCING C5 PROGRAM CONTROL STATEMENTS
49
24 USE THE fOr LOOP

Write a program that either adds or subtracts two integers. First,


prompt the user to choose an operation; then prompt for the
two numbers and display the result.
2. Is this fragment correct?
if (count < 100)
printf("Nurnbor is less than 100.");
printf("Its square is %d.", count * count);

E for LOOP
The for loop is one of C's three lootements. It allows one or more
statements to be repeated. If you have programmed in any other
computer language, such as BASIC or Pascal, you will be pleased to
learn that the for behaves much like its equivalent in other languages.
The for loop is considered by many C programmers to he its most
flexible loop. Although the for loop allows a large number of
v.iiations, we will examine only its most common form in this section.
Th e for loop s used to repeat a statement or block of statements a
specified number of times ItgènraT form for repeating i single
ita ment is shown here. -

nitiaiization; conditional-test; incremenO statement;


The initialization section is used to gve an initial value to the variable
that controls the loop This variahl&Ts usually referred to as the
loop-control variable. The initialization section is executed only once,
before the loop begins. The conditional test portion of the loop tests the
loop-control variable against a target value. If the conditional test
50 TEACH YOURSELF
V

evaluates true, the loop repeats. If it is false, the loop stops, and
program execution picks up with the next line of code that follows the
loop. The conditional test is performed at the start or top of the loop
for is
each time the loop is repeated. Th tncrernnt portion of the
cecuted at the bottom of the loop That is, the increment portion is
executed alter the stateme,rI(Or block that forms its bodj has been
executed. the purpose of the increment portion is to increase (or
decrease) the loocontrol value h3r a certain amount.
for loop to print the
As a simple first example, this program uses a
numbers 1 through 10 on the screen.
*include <stdio.h>

.ztnt main (void)

jflt nurn:

for(numl; num<Il; num=num+i) printf(-%d , num);


printf (terminatiflg)

return 0;

This program produces the following output:

1 2 3 4 5 6 7 89 10 terminating
program works like this: First, the loop control variable num is
num < 11 is evaluated. Since it
i nitialized to I. Next, the expression
is true, the for loop begins running. After the number is printed, num
is incremented by one and the conditional test is evaluated again. This
for
process continues until num equals 11. When this happens, the
loop stops, and terminating is displayed. Keep in mind that the
initialization portion of the for loop is only executed once, when
the loop is first entered.
As stated earlier, the conditional test is performed at the start of
c ai.h iteration. This means that if the test is false to begin with, the
lp will not execute even once. For is example, this program only
initialized to 11, causing the
diselays terminating because num
conditional test to fail.
INTRODUCING CS PROGRAM CONTROL STATEMENTS
51
24 USETHEIoi-LOOP '

#include <stdio.h>

jOt main(void)

mt flufli;

/ this loop will not execte


for(num=l1; num<ll; nuxn=num+l) printf%d ", nurn);

pri.ntf ( "terminating');

return 0;

To repeat several statements, use a block of code as the target of the


for loop. For example, this program computes the product and sum of
the numbers from 1 to 5:
#include <stdio.h>

mt main (void)

mt nujo, sum, prod;

sum = 0;
prod = 1;

for(num=l; num<6; num=num+1)


sum = Sum + nurn;
prod = prod num;

printf("product and sum: %d %d, prod, sum);

return 0;

A for loop can run negatively. For example, this fragment


decrements the loop-control variable.
for )num=20; num>0; num=num-l)

Further, the loop-control variable maybe incremented or decremented


by more than one. For example, this program counts to 100 by fives:
52 TMC1I t3.eaf

stdio.h>
V'
mt main(void)

mt i;

for(i=O; i<101; j=i.+5) printf(%d i);

return 0;
ii

EXAMPLES
1. The addition-drill program created earlier can he enhanced
using a for loop. The version shown here asks for the sums of
the numbers between 1 and 10. That is, it asks for I + I, then 2
+ 2, and so on. This program would be useful to a first grader
who is learning to add.
#include <stdio.h>

mt main(void)

mt answer, count;

for(countl; count<1l; countcouflt+l)


printf("What is %d + %d? ", count, count);
scanf ('%d", &answer);

if (answer == count+cOUflt). printf("Right!


else
printf(Sorry you're wrong. .);
printf("The answer is %d. ", count+count);

return 0;

Notice that this program has an if statement as part of the for


block. Notice further that the target-of else is a block of code.
Tlik is perfectly valid. In C, a code block may contain
INTRODUCING CS PROGRAM CONTROL STATEMENTS
53
24 USE THEIo, LOOP

statements that create other code blocks. Notice how the


indent ,ion adds clarity to the structure of the program.
se a for loop to create a program that determines if a
-' z5a1ber is prime. The following program asks the user to enter
a number and then checks to see if it has any factors.
/* Prime number tester. */

*include <stdio.h>

mt main(void)

mt flUm, I prime;

printfEnter the number to test; );


scanf('%d, &nurn);

/ now test for factors *1

is—prime = 1;
for(i=2; i<=num/2; i=j+l)
If((nurn%i)==O) is prime 0;

if(is_prime==1) printf("The number is prime.);


else printf('The number is not prime.;

return 0;

EXERCISES
1. Create a program that prints the nuhers from I to 100.
2. Write a program that prints the numbers between 17 and 100
that can be evenly divided b y 17.
3. Write a program similar to the prime-number tester, cxcpt that
it displays all the factors of a number entered by the user. For
example, if the user entered 8, it would respond with 2 and 4.
54 TEACH YOURSELF
V

SUBSTITUTE C'S INCREMENT AND


DECREMENT OPERATORS
When you learned about the for in the preceding section, the increment
portion of the loop looked more or less like the one shown here:
for(num=O; num<some_v1ue; num=nurn±1)

Although not incorrect, you will almost never see a statement like
num = num + 1 in professionally written C programs because C
provides a special operator that increments a variable by one. The
increment operator is ++(two pluses with no intervening space). Using
the increment operator, you can change this line of code:
I = I + 1;

into this:

Therefore, the for shown earlier will normally be written like this:
for(num=O; nurn<ome_va1ue; num++)

In a similar fashion, to decrease a variable by one, you can use C's


decrement peraLor: --. (There must he no space between the two
minus signs.) Therefore,
count = count - 1;

can be rewritten as
count--;

Aside from saving you a little, typing effort, the reason you will want
to use the increment and decrement operators is that, for most C
compilers, they will be faster than the equivalent assignment
statements. The reason for this difference is that the C compiler can
often avoid separate load-and-store machine-language instructions and
substitute a single increment or decrement instruction in the
executable version of a program.
The increment and decrement operators do not need to follow the
variable; they can precede it. Although the effect on the variable is the
INTRODUCING CS PROGRAM CONTROL STATEMENTS 55
25 SUBST770E CS INGREMENTAND DECREMENT OPERA TORS

same, the position of the operator does affect when the operation is
performed. To see how, examine this program:

*include <stdio.h>

mt main(void)

mt i, j;

I = 10;
j =

*/
/ this will print 11 10
prinf("J- and 1; %d %d", 1, J);

return 0;

Dont let the , j


i*+statement trouble you. The increment
operator maybe used as part of any valid C expression. This statement
works like this. First, the current value of i is assigned to j . Then i is
incremented. This is why has the value 10, not 11. When the
increment or decrement operator follows the variable, the operation
is performed after its value has been obtained for use in the
expression. Therefore, assuming that max has the value I, an
expression such as this:
count = 10 *

assigns the value 10 to count and increases max by one.


If the variable is preceded b y the increment or decrement operator,
the operation is performed first, and then the value of the variable is
obtained for use in the expression. For example, rewriting the
previous program as follows causes to be 11.

#iriclude <stdio.h>

mt main(void

mt I, j;

I = 10;
j =
56 TEACH YOURSELF
V

/* this will print 11 11 /


printf("i and j: %d %d, i, j);

return 0;

If you are simply using the increment or decrement operators to


replace equivalent assignment statements, it doesn't matter if the
operator precedes or follows the variable. This is a matter of your own
personal style.

1. Here is the addition drill program developed in Section 2. It has


been rewritten using the increment operator.
#include <stdio.h>

jilt main (void)

mt answer, count;

for(count=l; count<ll; count++) {


printf(What is %d + %d? ", Count, count);
scanf ( "%d", &answer);

if (answer == count+count) printf("Right!


else
printf("Sorry, you're wrong.
printf("The answer is %d. ", count+count);

return 0;

2. This program illustrates the use of the increment and


decrement operators:
#iriclude <stdio.h>

mt main(void)
INTRODUCING CS PROGRAM CONTROl. STATEMENTS 57
25 SUBS TJ7)JTE C'S !NCREMElVT AND DECREMENT OPERA TORS

LI
mt i;

i = 0;

printf('%d ", i); / prints 1 */


1--;
printf("%d ", i); / prints 0

return 0;
ii

EXERCiSES

1. Rewrite the answer to the for loop exercises in the previous


section so that they use the increment or decrement operators.
2. Change all appropriate assignment statements in this program
to increment or decrement statements.
#include <stdio.h>

mt main (void)

mt a, b;

a = 1;

a = a + 1;

b a;

b = b - 1; S

priritf(%d %d", a, b);

return 0;
58 TEACH Y

^XPA D p rintfl( )'S CAP ABILITIES


So far, we have used printf( ) to output strings and numbers.
However, you might have been wondering how to tell printf( ) that
you want the output to advance to the next line. The way to accomplish
this and other actions is to use C's backslash-character constants. The C
language defines several special character codes, shown in Table 2-1,
which represent characters that cannot be entered from the keyboard,
are non-printing characters, may not be found in all character sets,
or that serve other unique needs, You can use the backslash codes
anywhere you can use a normal character. The backslash constants
are also referred to as escape sequences.

Code Mea ning


\b --- Backspace

\f Form feed
\n -
\r Carriage return
\t --- _-Horizontal tab
Double quote
V - -Single quote
\O NLIII
Backslash
\v Vertical tab
\a ,. Alert
\? Question mark
\N .----- _____------------------
Octal constant (where Nis an octal value)
\xN Hexadecimal constant (where N is a hexidecimal value)

5015 C's Backslash Codes V


INTROO&JCIP4G CS PROGRAM CONTROl. STATEMENTS 59
26 FyDANnmifltfsCAPABjLmEs

Perhaps the single most important backslash code is \n, which is


often referred to as the newline character. When the C compiler
encounters \n, it translates it into a carriage return/linefeed
combination. For example, this program:
*include <stdio.h>

mt main(void)

printf('This is line one.\n);


pri.ntf(This is line two.\n");
printf("This is line three.");

return 0;

iisplays

This is line one.


This is line two.
This is line three.
on the screen.
Remember, the backslash codes are character constants. Therefore,
to assign one to a character variable, you must enclose the backslash
code within single quotes, as shown in this fragment:
char ch;

ch = '\t'; 1* assign ch the tab character /

1. This program sounds the bell:


#include <stcuio.h>

mt main(void)

printf ("\a")
60 TEACH YOURSELF
V

return 0;

2. You can enter any special character by specifying it as an octal


or hexadecimal value following the backslash. The octal number
system is based on 8 and uses the digits 0 through 7. In octal,
the number 10 is the same as 8 in decimal. The hexadecimal
number system is based on 16 and uses the digits 0 through 9
plus the letters 'A' through 'F', which stand for 10, 11, 12, 13,
14, and 15. For example, the hexadecimal number 10 is 16 in
decimal. When specifying a character in hexadecimal, you must
follow the backslash with an 'x', followed by the number.
The ASCII character set is defined from 0 to 127. However,
many computers, including most PCs, use the values 128 to 255
for special and graphics characters If your computer supports
these extra characters, the following program will displa y a fe w
of them on the screen.
#include <stdio.h>

mt main(void)

printf("\xAO \xAl \x.A2 \xA3');

return 0;

3. The \n newline character does not have to go at the end of the


string that is being output by printf( ); it can go anvvherc in
the string. Further, there can be as many newline charac t ers in
a string as you desire. The point is that there is no connection
between a newlinc and the end of string. For example, this
program:
4inc1ude <scdio.h>

mt main(void)

printf(one\ntwo\nthree\nfour);

return 0;
INIt., - C'S PROGRAM CONTROL STATEMENTS
61
27 FWCGI .1 p4(71 C5 ADA T7ONAL AND LOGFC4.L OPERA TORS

displays

one
two
three
four
an the screen.

EXERCISES

1. Write a program that outputs a table of numbers. Each line in


the table contains three entries: the number, its square, and its
cube- Begin with 1 and end with 10 Also, use a for loop to
generate the numbers.
2. Write a program that prompts the user for an integer value.
Next, using a for loop, make it count down from this va]uc to 0,
displaying each number on its own line. When it reaches U, have
it sound the bell.
0G13'"
3. Experiment on your own with the backslash codes-

WITH C'S RELATIONAL AND


rYÔICA1. OPERATORS
The C language contains a rich set of operators. In this section you will
learn about C's relational and logical operators. As you saw earlier, the
relational operators compare two values and return a true or false
result based upon that comparison. The logical operators connect
together true/false results. These operators are shown in Table 2-2
and Table 2-3.
62 TEACH YOURSELF
V

Action

Greater than
Greater than or equal
Less than
Less than or equal
Equal
IM Not equal

[CMM Relational Operators V

The logical operators are used to support the basic logical operations
of AND, OR, and NOT according to this truth table. The table uses 1
for true and 0 for filse.

X q p&&q pIIq

The relational and logical operators are both lower in precedence


than the arithmetic operators. This means that an expression like
10 + count > a + 12

c\4ator
&& AND
II OR
NOT

IIL L gtcni ()p?r!or. Y


INTRODUCING CS PROGRAM CONTROL STATEMENTS 63
2.7 PROGRAM WITH CS RELATIONAL AND LOGICAL OPERATORS

is evaluated as if it were written


110 + count) > (a + 12)

You may link any number of relational operations together using


logical operators. For example, this expression joins three relational
operations.
var > max (max=100) && 0 <= item

The table below shows the relative precedence of.the relational and
logical operators.

Highest I
> >= < <=

&&
Lowest II
There is one important fact to remember about the values produced
by the rr lational and logical operators: the result is either 0 or 1. Even
though C defines true as any nonzero value, the relational and logical
operators always produce the value 1 for true. Your programs may
make use of this fact.
You can use the relational and logical operators in both the if and
for statements. For example, the following statement reports when
both a and b are positive:
if(a>0 && b>0) printf(Both are positive.');

1. In professionally written C code, it is uncommon to find a


statement like this:
if (count 0)..

The reason is that in C, true is any nonzero value and false is zero.
Therefore, the preceding statement is generally written as this:
if(court)
64 TEAaI YOURSELF
V

Further, statements like this:


if(count == 0)..

are generally written as:


if(!count)

The expression Icount is true only if count is zero.


2. It is important to remember that the outcome of a relational or
logical operation is 0 when false and 1 when true. For example,
the following program requests two integers, then displays the
outcome of each relational and logical operation when applied
to them. In all cases, the result will he a 0 or a 1.
*include <stdio.h

int main(void)

mt i, j;

printf('Enter first number: ")


scanf("%d, &i);
printf("Eriter second number: );
scanf("%d, &j);

/* relational operations */
printf('i < j %d\n, i < :1);
printfVi <= j %d\n', i <=
prirttf(-i == j %d\n, j == j)
printf('i > j %d\n, i > :1);
printf(i >= j %d\n, i >=

/ logical operations /
printf("i && j %d\n", i && j);
printf(i j %d\n' , i 11 i)
prirttf("i !j %d %d\n', !i,

return 0;

3. C does not define an exclusive-OR (XOR) logical operator.


I lowever, it is easy to create a function that performs the
operation. The XOR operation uses this truth table:
INTRODUCING C'S PROGRAM CONTROL STATEMENTS 65
27 PROGRAM WITH CS RELATIONAL AND L(,''AL OPt RATORS


P q XOR

o a 0

o
1 0
0

That is, the XOR operation produces a true result when one and
only one operand is true. The following function uses the &&
and 11 operators to construct an XOR operation. It compares the
values of its two arguments and returns the outcome of an XOR
operation.
mt xor(int a, irit b)

return (a 11 b) && !(a && b);

The following program uses this function. It displa ys the result


of ail AND, OR, and XOR on the values you enter.
/ This program demonstrates the xor() function. '1
#include <stdio.h>

mt xor(int a, mt b);

mt main(void)

mt p q;

printf ('enter p (0 or 1) -)
scanf("%d', &p);
printf("enter Q (0 or 1):
scanf('%d", &q);
printf('P AND Q: %d\n, p && q);
printf("P OR Q: %d\n", p 11 q)
printf('P XOR Q; %d\n', xor(p, q));

return 0;

irit xor(int a, mt b)

5
YOURSELF
66 TEACH

II
reLurn (a 11 b) && ( && b)

EXERCISES

I. What does this loop do?


f0r(x0; x<100; x++) printfV%d , xl;

2. Is this expression true?


(10=9)

3. Do these two expressions evaluate to the same outconle?


a. 0&&I fli
b. (I & (1 H 1)
4. On your own, experiment with the relational and logical
operators.

Maste
Skills check

1. Write a irJam that plays a computerized fbrrn of the guess


the magic number game. it works like this: The player has ten
tries to guess the magic number. If the number entered is the
value you have selected for your magic number, have the
program print the message "RIGHT!" and then terminate.
Otherwise, have the program report whether the guess was
high or low and then let the player enter another number. This
process goes on until the player guesses the number or the ten
tries have been used up. For fun, you might want to report the
number of tries it takes to guess the number.
INTRODUCING CS PROGRAM CONTROL STATEMENTS 67
27 PROGRAM WITH C'S RELATIONAL AND L OG1CRJ OPERATORS

2. Write a program that computes the square footage of 'a lioLise


given the dimensions of each room. Have tile program ask the
user how many rooms are in the house and then request the
dimensions of each room. Display the resulting total square
footage.
I what are the increment and decrement operators and what
do they do?
4. Create an improved addition-drill program that keeps track of
the number of right and wrong answers and displays theiii when
the program ends.
5. Write a program that prints the numbers I to 100 using 5
columns. Have each number separated froni the next by a tab.
-
3
(i More C Program
Control Statements

chapter objectives
3.1 Input characters
3.2 Nest if statements
3.3 Examine for loop variations
3.4 Understand C's while loop
3.5 Use the do loop
3.6 Create nested loops

0
3.7 Use break to exit a loop
3.8 Know when to use the continue statement
3.9 Select among alternatives with the switch
statement
.-A 3.10 Understand the goto statement

69
V

70 TEACH YOURSELF

1-fis chapter cOntitilieS the tlisi usslon Of C's program (:oritrol


statements. Before doing so, however, the &;Ici t:r begins
by explaining how to read characters from the keyboard.
Although you know how to Input numbers, it is now time
T r Volt to know how to input iiidividiiii .liaracters because
several examples in this hapter will MAX, LISV of tileill. Next, the
chapter finishes the discussion of the if' and For stateiiieiits. 'limo it
presents C's two other loop stateillents, the while irid do. Next YOU
will learn about nested loops and two inure ()t C's control st;mte Till , tits,
the break and continue. 'I'his (:haptcr also covers US othi' r selection
state merit, the switch. it ends with a short discussion of (s
1.1 il(.Oil(.h itiorl.Il )ti rnp stiteriicflt, goto.

.4
.,: Review
Skills Check

l:fore pr ccedini., y ou should he able to answer these questh)rls


and perform these exercises:

What Sire C's relational and logical operators.


2. What is a block of' code: I low do you make one:'
3, H OW do YOU output
P' ;I ne using printt'( )
.1. Write a plogriim diar, prints the nLimbers -100 to 100.
5. Write a program that prints 5 different proverbs. Tue program
prompts the user for the number of the proverb to print and
Own displays it. (Use any proverbs von like.)
I low can this statement be rewritten.'
COUflt - COUflt 1;

7. What values arc true in C? What values are false.'

INPUT CHARACTERS
Although ntmniii)ei'S are iiiiportaitt, y our progrinis will also teed to read
characters from the keyboard. Lu C y ou cart do this in a variety of
wa y s. tJnt6rtunate1', this conceptually simple task is coiiiphietted by
MORE C PROGRAM CONTROL STATEMENTS 71
31 INP/1 C/WIAC'IERS

Some baggage left over from the origins 01 C. I lowever, let's begin with
the traditional wily characters are read from the ke yboard. Later von
will learn an alternative.
C defines a function called getchar( ), which returns a si ngh
character typed oil keyboard. When called the lii nction \VJ its for a
key to be pressed. Then getchar( ) echoes the ke ystroke to the seen
and returns the value of the key to the caller. The gctchar( ) fiiiX:tion
is defined by the ANSI C standard and requires the header file S'11,I0.I I.
This program illustrates its use by reading a character ,iriil then telling
YOU what it received. (Remember, to displa y a character, use the %c
printf( ) format specifier.)
#include <stdi.o.h>

jot main(void)

char ch;

cli = getchar; / read a char


printf(" you typed: %c, ch);

return 0;

lfyou try this program, it may behave differentl y than von


expected. The trouble is this: in many C compilers, getchar( ) is
implemented in such a way that it line buffers input. That is, it does not
immediately return as soon as you have pressed a key, but waits until
y ou have entered an entire line, which may include several other
characters. This means that even though it will read and return only
one character, gctchar( ) waits until y ou enter a carriage return (i.e.,
Press ENTER) before doing so. When gctchar( ) returns, it will return
the first character you typed. However, any other characters that vou
entered, including the carriage return, will still he in the input butter.
These characters will be consumed b y subsequent input requests, such
as through calls to scanf( ). In some circumstances, this can lead to
trouble. This situation is examined more closely in Chapter ft For
now, just he aware that gctchar( ) may behave differentl y than your
intuition would suggest. Of course, the programs shown in this book
behave properly.
72 TEACH YOURSELF
V

, rhc rc,isciic that gctchar( ) works the way it does is that the version
of UNIX lor which C was developed line-buffered input. When C
inpilrrs wee created for other interactive environments, developers
had to dvcidf . how to make gctchar( ) behave. Many C compiler
cleve lope rs have decided, for the sake of compatibility, to keep
gct;har( ) line-buttered, even though there is no technical reason for
it. (fri (wt, the ANSI C standard states that gctchar( ) need not be
I inr-bci tIered ) When gctchar( ) is implemented in a I nc-buffered
fashion in a modern interactive environment, its use is severely
limited.
l(c(ausc man y compilers have implemented line-buffered versions
of getchar( ), most C compilers supply another function to perform
interactive console input. Although it is not defined by the ANSI C
st,ciid,ird, most compilers call this function gctehc( ). You use it just
lcl gett.har( ), except that it will return its value immediately after a
hc is jc essed; it (foes not line-buffer input. For most compilers, this
him liml r l 'cic nres a header tile called CON 10.11, but it might he called
sound hiiig different in y our compiler. Thus, if y ou want to achieve
intl Ic.tive 1 .hara:ter input, you will USUJIIV need to use the gctchc( )
I unction rather than getchar( ).
Si iii e till readers will have access to the gctchar( ) function, it will
I,(: used by most of the examples in this hook that require character
input I luwever, smite examples will use the gctche( ) function. If
voui compiler does not include this function, substitute gctchar( )
You should kcl free to experiment with getchc( ) on your own.

Note

Al the lime of this writing, when using Microsoft's Visual C++ compiler,
geicheG is not compatible with C's standard input functions; such as scanfLi,
Instead, you must use special console versions of these of these functions,
such as cscanf(). This and other non-standard I/O functions are described in
Chapter 8. The examples in this book that use getche() work correctly with
Visual C++ because they avoid the use of the standard input functions.

Virtually all computers use the ASCII character codes when


representing characters. Therefore, characters returned by either
getchar( ) or gctchc( ) will be represented by their ASCII codes. This
is 1 isi'fOl because the ASCI I character codes are an ordered sequence;
(',oh letter's code is one greater than the previous letter; each digit's
u nib' is one greater than the previous digit. ]'lcis means that 'a' is less
MORE C PROGRAM CONTROL STATEMENTS 73
'V
31 /NP(Jr CHARACTERS

than h, IT is less than '3', and so on. You may compare characters Just
like you compare numbers. For example,
ch = getcharO;
if(ch < 'f' printft'character is less than f)

is a perfectly valic fragment that will display its message if the user
enters any character that conies before f.

This program reads a character and displays its ASCI I code. This
illustrates an important feature of C: You can USC it as
if it were a"little integer." The program also denionsirates the
use ol the gctche( ) function.
tinclude <conio.h>
4inelude <stdio.h>

tnt inatn(void)

char ch;

printf("Enter a character:
ch = getche{):
printf("\nits ASCII code is %d", ch);

return 0;

Because this program uses getche( ), it responds as soon as you


press a ke y . Before continuing, tr y substituting getc:har( ) for
gctchc( in this pr gram and observe the res tilts. As You will
see, gctchur( ) does not return a character to vow i i og!iiii
until you press ENTER.
2. One of the most common uses of character 1n1)Lit is to obtain it
menu selection. For example, this program allows the user to
add, subtract, multiply, or divide two numbers.
#include <stdio.h>
74 TEACH YOURSELF
V

irit main(void)

tnt a, b;
char ch;

printf("Do you want to:\n");


printf("Add, Subtract, Multiply, or Divide?\n);
printf("Enter first letter:
ch = cjctchar();
printf (

printf ('Enter first number: "I


scanfV%d", &a);
printf("Eriter second number;
scant ('Ad", &b)

if(ch'A') printf("%d", a+b);


if(ch--'S') printf("%d,", ab);
if)ch=='M') printf("%d", ab);
i f(ch= : 'D' && b!=O) printf)"%d", a/b)

return 0;

One point to keep in nnnd is that C makes a distinction between


tipper- and lowercase letters. So, if the user enters an s, the
program will not recognize it as a request to subtract. (Later,
VOU will learn how to convert the case ofa (;haractcr.

t. Another conirnon reason that your program will need to read a


character from the ke yboard is to obtain a yes/no response from
the user. lor example, this fragment determines if the user
wants to proceed.
printfVuo you wish to continue? (Y/N
ch = getche();
if(ch=='Y')
1* continue with something '7
MORE C PROGRAM CONTROL STATEMENTS 75
32 NESTiISrAItMENIS V

EXERCISES

1. Write a program that reads ten letters. After the IcItcis Icive
been read, display the one that comes earl iest in thebalpha et.
(I lint: The one with the smallest value comes first.)
2. Write a program that displa y s the ASCII codes tir the cihiracters
A through 7. and a through Z. H ow do the codes diltet h('tWccLl
the upper- and lowercase :haractcrs?

N jjj^S-Ti STATEMENTS

When an if statement is the target of another if or else, it is said to hh


nested widiiii the Outer if. I lore is a simple example of a nested if':

i f (cou:iL [flax) / * outer if


I (trir ) pr intl ''f-or, try again.') / nested i I 1

II : re the printf'( ) state ruent will onl y execute if count is goiter


ti t,ni max and if error is nonzero. Notice how the tiested if is
incletited. 'f'lns is common practice. It enables anyone reading your
to know qtii(:klv that the if is nested and what 1(.I ions arc
nested. A nested if may also appear inside a block of statetneiils that
are the t:Lrget Of the outer if
An ANSI-staiid,ird compiler will allow you to neSt if at least 15
levels deep. (I lowever, it would be rare to find such a deep nesting.
One conlusittg aspect Cit nested ifs is illustrated by the lohliwitig
Iragnic ii t

i f (P)
f kit p t in f( "a and h are ttue"

else print f("To which statement, does this else apuiy'")

'l'lu; question suggested by the second printf( ) is: which if' is


issi,o.ittid with the else' Fortunatel y , the aiiswer is quito: :,osv: ,\tj
cisc alwa y s associates with the nearest if in the sum: block that does
not alread y have an else associaled with it. In ibis example, tIc else is
assoc iated with the second if.
76 TEACH YOURSELF
V

It is possible to StriiiL t(oi,etl1o'i sevi:ril ifs arid elscs ill(() Iiit is


snlTh:times called an iJil.se-i •f hiol.Iei in if dsi:-if 5((1ti01I51 Eiii,iiise
(if its visual iippearancc. In this situation a nested it his as its
target triotIo'r if. The genital hit rit of the il-CIS(-if LiIdi'r IS
shown hew:

I f(expwssion) statement,
else
if(expwss/on) statement,
else
JJ\( expre5sion) statement

else statement;
'l'hie I:Xpn'issionis are evaluated rouii the till) downwai(l. As' Soon
as a true condition is found, the statement associated with it is
execuied, arid the rest of the Ladder is bypassed. If llonr of the
expressions are trio:, the final else will he executed. I hat is, it
all other conditional tests fail, the last cisc stati'nient IS
perlornited. If the final else is not present no a:tioi i will take
place if all expressions are false.
Although the indentation ol the general for-in of tin' iLelse-it
ladder just shown is technically correct, it can lead to overly
chi'() indentation). Because of this, the ifelse-i1 laddo'r is
generally rrtten1 like this:

if(expression) statement,
else if(expression) statement
else if(expression) statement;

else statement,'
We cat) inipn'(ive the. at' ithmetic program developed ill
Section 3.1 b y using an iteIse-if ladder, as showil heno:'
MORE C PROGRAM CONTROL STATEMENTS 77
32 NF.S)3ISfAIEM(NTS V

#inc!u(le tclin.h>

jilt rnain(void)

ml a,
char ch;

p intf ("Do you want to: \n");


printf("Add, Subtract, Multiply, or Divicl?\n")
prirttf('Eriter first letter:
rh citchar()
prinrf C'

priritf EnLer first number:


sca:tf ( 'd", &a)
priritf("Enter second number: );
scarif("%d", &b);

if (ch= 'A') printf ( '%d" , a*b)


else if(ch='S') printf("%d', a--b);
else if(ch=='M') printf("%d, ab);
else if(ch-='D' && b = O) printf(%d", a/b);

return 0;

This is an improvement over the original version because on(:(-


a match is found, any remaining if statements are skipped. This
means that the program isn't wasting time on needless
operations. While this is not too important in this cxaiiiplc, you
will encounter situations where it will he.
in
2. Nested it statements are very coni mon programming. For
example, here is a further improvement to the addition drill
program developed in the preceding (.hapt('r. R lets the user
have a second try at getting the right answer.
#include <stdio,h>

mt main(void)

irit answer, count;


78 TEACH YOURSELF
V

mt again;

for(count=l; count<11; Count++)


printf("What is %d + %d? , count., count.);
scanf('%d" &answer);

if (answer count.+count) pxintf('Right!\n);


else
printf("Sorry, you're wrong\n);
printfVTry again.\n

printf(\nWhat is %d + %d? , count, count);


scanf ( "%d, &answer);

1* nested if /

if (answer count+count) printf("Right!\n");


else
printf(Wrong, the answer is %d\n',
count +count);

return 0;

here, the second if is nested within the outer ifs else. block.

EXERCISES
1. To which if does the else relate to in this example?
if(ch=='S') { / first if
printf VEnter a number: );
scant ("%d, &y:

/ second i /
if(y) printf('ltS square is %d., y*y);

else printf("Make next selection.);

2. Write a program that computes the area oF either a circle,


rectangle, or triangle. Use an if-else-if ladder.
MORE C PROGRAM CONTROL STATEMENTS 79
3.3 EXAMINE for LOOP VAR/A OONS

EXAMINE for LOOP VARIATIONS


The for loop in C is significantly more powertul and tlexthle than in
most other computer languages. When you were introduced to the for
loop in Chapter 2, you were only shown the hrrn similar to that used by
other languages. Hpwcver, you will see that for is much more flexible.
The reason that for is so flexible is that the expressiois we called
the initialization, conditional-rest, and increment portions of the loop are
not limited to these narrow roles. The for loop places no limits on the
types of expressions that occur inside it. For example, you do not have
to use the initialization section to initialize a loop-control variable.
Further, there does not need to be any loop-control variable because
the conditional expression may use some other means of stopping the
loop. Finally, the increment portion is technically just an expression that
is evaluated each time the loop iterates. It does not have to increment
or decrement a variable.
Another important reason that the for is so flexible is that one or
more of the expressions inside it may he empty. For example, if the
loop-control variable has already been initialized outside the for, there
is no need for an initialization expression.

1. This program continues to loop until a q is entered at the


keyboard. Instead of testing a loop-control variable, the
conditional test in this for checks the value of a character
entered by the user.
#include <stdio,h>
tiriclude <conio.h>

mt main(void)

mt i;
char ch;

ch = a'; /* give ch an initial value /

for(iO; ch != ; j++)
printf(pass: %d\n, i);
80 TEACH YOURSELF
C

ch = getche;

return 0;

I t -re, the condition that controls the loop has nothing to do with
the loop-control variable. The reason ch is given an initial value
is to prevent it from accidentally containing a q when the
program begins.
2. As stated earlier, it is possible to leave an expression to a loop
empty. For example, this program asks the user for a value and
then counts down to zero from this number. Here, the
loop-control variable is initialized by the user outside the loop,
so the initialization portion of the loop is empty.
#include <stdio.h>
mt main(void)

mt i
printf(Enter an integer:
scanf('%d", &i);

for(; i i--) priritf(%d

return 0;

3. Another variation to for is that its target may be empty. For


example, this program simply keeps inputting characters until
the user types q.
*include <stdlo.h>
#include zconio.h'

jut main(void)

char ch;
for(ch=getche(}; ch = 'q; ch=getcheW;
printf('FOund the q.);
MORE C PROGRAM CONIBOL STATEMENTS
81
33 EXMiWEfo.r LOOP VAR/A 710/15 'V

return U;

Notice that the statements assigning ch a value have been


moved into the iop. This means that when the loop starts,
getche( ) is called. Then, the value of ch is tested against q.
Next, conceptually, the nonexistent target of the for is executed,
and the call to gctche( ) in the increment portion of the loop is
executed. This process repeats until the user enters a q.
The reason the target of the for can be empty is because C
allows null statements.
4. Using the for, it is possible to create a loop that never stops.
This type of loop is usually called an infinite loop. Although
accidentally creating an infinite loop is a hug, you will sometimes
want to create one on purpose. (Later in this chapter, you will
see that there are ways to exit even an infinite loop!) To create
an infinite loop, use a for construct like this:
for( ; ; )

As you can see., there are no expressions in the for. When


there is no expression in the conditional portion, the compiler
assumes that it is true. Therefore, the loop continues to run.
5. In C, unlike most other computer languages, it is perfectly valid
for the loop-control variable to be altered outside the increment
section. For example, the following program manually
inorements i at the bottom of the loop.
*include <stdio.h>

mt main (void)

mt 1;

or(i'O; i<10; I
priiitf(%d ,
Y01AISELF

EXERCISES
\rite a program that compLEtes driving time when given the
distance and the average speed. Let the user specify the
number of drive time computations he or she wants to perform
2 To create time-delay loops, for loops with empty targets are
often used. Create a program that asks the user for a number
and then iterates until zero is reached- Once the countdown is
done, sound the bell, but don't display anything on the screen.
3. Even if a for loop uses a loop-control variable, it need not he
increnieiited or decremeuted by a fixed amount. Instead, the
amount added or subtracted may vary. Write a program that
begins at I and runs to 1000. Have the program add the
loop-control variable to itself inside the increment expression.
This is an easy way to produce the arithmetic progression 1 2 4
8 16, and so on.

It NDERSTAND C'S while LOOP


Another of C's loops is while It has this general form;

while(expression) statement;
01 course, the target of while may also be a block of code. The-Wile
loop works b y repeating its target as long as the expression is true.
When it becomes false, the loop stops. The value of the expression is
cYie.ckcd at the-tap of the -loop. This means that if the expression is
fa1e to begin with, the loop will not execute even once.
MORE C PROGRAM CONTROL STATEMENTS
83
14 UNDERSTAND C5while LOOP

EXAMPLES
Even though the for is flexible enough to allow itself to be
controlled by factors not related to its traditional use, you should
generally select the loop that best fits the needs of the situation.
For example, a better way to wait for the letter q to be typed is
shown here using while. If you compare it to Example 3 in
Section 3.3, you will see how much clearer this version is.
(However, you will soon see that a better loop for this job exists.)
#include <stdio.h>
#include <conio.h>

mt main (void)

char ch;

ch = getche();

while(ch!='q') ch=getcheu;
printf)Found the q.");

return 0;

2. The following program is a simple code machine. It translates


the characters you type into a coded form by adding I to each
letter. That is, 'A' becomes 'B,' and so forth. The program stops
when you press ENTER. (The getchc( ) function returns \r
when ENTER is pressed.)
#inclucie <stdio.h>
include <conio.h>

mt main(void)

char ch;

printf ("Enter your message.\n);

ch = getcho();
while(ch \r')
04 TEACH YOURSELF
V

prirtf("%c, ch1);
ch = getcheO;

return 0;

EXERCISES
1. In Exercise I of Section 3.3, you created a program that
computed driving time, given distance and average speed. You
used a for loop to let the user compute several drive times.
Rework that program so that it uses a while loop.
2. Write a program that will decode messages that have been
encoded using the code machine program in the second
example in this section.

1/SE THE do LOOP


C's final loop is do, which has this general form:

do(
statements
I while(expression)
If only one statement is being repeated, the curly braces are not
necessary. Most programmers include them, however, so that they cai
easily recognize that the while that ends the do is part of a do loop,
not the beginning of a while loop.
The do loop repeats the statement or statements while the
expression is true. It stops when the expression becomes false. The do
loop is unique because it will always execute the code within the loop
at least once, since the expression controlling the loop is tested at the
bottom of the loop.
MORE C PROGRAM CONTROL STATEMENTS
85
5 LJ.SETHEdoLOOP

I u' Lii tho do will always execute the bod y of its loop at least
;i . miLes it je fect for checking menu input. For example,
v rsion oF the arithmetic program reprompts the user until
a v.;cl tcsponsc is entered.
4ilude <Ldio.h>

iri main(vcjd)

(::ar ch:

orintf I wd;: to: \n')


prinf(Ar[i btdct, Multiply, or Divide?\n');

/* foLce user to enter a valid response *1


do
prjntf 'Enter first letter: ")
ch getchar;
while(ch='A' && ch!='S' && ch!='M &&
printf ( \n')

p rintf(Enter first number: );


scanf("%d', &a);
printf)Eriter second number: );
scanf(%d", &b);

if(ch=='A) printf("%d", a+b);


else if(ch=='S') printf(%d", a-b);
else if(ch=='tl') printf(%d', a*b);
else if)ch='fl' && b!=O) p rintf('%d, a/b);

return 0;

2. The do loop is especially useful when your program is waiting


for some event to occur. For example, this program waits for the
user to type a q. Notice that it contains one less call to gctche( )
than the equivalent program described in the section on the
while loop.
include <stdio.h>
#include <conio.h.
86 TEACH YOURSELF
V

mt rnain{voi.1

char ch;

do
ch = getcheU;
whi1e(chq');

printf('Found the q.");

return O

Since the loop condition is tested at the bottom, it is not


necessary to initialize ch prior to entering the loop.

EXERCES
1. Write a program that converts gallons to liters Using a do loop,
allow the user to repeat the conversion. (One gallon is
approximately 3.7854 liters.)
2. Write a program that displays the menu below and uses a do
loop to check for valid responses. (Your program does not need
to implement tile actual functions SilOwil in the menu.)

Mailing list menu:

1. Enter addresses

2. Delete address

3. Search the list

4. Print the list

5. Quit
Enter the number of your choice (1-5).
MORE C PROGRAM CONTROL STATEMENTS 87
36 CREATE NESTED WQPS

CREATE NESTED LOOPS


mftdv

When the body of one loop contains another, the second is said i
be nested inside the first. Any of C's loops may be nested within any
other loop. The ANSI C standard specifies that loops ma y he nested
at least 15 levels deep. However, most compilers allow nesting to
virtually any level. As a simple example of nested fors, this fragment
prints the numbers 1 to 10 on the screen ten times.
for)i=D; i<10; j++)
for(j=l; j<11; j++) printf('%d , j); /* nested loop
printf("\n")

1. You can Use a nested for to make another improvement to the


arithmetic drill, In the version shown below, the program will
give the user three chances to get the right answer. Notice the
use of the variable right to stop the loop early if the correct
answer is given.
U.include stdio.h'

mt main (void)

mt answer, count, chances, right;

for(count=1; count<11; count++)


priritf)"What is %d + %d?', count, count);
scanf("%d", &answer)

if (answer == count+count) printf)"Right!\n");


else
printf("Sorry, you're wrong.\n")
printf('rry again. \n");

right 0;
88 TEACH YOURSELF
V

/ nested for */
for(chances=U; chances<3 && right; chonces+-)
printf("1hat is %d + %d? count, count);
scanf('%d, &answer)

jf(ariswer == count+count) I
printf("Right\fl)
right 1;

1* if answer still wrong tell usel


if) right)
printt('The answer is %d.\n", count+count);

return 0;

2. This program uses three for loops to print the alphabet three
times, each time printing each letter twice:
*include <stdio.h>

mt main (void)

mt i, j, k;
for(i0; j .z3- i.+)
for(j=0; j<26; j*+(
for(k=O; k<2; k+ * ) printf("%c" 'A'+j)

return 0;

The statement
printt("%c", 'A*j);

works because ASCII codes for the letters of the alphabet are
strictly ascending—each one is greater than the letter that
precedes it.
MORE C PROGRAM CONTROL STATEMENTS
89
37 USE breakTOEXJTALOOP

EXERCISES
1. Write a program that finds all the prime numbers between 2
and 1000.
2. Write a program that reads ten diaractors from the keyboard.
Each time a character is read, use its ASCII code V,11 L ' to output
a string of periods equal in number to this code. For example,
given the letter 'A', whose code is 65, your program would
output 65 periods.

U SE break To EXIT A LOOP


The break statement allows you to exit a loop from an y point within
its body, bypassing its normal termination expression. When the break
statement is encountered inside a loop, the loop is immediacely
stopped, and program control resumes at the next statement following
the loop. For example, this loop prints only the numbers 1 to 10:
*include <stdioh>

mt main(void)

mt i;

for(i=l; i<lOO; i+i-)


printf(%d i);
if(i10) break; I' exit the loop *1

return 0;

The break statement can be used with all three of C's loops.
You can have as many break statements within a loop as you
desire. However, since too many exit points from a loop tend to
destructure your code, it is generally best to use the break for special
purposes, not as your normal loop exit.
90 TEACH VOURSEIJ
V

I. The break statement is commonly used in loops in which a


special condition can cause immediate termination. Here is an
example of such a situation. In this case, a ke y press can stop the
execution of the program.
include <stdio.h>
#include <conio.h>

mt main(void)

mt i;
char ch;

/ display all numbers that are multiples of 6 *1


for(j=l; 1<10000; i++)
if)Hi%6)) I
printE(%d, more? (YIN)', i);
ch = Oetche(i;
if(ch=='N') break; 1* stop the loop
printf('\n')

return 0;

2. Abreak will cause an exit from only the innermost loop. For
example, this program prints the numbers 0 to 5 five times:
tinclude <stdioh>

mt main(void)

mt i, j;

for(i=0; i<5; i++) {


for(j=0; j<100; j++)
printf(%d", ii;
if(j==5) break;

printf("\n')
MORE C PROGRAM CONTROl. STATEMENTS
91
37 USEIweikTOEYJTALOOP

return 0;

3. The reason C includes the break statement is to allow your


programs to be more efficient. For example, examine this
fragment:
do
printE(Load, Save, Edit, Quit?\n")
do {
printf(Enter your selection: };
ch = getchar;
hi1e(ch='L' && ch!=S' && ch!='E' && ch!=Q');

if(ch = {
/* do something *1

if(ch != 'Q')
7* do something else*/

/ etc.
while(ch SQ')

In this situation, several additional tests are performed on ch to


see if it is equal to 'Q to avoid executing certain sections of code
when the Quit option is selected. Most C programmers would
write the preceding loop as shown here:
for( ; ; { / infinite for loop /
printf(Load, Save, Edit, Quit?\n);
do
pr±ntf (Enter your selection: )
ch = getchar;
} while(ch'=L' && ch!='S' && ch!=E' && ch!=Q);

if(ch == 'Q') break;

/ do something /
/ do something else *7
/* etc. /
92 TEACH YOURSELF
V

In this version, ch need onl y he tested once 10 sec if it cflt,in


a 'Q' As you can see, this implementation is more cftIclCnt
because only one if statement is required.

EXERCISES

On your own, write several short programs that use break to


exit a loop. Be sure to try all three loop statements.
2. Write a program that prints a table showing the proper amount
of tip to leave. Start the table at $1 and stop at $100, using
increments of $1. Compute three tip percentages: 10%, 15%,
and 20%. After each line, ask the user if he or she wants to
continue. If not, use break to stop the loop and end the program

KNOW WHEN TO USE THE continue


STA TEMENT
The continue statement is somewhat the opposite of the break
statement. It forces the next iteration of the loop to take place,
skipping any code in between itself and the test condition of the loop.
For example, this program never displa ys any output:
*include <stdioji>

mt main(void)

mt x;

for(x=O; x<100; x++)


continue;
printf(%d x); / this is never executed /
MORE C PROGRAM CONTROL STATEMENTS 93
a8 KNOW WHENTO USE THE continue STAJ,1EPi7- V

return 0;

Each time the continue statement is reached, it causes the loop to


repeat, skipping the printf( ) statement.
In while and do-while loops, a continue statement will cause
control to go directl y to the test condition and then continue the
looping process. In the case offer, the increment part of the loop is
performed, the conditional test is executed, and the loop continues.
Frankl y , continue is seldom used, not because it is poor practice to
use it, but simply because good applications hii it are not common.

One good use for continue is to restart a statement sequence


when an error occurs. For example, this program computes a
inning total of numbers entered b y the user. Before adding
a value to the running total, it verifies that the number was
correctly entered by having the user enter it a second time.
If the two numbers don't match, the program uses cotinuC
to restart the loop.
#include <stdio.h>

irit main(void)

mt total, i . 3;

total 0;
do
printf ('Enter next number (0 to stop): ');
scanf("%d', &i);
printf VEnter number again
scanf(%d', &j);
if(j j) {
printf ('Mismatch\n')
continue;

total = total 4- 1;
94 TEACH YOURSELF
V

whi1ei);

printf("Total is %d\ri, total);

return 0;

EXERCE
1. Write a program that prints only the odd numbers between 1
and 100. Use a for loop that looks like this:
for(i=l; i<101; i++)

Use a continue statement to avoid printing even numbers.

"ONG ALTERNATIVES WITH


THE switch STATEMENT
While if is good for choosing between two alternatives, it quickly
becomes cumbersome when several alternatives are needed. C's
solution to this problem is the switch statement. The switch statement
is C's multiple selection statement. It is used to select one of several
alternative paths in program execution and works as follows. A value
is successively tested against a list of integer or character constants,
When a match is found, the statement sequence associated with that
match is '':c;itcd. The general foi in ni the switch statement is this:

switcli(value)
case constanti:
statement sequence
break;
MORE C PROGRAM CONTROL STATEMENTS 95
39 SELECTAMONGALTERAL4TIVES WiTH THE swftch STATEMENT

case constant2
statement sequence
break;
case constant3
statement sequent
break;

default:
statement sequence
break;

The default statement sequence is performed if no matches are


found. The default is optional. If all matches fail and default is
absent, no action takes place. When a match is found, the statements
associated with that ease are executed until break is en ountered or,
in the case of default or the last case, the end of the switch is reached.
As a 'iry simple example, this program recognizes the numbers 1,
2, 3, and 4 and prints the name of the one you enter. That is, if you
enter 2, the program displays two.
#include <stdio.h>

jot main(void)

mt 1;

printf("Eriter a number between 1 and 4:


scanI(%d', &i);

switch(i) {
case 1:
printf('one")
break
case :
printf(two")
break;
case 3:
printf( three")
break;
96 TEACH YOURSELF

case 4:
printf( four")
break;
default:
printf ( "unrecognized Nurnber)

return 0;

The switch statement differs from if in that switch can only test
for equality, whereas the if conditional expression can be of any type.
Also, switch will work with only mt or char t y pes. You cannot, for
example, use floating-point numbers.
The statement sequences associated with each case are not blocks;
they are not enclosed b y curly braces.
The ANSI C standard states that at least 257 case statements will he
allowed. In practice, you should usually limit the amount of case
statements to a much smaller number for efficiency reasons. Also, no
two case constants in the same switch can have identical values.
It is possible to have a switch as part of the statement sequence of
an outer switch. This is called a nested switch. If the case constants of
the inner and outer switch contain common values, no conflicts will
arise. For example, the following code fragment is perfectly acceptable:

switch(a)
case 1:
switch(b)
case 0: printf("b is false);
break;
case 1: printf("b is true);

break;
case 2:

An ANSI-standard compiler will allow at least 15 levels of nesting


for switch statements.

MORE C PROGRAM CONTROL STATEMENTS 97


39 FLEeT 4MONG AL (tUNA (I VIS Whit W[ switch SIVEMEW

The switch Stati:ment IS ()ftcfl used 11) )I()(.('SS Iiieiiii


rolunDinds. For example, the ar(tliinetjr Pr 4,aTII I an
recoded as shown licre. Ih is version ri fleets lie way
protissional C code is written.
tincJude <stdi€.]e'

mt main (void)

mt a, b;
char ch;

Print ("Do you want, to: \n"


prirtf("Add, SubLLdct, MUIL"p -, or
/ force user to Onter a vu a r
do
printf("Erter first letter:
ch = qet char ((
while(ch! = A' && ch = '3 eh - ti ii '
printf("\n")

prntf C Enter first, number


Scanf(°%d", &a);
print f("Enter sec-out number: ")
scnf("%cj', &b);

switch(ch)
case 'A': print I I ' 'l'
break;
case '3': p rintf("%d' a-b);
break;
case 'M': printf('%d" a*b);
break;
case 'D': if(b!=O) print.f('%d", a/h);

return 0;

7
98 TEACH YOURSELF
V

2 in' .hiicaiiv, thc break statement is optional. The break


St,1t,110'flt, wficii ciicou titcred within a switch, causes tile
prngrni how to exit fr(Jrit the entire switch statement and
(out tote ()11 to the tiext statcuilent outside the switch,
This is
nw:h tile way it 'orkswhen breaking out of a loop. I lowever,
a break st tetuidilt is omitted, execution cOfltiflUCS into the
bol lowiuic case or default shiltemetit (if either exists). That is,
w In' n il break st:utemcuit is missing, execution falls through"
HIM till: next case and slops only when a break statement or
Ito' ('rid oh the switch is encountered. For example, study this
prograni care I iii ly
tine <std io .
((include <oiiio.h>

mt main(void)

cilol Cn:

tu t
prinrf('\nEnter a character, q to quit:
cli = getche()
printf ("\n")

swi Lch chi I


case 'a'
printf ("Now is
case 'b'
printfVt.he time
case 'c'
printf("for all good men');
break;
case 'd'
printft"The summer
case 'e'
printft'soidiei

} whil'(ch

return 0;

If the user t y pes a, tite entire phrase Now is the time for all
good men is thiS I )1I'V('(] Ivpiiig b displays the time for all
MORE C PROGRAM CONTROL STATEMENTS 99
39 SELECT AMONG ALTERNATIVES 41TH THE switch STATEMENT

good men. As y ou can see, once execution begins inside a


it coiltiflucS until a break statement or the end of the switch Is
ciicotintered.
3. The statement s quence associated with a case iiiay he empty
This allows two or more cases to share a common statemne oh
sequence without duplication of code. For example, here is a
program that categorizes lettciS into vowels and consonants:
*include <stdio.h>
#include <conio.h>

mt main(void)

char ch;

printfVEnter the letter:


ch getche

switch(ch)
case a:
case 'e'
case
case o
case u
case 'y
printf( is a vowel\n);
break;
default:
printf(" is a consonant');

return 0;

EXERCISES

1. What is wrong with this fragment:'


Noat 1;

scanf)%f", &f); Iv.


100 TEACH YOURSELF
V

switchtf> {
case 10.05:

2 Write ;I that i:iiiints the numbers of letters, digits,


md coiiiniun punctuation symbols eiitcrr hr the user. Stop
uIlp (It t ing vlien the user presses RN till. Use A switrh state I Hunt
to I tegorize thc cliara:ters into p,,ticttiatioii. digits, and letters.
When the program ends, report the number of .liar;n;ters ill
4

each category. (If you hike, simply assume Ilbit, it a :hi,ira tci is
not a digit or punctuation, it is a letter Also, just IISC the most
I OFFlittOit puilctuat.ion sviitbols.

I
UNDERSTAND THE goto STATEMENJ
goto. RecJliSe
C. StipI}I Is a non-conditional in np stat" iiietlt, .,tlletl tue
is neer sar
C is a replacement for assembl y code the il(lltsi()Fl of gOt(J
hn'caiise it can he used to create very last routines. I lowe\ er, most
1irograilltners (10 not use goto bccause it destructioes ,i piogiafll ,iiod,
if huqtiently used, can render the progiaifl virtuall y impossible to
nnchi'rstaiid hater. Also, there is no routine that reqinies 1 gotO. br
thl('( reaSonS, it is not used in this hook outside oh thus section.
'lii' golo stateuleilt can perorin it within a unction. It cannot
Iabcl is a valid
101 1 1 ) het\Veeii functions. It works with a label. In C, a
dent itier mime followed hr a olon. For example, the hollowiiig goto
junips aiimnd the printi( ) statement:

1.t niylabel
,r. jj fp, Tjjis will not erint .
myab1 : printt C "This willprint.";
y nested
About the onl y good use br goto is to)jump out ul a deepl
routine when a catastrophic ei ror oc:urS
MORE C PROGRAM CONTROL STATEMENTS 101
3.10 UNDERSTAND THE gob STATUHENI V

I This program uses gWo to create the cquivacnt of a hr !Ooj)


rulilibog from I II) 10. (FIlls is just an example of goto. in actual
practice, YOU S110LLIJ itsi; it real for loop when one is iweded
#inc].iide .st.dio.h>

jni rnain(vcid)

int. i;
i = 1;
again
printf (%d it
i +;
if(i<10) cjOto again;

return 0;

EXERCISES

I Write a progritil that uses goto to emulate it loop that


coil ots flout I to 10.

maste
Skills Check

At this p01111, you should be aide to answer tilese (luestions and


perform these exercises:

• As illustrated by Lxerc:ise 2 in Section 3.! the ASCII codes for


the lowercase letters are separated from the uppercase letters
b y a difference of 12. Therefore, to convert a lowercase letter to
102 TEACH YOURSF
V

in uppercase one, simply subtract 32 front Write d program


that reads characters from the keyboard and displays lowercase
letters as uppercase ones- stop when crirn is prsed.
2 Using it if statement, write it program that prolllpts tlii
user tbr a number and then reports if the number IS positive,
zero, or negative.
3. Is this a valid for lOOp:
char ch;

uh=
for( ; ch ! ; ) ch = getche()

4. Show the traditional wa y to create all h)op in C.


. Using the three loop statenicrtts, show three different wa ys to
LOLl lit from I to M.
it
ti . What does the break statement do when tised in
7. Is this switch statement (;orrcct'
switch))) I
case 1: printf("rticke1),
break
case 2: printf("dime");
break;
vase 3: prinLf I qoar Let)

Is this goo fragment corrCct


qoLo alidoLle;

ill dor

This Se(tioIi checks how well you have integrated the material in
this chapter with that front chapters.

MORE C PROGRAM CONTROL STATEMENTS 103


.370 UNDFR.!AN1) TilE goto 1A ii Mt NT

I. Using a switch statement, write a program that reads litu ter


From the ke y board and watches for tabs, twwiiiis, ;iiid
backspaces. When one is received, display what it is ill -olds
For example when the user presses the 'I.\Ii ke y , mt tab
I lava the [tsar enter a (j to Stop the progran i.
2. While this program is not incorrect, 5110W h(1W It \'OItkl look it
wrttett b y an experienced C programmer,
*inrirrd <Ldio.h>

itit Ifll1fl(VClIC1)

mt m, j, k,

for(k=O; k<10; k=kt)


pr i ri L f ( Enter I I r nt nirtiher :
canf("%d", &]

pr i ntt I Enter second numht,i


scanf "%c1 j

if (j 0) printf(%d\n", i/j)
if U 0) print ft "cannt (IV ide by :x\n

return 0;
4
A Closer Look at
Data Types, Variables,
a. and Expressions
-
chapter objectives

€1 4.1 Use Cs data-type modifiers


4.2 Learn where variables are declared
4.3 Take a closer look at constants
4.4 Initialize variables
4.5 Understand type conversions in expressions
4.6 Understand type conversions in assignments
4.7 Program with type casts

105
V
106 TfACH YOLIRSEL F
V

HIS chapter more fully examines several ((Inccpts presented


iii Chapter 1 It covers Cs data-type modifiers, global and
local variables, and constants. It also discusses how C handles
V,][ iI)1IS t y pe cOnversions.
T

R eview
k^l I sCb!

Iclorc proceeding, you should he able to answer these questl Ins

and perform these exercises:


• Using C's three loop statements, show three wa ys to write a loop
that counts Inini 1 to 10.
2. Convert this series of its into art equlvaicTit switch.
it(c-.h=='L't load U;
else if(ch='S') saveU;
else if(ch=='E') enterl);
else if(ch='D' ) display(;)
else if(ch=='Q') quitt);

3. Write a program that inputs characters until the user strikes the
ENTER key.
1, what does break do?
F. What does continue do?
(. Write a program that displa y this menu, performs the selected
operation, and then repeats until the user selects Quit.

Convert
1 feet to meters
2. meters to feet
3. ounces to pounds
4. pounds to ounces
5. Quit
Enter the number of your choice:
A CLOSER LOOK AT DATA TYPES. VARIABLES, AND EXPRESSIONS
107
4 1 USE CS VA TA TYPE MOD/flIps

USE C'S DATA-TYPE MODIFIERS

Iii Chapter 1 you learned that (Thas five basic data types; yjjçlcliar,
int, float, and double. These basic types, CX(:et3f t y void, can he
' ituThg C's (rjpc p noth(icrs to note precisely fit your secilic
need. The t y pe modifiers are

long
short
signed
unsigned

The tvr)e modifier precedes the type rkitrle. For example this dcclares
a long integer:
I c-,nci i rlt i

l'hc efiect of each modifier is examined next.


'I'll(, long and short modifiers may be applied to mt. As a general
rule, short ints are often smaller than ints and long ints are often
larger than ints. For example, in most 16-bit environments, an mt
is 16 bits long and a long mt is 32 bits in length. I lowever, the precise
meaning of' long and short is implementation dependent. When the
ANSI C standard was created, it specified ninrinum mngcs for integers,
short integers, and long integers. It did not set fixed sizes fir these
items. (Sec Table 4-1.) For example, using the minimum ranges set
birth in the ANSI C standard, the smallest acceptable size fr all mt is
16 bits and the smallest acceptable size for a short mt is also 16 bits.
Thus, it is permissible For integers and short integers to he the saiiie
size! In bict, in most 16-hit environments, there is no difference between
an mt and a short mt. Further, in many 32-hit environments, you will
find that integers and bug integers are the same size. Since the exact
effect of long and short oil is determined by the environnient
in which you are working and by the compiler you are using, you will
need to check your compiler's documentation for their precise effects.
The long modifier may also he applied to double. Doing so roughly
doubles the precision of a Iloating point variable.
108 TEACH YOURSELF

lIie signed modifier is ubcd to sixe fya signed integer value. (A


signed nii nihrr i neans that it(-,anbe positive or_gIti':. ) I lowever,
lie use of signed on integers is redundant because the default integer
(ii'cIIrltion autonatically crc ites a signed variable. The nLuTl use
Of the signed modifier is with char, Whietfiei char is signi:d or
Iiflsigii('d l itself, is implementation dcpendriit. In sonic
niph' ilientations char is unsigned by default; in others, it is signed
To i'nstiri: a signed character variable ill all ei'ivimnmentS, you intist
declai'e it as signed char. Since iiii)st compilers implement chair as
signed, this book simply assunìes that characters are signed and will
not use the signed modifier.
'I'he wjnçd char and mt. It ma y illso
be used in comli imih1ongr' M '
r t. It is used to create all
unsigned integer. 'the di ference between signed and Unsigned
integers is in the way the high-order hit of' the integer is interpreted. If
a signed integer is specified, then the C compiler will generate code
that assumes the high-order bit is used as a sign flag. It' the sign flag is
f) the nuniber is positive; if it is I, the number is negative. Negative
numbers are generall y represented using the twos complement
approach. In this method, all bits in the number (except the sign flag)
are reversed, and I is added to this number. Finally, tin' sign flag is set
to I (The reason for this method of representation is that it makes it
easier for the (:[)[I perform arithmetic operations on negative values.
Signed i ttegers are important Ir a great many algorithms, but tI ny
onl y have half the absolute magnitude of ' their unsigned relatives. For
example, here is 32,767 shown in binary:

0111111111111111
II this is a signed value and the high-order hit is set to 1, the uiii mber
would then be interpreted as -1 ( assu uning two's complement format).
I lowevcr, if' this is all value, then when the high-order bit
is set to I, the number becomes 65,535.
Table 4-1 shows all allowed combinations of the basic t y pes and
the type modifiers. The table also shows the most common size and
minimum range for each type as specified by the ANSI C standard.
It is important to understand that the ranges shown in Table 4-I are
Just the minimums that all compilers must provide. The compiler is
Free to exceed them, and most compilers do for at least some data
types. As mentioned, an mt in a 32-bit environment will usually hiuve
-I larger than the minimum. Also, in environments that use

A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS 109


I (I.'F U,% I)AI/i TV/I MOL)I1ILIIS

Type Typical Size in Bits Minimal Range


ar8 -127to127
41111sioned char 8 0 to 255
Signed char 8 -127 to 127
16 or 32 - -32,767 to 32,767
jJrlSigFle(J int 1601 32 0 to 65.535
signed int 16 0132 same as int
shortin( 16 same as mt
unsigned short tnt 16 0 to 65,535
signed slinil lilt 16 same as short int
long j ilt 32 2,147,483647 to 2,147,483,647
Signed long int 32 sane as long int
LHIS1011WI liniq int 32 0 to 4,294,967,295
, Ioat 32 Six digijs of precision
Øoubte 64 Ten digits of precision
long double 80 Ten digits of precision

A// Data rypes Defined by the ANSI C Standard V

two's (a)Ltil)tclll(i'lt ;trithln(til; (which is ilic ('asc liii the v.tst nl;ijoritv
of CoMpiIi('Is). the hound
lower for signed (.har,t( lets and integers is
ol)i' gicatci' than the tninilrilin1s shown lor istitire, in nioSi.
ilvironiio'iits, a signed char has railg(' of'-] 28 to 1 27 itici a short
jot is tvpI( dlv -32,768 to 32,767. You will need to I:hel.k your
(a)nlpuier's doctuiuieiuiatt Ii for the specilu: ranges of the lilt, tvpes
as they appl y to \'odi r (:onlpiirr.
C allows a sliortlianid notation for (h'( h,ui lug unsigned, short, or
long itegers. You may simply use the wot d unsigned, short, or long
vithuiiiit the li-it The mt is implied. For example,
count
lUll; i qrII?d
qried i [It. rlurr;

bcnli declare unsigned mt variables,


It is important 1(1 r('nhu'mber that variables of t y pe chat- na y he used
to hold Values other than just the ASCI I ,har,1I:rer set. C :n,iki:s little
d sli uctiuu l between a charau icr mid an nte except for Ill('.
1 10 TEACH YOURSELF
V

inagnitiitics of the values each may hold. Therefore, as mentioned


v;irlicr, ;I char variable can also he used as a srnall integer
'licn the situation dues not require larger numbers.
When outputting integers modified by short, long, or unsigned
using printi( ), you cannot simply use the %d specifier. The reason is
that printf( ) needs to know precisel y what type of data it is
receiving. To use printf( ) to output a short, use %hd. To output a
long, use %ld. When outputting an unsigned value, use %u. To
output
u an unsigned long int, use %lu. Also, to output a long double
use %Lf.
Flie scanf( ) function operates in a fhshion similar to printf( ).
When reading a short mt using scanf( ), use %hd. When reading a
long int, use %ld. To read an unsigned long int, use %lu. To read a
double, USC %If. To read a long double, use %Lf.

EXAMPLE S I

This program ShOWS 110w to input aiid output short, long, and
unsigned values.
#incLude <stdio.h>

juL rnainlvoid>

unsigned u;
ioncj 1;
short a;

printf ("Enter an unsigned:


scanf("%u', &u);
printf VEnter a long:
scanf("%ld", &l);
printf(EnLer a short:
scanf("%hd", &s);

print:f ( ,, *u %ld %hd\n U, I , s)

tetuxj) 0;

• lo u nderstand the dillcreice between the way that signed and


unsigned integers are interprc'.ed by C, run the following short
pig1anl. (This program ass" ms that short integers are 16 hits wide.)
A CLOSER LOOK AT DATA TYPES, VARIABLES. AND EXPRESSIONS 111
4 ) USE CS DA 1k 1YI'E MOIJ/FIFRS

Vincludc' <stdio.h>

101 inain(void)

short jOt 1; a signed short integer *!


unsigned short lot U; /* an unsigned short integer

u 33000;

printf("%hd Thu'. I, u);

return 0;

\Wlicn this program is run, the output is -32536 33000. The


reason for this is that the hit pattern that 33000 represents
as an unsigned short mt is interpreted as -32536 as a signed
Short mt.
3. In C, you may use a char variable any place you would use an
mt variable (assuming the differences in their ranges is not a
tat:tom ). 1 example, the following program uses a char variable
to control the 1001) that is summing the numbers between I and
100. In Some cases it takes the computer less time to access a
single byte (one character) than it does to access two bytes.
'lii erefore, many professional programmers use a character
variable rather than an integer one when the range permits.
#i.nclude <st.dio.h>

mt main(void)

iflt i;
char j;

I=
for(j=1; j<101; j++) j +'j;

printf ("Total is: %d, i);

return 0;
1 12 TEACH YOURSELF
V

EXERCISES
I. Show how to declare an unsigned short mt called lot;_t:ountcr.
2. Write a pr gr;Lru that prompts the user for a distance aud
corn putes how long it takes light to travel that distance. Use an
unsigned long mt to hold the distance. (Light travels at
approximately 186,000 miles per se(,ond.)
. Write this statement another ay:
short mt 1;

LEARN WHERE VARIABLES ARE


DECLARED
As you learned in Chapter 1 there arc two basic places where a
variable will he declared: inside a binctiori and outside all fnnctonis.
I'hese variables are called local variables and ç1ohu1 variables,
respectively. It is now time to take a closer look at these two types
f• variables and the scope rules that govern them.
Local variables (declared inside a function) ma y be rd re need only
by statements that a re inside that ftfflction. They arc riot known
outside their own fu nction. One of the most important things to
ti ode rsta lid about local variables is that the y exist onl y wli Ic the fu nctioni
ill wli Hi they are declared is executing. That is a local variable is created
o pun entry into its function and destroyed upon exit.
Since local variables are not known outside their own function, it is
perfectly acceptable for local variables in different functions to Icive
the sanire name. Consider the following program:
#irictude <stdio.h>

void t I (void) f2 (void);

mt sairLvoidl

tic)
return 0;
A CLOSER 10011 AT DATA 1YPES, VARIABLES, AND EXPRESSIONS 113
4.2 LEARN $mERE VAPJA&ES ARE DECLARED

void fl(void)

mt Count;

for(count=O; count<lO; count++) f2();

void f2(void)

j ilt Count;

for(count=O; count<10; Counti-+) printfV%d count);

This program prints the numbers 0 through 9 on the screen ten Ii: :.
The fact that both functions use a variable called count has no Ci
upon the operation of the code. Therefore, what happens to count
inside f2( ) has no effect on count in fi ( ).
The C language contain ,; the keyword auto, which can he use( to
declare local variables. However, since all local variables are, l)'
default, assumed to be auto, it is virtuall y never used. I Inner', V u will
not see it in an y of the examples in this book.
Within a function, local variables can he declared at the start (it any
block. They do not need to be declared only at the start o the block
that defines the function. For example, the following progoiin is
perfectly valid:
#include <stdio.h>

jilt main (void)

j ilt 1;

for{i=Q; i<10 ii+} {


if (i==S) {
j ilt j; / declare j within the if block

= I * 10;
printf ('%d', j);

return 0:
1 14 TEACH YOURSELF
V

A v I I ijhle (If o le' ii uithjrt a block is known onl y to other code within
that block 1 is j ma y not he used outside ot its block. Frankl y , most
to r.irrnji' cl: Lire all variables used b y a function at the start of
tO: tiU tun' him k because it is simpl y more Convenient tO do SO.
[his 's rh: approach that will he used in this hook.
P ie;nl :1 iii trilportant poiot: You must decEit e all local variables
c .rrr of die bloc,k in which the y are defined, prior to arty
lroOr.tm St,itcilletltS. For example, the following is incorrect:

de

mirL(,'

program won't compile.);


:'r.ts shcid com€ firs

10;
pri.-t f

rern 0;

Wlc:r i . 1 f;rncric,n is called, its local variables are created, and upon
its erurn, the y are destro y ed. This means that local variables cannot
I(jaill their vjILWS between calls.
[hi: forrurl p;im.i;11t:rcrs to a function are also local variables Even
tlroe y h these v;;riahles perform the special task of receiving the value
of the ,irut; eros pissed to the function, the y can he used hke any
other loc.il variable within that function.
Unlike local 'arrahii-'s, global variables are known tltrou;hotrt the
entire prorIrn and ma y be used b y an y piet:e of code hi the purani
Also, di ev o' 11 hold ;lteir value durir the entire execor ion of the
piogoiru. EJehstl v,iri,ilr:s are createc; by declaring them outside any
function, Pot (u' arnple, consider this program:

tinc1:de <st:dioti>

void f (vcO d)

inz max; this is ,'i global variable .1

jot r:i.i:o)vc.id)

max = 10;

A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS 1 15


2 LEARN WHfRL VARIA8LIS 4RE DICtARTO

fi()

return 0;

void ti(void)

mt i;

for)i0; i<xnax; i++) pr intf '%d 1);

I lere both rnain( ) and 11 ( ) uSe the global variable


max. '11w main( )
function sets the value ol max to 10, arid fl ( ) uses this value to
control its for loop.

EXAMPLES]
I In C, a local variable and a global variable may have the same
name. For example, this is a valid program:

p nclude 'zstdjo.h>

void ii (void)

in count; '* g loba l count

jot main(void)

count = 10;
fl();
0 rintf("cour,t in nainU : d\o" 000:IL(

r.turn 0;

void ii (void)

mt count; * iocal count

count 100;
printf("cOur.r in Fl)) ; %dn', count);
1 16 TEACH YOURSELF
V

The prograin displa y s this cutput-

count in ho :100
count in main() 10
I n rniIili( ). the retrren( e to Count is tothe global varible.
lioide fl ( ), a mcii ar ,ihii ailed count is also cletifle(i. When
Ow assignment statement inside 11 ( ) is encountered, the
compiler first looks to si: it lucre is a local variable called
coLtnt. Since there is, the local variable is used, not the thjhal
one with the same name. 1 hat is, wlie 1 lo( al and global
variables share the same ni:i me, the . urn piler will alwa y s use the
local varial)le
1. Global variables are ver y helpful when the same data is used by
urn fly Functions in y our pgram However, y ou should always
use local vu riables wIuri: vi t can because the. excessive USC of
global variables has sonic negative consequences. First, global
variables use nnu:imiorv thu; entire time your program is
101 uling, riot ju't when the y are needed. III situat ants e here
memor y is ill short suppl y , this could be a problem. Second,
using ii global where a local variable, will do makes a function
less general, because it relies on something that must be defl ned
outside itself. For example, here is a case ivhere global variables
arc being used for no reason:
i'iciudo <sto.h>

irit po'.jer(void);

irit rr, e;

mt main(void)

M 2;
e = 3;

printft"%d rais"d to the 'li d foyer is %d", m o,

return 0;

! Mon-general vorsto:;
mt power(void)

A CLOSER LOOK AT DATA TYPES, VANIABUS. AND EXPRESSIONS 117


42 LEARN WHERE VARIABLES ARE DECLARED

iit temp, temp2;

tern;-) = I
ternp2 e;
for( ternp.O; tesp2--) temp - temp *

j(.1e , thil tuflCtiOfl power( ) is created to compute the value of


rn raised to the th Since iii and e arc global, the function
cannot bt , used to compute the power of other values. It can
(dliv ()iI rate on ti Se contained cttlun m and C. However, if
the pruLran1 is rewritten as follows, power( ) can he used with
an y two values.
nc1ucIe <stdio.h>

rn. irit. C);

rI;. n:l(VOIC)

1111. rt, 0;

to the %d is %d\n', In, e, poer(m, e));


to the 5th is %d\n", power (4, 5))
3 rho 3rd is %d\n", power (3. 3));

return 0;

P;t;;ieriJ ;ersior. of power. */


pcwer I icr. 1;-. 3

icr temp;

1.;
fc: ; e> 0; e- - I tdrrp = t€:rp *

terrr.;
1 18 TEACH YOURSELF
V

By trar Wii/iflL poWCF( ), y ou can Usr it to rrturtl tIt'


rrsult Of .tflV value raised to sonic power, as the progrtnl
00 r.liows

I lie innipoitatit p(nit is that ill the. Ii0n ]tcrali7.eLt versiOn,


lilY I° Jul that Uses pO%Cr( ) nitist k'avs d( , cl,IT( . lB and c1

as ohal vari;ih]c:s arid then load thetii with the desired values
earn (tim: powcr( ) is used. In the parunrtcriztd hum, ii
tunirt iou is ronipletui withill itsf-no uieCd hi:
can ccl about when it is used.
totall y using a hinge number of global variables mi I ad to
I ro o lam muons }iec; Of kimuiwni and cinwinted sick: ih:
\ 111,lior proliletmi in developing lange progrims is 01C mur hluo til
mo(luticatI;n of a '.'inahlcs value because it was used
in tiuc prouranl This cart happen in C if von use too man y IoIuul
vat ithims ill vow po >cra nis.

t Rc uin'Till u:r, loiti uarjaliles do thu_ut Ihuililtain) their '.al tue s H
limit otis tills. lor exatuiple the following pmgrnil will hut
Won k correctly:

(iHirulUdle <rtd;o.h.

ser€stvoid)

11:1. natri(voidi

mt 1;

fort i-CO i10; i + priru f runes

return

1* This is incorrect.
mt seLi:3(vo;:

j ut total;

= (total 1423) % 1422;


1 eturn total;
A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS 1119
43 TAcj A :JR,flOKr(:oT1,VTS

This program atwillpts to use series( ) to ciouu' a icinTh'r


series in which each number is based upon thc value
preceding one. 1 fowever, the value total will rift ' nitittii.ind
between function calls, and the function fails to arr, (nO li
4

intended task.

EXERCISES
1. What are ke y clilicrences between local and it ct:
2. Write a program that contains a function cal it'd smi tin iwed ( )
which computes tire number of seconds it will t.ike
travel a S pecified distance. Write thin program two c, Iii
vitli soil ndspecd( ) as a null-general (unction and siit:1, with
soundspccd( ) parariictcrrzed. (For the speed of 5(o(iI1( 15°'
11 79 tet per second).

TAKE A CLOSER LOOK AT CONSTANTS


Constants rnhtr to fixed vluns that ma y riot be alu ret) bvdte ant
For example, the number 100 is a Constant. We have beet tist i
constants in the preceding sample programs wthoLn iii uch tat: ..i cc
because, ill cases, their use is intuitive. I [owcvo'r, thu time has
come to cover them formally.
Integer Constants are Spnciticd as numbers without tr nal
components. For example, It) and -10)) are integer CoitisIttitti.
1-'loating-point constants recji ire the use of the decimal point to) I owed
b y the number's fractional component. For exanipic, II .1 Li Is it
tloating-ponit constant. C also allows YOU to Use scicitifu. lct,itoon hi
floating-point numbers. onstants using sc.re untic 110t,16 011 nit st 1014''
this general form

number E sign exponent

The sigo is optional. A10101.1 011 the general form is slnn':n with sp.c l'S
between the component parts for clarit y , there ma y he no spo us
between the parts in an actual number. For example, the flltwi rn.t
defines the value 1234.56 using scientific flotation:
120 TEACH YOURSELF
V

456E1

Character constants are enclosed between single quotes. For


example a' and '%' are both character constants. As some of the
examples have shown, this means that if y ou wish to assign a
character to a variable of t y pe char, you will use a statement similar to

ch = '7,'

lowever, there is nothing in C that prevents von from assigning a


character variable a value using a numeric constant. For example, the
ASCII corle for 'A' is 65. Therefore, these Iwo assignment statements
are equivalent

char cc,

ch
ch F5:

\\'hen von enter numeric constants into your program, the compiler
must c1('(lde what, t y pe of constant the y arc. For example, is 1000 an
int, an unsigned, or a short' The reason we haven't worried about
this earlier is that C automatically converts the t y pe of the right side of
an assignment statement to that (if the variable oil left. (We will
ex.Inline this process more fulllater in this chapter.) So, for man y
situations it doesn't matter what the compiler thinks 1000 is. I lowever,
this can be important wile!! von use a constant as an argument to a
In ration, such as in a call to printf( ).
lv default, the C compiler fits a numeric constant into the smallest
compatible data t y pe that will hold it. Assuming 1 6-hit integers, 10 is
an mt b y default and 100003 is a long. Even though the value 10 could
he fit into a char, the compiler will not do this because it means
crossing type boundaries. The onl y exceptions to the smallest-type
rule are floating-point constants, which are assumed to he doubles.
For virtu,illv all programs y ou will write as a beginner, the compiler
det,rul ts arc' perfectl y adequate. FIo'cver, as von will see later in this
hunk, there will come a point when von will need to specify precisely
the type of constant y ou want.
In cases where the assumption that C makes about a numeric
constant is not what you want, C allows y ou to specify the exact type
A CLOSER LOOK AT DATA TYPES, VARIABLES. AND EXPRESSIONS 121
t3 TAKE CLOSER LOOKAT CONSTANTS •

by using a suffix. For floating-point types, if you follow the number


with an 'F, the number is treated as a float. If you follow it with an 'U,
the number becomes a long double. For integer typ the 'U' suffix
stands for unsigned and the 'L' stands for long.
As you may know, in programming it is sometimes easier to use a
number s y stem based on 8 or 16 instead of 10. As you learned in
Chapter 2, the number system based oil is called octal and it uses the
digits 0 through 7. The base-16 number system is called hexadecimal
and uses the digits 0 through 9 plus the letters 'A' through 'F', which
stand for 10 through 15. C allows you to specify integer constants as
hexadecimal or octal instead of decimal if you prefer. A hexadecimal
constant must begin with 'Ox' (a zero followed by an x) then the
constant in hexadecimal form. An octal constant begins with a zero.
For, exaniple, OxAR is a hexadecimal constant and 024 is an octal
constant. You ma y use either upper- or lowercase letters when
entering hexadecimal constants.
C supports one other type of constant in addition to those of the
predefi ned data t y pes: the string. A strinlg is a Set of characters
enclosed by double quotes. You have been working with strings since
Chapter 1 because both the printf( ) and scanf( ) functions use
them. Keep in mind one important fact: although C allows you to
define string constants, it does not formally have a string data type.
Instead, as you will sec a little later in this book, strings arc supported
in C as character arrays. (Arrays are discussed in Chapter 5.)
To display a string using printf( ) you call make it part of
the control string or pass it as a separate argumeit and displa y it using
the %s ftffrnat code. For example, this program prints Once upon a
time oil screen:
*include <stdio.h

inc mair.(vojd)

printf("%s %s %s', "Once", upon", "a time");

return 0;

Here, each string is passed to printf( ) as an argument and


displa yed using the %s specifier.

122 TEACH YOURSELF


f

I EXAMPLESJ
lo see wh y it is ittipot tool to USe the correct type speciliel
with printl( ) tr y this program. (It assumes that short
integers ore 1 0 hits.) Instead of printmg the number
42310,
it clisp1vs -23196, beejuse it thinks that it is receiving a
signed short i ntecer. The problem is that 42,3 10 is outside the
range of a short mt Io make it work properly, YOU mUst use
Oil'. %hu specifier.
nc1ede <..i: h-

'ia in I vc Id 1

JEr't work right */

2. lo see wh y y ou ma y nc J to expli It)v tell tk compiler a hat


tYpe (It (.ur1stUfl von are try dos progiuilt. For most
(oInpilrrs, it will not produce tite clesied oiLtptit. (It it does
it is lv b y I ItO
4nC1i.c1 a'...

printti i:', 2 129

I-

'lius program is telling prm ntf( ) to expect a floating point


value, but the compiler aSsUilles dirt 2309 is simply an mt.
[cnce, it dries not output the corrt' t value. To tix it, you must
i ft 2309 as 23090. Adding the dcci nal point forces the
(olOpiler co treat the viluc as a dOUbIC

A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS 123

44 INITIALIZE VARIflA'c

EXERCISES

the C co III lnler that it til - jnt


• I 10 (11) y ou iefl
:i.iiit
should be re p resented as a float instead ot a double!
2. \V uc it pnogriin that reids and writes a long
mt value.
3. Write a programI that outputs I like C using three
separate strings.

,INITIALIZE VARIABLES
variable mahc.givcn anin I tial vaiLte when it is declared. 'Fins is
I '0) Oh;. i?tUilI:otlun J he general
torm of variable initialization
is sin c ' Iii) -

type ear -name = CWISIan!

I- OF (5ITiipl(' Eli is stateiiietit declares Count as an mt and gives it an


Ii titie of 100.

li p - nine aLlvitnrtg' usiiiO In tiltili/ation rather than a separate


Is s tic it 51.11 'Iii)' III is tltLI the toi til l itr iliac he able
to produce
I-st' ode. \lso , this .ivs sonic I:% ping etort \otir part.
\1ariables may he initiihzed using 0111: (;Iisnits. 1.oc
^ariablcs c., variables or EunC tmon calls
as long as each is valid at the time of the initialiiation, lb ,e''er . tiost
oltiti both udohal and local variables arc
ittitiali y.cd ttsitii unscliits
Global variables are trittiali-il onl y once, ;v the Stdrt o J)noranu
execution Local variables are initialized var' l l time if
is ell tered --
i
(;] () h ll variables that are not explicitl y initi. ii led it - iltotniti dlv
set to /en, Local variables
chat arc not itititliz-d h;lil he assumed
to 1 otitatit unkuiunvii values. Although
some C <iutiirs atLtotIijti:allv
mil i thi Iu)u.t.t?r/-11 c' i •iu'ithles to II , y o sitiuld not
count
on thu
124 TEACH YOURSELF
V

I. This program gives i the initial value of -1 and then the phys
its value.
#inciude <stdio.h>

jot main(void)

mt i = -1;

print fVi is initialized to %d', it;

return 0;

2. \\Iiiii VILE de(;Iarc it list of v. I I iihles, voll maY initiali ./ c 0111' or


more ot them. For csim j il. this iratnierut initializes will to II
and max to 100. It does nut initialize count.
mt rnin=Q, count, rnx100;

3. As stated earlier, local variables are initialized each tulic the


function is entered. For this reason, this program 1)1'iilts 10
three times.
4include <stdio.h>

void f (void)

mt. main(void)

f()
H)
H);

return 0;

void f(void)

j Ot i = 1C;

printf)"%d i);
A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS
125
4.4 INITIALIZE VARIABLES

4. A local variable can he initialized b y an y expression valid


at the time the variable is declared. For example consider
this pro-ram:
include <rtdio.h>

x =10; /* initialize global variable *1

i;t rryfunc(int it

mt main(void)

initialize a local variable using


a global variable */
mt y

1* initialize a local variable using another


local variable and a function call
mt. z = myfunc(y);

prmntf(%d %d, y,

return 0;

irit nyfunc(int it

return i/2;

The local variable y is initialized using the value of the global


variable x. Since x is initialized hehiire main( ) is called, it is
valid to use its value to initialize a local variable 'IIIe value of z
is initialized b y calling rnvtunc.( ) using v as an argument.
Since y has alread y been initialized it is entirel y proper to use it
as an argument to n'ftinc( ) at this PIflt

EXERCISES

)write a program that gives an iiiteg ' r varitHe called i an initial


value of 100 and thieii uses i to (outrol a for hoop that displ.iv.s
the flu mhc rs 100 down to I
126 flEACH YOU1F
'V

,t. Asstinie that this line o code declares global variables. Is


it corrcct.
mt b=2, C;

3. Ii the preceding declaration was for local variables, iciu1tl


it he cijri_ect?

I UNDERSTAND TYPE CONVERSIONS IN


EXPRESSIONS
hiihke tiuiiiiY other computer iiii , s, C lets vou lillY ditt('r('iit lylo
of data together in one expression. For exuiip1e, this is pet h' tiv vihtt
C code:

c:hir ch
inc
float
cD:re;

ID:

• :i /' f

C allows thr' nhixiiig 01 t y pes witluii .in isp resstan because ii has a

strict set (it conversion rules that cli:t:ite liciw Ii u' diltert'ii
resolved, Let's link closel y at ulu:in in this section.
One portion of C's (,onversioll rules is called i toll J,Ioieh:ni In C,
whenever a char or a short mt is used in an expression, its value is
atiwitiatitallv elevated to lilt uluriug the e aluatiun Of thiit i'xpi'ession
This is 'liv VM1 can use char v;iriahli's its"little iiitegers am where
V011 can use an j ilt variable. Keep in inirtd that the integral pt' )iliotioll
is oiilv in 'lii .t during the rv:iloatioii olaii espression. The variable
u's lwl )i'ioine ph y sicall y larger. (In essence, the coiiipiler 051 uses
a tern p r,iiy cop y of its value.)
Attiii t!tc automatic integral promotions have been applli'il ii.' C
1 iiiipilir will convert all oper:iiids up to toe t y pe of the largest

i'iprraucl This is called (if/.1 c ))IVI 1(010)1 and is C1011C oti <ii 0C1'Jti0ii-
A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS
127
4.5 UNDERSTAND TYPE CONVERSIONS IN EXPRESSIONS

b y -operation basis, as described in the following type-conversion


aloorithril.

IF an operand is a long double


THEN the second is converted to long double
ELSE IF an operand is a double
THEN the second is converted to double
ELSE IF an operand is a float
THEN the second is converted to float
ELSE IF an operand is an unsigned long
THEN the second is converted to unsigned long
ELSE IF an operand is long
THEN the second is converted to long
ELSE IF an operand is unsigned
THEN the second is converted to unsigned

I here is one additional special case: 11 one operand is long and the
ceiiei is unsigncd int, and if the value of the unsigned mt
cannot he
represented b y a long, both operands are converted to
unsigned long
Once these Conversion rules have lie/rn applied, each pair of
opeiands wil he of the same t y pe and the result of each operation will
as the type of both operands.

In this pro ant, i is cleated to ,i float during the evaluation of


the expression i • f. Thus, the prot am prints 2325
trnclude <SLdic.n

:nt main(vcjd)

mr .;
f1otr f;

i. = 10;
f = 23.25;

przt[("%f' j*f.

return 0;
TEACH YOURSELF
128
V

2 This program illustrates how short ints are automatically


promoted to ints. The printf( ) statement works correctly eve
though the %d modifier is used because i is automatically
elevated to mt when printf( ) is called.
#include <stdio.h>

mt main(void)

short: mt i;

printf(%d i);

return 0;

3 Even though the final outcome of an expression will he of the


largest type, the type conversion rules are applied on an
operation-by-operation basis. For example, in this expression
100.0/(10/31

the division of 10 by 3 produces an integer result, since both ar


integers. Then this value is elevated to 3.0 to divide 100.0.

EXERCISES

1. Given these variables,


char ch;
short
unsigned long ul;
float r;

c1iat is the o't;rall type of this expression:


f/ch -

vVhjt is the t y pe of the suhcxj)reSsiOn i'ul, above?


A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS
129
4.6 UNDERSTAND TYPE CONVERSIONS INASSIcNMENTS V

_UNDERSTAND TYPE CONVERSIONS IN


ASSIGNMENTS

in an asSigiirrlcflt statement in wliii:ii the type i) the right side difleis


from that of the left, the type of the right side is converted into cit
the left. When the type of the left side is larger than the t y pe of tin
right side, this process causes no problems. However, when III( , (v
of the left side is smaller than the t y pe of the right, data loss ?11i\
occur. For example, this program displays -24:
*include 'stdio.h>

int main(void)

char ch;
mt i;

I = 1000;
ch =

priritft'%d', ch);

return 0;

The reason for this is that only the ]ow-order eight bits of i are
copied into ch. Since this sort of assignment type conversion is not an
error in C, you will receive no error message. Remember, one reason
C was created was to replace assemhlj language, so it must allow all
sorts of type conversions. For example, in some instances YOU may
only want the low-order eight bits of i, and this sort of assignment is an
easy way to obtain them.
When there is an integer-to-character or a longer-integer to
shorter-integer type conversion across an assignment, the basic rule is
that the appropriate number of high-order bits will be removed. For
example, in many environments, this means 8 bits will he lost when
going from an mt to a char, and 16 hits will be lost when going from a
long to an mt.
When converting from a long double to a double or from ;I
to a float, preGision is lost. When converting from a floating-point

9
130 TEACH YOURSELF
C

vahie tO aTI integer value, the fractional part is lost, and if the number
is too large to fit in the target t y pe, a garbage value will result.
Remember two important points: First, the conversion of an mt to a
float or a float to double, and so on, will 1101 add any precision or
i('L:tiracv. ['hese kinds of conversions will only change the form in
which the value is represented. Second, some C compilers will always
treat a char variable as an unsigned value. Others will treat it as a
signed value. Thus, what will happen when a character variable holds
a value greater than 127 is i mplenientation-dcpcndent. If ' this is
important in a program that von 'r;te, it is best to declare the variable
(xplicitly as either signed or unsigned.

I EXAMPLES
A:-: stated, when converting from a floating-point value to an
i i:tger value, the fractional portion of the number is lost. The
h llowing program illustrates this fact. It prints 1234.0098 1234
4linc:Lude <stdio.h>

j Ot main(void)

mt 1;
tloat

= 1234.0098:
r f; / convert to ml
printf('%f %d". f, 1);

return 0;

2. When converting from a larger integer type to a smaller one, it


is possible to generate a garbage value, as this program
iliListrates. (This program assumes that short integers are 16 bits
10 ,4 and that long integers are 32 bits long.)

#include <stdio.h>

rut main(void)

stiort. inC Si
'long mt H:
A CLOSER 1.0(1K AT DATA TYPES. VARIABLES. AND EXPRESSIONS 131
4.6 UNDERSTAND TYPE CON VERSIONS INASSIGNMENTS

ii = 100000;
S i = ii; / I convert to short ml- *

print 1 { (,, Si);

return 0;

Since the largest value that a short integer can hold is 32767, it
cannot hold 100,000. What the compiler does, however, is copy
the lower-order 16 bits otli into si. This produces the
meaningless value of —31072 on the screen.

EXERCISES

1. What will this program display?


tinclude <stdio.h>

mt main(void)

mt i;
long double id;

id = 10.0;
f = id;

printf("%d. I);

2. What does this program display?


Jinclude <stdio.h>
mt main(void)

float f;
f 10 / I;
printf("%f", f)

return 0;
132 TEACH YOURSELF

ROGRAM WITH1 TYPE CASTS

Sciietimcs you may want to transform the type of a variable


tcinpoiarily. For example, you may want to use a floating-point value
for mic computation but wish to apply the modulus operator to it
c]sewll(re. Since the rnddulus operator can only be used on integer
vil ties, you have a problem. One solution is to create an integer
vi riable for use in the modulus operation and assign the value of the
flcititig-point variable to it when the time comes. This is a somewhat
ii I(lcga nt solution, however. The other way around this problem is to
use a 11pe cis(, which causes a temporary type change.
A type cast takes this general form:

(type) value
where njpc is the name of valid C data type. For example,
L1o,L i; -

f 100,2;

/ print f as an integer
priritf("%d, (int) f);

I lere, the type cast causes the value of f to he converted to an mt.

As you learned in Chapter 1, qrt( ), one of C's library


functions returns the square root of its argument. It USeS the
MATHJ1 header file. Its single argument must he of type
double, It also retilirns a double value. The following program
priits the square roots of the numbers between I and 100 using
a for loop. It also prints the whole number portion and the
tractional part of each result separately. To do so, it uses a type
cast to convert sqrt( )'s return value into all

A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS 133


4 7 PROGRAM WOO TYP! CASTS

include <stdio.h'
#incliide math.h>

mt main(void)

double 1.;

fct(i=1.0; 1<101.0; i++)


print", T;e square root of %lf i' I1 f\n" i
printf Thole number part: %d ', (int)sqrt ()
printf "Fractional part: %lf\n' sqr t C i ) - nt ) I

printf("\n')

return 0;

2. YOU cannot cast a variable that is on the left side ;Ili


itssignrncflt statenicrit. For example t1iis is an oval 1(1
5tat(!1iCt1t Iii C:
irlt nurn;

(float) rtum = 123.23; / this is incorrect /

EXERCISES
1. Write a program that uses for to irint thc nil flhl)crs I to 10 by
tenths. Use a floating-point variable to control the loop.
However, use a t y pe cast so that thc conditional expression is
evaluated as an integer expression in hc intcrcst ol spccd.
2. Since a floating point value cannot be used with the % opet ittor,
how can YOU fix this statement?
x = 123.23 % 3; / fix this statement /
134 TEACH YOURSELF
V

Mas ery

At this point you should be able to answer these (UcStI()flS and


perform these exercises:

• What are C's data-type mod i tiers and what function d o


they perform?
Z. I low do y ou explicitly dchnc an unsigned constant, a long
constant, and a long double constant?
t. Show how to give a float variable called balance an initial value
of 0.0.
h. What are Cs automatic integral prOI11OtiOfls

S. What is the difference between a signed and an unsigned


integer?
(. Gi veone reason why you might want to use a global variable in
your program.
7. Write a program that contains a function called series( ). Have
this Function generate a series of numbers, based upon this
formula:

next-number = 1previousnumber* 1468) % 467


Give the number an initial value of 21. Use a global variable to
hold the last value between function calls. In main( )
demonstrate that the function works by calling it ten times and
displaying the result.
t. What is a type cast? Give an example.
A CLOSER LOOK AT DATA TYPES, VARIABLES, AND EXPRESSIONS 135
4 7 PROGRAM WITH TWI CASTS

umuiative
j.skmscheck

This section checks how well you luve integrated the inaterlill ill
this chapter with that from earlier eliapters.

I As you know from Chapter 't, no two cases with the s:iflo:
switch may USC the same value. Thercibre is this switch
vii id
or invalid? Why? (1-Hut: the ASCII code fbr A' is 65.
switch (x)
case 'A printf("is an A)
break;
case 65 printf ("is the number 65'
break;

and geuhc( )
2. Technically, for traditional reasons the getchar( )
functions arc declared as retLirnilig integers, not character
values. However, the character read from the ke yboard is
'
contained in the low-order byte. Cqn you explain wh y this iiiu:
can be assigned to char variableS.'
3. In this fragment, will the 1001) ever terminate:' Wh y ? (
Asslillo

i ntegers are lb bits long.)


mt i
Eor(i=0; 1<33000; i++)

You might also like