Learning C++ For Beginners

Jason Moore
11 min readJul 1, 2021

--

Learning C++ is a great way to improve your worth. In this article, I start with the basics and will show you how to get started.

Introduction

C++ is very popular and has been around a long time. It has had several different versions. Every 3–4 years or so a new version gets released.

It is very fast. It is fast because it is a low level language. Often it is the backbone of other program languages and major applications. Operating systems, games, and compilers use C++ as their foundation.

Use A Text Editor

A text editor is the best way to get started in learning C++. The reason why is that it is simple to set up and use. You can use an IDE, which stands for integrated development environment, but that just complicates things. So use an editor that you like and are comfortable with.

Popular editors include Vim, Nano, Emacs, Atom, Sublime Text, and VS Code. There are many others but you can’t go wrong with any of those. It will also depend on what operating system you use. I use both Linux and Windows. When I am on Linux I like Vim but when I am on Windows I prefer Atom.

Installing Compiler

You only need to do this if you are using Windows. If that is the case you want to install MinGW-64 and add it to your path. When installing, leave all the defaults. After it is installed, it is time to add it to your path variable in Windows. Browse your installation folder until you get to the “bin” folder. That whole path is what you want to add.

Here is a video I found that shows you, in case you get confused.

If you use Linux, it already comes with a compiler. You do not have to do anything. If you use Linux, I am automatically assuming you know how to use a terminal and run things. Just run “g++” and you can use the help system if you need to know options.

Compiling Your Program

Whichever operating system you are on, it is helpful to know what a compiler does. A compiler translates your c++ code into an executable. Indeed, every time you edit your code from your text editor, you have to re-compile your code.

After you write your code, you have to name the file with a “.cpp” extension. This indicates, to the compiler, that it is a c++ program.

First Program

Lets make the typical first program, so we can start this ball rolling! Type this in your editor:

#include <iostream>
using namespace std;

int main()
{
cout << “I love pokemon!!”;
return 0;
}

Name this something simple, like “first.cpp”. Then, in your terminal, navigate to the directory where you saved it at. You can list the files in this directories, you should see your file there. Then, on Windows, you can run:

g++ -o pokemon pokemon.cpp

This is how you compile your code.

Then type “pokemon” to run your program.

This will give your the console output of “I love pokemon”.

On linux, you compile the same way but you need to run the program differently. Type:

./pokemon

This will then run your code and give you the same output.

Structure Of A Program

C++ programs aren’t complicated at the first. However, there are a few parts to them that you need to know about. Every program is made up of:

  • header file(s)
  • namespace
  • main function

A header file is a library. It contains multiple namespaces and other code that allow the c++ programmer to use. You will encounter other functions that need a certain header file in order to work. When that happens, you use it in an “#include” statement.

The namespace is a section of our “iostream” header file. It contains certain functions and code. The one we are using is the “std” namespace. It stands for “standard”. You can manually designate the namespace for a command if you want to.

For instance, if you don’t want to include a header file, you can just define the namespace for any command that needs it.

I should mention that many people advise not to define a namespace at the beginning of your code. However, that only matters later on. At the very beginning, it does not matter.

That is why I do it here. When it matters to you, go ahead and do it manually for objects that you use.

Next is the main function. Every program has one. A program can have many functions but it has to have the main one at the very least.

A function is a block of code that does something. It can output a line of text to the console or call a series of functions.

The “int” in front of main means integer. This defines the main function. It says the main function will return an integer. Indeed, the last line of the function says “return 0”.

So, it returned an integer and all is good. Every function must return a value. The kind of value it returns is in the function definition.

Now, if we have this line:

cout << "I love pokemon";

You will notice the semicolon at the end. This has to be done at the end of every c++ statement. It tells the compiler that this is the end of a statement.

Let us go over some more code now to see all this in action again. Specifically, I want to show you how to deal with lines.

#include <iostream>
using namespace std;
int main()
{
cout << "darkrai and vileplume are my favorite pokemon" << endl;
cout << " charizard is pretty cool too";
return 0;
}

In this small snippet, you can see I wrote two lines. If I want them to appear on two separate lines in the output, I have to use “endl”. This means to end the line and go to the next, in the output. You put a stream insertion operator “<<” in front of it.

You can also use the escape character sequence to go to the next line. Escape sequences do others things too, depending on which you use.

You will see more in the future. For now though, just know that you can use “\n” to skip a line too.

There are a few minor differences between “\n” and “endl” but at this stage they do the same thing. You use “\n” like this:

#include <iostream>
using namespace std;

int main()
{
cout << "I listen to music, too \n";
cout << "In fact, I like the groups: Big Bang, Super Junior, and 2pm ";
return 0;
}

The next thing I want to mention is comments. Comments are statements or notes to someone that are included in your code.

This is often done by developers who want to explain what they are doing in sections of their code. Let me give an example.

#include <iostream>
using namespace std;

int main()
{
// sending text to console
cout << "I miss playing the pokemon TCG";
return 0;
}

The highlighted section above is a comment. It starts with “//”. There are various ways to do this and I will go over other ways later.

So, anything on the line with “//” is ignored by the compiler. It is just a note and a good idea to use throughout your program.

Variables

Variables are very important in learning c++. They are used to hold values. Sometimes they can stay the same throughout a program or they can change.

It depends on you. To use a variable in c++, you have to declare it with a data type.

There are several different data types. They can include:

  • char
  • int
  • string
  • double
  • float
  • bool
  • const

There are also others but they are special cases or variations of the ones I just listed. These types go in front of a variable. That is declaring the variable. Here are some examples.

char type;
int number;
string name;
double regression;
float precision;
bool truth;

A “char” is just a single ascii character. It is not a numeric character, meaning you cant do calculations on it easily. It is anything in single quotes.

“Int” stands for integer and does not contain a decimal. It can be negative. Do all the math you want on these.

“String” is multiple characters, like a sentence. It is anything surrounded by double quotations. You can’t do numeric calculation on it easily. “Double” is another numeric type.

“Float” has a decimal and implies precision of a number. “Bool” is a logical operator and used for true or false operations.

Let’s get to some example now, so this is clearer. I will start with the usual “int” type.

#include <iostream>
using namespace std;

int main()
{
//variables
int x = 10;
int y = 15;

//output
cout << x + y;

return 0;
}

In these examples I used variables to do calculations. The highlighted section is where I declared an integer variable. i added the variables “x and y”. I declared these as integers so that mean I could perform calculations on them.

#include <iostream>
using namespace std;

int main()
{
//variables
int number = 10;

//output
cout << number * number;

return 0;
}

In the second example, I did a slightly different calculation. I declared my one variable. Then I printed to the console the result of multiplying the variable by itself.

It is time to try a “string” example now. To use this function, you must include the “string” header file. It won’t work right otherwise.

#include <iostream>
#include <string>
using namespace std;

int main()
{
// declare variables
string name = "darkrai is a dark pokemon";

//output
cout << name;

return 0;
}

In this example, we are simple printing to the console again. It is important to see how a “string” works, because it is different than an integer.

I want to mention that you need to declare a variable with the same type of data that you defined it with. For example, you can’t declare it with an integer value but give it a string value in double quotes. This will cause problems.

Getting User Input

Getting user input is very important. It is important because many types of programs are based off the input that a user gives you. For example, a calculator type program is like this. It depends on the input that a user gives you.

The Cin Object

There are various ways to get user input. Let’s start with the “cin” object. It stands for character input and it is the most basic way to get input.

It is used with the stream extraction character, “>>”, that is used directed after using “cin”. It is used with a space inbetween, just like the “cout” object does.

#include <iostream>
using namespace std;

int main()
{
//variable declarations
int num1, num2, num_out;

//directions to user
cout << "Enter two numbers you need to multiply together" << endl;
cout << "Please hit enter after each number" << endl;

// get user input
cin >> num1;
cin >> num2;

//calculation
num_out = num1 * num2;

//output
cout << "The answer is :" << num_out;
return 0;
}

