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

GJUHA C

C was once the most popular programming language, essential for programming across various systems, but its usage has declined in favor of languages like C++ and Java. Despite this, mastering C is crucial as it serves as a foundation for understanding many modern programming languages and enhances career prospects. The document outlines C's history, its unique characteristics, and the programming process, emphasizing the importance of planning and understanding the compile process for effective programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

GJUHA C

C was once the most popular programming language, essential for programming across various systems, but its usage has declined in favor of languages like C++ and Java. Despite this, mastering C is crucial as it serves as a foundation for understanding many modern programming languages and enhances career prospects. The document outlines C's history, its unique characteristics, and the programming process, emphasizing the importance of planning and understanding the compile process for effective programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 62

GJUHA C

C Is Fundamental

Just a few years ago, C was the most popular programming language being used. Programmers
wrote C code for PCs, mainframes, and supercomputers. C was standardized so that the same
program would run on every kind of computer using every kind of operating system available.

Today, the use of C has dramatically decreased. Rarely will a project be written in C.
Programmers are using languages such as C++ and Java to create applications that run on
standalone, networked, and Internet-based machines. Yet, when learning to program, C is
considered to be the one language it is imperative a programmer master before moving on to the
other languages in use today.

TIP
Due to the Internet's phenomenal growth, new languages are appearing to
handle the different challenges that Internet-based processing requires.
Companies looking for programmers in these newer, and sometimes obscure,
languages often advertise for C programming skills. The companies know that
someone well-versed in C can pick up these offshoot languages rapidly.
Therefore, learning C will boost your career potential even if you are never
hired to write C-based code.

The reason for C's recommended mastery, despite its low levels of actual use, is that C is the
common denominator of many of today's languages; learn C and these languages will be simple
to learn. Languages such as C++ and Java are based on C. In fact, many of the statements and
commands in these newer languages are identical to the ones found in C. Overall, C is much
simpler to learn than these languages because it carries with it a much slimmer toolkit of add-on
procedures.

CAUTION
When some people attempt to learn C, even if they are programmers in other
languages, they find that C can be cryptic and difficult to understand. This does
not have to be the case. When you are taught to write clear and concise C code,
in an order that builds on fundamental programming concepts, C is no more
difficult to learn or use than any other programming language.

The History of
C
Before you jump into C, you might find it helpful to know a little about the evolution of the C
programming language. Bell Labs first developed this language in the early 1970s, primarily so
that Bell programmers could write their UNIX operating system for a new DEC (Digital
Equipment Corporation) computer. Bell Labs designed UNIX to run efficiently on small
equipment, and it was the first operating system to be written entirely in a high-level
programming language. Until that time, operating systems were

written in assembly language, the computer's low-level, hardware-based language that is tedious,
time-consuming, and difficult to change. The Bell Labs designers knew they needed a higher-
level programming language to implement their project quicker and make its code easier to
maintain.

Because other high-level languages at the time (COBOL, FORTRAN, PL/I, and Algol) were too
slow to use for an operating system's code, the Bell Labs programmers decided to write their
own language. They based their new language on Algol and BCPL, two high-level but efficient
languages used throughout the European markets, but rarely in America. BCPL strongly
influenced C, although BCPL did not offer the various data types that the makers of C required.
After a few versions, these Bell programmers developed a language that met their goals very
well. C is efficient (it is sometimes called a high low-level language due to its speed of
execution) and flexible, and contains the proper constructs enabling it to be maintained over
time.

How C
Differs

