Search This Blog

Loading...

How to Assign Values to 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. The essential difference is that initialization takes place at the moment you create the variable.
Just as you can define more than one variable at a time, you can initialize more than one variable at creation. For example:
// create two long variables and initialize them
Ă‚long width = 5, length = 7;
This example initializes the long integer variable width to the value 5 and the long integer variable length to the value 7. You can even mix definitions and initializations:
int myAge = 39, yourAge, hisAge = 40;
This example creates three type int variables, and it initializes the first and third.
Listing below shows a complete program, ready to compile, that computes the area of a rectangle and writes the answer to the screen.

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
10: // of multiplying Width by Length
11: unsigned short int Area = Width * Length;
12:
13: cout << "Width:" << Width << "\n";
14: cout << "Length: " << Length << endl;
15: cout << "Area: " << Area << endl;
16: return 0;
17: }


Output: Width:5
Length: 10
Area: 50


Analysis: Line 2 includes the required include statement for the iostream's library so that cout will work. Line 4 begins the program.
On line 6, 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 is not initialized. On line 7, the value 10 is assigned to Length.
On line 11, an unsigned short integer, Area, is defined, and it is initialized with the value obtained by multiplying Width times Length. On lines 13-15, the values of the variables are printed to the screen. Note that the special word endl creates a new line.

No comments:

Post a Comment