 # Variables and Constants

• Print
This chapter is from the book

## 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 a value.

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 usevar.cpp Demonstrates the Use of Variables

``` 0: // Demonstration of variables
1: #include <iostream>
2:
3: int main()
4: {
5:   unsigned short int Width = 5, Length;
6:   Length = 10;
7:
8:   // create an unsigned short and initialize with result
9:   // of multiplying Width by Length
10:   unsigned short int Area = Width * Length;
11:
12:   std::cout << "Width: " << Width << "\n";
13:   std::cout << "Length: " << Length << std::endl;
14:   std::cout << "Area: " << Area << std::endl;
15:   return 0;
16: } ```

Output

```Width: 5
Length: 10
Area: 50```

Analysis

Line 1 includes the required include statement for the iostream's library so that cout will work. Line 3 begins the program.

On line 5, Width is defined as an unsigned short integer, and its value is initialized to 5. Another unsigned short integer, Length, is also defined, but it's not initialized. On line 6 the value 10 is assigned to Length.

On line 10 an integer, Area, is defined, and it is initialized with the value obtained by multiplying Width times Length. On lines 12 through 14 the values of the variables are printed to the screen. Note that the special word endl creates a new line.

Ending a Line

endl stands for end line and is end-L rather than end-one. It is commonly pronounced "end-ell."