In the above simple program, you can see how the “cin” object can be used. This is a sequential program, the program flows from top to bottom. You can see the order to things you want to do.

Basically, pretend the person to sitting in front of you and you ask them what they want. Tasks have to be done in a certain order so they make sense. Programming is no different.

We have to ask for input before we can out the answer. This may seem obvious, but many beginners have trouble with program logic. Hopefully, this way of thinking will help.

String Input

If you need to get input like a name, then you use a string. This is useful when you need one word that is character based. Here is a quick example.

string name;
cin >> name;
cout << name;

This is super simple and not practical, but shows how you initialize, request input, and print it to the console. Remember, it only takes character input. You can’t do calculations with string data.

Getline

Now, the problem is when you want to capture multiple words. Something like a sentence is what I am thinking of.

For that, we need to go back to “cin” and use one of its member functions. This member function is “getline”. It will capture a line of data.

getline(cin,name);

This will grab a line of input and put it into the variable that you designate. Let me do an example so it is clear.

#include <iostream>
#include <string>
using namespace std;

int main()
{
// variables
string name;

// get input
cout << "Please enter your full name" << endl;
getline(cin, name);

// output
cout << name;
return 0;
}

Again, this is simple but it shows how “getline” works. It is very useful. The more you learn, the more combinations we can use.

Many programs will use sequences like this to gather user input and do something with that data afterwards.

Doing Basic Math With C++

C++ has several options for doing math. To do calculations, choose the operator you need. An operator is the symbol that tells the compiler what action to take. Let me show some examples. I am not going to spend a lot of time here, it’s just basic math.

Math Operators

Here are the main mathematical operators:

  • +
  • -
  • *
  • /
  • %

Now, here are the operators in action. I did it all in one example but that should be understandable for anyone.

#include <iostream>
using namespace std;
int main()
{
// variables
int a=5;
int b=10;
int c,d,e,f,g=0;
// calculations
c = a + b;
d = a - b;
e = a * b;
f = b / a;
g = a % b;
// output
cout << "c = " << c << endl;
cout << "d = " << d << endl;
cout << "e = " << e << endl;
cout << "f = " << f << endl;
cout << "g = " << g << endl;
return 0;
}

You can copy that into your editor and compile. Play with it if you need and if you don’t understand something.

Min and Max Functions

These are useful functions later on. They are especially useful when you work on arrays, for example. These functions can analyze a series of numbers, like in an array, and output the largest and smallest of them. Below is a quick example.

#include <iostream>
using namespace std;
int main()
{
double a = 10;
double b = 15;
double x = 0;
double y = 0;
x = max(a,b);
y = min(a,b);
cout << "The highest value is " << x << endl;
cout << "The smallest value is " << y << endl;
return 0;
}

As you can see, I hardcoded two numbers into variables. I then had the <min> and <max> functions compare the numbers and tell me which was the largest and smallest.

Pow and Sqrt Functions

More nice math can be accomplished with these functions. The <pow> function reads a number with its exponent and evaluates it. The <sqrt> function does the opposite, it takes the square root of a number. Let’s look at another example.

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double A = 10;
double B = 2;
double C = pow(A,B);
double D = sqrt(C);
cout << "A to the B power is " << C << endl;
cout << "The square root of C is " << D << endl;
return 0;
}

Please notice that we had to use a new header for the pow function. It is the <cmath> header and is required. I first declared a couple variables with some values. Then I created variables to hold the <pow> and <sqrt> functions. I then displayed them to the console screen.

Thanks For Reading

I appreciate you reading this and wanted to thank you! I hope some of you will want to start learning c++ because of this article.

If you would like to join my newsletter you can do so here.

If you would like to read other articles I write then try here:

https://jason-46957.medium.com/

Originally published at https://aindien.com on July 1, 2021.

--

--

Jason Moore

I am a lover of math, astronomy, physics, and programming. I love writing and being outdoors also. You can connect with me at https://sciencebyjason.com.