C++ Programming Tutorial for Beginners: Learn in 2 Hours

What is C++?

C++ is a general-purpose programming language. It was created by Bjarne Stroustrup at Bell Labs circa 1980. C++ is very similar to C (invented by Dennis Ritchie in the early 1970s). C++ is so much compatible with C that it will probably compile over 99% of C programs without changing a line of source code. Though, C++ is a lot well-structured and safer language than C as it OOPs based.

Some computer languages are written for a specific purpose. Like, Java was initially devised to control toasters and some other electronics. C was developed for programming OS. Pascal was conceptualized to teach proper programming techniques. But C++ is a general-purpose language. It well deserves the widely acknowledged nickname “Swiss Pocket Knife of Languages.”

Popular programming languages in use?

Popular languages that are mainly in use are Java, C++, Python, and C.

Lower level languages like

  • Assembly Language
  • C
  • C++

These languages force the programmer to think more about the problem in computer programming terms and its implementations, instead of the business logic.

As you can see despite being old, C++ is relatively popular still today which is a feat in and its own. The graph is from stackoverflow.com

Is C++ best programming language?

The answer depends on perspective and requirements. Some tasks can be done in C++, though not very quickly. For example, designing GUI screens for applications.

Other languages like Visual Basic, Python have GUI design elements built into them. Therefore, they are better suited for GUI type of task.

Some of the scripting languages that provide extra programmability to applications. Such as MS Word and even photoshop tend to be variants of Basic, not C++.

C++ is still used widely, and the most famous software have their backbone in C++.

Who uses C++?

Some of today’s most visible used systems have their critical parts written in C++.

Examples are Amadeus (airline ticketing)

  • Bloomberg (financial formation),
  • Amazon (Web commerce), Google (Web search)
  • Facebook (social media)

Many programming languages depend on C++’s performance and reliability in their implementation. Examples include:

  • Java Virtual Machines
  • JavaScript interpreters (e.g., Google’s V8)
  • Browsers (e.g., Internet Explorer, Mozilla’s Firefox, Apple’s Safari, and Google’s Chrome)

Application and Web frameworks (e.g., Microsoft’s .NET Web services framework).

Applications that involve local and wide area networks, user interaction, numeric, graphics, and database access highly depend on C++ language.

5 Basic Concepts of C++

C++ Variables

  • Variables are the backbone of any programming language.
  • A variable is merely a way to store some information for later use. We can retrieve this value or data by referring to a “word” that will describe this information.
  • Once declared and defined they may be used many times within the scope in which they were declared.

C++ Control Structures

  • When a program runs, the code is read by the compiler line by line (from top to bottom, and for the most part left to right). This is known as “code flow.
  • When the code is being read from top to bottom, it may encounter a point where it needs to make a decision. Based on the decision, the program may jump to a different part of the code. It may even make the compiler re-run a specific piece again, or just skip a bunch of code.
  • You could think of this process like if you were to choose from different courses from Guru99. You decide, click a link and skip a few pages. In the same way, a computer program has a set of strict rules to decide the flow of program execution.

C++ Data Structures

Let’s use a list of courses on “guru99” as the example! You probably have a list of courses in front of you. But how do you think they stored that. There can be a lot of courses, and different users may register for different courses. Do they generate a different variable for each user? For example, let’s say we need to keep track of 10 courses.

First, the WRONG WAY:

If we need to store 10 courses, we would probably define 10 variables, right?

Wrong.

In the world of programming, this is just a horrible way of trying to store 10 different variables. This is because of two main reasons:

  • The huge amount of text that you’ll need to write in your program. Sure, right now we only have 10 courses, so it’s not too bad, but what if we had 1,000 courses! Imagine typing that out a thousand times! Forget about it!
  • The flexibility. Adding another course would need manual edits to the code. We would have created variable course11. This is just crazy!

So, what is the RIGHT WAY?

Storing them in data structures.

data structure is a great way to get around having to create thousands of variables. C++ contains many types of inbuilt data structures. Most often used is arrays which will be taught later.

C++ Syntax

The syntax is a layout of words, expression, and symbols.

Well, it’s because an email address has its well-defined syntax. You need some combination of letters, numbers, potentially with underscores (_) or periods (.) in between, followed by an at the rate (@) symbol, followed by some website domain (company.com).

So, syntax in a programming language is much the same. They are some well-defined set of rules that allow you to create some piece of well-functioning software.

But, if you don’t abide by the rules of a programming language or syntax, you’ll get errors.

C++ Tools

In the real world, a tool is something (usually a physical object) that helps you to get a certain job done promptly.

Well, this holds true with the programming world too. A tool in programming is some piece of software which when used with the code allows you to program faster.

There are probably tens of thousands, if not millions of different tools across all the programming languages.

