|
|
|
|
|
|
|
As you can see, myAge and myWeight are each declared as unsigned integer variables. The second line declares three individual long variables named area, width, and length. The type (long) is assigned to all the variables, so you cannot mix types in one definition statement. |
|
|
|
|
|
|
|
|
Assigning Values to Your Variables |
|
|
|
|
|
|
|
|
You assign a value to a variable by using the assignment operator (=). Thus, you would assign 5 to Width by writing |
|
|
|
|
|
|
|
|
unsigned short Width;
Width = 5; |
|
|
|
|
|
|
|
|
You can combine these steps and initialize Width when you define it by writing |
|
|
|
|
|
|
|
|
unsigned short Width = 5; |
|
|
|
|
|
|
|
|
Initialization looks very much like assignment, and with integer variables, the difference is minor. Later, when constants are covered, you will see that some values must be initialized because they cannot be assigned to. |
|
|
|
|
|
|
|
|
Listing 3.2 shows a complete program, ready to compile, that computes the area of a rectangle and writes the answer to the screen. |
|
|
|
|
|
|
|
|
LISTING 3.2 DEMONSTRATES THE USE OF VARIABLES |
|
|
|
 |
|
|
|
|
1: // Demonstration of variables
2: #include <iostream.h>
3:
4: int main()
5: {
6: unsigned short int Width = 5, Length;
7: Length = 10;
8:
9: // create an unsigned short and initialize with result
// of multiplying Width by Length
10: unsigned short int Area = Width * Length;
11:
12: cout << Width: << Width << \n;
13: cout << Length: << Length << endl;
14: cout << Area: << Area << endl;
15: return 0;
16: } |
|
|
|
|
|
|
|
|
Width: 5
Length: 10
Area: 50 |
|
|
|
|
|