Chapter 1 - 4
Chapter 1 - 4
Chapter 1 - 4
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
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
statement sequence
*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.
int main(void)
return 0;
6 TEACH YIMJRSELF
mt main (void)
printfY' This is );
printf("another C •');
prinet ( progrant. ')
return 0;
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
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.
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
/ 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;
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;
For example, to assign an integer variable named num the value 100,
you can use this statement:
- nun = 100;
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.
cl:de oh>
i-t main(void)
mt num;
riuin = 100;
printf("The value is %d num);
return 0;
The statement
mt nuin;
mt main(void)
char ch;
float f;
double d;
ch =
f = 100.123;
d = 123.009;
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
t main(void)
) mt nun;
/ float f;
printf(Enter an integer:
scanf("%d", &num);
printf("%d •, nun);
prmntf(*%f, f);
return 0;
C FUNDAMENTALS 17
5 PERFORM CAL CULA flOWS USING ARITHMETIC EXPRESSIONS'
F.XERCISES
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
answer;
arwer = 100 * 31;
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:
mt main(void)
printf("%d". 5/2);
printf(' %d, 5%2);
printf(' %d', 4/2);
printf (" %d", 4%2);
return 0;
1: min(void)
mt Ion, width;
priritf("Enter length:
Scant C "%d" ,
print.f("Enrer wath:
scanf("%d", &wi;It)-;);
return 0;
jet rn1flCV3td)
let
return 0;
EXERCISES
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:
/
This prograsn converts Earth days into Jovian years.
iincudc <stdio.h>
tnt main(void)
return 0;
EXERCISES
: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:
mt main(void)
I. .. 'I
I. ...
I.
ret-type IN(param-list)
I. .. •1
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.
include <stdio.h>
Int main(void)
pri.ritf("I
fund 1 C
prntf("C.");
return 0;
void ftnc1vo:d
prntfCiike
#include <stdio.h'
jOt main(void)
func2 ()
print
return 0;
funvi. (1
printL(.
void funcl(vo_d)
pr jot f ( 1 . ")
EXERCES
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
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
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
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.
mt 11 (void)
mt main (void),
double answer;
answer = fl();
prirtf%f", answer);
return 0
TEACH YOURSELF
32
C
mt f (void
return 100;
void func(void)
mt 1;
printfVEr.ter a number:
scanf &i)
return i;
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>
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
mt main(void)
outchart 'A');
outchar( 'B');
outchar( 'C');
return 0;
printf('%c ch);
C FUNDAMENTALS 35
7.10 REMEMBER THE C KE'WORDS
EXERCISES
mt main(void)
sqr_it(10.0)
return 0;
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
es
asm cs As
ss cdecl far huge
interrupt near pascal
Mastery
Skills Check
chapter obIeclivea
2.1 Become familiar with the if
2.2 Add the else
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
if(expression) statement;
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.
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;
return 0;
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;
mt main(void)
float num;
mt choice;
return 0;
EXERCISES
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);
return 0;
mt main(void)
mt nuinl, num2;
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
BLOCKS OF CODE
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.");
mt main(void)
float num;
mt 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;
mt main(void)
mt answer;
printf("What is 10 + 14? );
scarif(*%d, &answer);
return 0
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. -
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>
jflt nurn:
return 0;
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;
pri.ntf ( "terminating');
return 0;
mt main (void)
sum = 0;
prod = 1;
return 0;
mt 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;
return 0;
*include <stdio.h>
mt main(void)
mt flUm, I prime;
is—prime = 1;
for(i=2; i<=num/2; i=j+l)
If((nurn%i)==O) is prime 0;
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
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++)
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;
#iriclude <stdio.h>
mt main(void
mt I, j;
I = 10;
j =
56 TEACH YOURSELF
V
return 0;
mt answer, count;
return 0;
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;
return 0;
ii
EXERCiSES
mt main (void)
mt a, b;
a = 1;
a = a + 1;
b a;
b = b - 1; S
return 0;
58 TEACH Y
\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)
mt main(void)
return 0;
iisplays
mt main(void)
printf ("\a")
60 TEACH YOURSELF
V
return 0;
mt main(void)
return 0;
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
Action
Greater than
Greater than or equal
Less than
Less than or equal
Equal
IM Not equal
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
c\4ator
&& AND
II OR
NOT
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.');
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
int main(void)
mt i, 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;
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)
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
Maste
Skills check
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
.4
.,: Review
Skills Check
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;
return 0;
, 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.
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;
irit main(void)
tnt a, b;
char ch;
return 0;
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
i f (P)
f kit p t in f( "a and h are ttue"
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;
return 0;
mt main(void)
78 TEACH YOURSELF
V
mt again;
1* nested if /
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);
mt main(void)
mt i;
char ch;
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);
return 0;
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;
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.
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;
mt main(void)
char ch;
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.
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:
return 0;
mt rnain{voi.1
char ch;
do
ch = getcheU;
whi1e(chq');
return O
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.)
1. Enter addresses
2. Delete address
5. Quit
Enter the number of your choice (1-5).
MORE C PROGRAM CONTROL STATEMENTS 87
36 CREATE NESTED WQPS
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")
mt main (void)
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;
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.
mt main(void)
mt i;
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
mt main(void)
mt i;
char ch;
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;
printf("\n')
MORE C PROGRAM CONTROl. STATEMENTS
91
37 USEIweikTOEYJTALOOP
return 0;
if(ch = {
/* do something *1
if(ch != 'Q')
7* do something else*/
/ etc.
while(ch SQ')
/ do something /
/ do something else *7
/* etc. /
92 TEACH YOURSELF
V
EXERCISES
mt main(void)
mt x;
return 0;
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);
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++)
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;
jot main(void)
mt 1;
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:
mt main (void)
mt a, b;
char ch;
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
mt main(void)
cilol Cn:
tu t
prinrf('\nEnter a character, q to quit:
cli = getche()
printf ("\n")
} 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
mt main(void)
char ch;
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
switchtf> {
case 10.05:
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
jni rnain(vcid)
int. i;
i = 1;
again
printf (%d it
i +;
if(i<10) cjOto again;
return 0;
EXERCISES
maste
Skills Check
uh=
for( ; ch ! ; ) ch = getche()
ill dor
This Se(tioIi checks how well you have integrated the material in
this chapter with that front chapters.
itit Ifll1fl(VClIC1)
mt m, j, k,
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
105
V
106 TfACH YOLIRSEL F
V
R eview
k^l I sCb!
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
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
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
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;
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;
tetuxj) 0;
Vincludc' <stdio.h>
101 inain(void)
u 33000;
return 0;
mt main(void)
iflt i;
char j;
I=
for(j=1; j<101; j++) j +'j;
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;
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;
void f2(void)
j ilt 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>
j ilt 1;
= 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(,'
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)
jot r:i.i:o)vc.id)
max = 10;
fi()
return 0;
void ti(void)
mt i;
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)
jot main(void)
count = 10;
fl();
0 rintf("cour,t in nainU : d\o" 000:IL(
r.turn 0;
void ii (void)
count 100;
printf("cOur.r in Fl)) ; %dn', count);
1 16 TEACH YOURSELF
V
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;
return 0;
! Mon-general vorsto:;
mt power(void)
tern;-) = I
ternp2 e;
for( ternp.O; tesp2--) temp - temp *
rI;. n:l(VOIC)
1111. rt, 0;
return 0;
icr temp;
1.;
fc: ; e> 0; e- - I tdrrp = t€:rp *
terrr.;
1 18 TEACH YOURSELF
V
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;
return
1* This is incorrect.
mt seLi:3(vo;:
j ut total;
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).
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
ch = '7,'
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 •
inc mair.(vojd)
return 0;
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
I-
44 INITIALIZE VARIflA'c
EXERCISES
,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) -
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;
return 0;
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
i;t rryfunc(int it
mt main(void)
prmntf(%d %d, y,
return 0;
irit nyfunc(int it
return i/2;
EXERCISES
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
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.
:nt main(vcjd)
mr .;
f1otr f;
i. = 10;
f = 23.25;
przt[("%f' j*f.
return 0;
TEACH YOURSELF
128
V
mt main(void)
short: mt i;
printf(%d i);
return 0;
EXERCISES
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;
#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- *
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
mt main(void)
mt i;
long double id;
id = 10.0;
f = id;
printf("%d. I);
float f;
f 10 / I;
printf("%f", f)
return 0;
132 TEACH YOURSELF
(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);
include <stdio.h'
#incliide math.h>
mt main(void)
double 1.;
printf("\n')
return 0;
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
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