08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3 ■ Programs with Sequence Logic

As with printf, the first item is a string called the format string. In this example, the string

consists of the format specification %d only. It specifies the type of data to be read. Here, %d is used

to indicate that an integer value is to be read.

The second argument specifies where to store the value read. Even though we want the

value stored in a, scanf requires us to specify this by writing &a. The quick explanation is that we

must tell scanf the address of the memory location where the value is to be stored; &a stands for

“address of a.” You will need to take it on faith that in order to read a value into a variable using

scanf, the variable must be preceded by &, as in &a and &b. Note that this applies to the scanf

statement only. Other than this, the variable is used in its normal form (without &) as in:

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

We can use scanf to read more than one value at a time. For example, suppose we want to

read three integer values for variables a, b, and c. To do so, we would need to write %d three times

in the format specification, thus:

scanf("%d %d %d", &a, &b, &c);

When this statement is executed, it looks for three integers. The first one is stored in a, the

second in b, and the third in c. It is up to the user to ensure that the next three items in the data are

integers. If this is not so, an “Invalid numeric format” message will be printed and the program

will crash.

When entering the data, the numbers must be separated by one or more spaces, like this:

42 -7 18

When using scanf, data can be supplied in flexible ways. The only requirement is that the

data be supplied in the correct order. In this example, the three numbers could be supplied as

above or like this:

42

-7

18

or this:

42 -7

18

or even with a blank line, like this:

42

-7 18

51

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!