Printing Variables

Printing the values of variables will make use of the printf() function, which was used in Chapter 1 for creating a simple message. Sadly, you cannot simply place the variable names within the context of the message in order to print their values. Instead, you make use of different signifiers, which act as placeholders for the variables, and then follow the message itself with the list of variables to use. For example, the %d flag represents an integer:

int dob = 1947;
printf ("You were born in the year %d.",
 dob);

When the application is run, the value of dob will be used in place of %d, resulting in the message You were born in the year 1947.

Table 2.2 lists the most important signifiers. As you'll discover, d, f, c, and s will suit most of your needs.

Table 2.2. These signifiers give the printf() function formatting cues for inserting values in their stead.
printf() Signifiers
SignifierMeaning
dinteger
ffloating point number
hdshort integer
ldlong integer
huunsigned short integer
uunsigned integer
luunsigned long integer
lfdouble
Lflong double (not always available)
ccharacter
sstring

Since the printf() function is so critical, you should understand a few other things before using it. First, note that you can refer to multiple variables and types of variables in a single statement:

printf ("%s is %d years old.", name, age);

In that example, the value of name will be used in place of %s and the value of age will be filled in for %d.

You can also hardcode values, rather than use variables:

printf ("%s is %d years old.", name, 40);

Building on this, you can make calculations within the printf() function, rather than just printing variable values. For example:

printf ("The cost of %d widgets at $%f 
 price is $%f.
", qty, cost, qty * 
 cost);

In that example, the value of qty is used in place of %d, the value of cost is used in place of the first %f (preceded by a dollar sign), and the result of the multiplication of these two variables is used in place of the final %f (again preceded by a dollar sign).

Finally, the printf() function can take formatting one step further. For example, using %0.2f formats a floating point number to two decimal places. This next example will demonstrate all of this information, and you'll learn more about printf() in Chapter 5, “Standard Input and Output.”

To print variable values

1.
Open var2.c (Script 2.2) in your text editor or IDE.

2.
After setting the variable values but before the return statement, print the value of the age variable (Script 2.3):

printf ("You are %d years old.
", 
 age);

Script 2.3. Printing the value of a variable requires special syntax with the printf() function.


This statement will print out You are 40 years old., replacing %d with the value of age (which was set at 40 earlier). Because age is an integer, %d is used as the signifier; see Table 2.2.

The newline character is appended to the end of the statement so that the next statement will follow on the next line (see Chapter 1 for a refresher on white space in C).

3.
Print out the hourly wage, along with an estimated yearly salary:

printf ("Your hourly wage is $%0.2f. 
 This translates into approximately 
 $%0.2f per year.
", hourly_wage, 
 hourly_wage * 40 * 52);

This print statement will make use of two inserted values. The first will be a float (a decimal), based on the value of hourly_wage. The second will also be a float but will be based on the result of multiplying the hourly_wage variable times 40 (hours per week) times 52 (weeks per year). In both cases the result is formatted to two decimal places and preceded by a dollar sign.

4.
Add the getchar() function to make the application pause during runtime:

getchar();

This notion was also introduced in the previous chapter. It requires that the user press Return or Enter before the application stops running. This will ensure that the console or command-line window doesn't open and close before you have the chance to see the result.

5.
Save the file as var3.c.

6.
Compile and run the application (Figure 2.3).

Figure 2.3. The result of the basic application, where each variable's value is printed.


✓ Tips

  • If you use %f instead of %0.2f in this example, you'll see an odd result like that in Figure 2.4, as the entire float value is printed.

    Figure 2.4. Formatting variable values can be finely tuned using printf(). Compare the hourly wage and salary values here with those in Figure 2.3.

  • Perhaps the best beginning debugging technique you can use as you program with C is to print out the values of variables as your applications execute. That will give you a peek into what's happening behind the scenes.

  • C compilers will typically not generate an error if you have a mismatched number of formatting placeholders and variables in your printf() statements. Instead, you'll get odd results in the output such as pseudo-random numbers. You'll also see curious characters if you mismatch the type of placeholder and the associated value or variable.

  • More printf() signifiers will be covered over the course of this book, and Appendix B, “Resources,” contains the full list.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset