This series of articles is developed from Storm Dragon's class.
Before you begin this lesson, please read these articles:
In order to use variables in a program, they must be declared.
The first order of business is to decide the scope of the variable: global or local. If the variable is needed for many different functions, it is declared prior to the code for these functions. Variables must be declared outside of the function in which they are used.
To declare a variable, we must know what kind of a variable it is. Here are some types of variables and what that type means:
You are probably familiar with these operators.
Note:The percent sign ("%") does not calculate percentages. It returns the remainder after division. For example:
10%3returns "1" because after dividing "3" into "10" there is a remainder of "1".
There are a couple of ways to write calculations in c++. We declare myNumber to be an unsigned integer:
int unsigned myNumber;We want to assign it a value of "3".
myNumber = 3;Now we want to increase myNumber by adding "5" to it. There are two ways to do this.
myNumber = myNumber + 5;or
myNumber += 5;
We can use are other operators in the same way. Note:The equals sign comes last.
To receive information from a user and put that information into a variable we can write the following statement using our variable "myNumber":
cin >> myNumber;
Best Practices:Variables are clearly named. The first word in a variable's name is lower case while the remaining words are upper case. For example:
It is not necessary to use "endl" with "cout" when you ask for user input. This is done automatically.
Hello,followed by the name entered. Be sure to have the final prompt appear on a separate line.