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 1 ■ Elementary Programming Concepts

will print this:

The number of students = 52

This printf is a bit different from those we have seen so far. This one has two arguments—a string

and a variable. The string, called the format string, contains a format specification %d. (In our previous

examples, the format string contained no format specifications.) The effect, in this case, is that the

format string is printed as before, except that the %d is replaced by the value of the second argument, m.

Thus, %d is replaced by 52, giving this:

The number of students = 52

We will explain printf and format specifications in more detail in Chapter 2, but, for now, note that we

use the specification %d if we want to print an integer value.

What if we want to print more than one value? This can be done provided that each value has a

corresponding format specification. For example, suppose that a has the value 14 and b has the value 25.

Consider the statement:

printf("The sum of %d and %d is %d\n", a, b, a + b);

This printf has four arguments—the format string and three values to be printed: a, b, and a+b.

The format string must contain three format specifications: the first will correspond to a, the second to

b, and the third to a+b. When the format string is printed, each %d will be replaced by the value of its

corresponding argument, giving this:

The sum of 14 and 25 is 39

Exercise: What is printed by the following statement?

printf(“%d + %d = %d\n”, a, b, a + b);

1.8 Comments

All programming languages let you include comments in your programs. Comments can be used

to remind yourself (and others) of what processing is taking place or what a particular variable

is being used for. They can be used to explain or clarify any aspect of a program that may be

difficult to understand by just reading the programming statements. This is very important since

the easier it is to understand a program, the more confidence you will have that it is correct. It is

worth adding anything which makes a program easier to understand.

17

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!