Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Introduction to Data Types

A variable is something you can think of as a magic box into which you can place information—or, rather, data. But what kind of data?

All data on a computer is ultimately numeric, but it is organized into one of three basic formats: integer, floating-point, and text string.

There are several differences between floating-point and integer format. But the main rule is simple:

The principal floating-point data type in C++ is double. This may seem like a strange name, but it stands for “double-precision floating point.” There is also a single-precision type (float), but its use is relatively infrequent. When you need the ability to retain fractional portions, you’ll get better results—and fewer error messages—if you stick to double.

01fig09.jpg

A double declaration has the following syntax. Note that this statement is terminated with a semicolon (;), just as most kinds of statements are.

keyword.jpg
double variable_name;

You can also use a double declaration to create a series of variables:

double variable_name1, variable_name2, ...;

For example, this statement creates a double variable named aFloat:

double  aFloat;

This statement creates a variable of type double.

The next statement declares four double variables named b, c, d, and amount:

double  b, c, d, amount;

The effect of this statement is equivalent to the following:

double  b;
double  c;
double  d;
double  amount;

The result of these declarations is to create four variables of type double.

An important rule of good programming style is that variables should usually be initialized, which means giving them a value as soon as you declare them. The declarations just shown should really be:

double  b  = 0.0;
double  c  = 0.0;
double  d  = 0.0;
double  amount = 0.0;

Starting in the next chapter, I’ll have a lot more to say about issues such as data types and initialization. But for the next program, I’ll keep the code simple. We’ll worry about initialization in Chapter 2 onward.

Example 1.3. Convert Temperatures

Every time I go to Canada, I have to convert Celsius temperatures to Fahrenheit in my head. If I had a handheld computer, it would be nice to tell it to do this conversion for me; computers are good at that sort of thing.

Here’s the conversion formula. The asterisk (*), when used to combine two values, means “multiply by.”

Fahrenheit = (Celsius * 1.8) + 32

Now, a useful program will take any value input for Celsius and then convert it. This requires the use of some new features:

  • Getting user input
  • Storing the value input in a variable

Here is the complete program. Create a new project called “convert.” Then enter the new program, and compile and run (press Ctrl + F5 if you’re using Microsoft).

convert.cpp

// If you're using Microsoft V.S. leave in this line:
// #include "stdafx.h"

#include <iostream>
using namespace std;

int main()
{
     double  ctemp, ftemp;

     cout << "Input a Celsius temp and press ENTER: ";
     cin >> ctemp;
     ftemp = (ctemp * 1.8) + 32;
     cout << "Fahrenheit temp is: " << ftemp;
     return 0;
}

Remember, yet again (!), that if and only if you’re working with Microsoft Visual Studio, you must leave the following line in at the beginning of the program:

#include "stdafx.h"

Programs are easier to follow when you add comments, which in C++ are notated by double slashes (//). Comments are ignored by the compiler (they have no effect on program behavior), but they are useful for humans. Here is the more heavily commented version:

convert2.cpp

// If you're using Microsoft V.S. leave in this line:
// #include "stdafx.h"

#include <iostream>
using namespace std;
int main()
{

     double ctemp;   // Celsius temperature
     double ftemp;   // Fahrenheit temperature

     // Get value of ctemp (Celsius temp).

     cout << "Input a Celsius temp and press ENTER: ";
     cin >> ctemp;


     // Calculate ftemp (Fahrenheit temp) and output.

     ftemp = (ctemp * 1.8) + 32;
     cout << "Fahrenheit temp is: " << ftemp << endl;

     return 0;
}

This commented version, although it’s easier for humans to read, takes more work to enter. While following the examples in this book, you can always omit the comments or choose to add them later. Remember this cardinal rule for comments:

Using comments is always optional, although it is a good idea, especially if any humans (including you) are going to ever look at the C++ code.

How It Works

how.jpg

The first statement inside main declares variables of type double, ctemp and ftemp, which store Celsius temperature and Fahrenheit temperature, respectively.

double  ctemp, ftemp;

This gives us two locations at which we can store numbers. Because they have type double, they can contain fractional portions. Remember that double stands for “double-precision floating point.”

01fig11.jpg

The next two statements prompt the user and then store input in the variable ctemp. Assume that the user types 10. Then the numeric value 10.0 is put into ctemp.

In general, you can use similar statements in your own programs to print a prompting message and then store the input. The prompt is very helpful because otherwise the user may not know when he or she is supposed to do something.

The next statement performs the actual conversion, using the value stored in ctemp to calculate the value of ftemp:

ftemp = (ctemp * 1.8) + 32;

This statement features an assignment: the value on the right side of the equal sign (=) is evaluated and then copied to the variable on the left side. This is one of the most common operations in C++.

Again, assuming that the user input 10, this is how data would flow in the program:

Finally, the program prints the result—in this case, 50.

Optimizing the Program

optim.jpg

If you look at the previous example carefully, you might ask yourself, was it really necessary to declare two variables instead of one?

Actually, it wasn’t. Welcome to the task of optimization. The following version improves on the first version of the program by getting rid of ftemp and combining the conversion and output steps:

convert3.cpp

// If you're using Microsoft V.S. leave in this line:
// #include "stdafx.h"

#include <iostream>
using namespace std;

int main()
{
    double  ctemp;   // Celsius temperature

    // Prompt and input value of ctemp.

    cout << "Input a Celsius temp and press ENTER: ";
    cin >> ctemp;


    // Convert ctemp and output results.

    cout << "Fahr. temp is: " << (ctemp * 1.8) + 32;
    cout << endl;

    return 0;
}

Do you detect a pattern by now? With the simplest programs, the pattern is usually as follows:

  1. Declare variables.
  2. Get input from the user (after printing a prompt).
  3. Perform calculations and output results.

For example, the next program does something different but should look familiar. This program prompts for a number and then prints the square. The statements are similar to those in the previous example but use a different variable (x) and a different calculation.

square.cpp

// If you're using Microsoft V.S. leave in this line:
// #include "stdafx.h"

#include <iostream>
using namespace std;

int main()
{
    double  x = 0.0;

    // Prompt and input value of x.

    cout << "Input a number and press ENTER: ";
    cin >> x;


    // Calculate and output the square.

    cout << "The square is: " << x * x << endl;
    return 0;
}

Exercises

exerc.jpg

Exercise 1.3.1. Rewrite the example so it performs the reverse conversion: Input a value into ftemp (Fahrenheit) and convert to ctemp (Celsius). Then print the results. (Hint: The reverse conversion formula is ctemp = (ftemp − 32) / 1.8.)

Exercise 1.3.2. Write the Fahrenheit-to-Celsius program using only one variable, ftemp. This is an optimization of Exercise 1.3.1.

Exercise 1.3.3. Write a program that inputs a value into a variable x and outputs the cube (x * x * x). Make sure the output statement uses the word cube rather than square.

Exercise 1.3.4. Rewrite the example square.cpp using the variable name num rather than x. Make sure you change the name everywhere “x” appears.

  • + Share This
  • 🔖 Save To Your Account