CS Theory
C++ Tutorial 2
Variables And I/O
Previously, we wrote a program which printed a string to standard output. While we might find it useful to display some text occasionally, that program did very little in the way of "computing", and so today we will introduce the concept of variables. Variables provide us a convenient way of storing data, numbers, letters, pictures, etc. One of the crucially important things about the C++ language is that it separates data into different "types" where each of those types provide different ways for the programmer to interact with it. In C++, there are three basic types. The first type is called the "int" which allows us to store and manipulate integers, the second type is called a "float" which stores floating point numbers (numbers with decimal places), and finally "chars" which allow us to interact with characters. Consider the following code:
using namespace std;
int main()
{
cout << "x = " << x << endl;
x = 100;
cout << "x = " << x << endl;
cin.get();
return 0;
The first few lines of code:
using namespace std;
int main()
{
Should be familiar from the last tutorial. But the next couple of lines are probably unfamiliar:
cout << "x = " << x << endl;
x = 100;
cout << "x = " << x << endl;
The first line of code in this section initializes the integer "x" to the value 10. The word "int" is a keyword which C++ requires to create a variable. The letter "x" which follows immediately after "int" is the name of the variable. This variable is set to 10. "int" is short for "integer" so we can use this variables to store values like -100, 0, 100, 123, etc. We can use variables pretty much the same way we might use the values, called literals, that they are set to.
For example the line immediately after prints "x = 10" to the standard output. No where in this program do we print out literals - only variables.
Variables can also be set to another variable from what we initially set it to(assignment). After displaying, "x = 10" we then assign x the value 100. The following line might be a bit confusing. The exact same line of code which previously displayed "x = 10" now displays "x = 100". The reason for this behavior is because we have changed the value of x. In a program this simple, it's not too hard to keep track of the variables, we only have one, and the changes aren't too complicated, but more complicated programs are composed of almost exclusively variables, not constants, and their relationships.
The last two lines of code are the same as from before.
Arithmetic Operators
Because we are starting to look at variables, we need to understand in what
ways we can manipulate their data. There are many operators in C++. For the
purposes of this tutorial and subsequent tutorials, we will be using the
"Arithmetic Operators" except where otherwise specified. These operators work
on data in a mathematically. In other words, the same operations which you
learned about in middle school are still relevant here. A quick list is contained in
this tutorial, and a more complete list can be found in the reference page.
- + Addition operator
- - Subtraction operator
- * Multiplication operator
- / Division operator
- % Modulus operator (integer division)
Floating Point Variables
In this example, we will take user input, process that data into something useful, and print the result. This example converts meters into feet. Since meters can be fractional, unless you want to convert .5m to 50 cm but that is much more work, and since the conversion factor is also fractional we cannot use integers. "Float" is a computer science term which is short for "floating point number", which is a rather pedantic way of describing fractional numbers - numbers with decimal places. Although there are corner cases when dealing with floating point numbers, in general we can treat them in the same way as we do with integers; the only difference is that we use the keyword "double" instead of "int".
using namespace std;
int main()
{
double meter;
cout << "Enter a quantity of meters and press ENTER:";
cin >> meter;
cout << "Which is equals: " << (meter * factor) << " feet" << endl;
cin.get();
cin.get();
return 0;
This time we will skip over the boilerplate and jump ahead to the interesting parts.
The line:
Means that the user must enter a value for the variable meter, which we left undefined at the beginning of the program and could be anything, before the program can continue. Effectively, everything else is on pause until after the user enters a number and presses "enter".
The next line of interest is:
We've previously seen "cout" and "<<" in our programs before, but we have not seen so many statements chained together like this. In fact, we can chain as many of these together as we want. In the first program we could have written:
And achieved the same results. In this program, we take two doubles, meter and factor, and multiply them together using the "*" operator. Operators are crucially important for manipulating data and we will explore them more closely as we progress.
The next two lines of code:
cin.get();
Occur twice. Both lines do the same thing, but Visual Studio will count the time that the user presses "ENTER" as a key press. This means that the data will be processed, printed to the console, and the console closed too fast to read. If you are developing on OS X or Linux, you may wish to remove one of these lines of code for convenience. The final two lines of code are still boilerplate at this point.
The type "double" belongs to a classification of data types called "floating point numbers". The commonality of these data types is the ability to operate on numbers which have fractional parts. Essentially, any number which has a decimal point, such as: .5, 3.14, -.100, -.001, or could contain a decimal point after an operation such as 1 over 3, which would roughly equate to .3, must be expressed as a floating point number. Technically C++ has quite a few ways of doing this, but the two data types which you will most frequently see in this type of application are "double" and "float". In this example, you can use the word "float" anywhere in the code where you see the word "double" and not notice a difference.
The real difference between doubles and floats is measured by something called "precision". In short, this metric refers to the how many digits can be represented after the decimal point. The more digits after the decimal point, the more memory is required, doubles take up twice as much space in memory as floats - hence the name, and generally more precision also means that computations will be slower. There are occasions where we do not need any precision, 0 digits after the decimal point, and on occasions such as these it is much easier and simpler to use "integers". We will explore those more in the next tutorial.
Strings And Type Casting (Conversion)
At this point, we have already established that it is possible to print strings like "Hello World" to the console, and we just learned in the meters to feet example that it is possible to print a number that we have manipulated to the console. It is also possible to convert between these types of data. As it turns out, converting data types is a very common operation and in the nature of brevity is almost always called "casting". Casting can be extremely useful, but frequently introduces headaches to programmers since operations are not always interchangeable between types.
#include <string>
using namespace std;
int main()
{
int b = 0;
cout << "Enter a number" << endl;
cin >> a;
cout << "Enter another number" << endl;
cin >> b;
cout << "Adding" << a << " and " << b << " yields " << (a + b) << endl;
string aStr = to_string(a);
string bStr = to_string(b);
cout << "Concatenating:"<< aStr<< " and "<<bStr<<" yields:"<< (aStr + bStr) << endl;
return 0;
If we look at the second line of code:
It might seem a little familiar. If we write "#include" In a program, we are telling C++ that we need to include additional file containing code in order to work. In this case, the name of the file which we need is called "string" and all of the code that we need is written for us and can be called when we use this one line of code. The same is also true for the first line of code, but until now it wasn't worth mentioning what this line of code does. At this point, all of our code will be contained in one file but we will explore this concept in greater depth later on.
Now skipping ahead to the less familiar parts of the code we have two line in particular:
int b = 0;
In the last example, we saw doubles for the first time. In this example we are going to use integers. For the most part, we can use integers like we did with doubles, just remember that if you try to divide a number you may end up losing some data. For example, 3 / 2 would simply be represented as 1. Whenever you want to use an integer data type you can simply use the key word "int".
The next four lines of code:
cin >> a;
cout << "Enter another number" << endl;
cin >> b;
Are functionally very similar to the input/output we saw in the previous example. The only big difference is that this code can only accept integer inputs, but feel free to try using floating point numbers to see what happens.
The next line:
Prints a string, each of the two variables, and their sum. If you look closely at the end of this line might notice an operation, a + b, in parenthesis. Technically, you may omit the parenthesis, but they are generally helpful when reading a complicated expression like this. The important take away here is that we can evaluate an expression like a + b in a cout statement and print the expected result.
The next three lines of code are quite interesting:
string bStr = to_string(b);
cout << "Concatenating:"<< aStr << " and " << bStr << " yields:" << (aStr + bStr)<< endl;
The first thing that you should notice is that we are working with a new type. Previously, we've talked about strings and used them to print to standard output. This is the first time we have used a string as a variable. Unlike integers and doubles, strings and the data which they hold do not pertain to a mathematical quantity. Not in the way you're used to at least.
But the most interesting thing is probably what happens when we run the code above. The expected output is probably the sum of the two numbers. But if you run the program and input several different values you notice that this is not the case. This is a process called "concatenation". Concatenation is an operation which takes a string and a second string to the end. This operation is not commutative, meaning that the order of operands will change the output, which you might still expect considering that this operation shares the same operator as the familiar addition operator.
Here's an example that uses strings of characters instead of strings of numbers. We can use strings of numbers just as easily as strings of characters, but strings of characters are certainly easier to read. Also notice that we can put two, or three, or more operations in the same expression in the last cout satement.
#include <string>
using namespace std;
int main()
{
string b = "world";
cout << (a + b) << endl;
cout << (b + a) << endl;
cout << (a + " " + b) << endl;
return 0;
Concatenation is an important concept and we will certainly use them throughout the remainder of this tutorial. There are many additional types which we can use in C++ and many other operations which we have not used yet. More important though is that you take away the idea that different data types represent different things inside of a program and we have to use different approaches develop different strategies in order to use them. But before we move on, it's important to establish some ground rules about variables. These rules are universal in C++ regardless of what type we use. Variables, of any type, must start with a letter. The letter can be upper or lower case, but it cannot be a number and it generally cannot be a symbol. You may find it helpful to put an underscore, "_", in a variable name which contains two words since in C++ you cannot use spaces inside of a variable name. Additionally, variable names cannot match a keyword. Two variables cannot share the same name even if they are of the same type. And although it's unrelated to variable names, the value you are assigning a variable must match its type. Here are some example variable names and assignments that are not allowed in C++ and will probably cause whatever compiler you are using to shut down.
int 0x0F = 15;
int double = 10;
int = .0001;
double = "This is a string";