Lesson 2: Basic Variables, Calculations, and Comments in C++

2.1 Variables

One of the major parts of almost all programming languages is the variable. In C++, variables are like containers that hold a certain value. Variables have three components:

  1. Identifier (or variable name)
  2. Data type
  3. Value

The identifier of a variable is the variable's name. It's what you call it within your program.

The data type, as the phrase suggests, is the type of data that the variable can hold. For example, some variables can contain integers (e.g., 1, 2, 3), others contain characters (e.g., 'a', 'b', 'c'), some contain real numbers (e.g., 1.0, 1.4, 5.3, -2.3), some contain strings (e.g., "John", "Horse", "House", "chicken", "asdfgh123"), and as we will see in later chapters, there are many other data types that we can work with.

The value is what the variable actually holds. Sometimes the best way to understand a concept is to see an example. So, let's say we want to have a variable named numberOfDollars. Let's say we want its value to be 500. So, since we want a variable that represents the number of an item (in our case, dollars), we require an integer.

So here's what we know:

  1. Identifier : numberOfDollars
  2. Data type: int
  3. Value: 500

In C++, we write it like this:

int numberOfDollars = 500;
 

Notice the equals sign ( = ). In this case, we refer to it is the assignment operator. It takes two operands: a variable on the left side (numberOfDollars) and a value (500) on the right side.

There is another way we can assign a value to a variable that is slightly different than the example above.

int numberOfDollars;
numberOfDollars = 500;
 

Notice in this particular example, we declare the variable numberOfDollars without assigning it a value.  Then, in another statement, we assign the value 500 to the variable numberOfDollars.

In the first example, we declared the variable and assigned the variable a value all in one line.

2.2 Some Primitive Data Types

Primitive data types in C++ are built into the language itself. These data types typically represent simple character data and numbers.

You will discover in later lessons that there are more complex data types that are not built in to the C++ language itself, but rather designed and implemented by other programmers.

2.2.1 Review of Numbers

Some of the most basic data types are numbers. In C++, numbers are divided into different categories. These categories include integers, floats, and doubles.

Before we discuss what an integer is, we need to know another group of numbers known as natural numbers. Natural numbers (also known as counting numbers) are the numbers that you count with. For our purposes, we will include 0 in the natural numbers. Thus, the natural numbers are 0, 1, 2, 3, 4, ...

Integers are the natural numbers and their negatives: ... -3, -2, -1, 0, 1, 2, 3, ...

Floating point numbers, or floats are typically 4 byte (32 bit) numbers that can have a decimal point.

Doubles are typically 8 byte (64 bit) numbers that can have a decimal point.

Examples of floating points and doubles include 3.0, -4.77, -3.14159, 465.5684, and many others.

2.2.2   Int data type

In C++, integers are represented by the int data type.  Below are some examples of the int data type in action:

int counter = 0;
int boxA = 450;
int boxB;
boxB = 200;
int boxTotal = boxA + boxB;
 

Notice, as we saw earlier, you can declare a variable, and assign a value to it all in one line (as is the case with int counter = 0; and also int boxA = 450;), or you can declare a variable in one line (int boxB;), and assign a value to it in another (boxB = 200;).

Another interesting thing to notice is that you can assign a variable (such as boxTotal) the value of another variable (or variables), such as in the statement

int boxTotal = boxA + boxB;
 

In the entire code segment that we saw earlier, this would mean that boxTotal would take on the sum of boxA and boxB.  Thus, since boxA is 450, and boxB is 200, boxTotal would contain the value 650.

2.2.2   Floats and Doubles

In C++, floats and doubles are numbers that can have a decimal point.  For example, the following are examples of declaring and assigning floats and doubles.

float A = 4.5;
float B = 2.5;
double C;
C = 1.5;
double D = 2.0;
double total = C + D + 2.0;
 

Notice that, just like integers, you can assign values to floats and doubles in the same statement as their declaration, or in separate statements.  Also, just like integers, you can assign a double or float variable with the values of other variables, such as in the statement:

double total = C + D + 2.0;

In this particular example, total is being assigned the sum of C, D, and a literal double.  While C and D are variables, 2.0 is a literal.

2.2.3   Characters

Unlike numbers, characters are the most fundamental unit of written language.  In C++, we symbolize characters by surrounding them with single quotes, defined as follows:

char myChar = 'a';
char myOtherChar;
myOtherChar = 'b';
char myNumberChar = '5';
 

In these examples, myChar, myOtherChar, and myNumberChar are all character variables.  Just like integers, floats, and doubles, you can declare a character variable and assign a value all in one statement, or in separate statements.

Notice the variable myNumberChar.  The 5 inside the quotes is not recognized by C++ as being the same as the integer 5.  So the following are different:

int myNumber = 7;
char myNumChar = '7';
 

2.3 Calculations

So far, in this lesson, we have examined the basic data types that C++ offers.  In this section, we will explore performing calculations with C++.

Code Sample 2.3-1

#include <iostream>
using namespace std;

int main()
{
	int int1 = 5;
	int int2 = 10;
	int int3;

	//sum the integers
	int3 = int1 + int2;

	/* print out the sum
	of the integers */
	cout<<"The sum of "<<int1<<" and "<<
		int2<<" is "<<int3<<endl;

	//multiply the integers
	int3 = int1 * int2;

	/* print out the product
	of the integers */
	cout<<"The product of "<<int1<<" and "<<
		int2<<" is "<<int3<<endl;

	return 0;
}

