Chapter 5
Values and Constants
In This Chapter
Working with values
Using printf()
to display values
Formatting floating-point output
Letting the program do the math
Creating constants
Back in the old days, most people thought of computers in terms of math. Computers calculated rocket trajectories, conducted the census, and screwed up phone bills. They were scary, technological things, and the people who programmed computers were downright geniuses.
Ha! Fooled everyone.
Programmers merely write the equation and punch in a few numbers, and then the computer does the math. That’s the genius part. Punching in the wrong numbers is the non-genius part. Before you can get there, you have to understand a bit about values and variables and how the C programming language deals with them.
A Venue for Various Values
Computers deal with both numbers and text. Text comes in the form of individual characters or a parade of characters all lumped together into a string. Numbers are pretty much numbers until you get into huge values and fractions. The computer understands everything, as long you properly inform your program of which values are which.
Understanding values
You’ve probably dealt with numbers all your life, virtually tortured by them throughout your schooling. You may recall terms such as whole number, fraction, real number, and imaginary number. Ignore them! These terms mean nothing in computer programming.
When it comes to programming, you use only two types of numbers:
Integer
Float
An integer is a whole number — no fractional part. It can be positive. It can be negative. It can be a single digit, zero, or humongous value such as the amount of money the U.S. government spends in a week (no cents). All these numbers are integers in computer programming jargon.
A float is a number that has a fractional part — a decimal place. It can be a very, very small number, like the width of a proton. It can be a very, very large number, like the hat size of the planet Jupiter.
Examples of integers: –13, 0, 4, and 234792.
In programming, you don’t type commas in large values.
Examples of floats are 3.14, 0.1, and 6.023e23. That last number is written in scientific notation, which means that it’s the value 6.023 × 1023 — a huge number. (It’s Avogadro’s number, which is another term you’ve probably forgotten from school.)
Integers and floats can be either positive or negative.
Integers are judged by their size, as are floats. The size comes into play when you create storage places for numbers in your programs. Chapter 6 covers the details.
The term float is short for floating point. It refers to the method that’s used to store large numbers and fractions in the binary counting system of modern electronics.
Displaying values with printf()
The printf()
function, introduced in Chapter 4, is ideal for displaying not only strings of text but also values. To make that happen, you use conversion characters in the function's formatting string. Rather than bore you with a description, consider Exercise 5-1.
Exercise 5-1: Start up a new project, ex0501, using the source code illustrated in Listing 5-1. Save the project. Build it. Run it.
Listing 5-1: Displaying Various Values
#include <stdio.h>
int main()
{
printf("The value %d is an integer.\n",986);
printf("The value %f is a float.\n",98.6);
return(0);
}
The output from Exercise 5-1 looks something like this:
The value 869 is an integer.
The value 98.600000 is a float.
You’re probably surprised that the output doesn’t look like this:
The value %d is an integer.
The value %f is a float.
It doesn't, because the text included in a printf()
function isn't merely text — it's a formatting string.
The printf()
function's formatting string can contain plain text, escape sequences, and conversion characters, such as the %d
in Line 5 and the %f
in Line 6. These conversion characters act as placeholders for values and variables that follow the formatting string.
For the %d
placeholder, the integer value 986
is substituted. The %d
conversion character represents integer values.
For the %f
placeholder, the float value 98.6
is substituted. The %f
conversion character represents floating-point values. Of course, 98.6
isn't displayed. Instead, you see 98.600000
. This issue is addressed in the later section Minding the extra zeros.
The %d
and %f
are only two of many placeholders for the printf()
function's formatting string. The rest are covered in Chapter 7.
Exercise 5-2: Create a project that displays the following values by using the printf()
function and the appropriate conversion characters, either %d
or %f
:
127
3.1415926535
122013
0.00008
When typing a small floating-point value, remember to prefix the decimal point with a zero, as just shown, with 0.00008
. Likewise, when typing a float value without a decimal part, type the decimal and a zero anyway:
1000000.0
Minding the extra zeroes
When you wrote the code for Exercise 5-1, you probably expected the program's output to display the value 98.6
, just as it's written. The problem is that you directed the printf()
function to output that number in an unformatted manner — for example, 98.600000
. In fact, you may see more or fewer zeros, depending on your compiler.
The value 98.600000
is a floating-point number, and it most likely represents the way the value is stored inside the computer. Specifically, the value is stored using eight digits. The number is accurate, of course, but human beings don't usually write trailing zeros after numbers. Computers? They write as many zeros as fills eight digits (not counting the decimal).
To fix the output, direct the printf()
function to format the floating-point number. That requires a more complex version of the %f
placeholder, something you're introduced to in Chapter 7. Specifically, change the %f
placeholder to read %2.1f
. Here's the new Line 6:
printf("The value %2.1f is an float.\n",98.6);
By squeezing 2.1
between the %
and the f
, you direct printf()
to format the output with two digits to the left of the decimal and one digit to the right.
Exercise 5-3: Modify your source code from Exercise 5-2 so that the value 3.1415926535 is displayed by using the %1.2f
placeholder, and the value 0.00008 is displayed by using the %1.1f
placeholder.
The Computer Does the Math
It should come as no surprise that computers can do math. In fact, I’d bet that your computer is, right now, more eager to solve some mathematical puzzles than it is for you to visit Facebook. Some math examples shown earlier in this chapter merely bored the processor. Time to put it to work!
Doing simple arithmetic
Math in your C source code is brought to you by the +, –, *, and / operators. These are the basic math symbols, with the exception of * and /, mostly because the × and ÷ characters aren’t found on the typical computer keyboard. For reference, Table 5-1 lists the basic C language math operators.
Table 5-1 Basic Math Operators
Operator |
Function |
+ |
Addition |
– |
Subtraction |
* |
Multiplication |
/ |
Division |
More C math operators exist, as well as a tumult of mathematical functions. Chapter 11 helps you continue exploring math programming potential. For now, the basics will do.
Calculations in C are made by placing values on either side of a math operator, just as you did all throughout school, but with the benefit of the computer making the calculations. Listing 5-2 provides a sample.
Listing 5-2: The Computer Does the Math
#include <stdio.h>
int main()
{
puts("Values 8 and 2:");
printf("Addition is %d\n",8+2);
printf("Subtraction is %d\n",8-2);
printf("Multiplication is %d\n",8*2);
printf("Division is %d\n",8/2);
return(0);
}
Exercise 5-4: Create a project named ex0504 using the source code shown in Listing 5-2. Save. Build. Run.
The output looks something like this:
Values 8 and 2:
Addition is 10
Subtraction is 6
Multiplication is 16
Division is 4
What you see in this code are immediate calculations. That is, the value that's calculated, the result, isn't stored. Instead, the program does the math and deals with the result, which is stuffed into the %d
conversion character in the printf()
function's formatting text.
Exercise 5-5: Write a program that displays the result of adding 456.98 and 213.4.
Exercise 5-6: Write a program that displays the result of multiplying the values 8, 14, and 25.
Exercise 5-7: Write a program that solves one of those stupid riddles on Facebook: What’s the result of 0+50*1–60–60*0+10? Solve the equation yourself before you run the program to see the computer’s result. Refer to Chapter 11 to read why the results might be different.
Reviewing the float-integer thing
The difference between an immediate value being a float or an integer is how you specify it in a program. Consider Listing 5-3.
Listing 5-3: Another Immediate Math Problem
#include <stdio.h>
int main()
{
printf("The total is %d\n",16+17);
return(0);
}
The values 16 and 17 are integers; they have no decimal part.
Exercise 5-8: Create, build, and run the project ex0508 using the source code from Listing 5-3.
Building the project yields the answer, which is also an integer:
The total is 33
Exercise 5-9: Modify the source code to specify one of the values as a float. For example, change Line 5 to read:
printf("The total is %d\n",16.0+17);
Adding that point-zero doesn’t change the value. Instead, it changes the way the number is stored. It’s now a float.
Save the change in your source code. Build and run.
You may see some warning errors displayed, depending on whether your compiler is configured to display them. One of my computers shows a warning error on the printf()
format, explaining the mixed types int
and double
.
Here’s the result I see:
The total is 0
You may see another value, which is completely random. Regardless, the displayed result is incorrect. That's because the %d
integer placeholder was used when the calculation includes a float
. Change Line 5 again, specifying the %f
placeholder this way:
printf("The total is %f\n",16.0+17);
Build and run. The result now looks something like this:
The total is 33.000000
The answer is correct, and it's a float
.
Exercise 5-10: Rewrite the source code for Listing 5-3 so that all immediate values are floats. Ensure that the printf()
function displays them that way.
Anytime a floating-point number is used in a calculation, the result is a floating-point number. Various tricks can be employed to avoid this issue, but for now consider it solid.
It's possible for two integer values to be used and generate a result as a float
. For example, dividing 2 by 5 — both values are integers — yields 0.4, which is a floating-point value. Specifying the %f
placeholder, however, doesn't display the value 0.4
because the calculated result remains an integer. The solution is to typecast the calculation, a topic that's covered in Chapter 16.
Always the Same
Computers and their electronic brethren enjoy doing repetitive tasks. In fact, anything you do on a computer that requires you to do something over and over demands that a faster, simpler solution be at hand. Often, it’s your mission to simply find the right tool to accomplish that goal.
Using the same value over and over
It may be too early in your C programming career to truly ponder a repetitive program; the topic of looping is covered in Chapter 9. But that doesn’t mean you can’t code programs that use values over and over.
Exercise 5-11: Create a new project, ex0511, and type in the source code, as shown in Listing 5-4. Save it, build it, run it.
Listing 5-4: It’s a Magic Number
#include <stdio.h>
int main()
{
printf("The value is %d\n",3);
printf("And %d is the value\n",3);
printf("It's not %d\n",3+1);
printf("And it's not %d\n",3-1);
printf("No, the value is %d\n",3);
return(0);
}
The code uses the value 3
on every line. Here's the output:
The value is 3
And 3 is the value
It's not 4
And it's not 2
No, the value is 3
Exercise 5-12: Edit the code to replace the value 3
with 5
. Compile and run.
You might think that Exercise 5-12 is cruel and requires a lot of work, but such things happen frequently in programming. For example, I wrote a program that displays the top three most recent items added to a database. But then I wanted to change the list so that it shows the top five items. As you had to do in Exercise 5-12, I had to painstakingly search and replace throughout the entire source code, carefully plucking out references to 3
and substituting 5
.
There has to be a better way.
Introducing constants
A constant is a shortcut — specifically, something used in your code to substitute for something else. A constant operates at the compiler level. It's created by using the #define
directive, in this format:
#define
SHORTCUT constant
SHORTCUT
is a keyword, usually written in all caps. It's created by the compiler to represent the text specified as constant. The line doesn't end with a semicolon because it's a compiler directive, not a C language statement. But the constant you create can be used elsewhere in the code, especially in the statements.
The following line creates the constant OCTO
, equal to the value 8
:
#define OCTO 8
After defining the constant, you can use the shortcut OCTO
anywhere in your code to represent the value 8
— or whatever other constant you define; for example:
printf("Mr. Octopus has %d legs.",OCTO);
The preceding statement displays this text:
Mr. Octopus has 8 legs.
The OCTO shortcut is replaced by the constant 8
when the source code is compiled.
The #define
directive is traditionally placed at the top of the source code, right after any #include
directives. See the next section for an example.
You can define strings as well as values:
#define AUTHOR "Dan Gookin"
The string that’s defined includes the double quotes.
You can even define math calculations:
#define CELLS 24*80
The definitions can be used anywhere in the source code.
Putting constants to use
Anytime your code uses a single value over and over (something significant, like the number of rows in a table or the maximum number of items you can stick in a shopping cart), define the value as a constant. Use the #define
directive, as described in the preceding section.
Listing 5-5 shows an update to the source code in Exercise 5-11. The VALUE
constant is created, defined as being equal to 3
. Then that constant is used in the text. The constant is traditionally written in all caps, and you can see in the source code how doing so makes it easy to find, and identify as, a constant.
Listing 5-5: Preparing for Constant Updates
#include <stdio.h>
#define VALUE 3
int main()
{
printf("The value is %d\n",VALUE);
printf("And %d is the value\n",VALUE);
printf("It's not %d\n",VALUE+1);
printf("And it's not %d\n",VALUE-1);
printf("No, the value is %d\n",VALUE);
return(0);
}
Exercise 5-13: Create a new project named ex0513 using the source code from Listing 5-5. If you like, you can use the source code from Exercise 5-11 as a starting point. Build and run.
The output is the same as for the first version of the code. But now, whenever some bigwig wants to change the value from 3 to 5
, you need to make only one edit, not several.
Exercise 5-14: Modify the source code from Exercise 5-4 so that the two values 8
and 2
are represented by constants.