Most crucial tool, considered by many, is an IDE, an Integrated Development Environment. An IDE is a software which will make your coding life so much easier. IDEs ensure that your files and folders are organized and give you a nice and clean way to view them.

How to Download and Install C++ on Windows

Step 1) First you must download the Dev C++ on your Windows machine. http://www.bloodshed.net/dev/devcpp.html

Step 2) There are packages for different Operating Systems.

Step 3) Under package Dev-C++ 5.0 beta 9.2 (4.9.9.2) (9.0 MB) with Mingw/GCC 3.4.2 Click on the link ” Download from SourceForge”.

Step 4) This package will download .exe file for Windows that can be used to install on Windows 7/8/XP/Vista/10.

Step 5) You will direct to SourceForge website, and your download will start automatically.

  • Click on save button to save. By default, it is saved in “Downloads” folder.
  • After the download completes, go to the saved .exe file and click on it to Run.
  • The installer will ask you a language to select. Select “English” and click on “OK”.
  • Then screen for license agreement will appear. Click on “I agree” to proceed further.

Step 6) In this step,

  1. You can see different components of Dev C++ that will be installed with this package.
  2. Just click on “next” button.

Step 7) In this step,

  1. By default, the destination folder is in C drive. You are free to change this destination folder but make sure you have enough memory.
  2. Click on “Install” button.

In the next screen, installation begins

Now, Dev C++ is installed successfully on your Windows. Select ” Run Dev C++” to run it and click on ” Finish” button.

That’s it! Now you are ready to compile your C or C++ programs with Dev C++ compiler.

C++ Hello World Program

If this is your first time running C++, you will see the following screen.

Step 1) Select create the cache now option.

You should see a screen something like this

In some computers and operating systems, it asks whether to include all the libraries. If the option is selected, it will install all the libraries.

Step 2) Once the program opens, you need to create a new source file, so you can start writing your first program. To do this select File > New > Source File. The path is shown in the figure below.

This will open an area where you be able to type out your code.

Step 3) After that you can write the code as shown in the image below:

Code:

#include<iostream>    
using namespace std;    

int main()    
{    
    cout<<"Hello World"<<endl;    
    return 0;    
}    

Step 4) In this step,

Click on Execute->compile & run

Step 5) Save the file

After saving you should a black screen outputting “Hello World.”

First Program Explanation

C++ is a compiled language. The source code is compiled into object files. Object files are then combined by a linker creating an executable program.

A production C++ consists of many source code files (usually called source files).

  • Curly braces, {}, express grouping in C++. Here, they indicate the start and end of the function body.
  • Every C++ program has exactly one global function named main (). The program starts by executing that function. An int value is returned by main (), which it passes to the system.’ If no value is returned, then the system will receive a value 0 thus indicating successful completion. A nonzero value from the main () function indicates failure.

Explanation of Code

Code line 1: The first line is #include <iostream>. It instructs the compiler to include the standard stream I/O library. Without this header inclusion the expression would not compile

std::cout << "Hello, World"<<endl

Code line 4: int main().This is the main function of the program. Functions are denoted by the parentheses(). Before the main function is “int”. This means that the main function will return an integer to the function or process that called it.

Don’t worry about this, for the time being, simply note that the program must return an integer before the end. The curly braces, { and }, contain the code within a function. The program terminates, at the end of the main function denoted by }

Code line 6: The operator << writes its second argument onto its first. In this

case, the string literal “Hello, World!” is written onto the standard output stream std:: cout.

(Note: A string literal is a sequence of characters surrounded by double quotes. endl inserts a newline character on the same line)

Code line 7: return 0; This is the last command in the main function, the return statement. Its purpose is only to return a value to the function or process that called the main function. Don’t worry about this other than the fact that it is required by the “int” in front of the main function definition. It should return a zero from the main function meaning the program ran successfully and exited.

cout<<"Hello World"<<endl;

Note: Cout is a stream which outputs to the stream specified. It is by default the standard output stream. Cout is very common in programs as the ultimate motive in every program is to give some output. endl; represents the end of statements in C++. The semicolon in C++ separates different statements and must be put at the end of statements in C++.

Variable Types

C++ defines a whole set of primitive types

The void type has no associated values with it and can be used in only a few circumstances. It is most commonly as the return type of functions that do not return a value.

The arithmetic types include characters, integers, Boolean values, and floating-point numbers. Arithmetic type if further divided into 2 categories

  1. Floating-point types. The float (or floating type) represent decimal numbers. The IEEE standard specifies a minimum number of significant digits. Most compilers usually provide more precision than the specified minimum. Typically, floats are represented in by 32bits, doubles in 64 bits, and long doubles in either 96 or 128 bits.
  2. Integral types (which include character, integers, and Boolean types). The Boolean type has only two types of values: True or False. There are several char types, most of which exist to support internationalization. The most basic character type is char. A char is the same size as a single machine byte meaning a single byte.

