Programming With Integers - Output of Numbers

Chapter chap2 section 5

We have already encountered the library function printf(). Notice how the \n was omitted from the strings on lines 7 and 9 of the sum of two numbers program so that the prompt and the user response appeared on the same line when the program was executed.

The parameters associated with printf() on line 11

printf("The sum of x and y was %d\n",x+y);
are more interesting. The string always associated with printf() is, in fact, a format string or layout specification that consists of a mixture of things to be copied directly to the output and output conversion specifications. The second parameter and any subsequent parameters of printf() will be expressions whose values will be converted from internal binary form to external form in accordance with the conversion specifications in the format string.

As with scanf() there are a wide variety of possible conversion specifications. A conversion specification within a format string is always introduced by a percent symbol (%) and terminated by one of several key letters identifying a conversion type. Within format strings you must write %% if you want an actual % symbol to appear in the output. In this chapter we will only use the "d" conversion type. This means convert from internal binary to external decimal.

The value of x+y is, as you might have expected, the sum of the values stored in locations x and y. "x+y" is, technically, an expression. Whenever an expression occurs in a program the effect is that the computer calculates the value of the expression and leaves the value in a standard place. Expressions of arbitrary complexity may be included as parameters of printf() as well as numbers and variables which are special simple cases of expressions.


Another program to read in two numbers.