Code Sample 2.3-1 shows a program that performs a couple operations with integers.

Firstly, we declare three integers:

  • int1
  • int2
  • int3

Notice that we can use the word "int" as part of the variable name. We could not, however use "int" by itself as a variable name, because it is one of the reserved words (or keywords) of the C++ programming language. Namely, the data type of integers.

Next, we sum the integers int1 and int2, and store the result in int3. Then, we print out the two integers and their result in a cout<< statement.

Farther down in the program, you see that we can reuse the int3 variable. This second time, we store the product (the result of multiplication) in the variable int3. And, like the first section, we print out the product this time.

Figure 2.3-1

Figure 2.3-1 shows the output of Code Sample 2.3-1. As you can see, none of the comments are visible. Comments are explained in the next section.

However, before we move on, I will summarize and describe the basic mathematical operations that are available with C++ :

  • Addition  (using the + symbol.  For example, 5 + 4)
  • Subtraction (using the - symbol.  For example, 5 - 2)
  • Multiplication (using the * symbol.  For example, 4 * 2)
  • Division (using the / symbol.  For example, 4 / 2)
  • Modulus (using the % symbol.  For example, 4 % 2)

Most readers are probably familiar with addition, subtraction, multiplication, and division.  However, the modulus operator, %, is probably new to many readers.

Modulus is defined as the remainder of a division problem.  For example, here are the results of a few modulus operations:

  • 5 % 2 = 1, because 5/2 = 2 with a remainder of 1
  • 3 % 5 = 3, because 3 / 5 = 0 with a remainder of 3
  • 2 % 2 = 0, because 2/2 = 1, with a remainder of 0

One might ask how this is useful.  There are many situations in which a developer may want to know if a number is even or odd.

When we explore if-statements in a later lesson, you will see that we can execute a particular segment of code if certain conditions are true.  One such condition may be "if a number num is even".  How do we test this using C++?  Easy:

if (num % 2 == 0)
{
  //do something
}
 

Again, we have not yet explored if-statements in detail, but for now, let's focus on the condition num % 2 == 0.  What we're saying here is "If num yields a remainder of zero after being divided by 2, then it is even."

2.4 Comments

 Another important aspect of programming is the use of comments.  Comments are notes that programmers write within their source code that the compiler ignores during compilation.  They are primarily used to help the programmer (or a team of programmers) to know what is going on in the code.

While higher-level languages, like C++ and Java are closer to English than lower-level programming languages, like assembly language or machine code (which we saw in Lesson 1), they are still not always perfectly understandable.  Comments allow programmers to help explain sections of code so that they will understand what they were doing when they come back to a section of code, or, as is also common, so that their programming team will understand what they were doing.

In C++, there are two different types of comments.

  • C++ style comments (also called single line comments, denoted by // )
  • C style comments (also called multi-line comments or block comments, denoted by /*   */)

C++ style comments comment out anything following the double forward slashes ( // ) for the rest of the line on which the comment occurs.

C style comments (multi-line comments) on the other hand, start with a forward slash and then an asterisk (/*), and end with the mirror image (*/).  C style comments can be used for single lines, or multiple lines.

// These are C++ style comments (single line comments).
// I can comment several lines in a row
// but I have to make sure I put 
// slashes at the beginning of each line

/* this is a multi-lined comment
which can span more than one row
*/

/* this is a C style comment, but only on one line */

The above sample shows different ways to use comments.  Comments may not seem very important now, but as your programs become larger and more complex, they become significantly more important.  It is good programming practice to use comments and take advantage of their usefulness early on so you are comfortable with them.

A simple way to practice with comments is to put your name and the date at the beginning of your programs.  For example:

 

/*
    J.P. Baugh
    November 24, 2009
*/

#include <iostream>
using namespace std;

int main()
{
   cout<<"This is a basic program"<<endl;
   return 0;
}

2.5 Summary and Conclusions

 In this lesson, we explored basic built-in data types, calculations that can be performed on data types, as well as how to use comments to your advantage.

2.6 Exercises

 1.  Write a program that declares two variables of type double.  Name these two variables:

  • number1
  • number2

Have the program store the sum of these two numbers in a third double variable:

  • sumOfNumbers

Finally, have the program print (to the console) out the sum of the two original numbers that were stored in sumOfNumbers. 

HINT:  Use the following:

cout
 
 

2.  Add comments to the program in (1) that have your name at the very top of the program.

3.  Write another program involving characters.  In this program, create a variable of type char that stores the first letter of your first name.  Finally, print the character out to the console.

More by this Author


Comments 3 comments

Simon 6 years ago

thank you helped a lot ... didn't know i had to put the output variable first equals the others ... helped a lot thanks


Rosie 2 years ago

What a lovely, extremely-clear introduction to variables and calculations! Thanks so much for sharing! I like your style


Taranwanderer profile image

Taranwanderer 2 years ago

I am definitely going to need a computer programming book lol. Thanks for this tremendous intro - but I need more of a hand-hold instruction - http://hubpages.com/technology/Careers-in-Electron...

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working