If you have programmed before, you should understand a little about how C differs from other
programming languages on the market. (Today's new C-based languages, such as Java, also
contain many of C's nuances.) Besides being a very efficient language, C is known also as a
weakly typed language; that is, the data types you assign to variables do not necessarily require
that same type of data. (Proper coding techniques learned in this book, however, will help to
eliminate this problem.) If you declare a numeric variable, and then decide to put a letter into it,
C enables you to do this. The data may not be in the format you expect, but C does its best. This
is much different than stronger-typed languages such as COBOL and Pascal. These languages
require rigid conformity to consistent data types; you cannot store, for example, a character in a
numeric storage location. Although you can get into trouble a little more easily, C enables you to
view the same data in different ways.
C's weakly typed nature places much more responsibility on the programmer. C is an extremely
flexible language—particularly if it is to be used to write operating systems. At any one time, an
operating system does not know what is coming down the line. If, for example, an operating
system expects a number but instead receives a letter, the language used must be flexible enough
to handle this different data without aborting.

NOTE
C's philosophy is this: Trust the programmers—they must know what they're
doing!

The added responsibility of the weakly typed, flexible C language adds to the programmer's
burden of being careful while programming. Although the

programmer has more freedom with data storage, the languages do not check data type accuracy
for the programmer. The trade-off is worth it, however. The designers of C did not want to
hamper C programmers by adding lots of strict rules to the language.

C is a small, block-structured programming language. C has fewer than 40 keywords. To make


up for its small vocabulary, C has one of the largest assortments of operators, such as those
used for calculations and data comparisons. (The C-based languages have more operators than
virtually every other language in existence, second only to APL.) The large number of operators
in C could tempt programmers to write cryptic programs that do a lot with a small amount of
code. As you learn throughout this book, however, making the program more readable is more
important than squeezing out bytes. This book teaches you how to use the C operators to their
fullest extent, while maintaining readable programs.

C's large number of operators (more than the number of keywords) requires a more judicious
use of an operator precedence table that states the order in which C processes multiple
operators inside a single statement.

• Appendix B, ''C's Precedence Table," page 476, contains C's operator


precedence table that you can refer to as you learn C.
Unlike most other languages that have only four or five levels of precedence, C has 15. As you
learn C, you need to master each of these 15 levels. The precedence table is not as difficult as it
sounds, but its importance cannot be overstated.

C also has no input or output statements. (You might want to read that sentence again!) C has no
commands that perform input or output. This is one of the most important reasons why C and C-
based languages are available on so many different computers. The I/O (input and output)
statements of most languages tie those languages to specific hardware. QBasic, for instance, has
almost 20 I/O commands—some of which write to the screen, to the printer, to a modem, and so
on. If you write a QBasic program for a microcomputer, chances are sky-high that the program
cannot run on a mainframe.

C's input and output is performed through the abundant use of function calls. With every C
compiler comes a library of standard I/O functions that your program calls to perform input and
output. These standard routines are hardware independent, because they work on any device
and on any computer that conforms to the ANSI C standard (as most do).

To master C completely, you need to be more aware of your computer's hardware than most
other languages require you to be. You certainly do not have to be a hardware expert, but
understanding the internal data

representation makes C much more usable and meaningful. You also should eventually become
familiar with binary and hexadecimal numbers. If you do not want to learn these topics, you can
still become a very good C programmer, but knowing what goes on ''under the hood" will make
C more meaningful to you.

• Appendix A, "Memory Addressing, Binary, and Hexadecimal," page 460,


contains a tutorial on these topics before you start to learn the C language.

The C Programming Process


To give C programming instructions to your computer, you need an editor and a C compiler. An
editor is similar to a word processor; it is a program that enables you to type a C program into
memory, make changes (such as moving, copying, inserting, and deleting text), and save the
program more permanently in a disk file. After you use the editor to type the program, you must
compile it before you can run it. The compiler takes the C instructions you write and converts
those instructions to code the computer can understand.

Many of today's compilers come with their own built-in editor, as well as a debugger to help
locate and correct errors (called bugs) that creep into most people's programs at one time or
another during the writing stage. Unless the only language in your background is an interactive
language such as QBasic, or a macro language such as those found in major software
applications such as Microsoft Office, it is most likely that you've used a debugger. Only after
compiling the C program that you write can your computer run the program and show the
results from that program.

NOTE
Actually, you might have a difficult time even locating a C compiler today.
Generally, C is included with C++ compilers since C++ is based on C and uses
a technique called object-oriented programming, OOP, in which data values
perform actions that the programmer gives them. Therefore, a compiler such as
Visual C++ or Borland C++ will recognize your C code once you've set the
proper options to inform the compiler that you are writing C programs.

CAUTION
Today's compilers are often Windows-based. UNIX computers also run
windowing environments. To write and execute a C program, you'll have to run
the program in a text window. Otherwise, you have to not only learn C, but also
programming for the graphical user interface, such as Windows, as well—which
is quite a feat. This book teaches C in a text-based environment so that you can
concentrate on learning the language and all its nuances. However, where you
apply that knowledge is often in a windows environment—after you learn the
proper techniques for programming in a windowed environment.

While you are programming, remember the difference between a program and its output. Your
program contains only the C instructions that you write. But the computer follows your
instructions only after you run the program. Throughout this book's examples, you will often see
a program listing (that is, the C instructions in the program) followed by the results that occur
when you run the program. The results are the output of the program, and they go to an output
device such as the screen, the printer, or a disk file.

All C programs use the .C filename extension. One way that C++ compilers know that you are
compiling a C program is the .C filename extension as opposed to the .CPPextension C++
programs require.

Proper Program
Design

You must plan your programs before typing them into your C editor. When builders construct
houses, for example, they don't immediately grab their lumber and tools and start building. They
first find out what the owner of the house wants, draw up the plans, order the materials, gather
the workers, and then they start building the house.

Exampl
e

The hardest part of writing a program is breaking the problem into logical steps that the
computer can follow. Learning C is a requirement, but C is not the only thing you should
consider. There is a method of writing programs—a formal procedure you should learn—that
makes your programming job easier. To write a program you should

1. Define the problem to be solved with the computer.

2. Design the program's output (what the user should see).


3. Break the problem into logical steps to achieve this output, including determining the input
required by the program. Often, the input comes from a user at the keyboard or from a data file.

4. Write the program (using the editor).

5. Compile the program.

6. Test the program to make sure it performs as you


expect.

As you can see from this procedure, the typing of your program occurs toward the end of your
programming. This is important, because you first need to plan how to tell the computer how to
perform each task. Designing the program in advance makes the entire program structure more
accurate, and helps to keep you from having to make many changes later. A builder, for
example, knows that a room is much harder to add after the house is built. So, if you do not
properly plan every step, it is going to take you

longer to create the final, working program. It is always more difficult to make major changes
after your program is written.

Planning and developing according to these six steps becomes much more important as you
write longer and more complicated programs. Throughout this book, you learn helpful tips for
program design. But now it's time to launch into C, so you can experience typing in your own
program and then seeing it run.

NOTE
This book teaches the ANSI C standard programming language, programs that
adhere to the standard C programming language adopted by the American
National Standards Institute (ANSI), and makes no attempt to tie in specific
editor or compiler commands— there are too many on the market to cover them
all in one book. As long as you write ANSI C-specific programs, the tools you
use to edit, compile, and run those programs are secondary. Your goal of good
programming is the result of whatever applications you produce, not the tools
you use to do it.
The Compile
Process

After you type and edit your C program's source code, you must compile the program. The
process you use to compile your program depends on the version of C and the computer you are
using.

NOTE
Each program in this book contains a comment that specifies a recommended
filename for the source program. You do not have to follow the file-naming
conventions used in this book; the filenames are only suggestions. If you use a
mainframe, you need to follow the dataset-naming conventions set up by your
system administrator.

Unlike many other programming languages, your C program must be routed through a
preprocessor before it is compiled. C source code can contain preprocessor directives that
control the way your programs compile.

You may have to refer to your compiler's reference manuals or to your company's system
personnel to learn how to compile programs for your programming environment. Again,
learning the programming environment is not as critical as learning the C language. The
compiler is just a way to transform your program from a source code file to an executable file.

Your program must go through one additional stage after compiling and before running. It is
called the linking, or the link editing, stage. When your program is linked, the compiler sends
runtime information to your program such as the memory addresses where variables and code
will be stored when your program executes. You can also combine several compiled programs
into one executable program by linking them. Most of the time, however, your compiler initiates
the link editing stage and you do not have to worry about controlling the linking process.

Figure 1.1 shows the steps that your C compiler and link editor perform to produce an
executable program. Again, many of today's C compiling systems perform most of these steps
behind your back so you can be left concentrating on the source code.
Figure 1.1:
Compiling C source code into an executable
program.

Running a
Program

One of the most important tasks you can perform now is to start your C compiler, enter a
program, and see the results. This may or may not be a trivial task depending on your compiler.
Some Windows-based compilers are loaded with so many features that doing something simple,
such as compiling a small, text-based C program, might require a study of the documentation
until you locate the options necessary to compile and view the executable results of a source
program that ends with the .C extension.

NOTE
Be sure to install your compiler and familiarize yourself with your compiler's
editor. Entering a program should be relatively simple because an editor works
like a simple word processor for programs that you enter.
Exampl
e

Starting with Chapter 2, ''Analyzing C Programs," you should put all your concentration into the
C programming language and not worry about using a specific editor or compiling environment.
Therefore, start your editor of choice and type the program in Listing 1.1 into your computer.
Be as accurate as possible—a single typing mistake could cause the C compiler to

generate a series of errors. You do not have to understand the program's content at this point; the
goal is simply to give you practice in using your editor and compiler.

Listing 1.1: This C program is simple to give you practice with your C compiler.

/* Filename: C1FIRST.C
Requests a name, prints the name 5 times, and rings a bell */

#include <stdio.h>
#define BELL '\a'

main()
{
int ctr=0; /* Integer variable to count through loop */
char fname[20]; /* Define character array to hold name */

printf(''What is your first name? "); /* Prompt the user */


scanf(" %s", fname); /* Get the name from the keyboard */
while (ctr < 5) /* Loop to print the name */
{ /* exactly 5 times */
printf("%s\n", fname);
ctr++;
}
printf("%c", BELL); /* Ring the terminal's bell */
return 0;
}
Again, be as accurate as possible. In most programming languages—and especially in C—the
characters you type in a program must be accurate. In this sample C program, for instance, you
see parentheses, (), brackets, [], and braces, {}, but you cannot use them interchangeably.

The comments (words between the two symbols, /* and */) to the right of some lines do not
need to end in the same alignments that you see in the listing. However, you should familiarize
yourself with your editor and learn to space characters accurately so you can type this program
exactly as shown.

Compile the program and execute it. Granted, the first time you do this you might have to check
your reference manuals or contact someone who already knows your C compiler. But do not
worry about damaging your computer: Nothing you do from the keyboard can harm the physical

computer. The worst thing that may happen is your computer will freeze and you'll have to
reboot and restart your C compiler.

Outpu
t

The program from Listing 1.1 asks the user for his or her first name, prints the entered name five
times, and beeps the computer's speaker. Here is a sample execution of the program:

What is your first name? Terry

Terry
Terry
Terry
Terry
Terry
<Beep>

Handling Errors

Because you are typing instructions for a machine, you must be very accurate. If you misspell a
word, leave out a quotation mark, or make another mistake, your C compiler informs you with
an error message. The most common error is a syntax error, and this usually implies a
misspelled word.

When you get an error message (or more than one), you must return to the program editor and
correct the error. If you don't understand the error, you may have to check your reference manual
or scour your program's source code until you find the offending problem. Often, a built-in
debugger helps you locate and correct errors.

After you have typed your program correctly using the editor (and you get no compile errors),
the program should run properly by asking for your first name, and then printing it five times on
the screen. After it prints your name for the fifth time, you hear the computer's bell ring.

GETTING THE BUGS OUT


One of the first computers, owned by the military, refused to print some
important data one day. After its programmers tried for many hours to find the
problem in the program, a programmer by the name of Grace Hopper decided to
check out the printer.

She found a small moth lodged between two important wires. When she
removed the moth, the printer started working perfectly (although the moth did
not have the same luck).

Grace Hopper is now a retired admiral from the Navy and, although she is
responsible for developing many important computer concepts (she was the
author of the original COBOL language), she may be best known for
discovering the first computer bug.

Chapter 2—
Analyzing C
Programs

Once you complete this chapter, you'll better understand just why a C program looks the way it
does. A C program is rather cryptic until you familiarize yourself with its structure, even if you
understand other programming languages. C's heavy reliance on special characters, as opposed
to a heavy use of commands, makes C programs rather mysterious to newcomers.

This chapter teaches you the following:

• The fundamentals of C program structures

• The two kinds of C comments

• Variable and constant locations

• Simple math operators

• Textual screen output format

Studying a
Program
Figure 2.1 shows a high-level look at a C program. The figure contains no commands or
variables; instead, the figure illustrates the simple, general structure to which all C programs
adhere. Although there is much more to a C program than Figure 2.1 implies, the figure is a
great place to begin studying the examples that appear in the rest of this book.

Figure 2.1:
Begin analyzing C programs with this general outline.

TIP
As you progress through this book, remember that many other languages, such
as Java and Visual J++, are based on C. The structure of these other programs
often mimics that of C programs, so you're gaining valuable insight into more
than just C.

Exampl
e

To get acquainted with C programs as quickly as possible, you should look at a C program in its
entirety. Listing 2.1 contains a program for your study. The program is simple so you can start
easy. Although the program does not do a lot, it enables you to see the general nature of C
programming. The next few sections discuss elements from this and other programs. You may
not understand everything in this program, even after finishing this chapter, but the program is a
good place to start.

Listing 2.1: A simple C program gives you general insight into the nature of the C language.

/* Filename: C2FIRST.C
Initial C program that demonstrates the C comments
and shows a few variables and their declarations */
#include <stdio.h>

main()
{
int i, j; /* These 3 lines declare 4 variables */
char c;
float x;

continue
s

i = 4; /* i and j are assigned integer values */


j = i + 7;
c = 'A'; /* All character constants are
enclosed in single quotes */
x = 9.087; /* x requires a floating-point value since it
was declared as a floating-point variable */
x = x * 4.5; /* Change what was in x with a formula */

/* Sends the values of the variables to the screen */


printf(''%d %d %c %f", i, j, c, x);

return 0; /* End programs and functions with return */


}
Outpu
t

The output of this program is minimal—it simply displays four values on the screen after
performing some assignments and calculations of values, as shown here:

4 11 A 40.891499

Just concentrate on the general format at this point. Begin to familiarize yourself with the
structure of C program code. See whether or not you can understand part of all of the program in
Listing 2.1. Since you are not completely new to programming, you already know that the
computer looks at each line of the program, starting with the first line, and work its way down
until the computer has carried out all the instructions in the program. (Of course, the computer
does nothing with this code until you issue the command to compile, link, and execute the
program as the previous chapter described.)

• Chapter 1, "What C Is All About," page 4, describes the complete compile


process.

The Format of a C Program

You can include as much white space (separating lines and spaces) in your C programs as you
wish. The more readable your program is, the easier your program is to maintain when you have
to change the program. Insert as many blank lines in your programs as you wish. Blank lines
help separate the sections of the program from each other.
The sample program shown in Listing 2.1 is called C2FIRST.C (you'll find the name of each
program in this book in the first line of each program listing). C2FIRST.C contains several
blank lines to help separate parts of the program from each other. In a simple program such as
C2FIRST.C, this separation is not as critical as it might be in a longer and more complex
program.

Exampl
e

Your goal should not be to make your programs as compact as possible. Your goal should be to
make your programs as readable as possible. For example, the C2FIRST.C program shown in
Listing 2.1 could be rewritten as in Listing 2.2 with the same executable results but with
dramatically more difficult maintenance headaches.

Listing 2.2: By eliminating extra space, you greatly reduce a program's readability.

/* Filename: C2FIRST.C Initial C program that


demonstrates the C comments and shows a few variables
and their declarations */
#include <stdio.h>
main() {int i,j;/* These 3 lines declare 4 variables */
char c;float x;i=4;/* i and j are assigned integer values */
j=i+7;c='A';/* All character constants are enclosed in
single quotes */x=9.087;/* x requires a floating-point
value since it was declared as a floating-point variable */x=
x*4.5;/*Change what was in x with a formula */ /* Sends the values of the
variables to the screen */printf(''%d %d %c %f",i,j,c,x);return 0;/* End prog
rams
and functions this way*/}

To your C compiler, the two programs are exactly the same, and they produce exactly the same
result. However, to people who have to read the program, the first style is much more readable.
Granted, Listing 2.2's compressed version is an extreme example of a program lacking in white
space and readability.

Readability Is the
Key

As long as programs do their job and produce correct output, who cares how well they are
written? Even in today's world of fast computers and abundant memory and disk space, you, the
programmer, should still care. Even if nobody else ever looks at your C program, you might
need to make a change at a later date. The more readable you make your program, the faster you
can find what needs changing, and then make your changes.

If you work as a programmer for a company, you can almost certainly expect to modify
someone else's source code—and others can certainly

modify yours. In programming departments, it is said that long-term employees write readable
programs. Given this new global economy and all the changes that will face business in the
years ahead, companies are seeking programmers who write for the future, that is, people whose
programs are straightforward, readable, full of white space, and devoid of hard-toread ''tricks"
that make for messy programs.

TIP
You can break a line just about anywhere except between a quoted phrase. To
continue a quoted phrase on the next line (to keep a single statement from
becoming too lengthy), end the first line with a backslash, like this:

printf("This is a very, very, \


very, very, very long line.");

Use lots of white space so you can have separate lines and spaces throughout your programs.
Notice that the first few lines of C2FIRST.C start in the first column, but the body of the
program is indented from the left. This indention helps programmers "zero in" on the important
code. When you write programs that contain several sections (called blocks), your use of white
space helps the reader's eye drop down to, and recognize, the next indented block.
Uppercase Versus
Lowercase

Your uppercase and lowercase letters are much more significant in C than in most other
programming languages. You can see that most of C2FIRST.C is lowercase. The entire C
language is in lowercase. For example, you must type the keywords int, char, and return
into programs using lowercase characters. If you use uppercase letters, your C compiler
produces many errors and refuses to compile the program until you correct the errors. Not one C
command uses uppercase letters.

CAUTION
Turn off that Caps Lock key while programming in C!

Many C programmers reserve uppercase characters for some words and messages sent to the
screen, printer, or disk file; they use lowercase letters for almost everything else. There is,
however, one exception to this rule that you will read about in Chapter 5, "Preprocessor
Directives." This exception is the #define preprocessor directive, a statement that modifies
your actual source code before the C compiler turns your program into an executable format.

Braces and
mainx()

All C programs require the following lines:

main()
{

The statements that follow main() are the first statements executed. The section of a C
program that begins with main(), followed by an opening brace ({) is called the main
function. A C program is actually a collection of functions (small sections of code). The
function called main() is always required and always the first function executed.
In the sample program, almost the entire program is main() because the matching closing
brace that follows main()'s opening brace is at the end of the program. Everything between
two matching braces is called a block. You read more about blocks later. For now, you only
need to realize that this sample program contains just one function, main(), and the entire
function is a single block because there is only one pair of braces.

All executable C statements must have a semicolon (;) after them so C knows where the
statements end. Because the computer ignores all comments, do not put semicolons after your
comments. Notice that the lines containing main() and braces do not end with semicolons
either, because these lines simply define the beginning and ending of the function and do not
execute.

As you become better acquainted with C, you learn when to include the semicolon and when to
leave it off. Many beginning C programmers learn quickly when semicolons are required; your
compiler certainly informs you if you forget to include a semicolon where one is needed.

TIP
Many programmers use program templates that are nothing more than skeleton
programs with the typical main() and other C program elements already in the
code. Instead of typing the same required portions of the program every time the
programmer begins, the programmer loads the template program into the editor
and then modifies whatever needs changing for the particular job at hand.

Figure 2.2 repeats the sample program shown in Figure 2.1. It contains additional markings to
help acquaint you with these new terms as well as other items described in the remainder of this
chapter.
C
Comments

As a programmer in another language before you began learning C, you know the difference
between a program and its output. Most users of a program do not see the program's instructions,
the source code, itself; they see the output from the execution of the program's instructions.
Programmers, on the other hand, look at the program listings and add new routines, change old
ones, and update for advancements in computer equipment.

As explained previously, the readability of a program is important so that you and other
programmers can look through it easily. Nevertheless, no matter how clearly you write C
programs, you can always enhance their readability by adding comments throughout.

Comments are messages that you insert into your C programs, explaining what is going on at
that point in the program. For example, if you write a payroll program, you might put a comment
before the check-printing routine that describes what is about to happen. You never put C
language statements inside a comment, because a comment is a message for people— not
computers. Your C compiler ignores all comments in every program.

NOTE
C comments begin with a /* symbol and end with a */ symbol. An optional
method, preferred by many of today's programmers, enables programmers to
begin comments with two forward slashes, //.
Comments can span more than one line. Notice in the sample program, C2FIRST.C, that the
first three lines are actually a single comment. This comment explains the filename and a little
about the program.

Comments can also share lines with other C commands. There are several comments to the right
of much of the C2FIRST.C program, explaining what the individual lines do. Use abundant
comments, but remember who they are for: people and not computers. Use comments to help
explain your code, but do not over-comment.

Exampl
e

Even though you may not be familiar with C yet, the following statement is easy: It prints ''C By
Example" on the screen.

printf("C By Example"); /* Print C By Example on the screen */

This comment is redundant and adds nothing to your understanding of the line of code. It would
be much better, in this case, to leave out the comment. If you find yourself almost repeating the
C code, leave out that particular comment. Not every line of a C program should be commented.
Only comment whenever code lines need explaining—in English—to the people looking at your
program.

Comments Are for


You

It does not matter if you use uppercase, lowercase, or a mixture of both in your comments
because C ignores them. Most C programmers capitalize the first letter of sentences in
comments, just as you would in everyday writing. Because only people read comments, use
whatever case seems appropriate for the letters in your message.

CAUTION
Do not nest C comments by embedding one comment within another comment.
If you do, the C compiler gets confused when it sees the first comment end in
the middle of a second one.

Exampl
e

The section of a C program that follows is illegal because one comment resides within another:

sales = 3456.54 * bonus;


/* This is an example of a C program
/* It does NOT
comment correctly! */
The first comment did not end before the second began. */

This sometimes confuses programmers who are just learning C, but who know another
programming language. In C, you cannot comment out large sections of code just by inserting /*
at the beginning of the section and */ at the end if any lines within that section already have
comments. In some languages, programmers can comment out several lines in a program so that
those lines do not execute. This enables the programmer to test remaining lines independently
from those commented out. If you were to

try this in C—and nested comments result—your compiler might confuse a comment with code
and produce compile errors.

COMMENT AS YOU GO
Insert your comments as you write your programs. You are most familiar with
your program logic at the time you are typing the program into the editor. Some
people put off adding comments until after the program is written. More often
than not, however, those comments never get put in, or else they get written
halfheartedly.

If you comment as you write your code, you can glance back at your comments
while working on later sections of the program—instead of having to decipher
the previous code itself. This greatly helps whenever you want to see something
earlier in the program.

Exampl
e

1. Suppose you want to write a C program that produces a fancy boxed title containing your
name with flashing dots around it (like a marquee). The C code to do this might be difficult to
understand and might not be understandable—by itself—to others who look at your program
later. So, before such code, you might want to insert the following comment:

/* The following few lines draw a fancy box around


a name, then display flashing dots around the
name like a Hollywood movie marquee. */

This would not tell C to do anything because a comment is not a command, but it would make
the next few lines of code more understandable to you and others. The comment explains in
English, for people reading the program, exactly what the program is getting ready to do.

2. You should also put the disk filename of the program in one of the first comments. For
example, in the C2FIRST.C program shown earlier, the first line is really the beginning of a
comment:

/* Filename: C2FIRST.C

The comment would continue to the subsequent lines, but this part tells you in which disk file
the program is stored. Throughout this book, programs have comments that include a possible
filename under which the program can be stored. They begin with Cx, where x is the chapter
number in which they appear (for example, C6VARPR.C and C10LNIN.C). This naming
convention helps you to find these programs when they are referred to in another section of the
book.

TIP
It may be a good idea to put your name at the top of a program in a comment. If
people need to modify your program at a later date, they first might want to
consult with you, the original programmer, before they change it.

The New
Comment: / /

C++ is sometimes called a ''better C." Some programmers don't necessarily agree with the
"better" label, but almost every programmer does agree that C++ introduced a new style of
commenting into the language that is often preferable to C's /*...*/ style. As a matter of fact,
after the C++ style was introduced, most C compiler manufacturers changed their compilers to
recognize the new comment style, and all C major compilers today recognize both the old and
new comment style.

The new style requires only that a comment begin with two forward slashes (//) and continue
until the end of the line. You can mix the two commenting styles if you wish. A number of
reasons occur for the new style's popularity:

1. C programmers can forget to terminate the older style of comments, resulting in several lines
of comments that were meant to be code. This commented-out code can sometimes be difficult
to debug.
2. C programs require less typing because the new style of comments requires no characters to
end them.

3. Mainframe programmers used to JCL (Job Control Language, a batchlike language used to
control processing on mainframes) like the new style of C comments because JCL comments
also begin with //.

4. Commenting several lines out of a program, leaving the code but turning the section of code
into one long comment for testing purposes, is simpler and less error-prone with the new style
of C comments.

Exampl
e

Listing 2.3 contains a program that uses the new style of C comments exclusively.

Listing 2.3: The new style of C comment is often simpler to use.

// Filename: C2COMM.C
// This program contains the new comments
//
#include <stdio.h>
main()
{
int age = 30; // Declare variable and assign value
printf("Your age is %d years old\n", age);
// Now, print a closing message
printf("%d is still young!\n", age);
return 0;
}

Notice that the new comments can appear by themselves on a line or anywhere to the right of a
statement.

CAUTION
Unlike the old style of C comments, the new style does not enable you to put
executable code to the right of a comment. A comment in the new style must be
the final item on the line.

Studying the Sample Program

Now that you have an overview of a C program, its structure, and its comments, the rest of this
chapter walks you through the entire sample program. Do not expect to become a C expert just
by completing this section—that is what the rest of the book is for. For now, just sit back and
follow this walk-through of the program code.

As described earlier, this sample program contains several comments. The first three lines of the
program are comments:

/* Filename: C2FIRST.C
Initial C program that demonstrates the C comments
and shows a few variables and their declarations */

This comment tells you the filename and explains the purpose of the program. This is not the
only comment in the program; others appear throughout the rest of the code.

The next two lines (following the blank separating line) are shown here:
main()
{

This begins the main() function. Basically, the main() function's opening and closing braces
enclose the body of this program and the instructions that execute. C programs often contain
more than one function, but they must always contain a function called main(). The main()
function does not need to be the first one, but it usually is. The opening brace begins the first
and only block of this program.

When this program is compiled and run, the computer looks for main() and starts executing
whatever instruction follows main()'s opening brace. Here are the three lines that follow:

int i, j; /* These 3 lines declare 4 variables */


char c;
float x;

These three lines declare variables. A variable declaration describes all variables used in that
block of code.

A C program processes data into meaningful results. All C programs include the
following:

• Commands

• Data

Data is made up of variables and constants. As the name implies, a variable is data that can
change (become variable) while the program runs. A constant remains the same. In life, a
variable might be your salary. It increases over time (if you are lucky). A constant would be
your first name or social security number, because each remains with you throughout life and
does not (naturally) change.

Chapter 3, ''Variables and Constants," fully explains these concepts. However, to give you an
overview of the sample program's elements, the following discussion explains variables and
constants in this program.

C enables you to use several kinds of literal constants, often just called constants or literals
throughout the rest of the book. A C constant is any number, character, word, or phrase. The
following are all valid C constants:

5.6
-45
'Q'
"Mary"
18.67643
0.0

As you can see, some constants are numeric and some are character-based. The single and
double quotation marks around two of the constants, however, are not part of the constants
themselves. A single character constant requires single quotation marks around it; a string of
characters, such as "Mary", requires double quotation marks.

Look for the constants in the sample program. You can find
these:

4
7
'A'
9.087
4.5
A variable is like a box inside your computer that holds something. That ''something" might be a
number or a character. You can have as many variables as your program needs to hold data that
changes in the program. After you put a value into a variable, it stays in that variable until you
change it or put something else into it.

Variables have names so you can tell them apart. You use the assignment operator, the equal
sign (=), to assign values to variables. The following statement

sales=25000;

puts the constant value 25000 into the variable named sales. In the sample program, you can
find the following variables:

i
j
c
x

The three lines of code that follow the opening brace of the sample program declare these
variables. This variable declaration lets the rest of the program know that two integer variables
named i and j as well as a character variable called c and a floating-point variable called x
appear throughout the program. The terms integer and floating-point basically refer to two
different types of numbers: Integers are whole numbers, and floating-point numbers contain
decimal points.

You can see the variables being assigned values in the next few statements of the sample
program:

i = 4; /* i and j are assigned integer values */


j = i + 7;
c = 'A'; /* All character constants are
enclosed in single quotes */
x = 9.087; /* x requires a floating-point value since it
was declared as a floating-point variable */
x = x * 4.5; /* Change what was in x with a formula */

The first line puts 4 in the integer variable i. The second line adds 7 to the variable i's value to
get 11, which then gets assigned to (or put into) the variable called j. The plus sign (+) in C
works just like it does on calculators. The other primary math operators are shown in Table 2.1.

Table 2.1: The primary math operators.


Operator Meaning Example
+ Addition 4+5
_ Subtraction 7-2
* Multiplication 12 * 6
/ Division 48 / 12

The statements that appear before Table 2.1 require only slight explanation. The character
constant A is assigned to the c variable. The number 9.087 is assigned to the variable called x,
and then x is immediately overwritten with a new value: itself (9.087) multiplied by 4.5. This
helps illustrate why computer designers use an asterisk (*) for multiplication and not a
lowercase x as people generally do to show multiplication; the computer would confuse the
variable x with the multiplication symbol, x, if both were allowed.

NOTE
If mathematical operators are on the right side of the equal sign, the math is
completely carried out before the assignment is performed.

The next line (after the comment) includes the following special—and, at first, confusing—
statement:

printf("%d %d %c %f", i, j, c, x);


When the program runs and gets to this line, it prints the contents of the four variables to the
screen. It does not print %d %d %c %f, even though it might look as if it does. The ''%d %d %c
%f" is called a format string, which describes the format of what is to follow. The %d means
that a decimal integer prints in that location. The %c and %f mean that a character and a
floating-point value, respectively, print in those locations. This should make more sense to you
later.

For now, you can ignore format strings inside printf lines until Chapter 6, "Input and
Output," explains them more fully. The important part of this line is that the four values for i,
j, c, and x print on the screen.

The output from this line is

4 11 A 40.891499

Because this is the only printf in the program, this is the only output the sample program
produces. You might think that the program is rather long for such a small output. After you
learn more about C, you should be able to write more useful programs.

It's important that you keep in mind that printf() is not a C command. You might recall
from the previous chapter that C has no built-in input/output commands. The printf is a built-
in function, not an actual command. You have seen one function already, main(), which is one
you write the code for. The C programming designers have already written the code for the
printf function. At this point, you can think of printf as being a command that outputs
values to the screen, but it is really a built-in function.

To differentiate printf from regular C commands, parentheses are used after the name, as in
printf(). All function names have parentheses following them in a C program. Sometimes
these parentheses have something between them, and sometimes they are blank.

The last two lines in the program are shown here:


return 0; /* ALWAYS end programs and functions with return */
}

The return command simply tells C that this function is finished. C returns control to
whatever was controlling the program before it started running. In this case, because there was
only one function, control is returned to DOS or to the C editing environment. A value of 0, the
traditional value that the program is terminating correctly, is returned to the operating system as
well in case the execution of the next program is dependent on the successful execution of this
program. If you do not include a value, C typically returns the 0 anyway. (Many programs in
this book do not include the zero.) As you learn more about C, you'll learn more about how to
utilize these return values.

Actually, the return statement is optional. C would know when it reached the end of the
program without this statement. But it is a good programming practice to put a return
statement at the end of every function, including main(). Because some functions require a
return statement (if you are returning values), it is better to get in the habit of using them,
rather than run the risk of leaving one out when you really need it.

The closing brace after the return does two things in this program. It signals the end of a
block (begun earlier with the opening brace), which is the end of the main() function, and it
signals the end of the program.

What's Next

Although this chapter only skimmed the surface of C, you should have a better understanding of
C's nature. This understanding will launch well into the next chapter that explains in more detail
about variables and literal constants. Only after you can successfully specify data in a program
can you properly write code that acts upon that data and processes the data appropriately.
Chapter 3—
Variables and Constants

Now that you have seen an overview of the C programming language, you can start writing C
programs. In this chapter, you begin to write your own programs from scratch. To understand
data processing with C, you must understand how C creates, stores, and manipulates data. This
chapter teaches you how C handles data.

This chapter teaches you the following


topics:

• Variables and literal constants

• Types of variables and constants


• Special
constants

• How to name variables

• How to declare
variables

• Assigning values to variables

C
Variables

Variables have characteristics. When you decide your program needs another variable, you
simply declare (or define) a new variable and C makes sure you get it. You declare all C
variables at the top of whatever block of code needs them. Variable declaration requires that
you inform C of the variable's name and data type. Other information you might want to include
is optional depending on the goals of your program. To declare a variable, you must understand
the following characteristics:

• Each variable has a


name.

• Each variable has a type.

• Each variable holds a value you put there, when you assign that value to that variable.
Naming
Variables

Because you can have many variables in a single program, you must assign names to them so
you can keep track of them. Variable names are unique, just as house addresses are unique. If
two variables have the same name, C does not know which variable to use when you request
one.

Variable names can be as short as a single letter or as long as 31 characters. Their names must
begin with a letter of the alphabet, but after the first letter, they can contain letters, numbers, and
underscore (_) characters.

TIP
Spaces are not allowed in a variable name, so use the underscore character and
combine upper- and lowercase characters to help separate parts of the name.

Exampl
e

1. The following list of variable names are all valid:

salary aug99_Sales i index amount


2. C treats uppercase letters in variable names differently than lowercase letters. For example,
each of the following four variables are viewed differently by your C compiler:

sales Sales SALES sALES

3. Do not give variables the same name as a command or built-in function, and do not begin a
name with a number. Use meaningful variable names, so that later you can look at your program
and know for what each variable is used.

4. Along with not using spaces or other non-alpha numeric characters (except the underscore),
do not use other C functions and code as variable names, either. The following are invalid
variable names:

2001_sales Aug99+Sales MY AGE printf

Variable
Types

Variables can hold different types of data. Table 3.1 lists the different types of C variables. For
instance, if a variable holds an integer, C assumes no decimal point or fractional part (the part to
the right of the decimal point) exists for the variable's value. A very large number of types are
possible in C. For now, the most important types you should concentrate on are char, int, and
float. You can append the prefix long to make some of them hold larger values than they
would otherwise hold. Using the unsigned prefix enables them to hold positive numbers
only.
Table 3.1: Some C variable types.
Declaration Name Type
char Character
unsigned char Unsigned character
signed char Signed character (same as char)
int Integer
unsigned int Unsigned integer
signed int Signed integer (same as int)
short int Short integer
unsigned short int Unsigned short integer
signed short int Signed short integer (same as short int)
long Long integer
long int Long integer (same as long)
signed long int Signed long integer (same as long int)
unsigned long int Unsigned long integer
float Floating-point
double Double floating-point
long double Long double floating-point

The next section more fully describes each of these types. For now, you need to concentrate on
the importance of declaring them before using them.

Declaring
Variables

There are two places where you can declare a


variable:

• After the opening brace of a block of code (usually at the top of a function)
• Before a function name (such as before main() in the
program)

The first of these is the most common, and is used throughout much of this book. (If you declare
a variable before a function name, it is called a global variable. Later chapters address the pros
and cons of global variables.) To declare a variable, you must state its type, followed by its
name. In the previous chapter, you saw a program that declared four variables in the following
way:

main()
{
int i, j; // These 3 lines declare 4 variables
char c;
float x;
// Rest of program follows

This declares two integer variables named i and j. You have no idea what is inside those
variables, however. You generally cannot assume that a variable holds zero—or any other
number—until you assign it a value. The first line basically tells C the following:

''I am going to use two integer variables somewhere in this program. Be expecting them. I want
them named i and j. When I put a value into i or j, I ensure that the value is an integer."

Without such a declaration, you could not assign i or j a value later. You must declare all
variables before you use them. You could declare each of these two variables on lines by
themselves, as in the following code:

main()
{
int i;
int j;
// Rest of program follows

You do not gain any readability by doing this, however. Most C programmers prefer to declare
variables of the same type on the same line.

The second line from the program excerpt declares a character variable called c. Only single
characters should be placed there. Next, a floatingpoint variable called x is declared.

Exampl
e

1. Suppose you had to keep track of a person's first, middle, and last initials. Because an initial
is obviously a character, it would be prudent to declare three character variables to hold the
three initials. In C, you could do that with the following statement:

main()
{

char first, middle, last;


// Rest of program follows

This statement could go after the opening brace of main(). It lets the rest of the program know
that you require these three character variables.

2. You could also declare these three variables on three separate lines, although it does not
necessarily improve readability to do so. This could be accomplished with the following code:
main()
{
char first;
char middle;
char last;
// Rest of program follows

3. Suppose you want to keep track of a person's age and weight. If you want to store these
values as whole numbers, they would probably go in integer variables. The following statement
would declare those variables:

main()
{
int age, weight;
/* Rest of program follows */

Understanding Data
Types

You might wonder why it is important to have so many variable types. After all, a number is
just a number. But C has more data types than almost all other programming languages. The
variable's type is critical, but choosing the type among the many offerings is not as difficult as it
may first appear.

The character variable is easy to understand. A character variable can hold only a single
character. You cannot put more than a single character into a character variable.

NOTE
Unlike many other programming languages, C does not have a string variable.
Also, you cannot hold more than a single character in a C character variable. To
store a string of characters, you must use an aggregate variable type that
combines other fundamental types, such as an array. Chapter 5, ''Preprocessor
Directives," explains this more fully.
Integers hold whole numbers. Although mathematicians may cringe at this definition, an integer
is really just any number that does not contain a decimal point. All of the following expressions
are integers:

4 - 0 1 5421
5 932 2

Floating-point numbers contain decimal points. They are known as real numbers to
mathematicians. Any time you need to store a salary, a temperature, or any other number that
may have a fractional part (a decimal portion), you must store it in a floating-point variable. All
of the following expressions are floating-point numbers, and any floating-point variable can
hold them:

45.1 - 0.00 .04594


2 2344.5432

Sometimes you need to keep track of very large numbers, and sometimes you need to keep track
of smaller numbers. Table 3.2 shows a list of ranges that each C variable type might hold.

CAUTION
These ranges are typical, but they may differ from computer to computer. The
computer's word size determines the range of values (see Appendix A,
''Memory Addressing, Binary, and Hexadecimal," for more information on word
sizes). Your C compiler's manual will include the exact ranges you can use.
Table 3.2's ranges are the minimum that are in use because they adhere to the
ANSI C standard, set up by the American National Standards Institute.

Table 3.2: Typical ranges C variables might hold.


Type Range*
char -128 to 127
unsigned_char 0 to 255
signed_char -128 to 127
int -32768 to 32767
unsigned_int 0 to 65535
signed_int -32768 to 32767
short_int -32768 to 32767
unsigned_short_int 0 to 65535
signed_short_int -32768 to 32767
long_int -2147483648 to 2147483647
signed_long_int -2147483648 to 2147483647
float -3.4E+38 to 3.4E+38
double -1.7E+308 to 1.7E+308
long_double -1.7E+308 to 1.7E+308
*Use this table only as a guide; different compilers and different computers may allow different
ranges.

The floating-point ranges in Table 3.2 are shown in scientific notation. To determine the actual
range, take the number before the E (meaning

Exponent) and multiply it by 10 raised to the power after the plus sign. For instance, a floating-
point number (type float) can contain a number as small as -3.4 ´ 1038.

Notice that long integers and long doubles tend to hold larger numbers (and therefore, have a
higher precision) than regular integers and regular double floating-point variables. This is due to
the larger number of memory locations used by many of the C compilers for these data types.
Again, this is usually—but not always—the case.

LIMIT EXCESSIVE DATA TYPING


If the long variable types hold larger numbers than the regular ones, you might
initially want to use long variables for all your data. This would not be required
in most cases, and would probably slow your program's execution.

As Appendix A describes, the more memory locations used by data, the larger
that data can be. However, every time your computer has to access more
storage for a single variable (as is usually the case for long variables), it takes
the CPU much longer to access it, calculate with it, and store it.
Use the long variables only if you suspect your data overflows the typical data
type ranges. Although the ranges differ among computers, you should have an
idea of whether your numbers might exceed the computer's storage ranges. If
you are working with extremely large (or extremely small and fractional)
numbers, you should consider using the long variables.

Generally, all numeric variables should be signed (the default) unless you know for sure that
your data contains only positive numbers. (Some values, such as age and distance, are always
positive.) By making a variable an unsigned variable, you gain a little extra storage range (as
explained in Appendix A), but that extra range of values must always be positive.

Obviously, you must be aware of what kinds of data your variables hold. You certainly do not
always know exactly what all variables are holding, but you can have a general idea. For
example, in storing a person's age, you should realize that a long integer variable would be a
waste of space, because nobody can live to an age that can't be stored by a regular integer.

At first, it might seem strange for Table 3.2 to state that character variables can hold numeric
values. In C, integers and character variables frequently can be used interchangeably. As
explained in Appendix A, each ASCII table character has a unique number that corresponds to
its location in the table. If you store a number in a character variable, C treats the data as if it
were the ASCII character that matched that number in the table. Conversely, you can store
character data in an integer variable. C finds that character's ASCII number, and stores that
number instead of the character. Examples that help illustrate this follow a little later in the
chapter.

DESIGNATING LONG, UNSIGNED, AND FLOATING-POINT LITERAL CONSTANTS


When you type a number, C interprets its type as the smallest type that can hold that number. For example, if you
print 63, C knows that this number fits into a signed integer memory location. It does not treat the number as a long
integer, because 63 is not large enough to warrant a long integer constant size.

However, you can append a suffix character to numeric constants to override


the default type. If you put an L at the end of an integer, C interprets that
integer as a long integer. The number 63 is an integer constant, but the number
63L is a long integer constant.

Assign the U suffix to designate an unsigned integer constant. The number 63


is, by default, a signed integer constant. If you type 63U, C treats it as an
unsigned integer. The suffix UL indicates an unsigned long constant.
C interprets all floating-point constants (numbers that contain decimal points)
as double floating-point constants. This ensures the maximum accuracy for
such numbers. If you use the constant 6.82, C treats it as a double floating-point
data type, even though it would fit in a regular float. You can append the
floating-point suffix (F) or the long double floating-point suffix (L) to constants
that contain decimal points to represent a floating-point constant or a long
double floating-point constant, respectively, instead of the default double
constant value.

You might rarely use these suffixes, but if you need to assign a constant value to
an extended or unsigned variable, you may gain a little more accuracy if you
add U, L, UL, or F (their lowercase equivalents work, too) to the end of the
constant. For example, if you are making changes to someone else's C program,
you may want to specify the exact data type of a constant you assign to one of
the program's variables. Without the suffix, the program might assume a data
value with less precision. By specifying the suffix, you don't have to change the
data type of the variable throughout the entire program.

Assigning Values to
Variables

Now that you know about the C variable types, you are ready to learn the specifics of putting
values into those variables. You do this with the assignment statement. The equal sign (=) is
used for assigning values to variables.

The format of the assignment statement is the


following:

variable=expression;

The variable is any variable that you declared earlier. The expression is any variable,
constant, expression, or combination that produces a resulting data type that is the same as the
variable's data type.

Exampl
e

1. If you want to keep track of your current age, salary, and dependents, you could store these
values as three C variables. You first declare the variables by deciding on correct types and
good names for them. You then assign values to them. Later in the program, these values might
change (for example, if the program calculates a new pay increase for you).

Good variable names might be age, salary, and dependents. To declare these three
variables, the first part of the main() function might look like this:

/* Declare and store three values */


main()
{
int age;
float salary;
int dependents;

Notice that you do not need to declare all integer variables together on the same line. After these
variables are declared, the next three statements could assign them values, such as

age=32;
salary=25000.00;
dependents=2;
/* Rest of program follows */
2. Do not put commas in values that you assign to variables. Numeric constants should never
contain commas. The following statement is invalid:

salary=25,000.00;

3. You can assign variables or mathematical expressions to other variables. Suppose you stored
your tax rate in a variable called taxRate earlier in a program, then decided to use your tax
rate for your spouse's rate as well. At the proper point in the program, you could code the
following:

spouseTaxRate = taxRate;

(The spaces around the equal sign are optional and serve to help make the statement more
readable.) At this point in the program, the value in taxRate would be copied to a new
variable named spouseTaxRate. The value in taxRate would still be there after this line
finishes. This assumes that the variables were declared earlier in the program.

If your spouse's tax rate is going to be 40% of yours, you can assign an expression to the
spouse's variable, as in

spouseTaxRate = taxRate * .40;

Any of the four mathematical symbols you learned in the last chapter, as well as the additional
ones you learn about later in the book, can be part of the expression you assign to a variable.

4. If you want to assign character data to a character variable, you must enclose the character in
single quotation marks. Enclose all C character constants in single quotation marks.
The following section of a program declares three variables, and then assigns three initials to
them. The initials are character constants because they are enclosed in single quotation marks.

main()
{
char first, middle, last;
first = 'G';
middle = 'M' ;
last = 'P' ;
/* Rest of program follows */

Because these are variables, you can put other values into them later if the program warrants it.

CAUTION
Do not mix types between variables and values when using assignment
statements. In most cases, C lets you do this, but the results are unpredictable.
For instance, in the middle variable presented in the last example, you could
have stored a floating-point constant:

middle = 345.43244; /* Do not do this! */

If you did so, middle would hold a strange value that would seem to be
meaningless. Make sure that values you assign to variables match the variable's
type. The only major exception to this occurs when you assign an integer to a
character variable, or a character to an integer variable, as you will learn shortly.

Literal Constants

As with variables, there are several types of C constants. Remember that a constant does not
change. Integer constants are whole numbers that do not contain decimal points. Floating-point
constants are numbers that contain a fractional portion (a decimal point with an optional value
to the right of the decimal point).
Integer
Constants

You already know that an integer is any whole number without a decimal point. C lets you
assign integer constants to variables, use integer constants for calculations, and print integer
constants in the printf() function.

A regular integer constant cannot begin with a leading 0. To C, the number 012 is not the
number twelve. If you precede an integer constant with a 0, C thinks it is an octal constant. An
octal constant is a base-8 number. The octal numbering system is not used much in today's
computer systems. The newer versions of C retain octal capabilities for compatibility with
previous versions.

An octal integer constant contains a leading 0, and a hexadecimal constant contains a leading
0x.

A special integer in C that is still greatly used today is the base-16 (or hexadecimal) constant.
Appendix A describes the hexadecimal numbering system. If you want to represent a
hexadecimal integer constant, add the 0x prefix to it. All of the following numbers are
hexadecimal numbers:

0x10 0x204 0xFFFF 0x9

Notice that it does not matter if you use a lowercase or uppercase letter x after the leading zero,
or an uppercase or lowercase hexadecimal digit (for hex numbers A through F). If you write
business application programs in C, you might think you never have the need for using
hexadecimal, and you might be correct. For a complete understanding of C and your computer
in general, however, you should become a little familiar with the fundamentals of hexadecimal
numbers.
Table 3.3 shows a few integer constants represented in their regular decimal, hexadecimal, and
octal notations. Each row contains the same number in all three bases.

Table 3.3: Integer constants represented in three different bases.


Decimal Hexadecimal Octal
(Base 10) (Base 16) (Base 8)
16 0x10 020
65535 0xFFFF 177777
25 0x19 031

NOTE
Floating-point constants might begin with a leading zero, for example, 0.7. They
will be properly interpreted by C. Only integers are hexadecimal or octal
constants if preceded by a zero.

YOUR COMPUTER'S WORD SIZE IS IMPORTANT


If you write a lot of system programs that use hexadecimal numbers, you probably want to store those numbers in
unsigned variables. This keeps C from improperly interpreting positive numbers as negative numbers.

For example, if your computer stores integers in 2-byte words (as most PCs
do), the hexadecimal constant OxFFFF represents either -1 or 65535,
depending on how the sign bit is interpreted. If you declared an unsigned
integer, such as

unsigned int i_num = 0xFFFF;

C knows you want it to use the sign bit as data and not as the sign. If you
declared the same value as a signed integer, however, as in

int i_num = 0xFFFF; // The word "signed" is optional


C thinks this is a negative number (-1) because the sign bit is turned on. (If you
were to convert OxFFFF to binary, you would get sixteen number 1s.)
Appendix A describes these concepts in more detail.

String
Constants

A string constant is always enclosed in double quotation


marks.

One type of C constant, called the string constant, does not have a matching variable. A string
constant is always enclosed in double quotation marks. Here are examples of string constants:

"C Programming" "123" " " "4323 E. Oak Road" "x"

Any string of characters between double quotation marks—even a single character between
double quotation marks—is considered to be a string constant. A single space, a word, or a
group of words between double quotation marks are all C string constants. If the string constant
contains only numeric digits, it is not a number; it is a string of numeric digits that you cannot
use to perform mathematics. You can perform math only on numbers, not on string constants
that contain numbers or even on a character constant that might contain a number (enclosed in
single quotation marks).

NOTE
A string constant is any character, digit, or group of characters enclosed in
double quotation marks. A character constant is any character enclosed in
single quotation marks.

The double quotation marks are never considered part of the string constant. The double
quotation marks surround the string and simply inform your C compiler that it is a string
constant and not another type of constant.
It is easy to print string constants. Simply put the string constants in a printf() function. No
other printf() characters you have seen, such as ''%d" or "%c", are needed. Here is an
example of what you need to type to print a string constant to the screen:

printf("C By Example");

Exampl
e

1. The following program displays a simple message onscreen. No variables are needed because
no data is stored or calculated.

/* Filename: C3ST1.C
Display a string on-screen */
#include <stdio.h>
main()
{
printf(''C programming is fun!");
return;
}

Remember to make the last line in your C program (before the closing brace) a return
statement.

2. You probably want to label the output from your programs. Do not print the value of a
variable unless you also print a string constant describing that variable. The following program
computes sales tax for a sale and prints the tax. Notice a message is printed first that tells the
program user what the next number means:

/* Filename: C3ST2.C
Compute sales tax and display it with an appropriate message */
#include <stdio.h>

main()
{
float sale, tax;
float tax_rate = .08; /* Sales tax percentage */

/* Determine the amount of the sale */


sale = 22.54;

/* Compute the sales tax */


tax = sale * tax_rate;

/* Print the results */


printf("The sales tax is:");
printf("%f", tax);

return 0;
}

String-Constant
Endings

An additional aspect of string constants sometimes confuses beginning C programmers. All


string constants end with a zero. You do not see the zero, but C makes sure it stores the zero at
the end of the string in memory. Figure 3.1 shows what the string ''C Program" looks like in
memory.
Figure 3.1:
In memory,
a string
constant always
ends with 0.

You do not put the zero at the end of a string constant; C does it for you every time it stores a
string. If your program contained the string "C Program", for example, the compiler
recognizes it as a string constant (from the double quotation marks) and stores the zero at the
end.

The zero is important to C and is called the string delimiter. Without the string delimiter, C
would not know where the string constant ended in memory. (Remember that the double
quotation marks are not stored as part of the string, so C cannot use them to determine where the
string ends.)

The string-delimiting zero is not the same as the character zero. If you look at the ASCII table in
Appendix C, "ASCII Table," you can see that the first entry, ASCII number 0, is the null
character. (If you are unfamiliar with the ASCII table, you should read Appendix A for a
review.) This differentiates the string-delimiting zero from the character '0', whose ASCII value
is 48.

As explained in Appendix A, all memory locations in your computer actually hold bit patterns
for characters. If the letter A is stored in memory, an A is not really there; the binary bit pattern
for the ASCII A (01000001) is stored there. Because the binary bit pattern for the null zero is
00000000, the string-delimiting zero is also called a binary zero.

To illustrate this further, Figure 3.2 shows the bit patterns for the following string constant when
stored in memory:

"I am 30"
Figure 3.2 shows how a string is stored in your computer's memory at the binary level. It is
important for you to recognize that the character 0, inside the number 30, is not the same zero
(at the bit level) as the stringterminating null zero. If it were, C would think this string ended
after the 3, which would be incorrect.

C's method of storing strings is a fairly advanced concept, but you truly need to understand it
before continuing. If you are new to computers, reviewing the material in Appendix A will help
you understand this concept.

String
Lengths

Many times, your program needs to know the length of a string. This becomes critical when you
learn how to accept string input from the keyboard. The length of a string is the number of
characters up to, but not including, the delimiting null zero. Do not include the null character in
that count, even though you know C adds it to the end of the string.

Exampl
e
1. The following are all string
constants:

"0" "C" "A much longer string constant"

2. The following shows some string constants and their corresponding string lengths. All string
constants have a specified length.

String Length
"C" 1
"0" 1
"Hello" 5
" " 0
"30 oranges'' 10

Character
Constants

All C character literal constants should be enclosed within single quotation marks. The single
quotation marks are not part of the character, but they serve to delimit the character. The
following are valid C character constants:

'w' 'W' 'C' '7' '*' '=' '.' 'K'

C does not append a null zero to the end of character constants. You should know that the
following are very different to C:

'R' and "R"


'R' is a single character constant. It is one character long, because all character constants (and
variables) are one character long. ''R" is a string constant because it is delimited by double
quotation marks. Its length is also one, but it includes a null zero in memory so C knows where
the string ends. Because of this difference, you cannot mix character constants and character
strings. Figure 3.3 shows how these two constants are stored in memory.

All of the alphabetic, numeric, and special characters on your keyboard can be character
constants. Some characters, however, cannot be represented with your keyboard. They include
some of the higher ASCII characters (such as the Spanish Ñ). Because you do not have keys for
every character in the ASCII table, C lets you represent these characters by typing their ASCII
hexadecimal number inside single quotation marks.

For example, to store the Spanish Ñ in a variable, look up its hexadecimal ASCII number from
Appendix C. You find that it is A5. Add the prefix \x to it and enclose it in single quotation
marks, so C will know to use the special character. You could do that with the following code:

char sn='\xA5'; // Puts the Spanish N into the variable called sn

This is the way to store (or print) any character from the ASCII table, even if that character does
not have a key on your keyboard.

The single quotation marks still tell C that a single character is inside the quotation marks.
Even though '\xA5' contains four characters inside the quotation marks, those four characters
represent a single character, not a character string. However, if you were to include those four
characters inside a string constant, C would treat \xA5 as a single character within the string.
The following string constant

"An accented a is \xA0"

is a C string that is 18 characters long, not 21 characters. C interprets the \xA0 character as the
á, just as it should.

Any character preceded by a backslash, \, (such as these have been) is called an escape
sequence, or escape character. Table 3.4 shows some additional escape sequences that come in
handy when you want to print special characters.

TIP
Include \n in a printf() when you want to skip to the next line.

Table 3.4: Special C escape sequence characters.


Escape Sequence Meaning
\a Alarm (the terminal's bell)
\b Backspace
\f Form feed (for the printer)
\n Newline (carriage return and line feed)
\r Carriage return
\t Tab
\v Vertical tab
\\ Backslash (\)
\? Question mark
\' Single quotation mark
\" Double quotation mark
\ooo Octal number
\xhh Hexadecimal number
\0 Null zero (or binary zero)
MATH WITH C CHARACTERS
Because C links characters so closely with their ASCII numbers, you can perform arithmetic on character data. The
following section of code

char c;
c = 'T' + 5; /* Add 5 to the ASCII character */

actually stores a value Y in variable type c. The ASCII value of the letter T is
84. Adding 5 to 84 produces 89. Because the variable c is not an integer
variable, but is a character variable, C knows to put in c the ASCII character
for 89, not the number itself.

Conversely, you can store character constants in integer variables. If you do, C
interprets and stores the matching ASCII number (an integer) instead of the
character. The following section of code

int i='P';

does not put a letter P in i because i is not a character variable. C assigns the
number 80 in the variable because 80 is the ASCII number for the letter P.

Exampl
e
1. To print two names on two different lines, include the \n between them:

printf("Harry\nJerry");

When the program gets to this line, it prints the following:

Harry
Jerry

2. The following short program rings the bell on your computer by assigning the \a escape
sequence to a variable and then printing that variable:

/* Filename: C3BELL.C
Rings the bell */
#include <stdio.h>

main()
{
char bell='\a';
printf(''%c", bell); /* "%c" means print a character value */
return;
}

Chapter 4—
Introduction to
Arrays

Even though C does not support string variables, you can make C think it supports string
variables with character arrays. The concept of arrays might be new to you, but this chapter
explains how easy they are to declare and use. After you declare these arrays, they can hold
character strings—just as if they were real string variables. Manipulating characters and words
is one thing that separates your computer from a powerful calculator; this capability gives
computers true data processing capabilities.

This chapter teaches you the following


topics:

• Character arrays

• How character arrays and strings are alike and how they
differ

• Declaring character arrays as


strings

You might also like