The Integral types may be signed or unsigned.

Signed Type: They represent negative or positive numbers (including zero). In a signed type, the range must be evenly divided between +ve and -ve values. Thus, an 8-bit signed char will hold values from –127 through 127.

Unsigned Type: In an unsigned type, all values are >= 0. An 8-bit unsigned char can contain 0 through 255 (both inclusive).

C++ Variable

A variable provides us with a named storage capability. It allows programmer to manipulate data as per the need. Every variable in C++ has a type. The variable type helps to determine the size and layout of the variable’s memory map, the range of values that can be stored within that memory, and the set of operations that can be applied to it.

Variable Name or Identifiers

Identifiers can be composed of some letters, digits, and the underscore character or some combination of them. No limit is imposed on name length.

Identifiers must

  • begin with either a letter or an underscore (‘_’).
  • And are case-sensitive; upper and lowercase letters are distinct:

// defines four different int variables

int guru99, gurU99, GuRu99, GURU99;

The C++ language has reserved some names for its use.

There are many accepted conventions for naming variables in different programming languages. Following these conventions can improve the readability of the program.

  • An identifier should give at least some indication of its meaning.
  • Variable names are usually lowercase—guru99, not Guru99 or GURU99.
  • The classes we define usually begin with an uppercase letter.
  • Identifiers that contain multiple words should visually distinguish every word. For example, guru99_website not guru99website.

Variable declaration and definition

A declaration of a variable makes a name known to the program in the scope in which it is defined. Example:

int a=5;
int b;
char c='A'; 
int a,b;
a=b=1000;
List initialization
int a(5);
int b{5};

The const qualifier

Suppose there is a variable buffsize which states the number of inputs to be taken from the user. Here, we don’t want to change the value of buffsize throughout the program. We want to define a variable whose value we know should not change.

In such case, use the keyword const

const int bufSize = 512;    // input buffer size

This defines bufSize as a constant. Any attempt to assign to or change bufSize gives an error.

Here, we can’t change the value of a const object after we create it, it has to be mandatory be declared and initialized. Otherwise compiler throws an error.

const int i = get_size();  // ok: initialized at run time
const int j = 42;          // ok: initialized at compile time
const int k;               // error: k is uninitialized const
int i = 42;
const int ci = i;    	   // ok: the value in i is copied into ci 

Scope of a Variable

A scope is a span of a program where a variable has a meaning. Mostly the same name can be used to refer to different entities within different scopes. Variables are visible from the point where they are declared until the end of the scope in which their declaration appears.

#include <iostream>	
int main()	
{	
    int sum = 0;	
    // sum values from 1 through 10 inclusive	
    for (int val = 1; val <= 10; ++val)	
        sum += val;  // equivalent to sum = sum + val	
    cout << "Sum of 1 to 10 inclusive is "<< sum <<endl;	
    return 0;	
}	 

This program defines 3 names, viz, main, sum, and val. It uses the namespace name std, along with two other names from that namespace—cout and endl.

  • The function name “main” is defined outside the curly braces. The function name main—like most other names defined outside a function—has a global scope. Which means that once declared, names which are at the global scope are accessible throughout the program.
  • The variable sum is defined within the scope of the block which is the body of the main function. It can be accessed from its point of declaration and throughout the rest of the main function’s body. However,not outside of it. This means that variable sum has block scope.
  • The variable val is defined in the scope of “for statement”. It can easily be used in that statement but not elsewhere in the main function. It has local scope.

Nested Scope

The scope can contain other scopes. The contained (or nested) scope is referred to as an inner scope. The containing scope is the outer scope.

#include <iostream>	
using namespace std;	
// Program for illustration purposes only: It is bad style for a function	
// to use a global variable and also define a local variable with the same name	
int reused = 42;  // reused has global scope	
int main()	
{	
    int unique = 0; // unique has block scope	
    // output #1: uses global reused; prints 42 0	
    cout << reused << " " << unique << endl;	
    int reused = 0; // new, local object named reused hides global reused	
    // output #2: uses local reused; prints 0 0	
    cout << reused << " " << unique << endl;	
    // output #3: explicitly requests the global reused; prints 42 0	
    cout << ::reused << " " << unique << endl;	
    return 0;	
}	 

Output #1 appears before the local definition of reused. Thus, this output

statement is the one which uses the name reused that is defined in global scope. This statement outputs

42 0

Output #2 occurs after the local definition of reused. It is now in scope. Therefore, this second output statement simply uses the local object named reused rather than global one and outputs

0 0

Output #3 overrides the default scoping rules using the scope operator. The global scope has no name. Thus, when the scope operator(::) has an empty left-hand side. It interprets it as a request to fetch the name on the right-hand side of the global scope. Thus, the expression uses the global reused and outputs

