We’ve seen the use of
printf() to send information to the computer screen.
printf() is a very large and complicated function with many possible variants of format specifiers. Format specifiers are the “% things” used as placeholders for values. Some examples are:
|%lf||double (long float)|
|%e||float using exponent notation|
|%g||float using shorter of e or f style|
|%ld||decimal long integer|
|%x||hexadecimal (hex or base 16) integer|
|%o||octal (base 8) integer|
Suppose that you wanted to print out the value of the variable
ans in decimal, hex, and octal. The following instruction would do it all:
printf(“The answer is %d, or hex %x, or octal %o.\n”, ans, ans, ans );
Note how the three variables are labeled. This is important. If you printed something in hex without some form of label, you might not know if it was hex or decimal. For example, if you just saw the number “23”, how would you know it’s 23 decimal or 23 hex (35 decimal)? For that matter, how would you set a hex constant in your C code? The compiler would have no way of “knowing” either. To get around this, hex values are prefixed with
0x. Thus, we have
0x23 for hex 23. The
printf() function does not automatically add the
0x on output. The reason is because it may prove distracting if you have a table filled only with hex values. It’s easy enough to use
0x%d instead of just
%d for the output format.
You can also add a field width specifier. For example,
%5d means print the integer in decimal with 5 spaces minimum. Similarly,
%6.2f means print the floating point value using 6 spaces minimum. The “.2” portion is a precision specifier and in this case indicates 2 digits after the decimal point are to be used. As you can see, this is a very powerful and flexible function!
The mirror input function is
scanf(). This is similar to Python’s
input statement. Although you can ask for several values at once, it is generally best to ask for a single value when using this function. It uses the same sort of format specifiers as
printf(). There is one important point to note. The
scanf() function needs to know where to place the entered value in computer memory. Simply informing it of the name of the variable is insufficient. You must tell it where in memory the variable is, in other words, you must specify the address of the variable. C uses the
& operator to signify “address of”. For example, if you wish to obtain an integer from the user and place it in a variable called
voltage, you might see a program fragment like so...
printf(“Please enter the voltage:”); scanf(“%d”, &voltage);
It is very common for new programmers to forget the &. Be forewarned!