08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 2 ■ C – The Basics

The first statement assigns 12 to a; the second assigns 5 to b; the third assigns 14 to c; no

problem so far. However, when the computer attempts to execute the fourth statement, it runs

into a problem. There is no value for e, so the expression c + e cannot be evaluated. We say that e

is undefined—it has no value.

Before we can use any variable in an expression, it must have been assigned a value by some

previous statement. If not, we will get an “undefined variable” error and our program will halt.

The moral of the story: a valid program is not necessarily a correct program.

Exercise: What is printed by the following?

a = 13;

b = a + 12;

printf("%d %d\n", a, b);

c = a + b;

a = a + 11;

printf("a = %d b = %d c = %d\n", a, b, c);

2.9 printf

We have seen several examples of the printf statement. We have used it to print string constants,

integer values, and floating-point values. And we have printed values with and without field

widths. We have also seen how to use the escape sequence \n to force output onto a new line.

It is worth emphasizing that the characters in the format string are printed exactly as they

appear except that a format specification is replaced by its corresponding value. For example, if a

is 25 and b is 847, consider the statement

printf("%d%d\n", a, b);

This will print

25847

The numbers are stuck together and we cannot tell what is a and what is b! This is so because

the specification %d%d says to print the numbers next to each other. If we want them separated by

one space, say, we must put a space between %d and %d, like this:

printf("%d %d\n", a, b);

This will print

25 847

To get more spaces between the numbers, we simply put how many we want between %d and %d.

42

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!