42 0

Variable Type Conversion

A variable of one type can be converted into another. It is known as “Type Conversion.” Let’s see the rules for converting different variables types:

Assigning of non-bool to a bool variable yields false if the value is 0 and true otherwise.

bool b = 42;            // b is true

Assigning of a bool to one of the other arithmetic types yields 1 if the bool is true and 0 if the bool is false.

bool b = true;
int i = b;              // i has value 1

Assigning a floating-point value to a variable of int type yields the value which is truncated. The value that is stored is the part before the decimal point.

int i = 3.14;               // i has value 3

Assigning of an int value to a variable of float type results in the fractional part becoming zero. Precision is usually lost if the integer has more bits than the floating variable can accommodate.

Int i=3;
double pi = i;          // pi has value 3.0

If we try to assign an out of range value to a variable of unsigned type, the result is the remainder of the value %(modulo)

For example, an 8-bit unsigned char type can hold values from 0 through 255, inclusive. Assigning a value outside this range will result in the compiler assigning the remainder of that value modulo 256. Therefore, by the logic above, assignment of –1 to an 8-bit unsigned char gives that object the value 255.

unsigned char c = -1;   // assuming 8-bit chars, c has value 255

If we try to assign an out-of-range value to an object of signed type, the result is unpredictable. It is undefined. The program might appear to work on the outside, or it might crash, or it might produce garbage values.

signed char c2 = 256;   // assuming 8-bit chars, the value of c2 is undefined

The compiler applies these same type of conversions when we use a value of one type where a value of other type is expected.

int i = 42;
if (i) // condition will evaluate as true
i = 0; 

If this value= 0, then the condition is false; all other (non-zero) values yield true. By the same concept, when we use a bool in an arithmetic expression, its value is always converted to either 0 or 1. As a result, using a bool in an arithmetic expression is usually almost surely incorrect.

Caution: Don’t Mix Signed and Unsigned Types

Expressions that mix signed and unsigned can yield surprising and wrong results when the signed value is negative. As discussed above signed values are automatically converted to unsigned.

For example, in an arithmetic expression like

x* y

If x is -1 and y is 1, and if both x and y are int, then the value is, as expected, -1.

If x is int and y are unsigned, then the value of this expression depends on how many bits an integer has on the compiling machine. On our machine, this expression yields 4294967295.

Register Variables

Registers variables are faster to access compared to memory variables. So, variables which are frequently used in a C++ program can be put in registers using register keyword. The register keyword tells the compiler to store the given variable in a register. It’s compiler’s choice whether to put it in a register or not. Generally, compilers themselves do various optimizations which include putting some of the variables in the register. There is no limit on the number of register variables in a C++ program. But the compiler may not store the variable in a register. This is because register memory is very limited and is most generally used by the OS.

To define:

register int i;

Comments

Comments are the portions of the code ignored by the compiler. It allows the programmer to make notes in the relevant areas of the source code/program. Comments come either in block form or single lines. The program comments are explanatory statements. It can be included in the C++ code which helps anyone reading its source code. All programming languages allow some form of comments. C++ supports both single-line and multi-line comments.

  • Single-line comments are the ones which start with // and continue until the end of the line. If the last character in a comment line is a \ then the comment will continue in the next line.
  • Multi-line comments are the ones which start with /* and end with */.
/* This is a comment */
/* C++ comments can  also 
* span multiple lines 
*/

Escape Sequences

Some characters, such as backspace and control characters, have no visible image. Such characters are known as non-printable characters. Other characters (single and double quotation marks, question mark, and backslash) have special meaning in the many programming languages.

Our programs are not able to use any of these characters directly. Instead, we can use an escape sequence to represent such char. An escape sequence begins with a backslash.

The C++ programming language defines several escape sequences:

What does it do?

Character

Newline

\n

Vertical tab

\v

Backslash

\\

Carriage return

\r

Horizontal tab

\t

Backspace

\b

Question mark

\?

Formfeed

\f

Alert (bell)

\a

Double quote

\”

Single quote

\’

We use an escape sequence as if it were a single character:

cout << '\n';        // prints a newline
cout << "\tguru99!\n";   // prints a tab followed by "guru99!" and a newline 

We can also write generalized escape sequences \x followed by one or more hexadecimal digits. Or we use a \ followed by one, or two, or three octal digits. The generalized escape sequence represents the numeric value of the character. Some examples (assuming the Latin-1 char set):

\7 (bell)    \12 (newline)      \40 (blank)
\0 (null)    \115 ('M')         \x4d ('M') 

We can use pre-defined escape sequences, as we are using any other character.

cout << "Hi \x4dO\115!\n";  // prints Hi MOM! followed by a newline
cout << '\115' << '\n';     // prints M followed by a newline