Introduction to C++

C++ is a programming language which allow you to control your computer, making it do what you want it to do. This programming tutorial series is all about helping you to take full advantage of C++.

C++ Compilers

The very first thing you need to do, before starting out in C++, is to make sure that you have a compiler. What is a compiler, you ask? A compiler turns the program that you write into a executable that your computer can actually understand and run. If you’re taking a course, you probably have one provided through your school. If you’re starting out on your own, your best bet is to use Code::Blocks. Our page on setting up Code::Blocks will take you through setting up the Code::Blocks compiler in great detail.

Introduction to the C++

A C++ program is a collection of commands, which tell the computer to do “something”. This collection of commands is usually called C++ source code, source code or just code. Commands are either “functions” or “keywords”. Keywords are a basic building block of the language, while functions are, in fact, usually written in terms of simpler functions–you’ll see this in our very first program, below. (Confused? Think of it a bit like an outline for a book; the outline might show every chapter in the book; each chapter might have its own outline, composed of sections. Each section might have its own outline, or it might have all of the details written up.) Thankfully, C++ provides a great many common functions and keywords that you can use.

But how does a program actually start? Every program in C++ has one function, always named main, that is always called when your program first executes. From main, you can also call other functions whether they are written by us or, as mentioned earlier, provided by the compiler.

So how do you get access to those prewritten functions? To access those standard functions that comes with the compiler, you include a header with the #include directive. What this does is effectively take everything in the header and paste it into your program.

Let’s look at a working program:

#include <iostream>

using namespace std;

int main()
{

cout<<“Hello World!\n”;
cin.get();

}

The #include is a “preprocessor” directive that tells the compiler to put code from the header called iostream into our program before actually creating the executable. By including header files, you gain access to many different functions.

The next important line is int main(). This line tells the compiler that there is a function named main, and that the function returns an integer, hence int. The “curly braces” ({ and }) signal the beginning and end of functions and other code blocks. You can think of them as meaning BEGIN and END.

In C++, however, the cout object is used to display text (pronounced “C out”). It uses the << symbols, known as “insertion operators”, to indicate what to output. cout<< results in a function call with the ensuing text as an argument to the function. The quotes tell the compiler that you want to output the literal string as-is. The ‘\n’ sequence is actually treated as a single character that stands for a new line.

The next command is cin.get(). This is another function call: it reads in input and expects the user to hit the return key. Many compiler environments will open a new console window, run the program, and then close the window. This command keeps that window from closing.

Upon reaching the end of main, the closing brace, our program will return the value of 0 (and integer, hence why we told main to return an int) to the operating system. This return value is important as it can be used to tell the OS whether our program succeeded or not. A return value of 0 means success and is returned automatically (but only for main, other functions require you to manually return a value), but if we wanted to return something else, such as 1, we would have to do it with a return statement:

#include <iostream>

using namespace std;

int main()
{

cout<<“Hello World!\n”;
cin.get();

return 1;

}

C++ Comments

When you tell the compiler a section of text is a comment, it will ignore it when running the code, allowing you to use any text you want to describe the real code. To create a comment use either //, which tells the compiler that the rest of the line is a comment, or /* and then */ to block off everything between as a comment. Certain compiler environments will change the color of a commented area, but some will not. Be certain not to accidentally comment out code (that is, to tell the compiler part of your code is a comment) you need for the program. When you are learning to program, it is useful to be able to comment out sections of code in order to see how the output is affected.

Variables in C++

Variables are reserved memory locations which are used to store various information which means that some space in memory will be reserved for that variable.

A variable of type char stores a single character, variables of type int store integers (numbers without decimal places), and variables of type float store numbers with decimal places. Each of these variable types – char, int, and float – is each a keyword that you use when you declare a variable.

Using the right variable type can be important for making your code readable and for efficiency–some variables require more memory than others. Moreover, because of the way the numbers are actually stored in memory, a float is “inexact”, and should not be used when you need to store an “exact” integer value.

Declaring Variables in C++

Here are some variable declaration examples:

int x;
char letter;
float the_float;

It is permissible to declare multiple variables of the same type on the same line; each one should be separated by a comma.

int a, b, c, d;

If you were watching closely, you might have seen that declaration of a variable is always followed by a semicolon.

Common Errors when Declaring Variables in C++

If you attempt to use a variable that you have not declared, your program will not be compiled or run, and you will receive an error message informing you that you have made a mistake. Usually, this is called an undeclared variable.

#include <iostream>

using namespace std;

int main()
{

int thisisanumber;

cout << “Please enter a number: “; cin >> thisisanumber;
cin.ignore();
cout << “You entered: ” << thisisanumber << “\n”;
cin.get();

}

if Statement in C++

The ability to control the flow of your program, letting it make decisions on what code to execute is valuable to the programmer. The if statement in c++ allows you to control if a program enters a section of code or not based on whether a given condition is true or false. Below you will find sample conditional statements and a list of relational operators to use with the statements.

Relational Operators

equals to ==
not equals to !=
less than <
greater than >
less than or equal to <=
greater than or equal to >=
not !
and &&
or ||

The if Statement

if (Boolean Expression) {

statement(s) to execute.

}

if…else Statement

if (Boolean Expression) {

statement(s) to execute if condition is true.

} else {

statement(s) to execute if condition is false.

}

if Statement Example

if (age == 20) {

cout << “I am twenty years old.”;

}

if…else Statement Example

#include <iostream>

using namespace std;

int main()
{

int age;

cout<<“Please input your age: “; cin>> age;
cin.ignore();

if ( age < 100 ) {

cout<<“You are pretty young!\n”;

} else if ( age == 100 ) {

cout<<“You are old\n”;

} else {

cout<<“You are really old\n”;

}

cin.get();

}

Switch Statement in C++

Switch statement is a substitute for long if statements that compare a variable to several integral values (integral values are simply values that can be expressed as an integer, such as the value of a char). The basic format for using switch case is outlined below. The value of the variable given into switch is compared to the value following each of the cases, and when one value matches the value of the variable, the computer continues executing the program from that point.

Switch Statement Syntax

switch (value) {

case this-value:

Code to execute if value == this-value
break;

case that-value:

Code to execute if value == that-value
break;

default:

Code to execute if value does not equal any of the cases
break;

}

Switch Statement Example

int age;
cout << “What is your age: “; cin >> age;

switch (age)
{

case 1:

cout << “You are 1 year old”;
break;

case 2:

cout << “You are 2 years old”;
break;

case 3:

cout << “You are 3 years old”;
break;

default:

cout << “You are older than 3 years”;

}

Break Statement

The break command can be used to exit a loop at any time. Here is an example that will print “Hello” 5 times and then break out of the loop.

int x;
for (x = 1; x <= 10; x++)
{

cout << “Hello\n”;
if(x == 5)
break;

}

Continue Statement

The continue command lets you start the next iteration of the loop. The following example will not print “Hello” on 5th iteration because the continue command goes back to the beginning of the loop.

int x;
for (x = 1; x <= 10; x++)
{

if(x == 5)
continue;
cout << “Hello\n”;

}

Loops in C++

Loops are probably one of the most important programming concepts in existence. There are so many applications of loops it would be impossible to list them all. To name a few though, things like parsing an array, trapping for errors, and animation. Also, since it will allow you to execute a block of code over and over, it saves time and typing. Now, depending on what kind of programming language you came from, loops might already be familiar to you, but if you’ve come from a low level programming language such as assembly or GWBasic, you are probably more familiar with jump or goto statements. Well, loops take into account all that lovely comparison crap you used to have to do before and puts it into one nice package.

C++ for Loop

The easiest and most used of these loops is the for loop.

for Loop Syntax

for ( variable initialization; condition; variable update ) {
Code to execute while the condition is true
}

for Loop Example

#include <iostream>
using namespace std;

int main() {

for ( int x = 0; x < 10; x++ ) {

cout<< x << “\n”;

}
return 0;

}

C++ while Loop

The while loop is almost exactly the same as the do loop except that its condition is tested at the start of the loop instead of at the end… and the format is slightly different. The easiest way to see this is simply to re-write the above example with a while loop.

while Loop Example

#include <iostream>

using namespace std;
int main()
{

int x = 0;

while ( x < 10 ) {

cout<< x << “\n”;
x++;

}

return 0;

}

C++ do.. while Loop

The do while loop is like the while loop except that the condition is tested at the bottom of the loop.

do.. while Loop Syntax

do {

statement(s);

} while (condition);

do.. while Loop Example

#include <iostream>

using namespace std;

int main()
{

int x;

x = 0;
do {

cout<<“Hello, world!\n”;

} while ( x != 0 );

return 0;

}

Functions in C++

A function is a block of statements which is used to perform a task. Any C++ program has at least one function which is main().  When you have a piece of code that is often repeated you should put it into a function and call that function instead of repeating the code.

Function Definition

You define a function in similar way as you define the main function. First put return type then the function name and function parameters in brackets. The function code goes between curly brackets.

returnType functionName( parameters ) {

statement(s);

}

Example

void PrintHello()
{

cout << “Hello\n”;

}

Calling a Function

Once you have created the function you can call it from the main program. Here is an example of how to call the PrintHello function.

void PrintHello()
{

cout << “Hello\n”;

}

void main()
{

PrintHello();

}

Local and Global Variables

If you declare a variable inside a function it is only accessible by that function and is called a local variable. If you declare a variable outside of all functions it is accessible by any function and is called a global variable.

Example

int g; // Global variable

void MyFunction()
{

int l; // Local variable
l = 5;
g = 7;

}

void main()
{

g = 3;

}

Function Arguments

The arguments are used to pass values to a function. Arguments goes between the brackets after the function name. You must choose the datatype of all parameters. Here is a function that receives a number as a parameter and then prints it.

void PrintNumber(int n, int m)
{

cout << n << m;

}

void main()
{

PrintNumber(5, 6);

}

Passing Parameters by Reference

You can either pass a parameter by reference or by value. The default is by value which means that a copy of the variable is made for that function. If you use a * in front of the parameter then you will be passing only a pointer to that variable instead of making another copy of it.

void PrintNumber(int *n)
{

cout << *n;

}

void main()
{

int i = 5;
PrintNumber(&i);

}

Returning Values

A function can return a value that you can store in a variable. We have been using void in the place of the return variable until now. Here is an example of how to return the number 5 from a function and store it in a variable.

int GetNumber()
{

return 5;

}

void main()
{

int i = GetNumber();

}

Pointers in C++

A pointer is a variable that holds a memory address. It is called a pointer because it points to the value at the address that it stores.

Pointers in C++

If you want to declare a pointer variable in c++ you must first choose what data type it will point to such as an int or a char. You then declare it as if you were declaring a variable in the normal way and then put a * in front of its name to show that it is a pointer. Here is an example of how to declare a pointer to an integer.

int *pi;

You can store the address of another variable in a pointer using the & operator. See the below example of how to store the address of a variable called i in the pointer called pi.

int i;
int *pi;
pi = &i;

You must dereference a pointer to get the value at the memory location that the pointer points to. You use the * operator to dereference a pointer. Here is an example of how we first set the value of i to 5 and then set its value to 7 by dereferencing the pointer.

int i = 5;
int *pi;
pi = &i;
*pi = 7;
cout << i;

new & delete operators

The new operator is used to allocate memory that is the size of a certain data type. It returns a pointer to the address of the newly allocated memory. Here is an example of how to allocate memory for an integer and then set its value to 5.

int *pi;
pi = new int;
*pi = 5;

The delete operator deallocates memory. You need to deallocate the memory for all the memory that you have previously allocated before exiting the program or else you will have memory leaks.

int *pi;
pi = new int;
*pi = 5;
delete pi;

Typed and untyped pointers

We have been using typed pointers so far because they point to a specific data type. An untyped pointer can point to anything. You declare an untyped pointer as the data type void.
void *up;

malloc() and free() functions

The malloc command allocates a certain number of bytes and returns a pointer to the first byte. You must use the free command to deallocate the memory that was allocated with malloc. To be able to use malloc and free you must include the malloc header file. Here is an example that allocates 100 bytes of memory and stores the address of it in the pointer called up and then deallocates the memory.

void *up;
up = malloc(100);
free(up);

Arrays in C++

Arrays are used to store a number of items of the same type in one single variable. They are usually placed in the same segment of memory with accessible elements for each. This tutorial will explain you the tricks to C++ arrays.

Array Declaration

To declare arrays in C++ you need to specify the type of the array elements, name of array variable and the number of elements required by an array.

type variableName [size];

Example

int foo[5];

Array Initialization

In C++ array elements can be initialized one by one or through a single statement.

int bar[12];
bar[0] = 8;
bar[3] = 2;

OR

int bar[12] = {8,1,3,2,9,7,4,0,5,11,12,6};

The number of values between braces {} can not exceed the size of array which was specified at the time of array declaration.

Accessing Array Elements

The value of any of the elements in an array can be accessed by indexing the array name. You can access the value of 5th element of bar[] array as follows.

count << bar[4];

Example

#include <iostream>
using namespace std;

int main () {

int bar[12] = {8,1,3,2,9,7,4,0,5,11,12,6}; // bar is an array of 12 integers

// output each element of array
for(int i = 0; i < 12; i++ ){

cout << bar[i] << “\n”;

}

return 1;

}

Multidimensional Arrays

Arrays of arrays are called multidimensional arrays. C++ allows multidimensional arrays.

Multidimensional array declaration

int foo[2][4];

Multidimensional Arrays Example

#include <iostream>
using namespace std;

int main () {

// an array with 5 rows and 2 columns.
int foo[5][2] = { {1,3}, {0,2}, {2,6}, {3,1},{9,1}};

// output each array element’s value
for ( int i = 0; i < 5; i++ ) {

for ( int j = 0; j < 2; j++ ) {

cout << “foo[” << i << “][” << j << “]: “;
cout << foo[i][j]<< endl;

}

}

return 0;

}

Output

foo[0][0]: 1
foo[0][1]: 3
foo[1][0]: 0
foo[1][1]: 2
foo[2][0]: 2
foo[2][1]: 6
foo[3][0]: 3
foo[3][1]: 1
foo[4][0]: 9
foo[4][1]: 1

C++ Strings

C++ Strings are character type array and string literals are words surrounded by double quotation marks.

String Declaration

C++ strings are declared as one-dimensional array of characters which is terminated by a null (‘\0’) character. The the size of the character array containing the string is one more than the number of characters it holds due to the null character at the end.

Example

char myString[6] = {‘G’, ‘e’, ‘n’, ‘l’, ‘e’, ‘\0’};

You can also declare and initialize myString as

 char myString[] = “Genie”;

This would declare a string with a length of 6 characters. Do not forget that arrays begin at zero. A string ends with a null character so remember that there will be an extra character at the end on a string. Technically, in a 6 character array you could only hold 5 letters and one null character at the end to terminate the string.

char *arr; can also be used as a string. If you have read the tutorial on pointers, you can do something such as:

arr = new char[256];

which allows you to access arr just as it is an array. Keep in mind that to use delete you must put [] between delete and arr to tell it to free all 256 bytes of memory allocated.

delete [] arr;

The getline() function

Strings are useful for holding all types of long input. If you want the user to input his or her name, you must use a string. Using cin>> to input a string works, but it will terminate the string after it reads the first space. The best way to handle this situation is to use the function cin.getline. Technically cin is a class (similar to a structure), and you are calling one of its member functions. The most important thing is to understand how to use the function however.

getline(char *buffer, int length, char terminal_char);

The char *buffer is a pointer to the first element of the character array, so that it can actually be used to access the array. The int length is simply how long the string to be input can be at its maximum (how big the array is). The char terminal_char means that the string will terminate if the user inputs whatever that character is. Keep in mind that it will discard whatever the terminal character is.

It is possible to make a function call of cin.getline(arry, 50); without the terminal character. Note that ‘\n’ is the way of actually telling the compiler you mean a new line, i.e. someone hitting the enter key.

getline() example

#include <iostream>

using namespace std;

int main()
{

char string[256];

cout<<“Please enter a long string: “;
cin.getline ( string, 256, ‘\n’ );
cout<<“Your long string was: “<< string;
cin.get();

}

Remember that you are actually passing the address of the array when you pass string because arrays do not require an address operator (&) to be used to pass their address. Other than that, you could make ‘\n’ any character you want (make sure to enclose it with single quotes to inform the compiler of its character status) to have the getline terminate on that character.

C++ String Functions

<string> is a header file that contains many functions for manipulating strings. See some of string function below.

strcmp() function

int strcmp (s1, s2);

strcmp accept two strings and return an integer. This integer will either be:

Negative if s1 is less than s2.
Zero if s1 and s2 are equal.
Positive if s1 is greater than s2.

strcat() function

char strcat (dest, src);

strcat is short for string concatenate. It appends the second string at the end of the first string. Beware this function, it assumes that dest is large enough to hold the entire contents of src as well as its own contents.

strcpt() function

char strcpy (dest, src);

strcpy is short for string copy, it copies the entire contents of src into dest.

strlen() function

size_t strlen (s);

strlen() will return the length of the string excluding the null character. The size_t is nothing to worry about. Just treat it as an integer that cannot be negative.

C++ Structures

C++ structures provides a way to store many different values in variables of potentially different types under the same name. It makes the program more modular, which is easier to modify because its design makes things more compact. Structures are useful whenever a lot of data needs to be grouped together e.g. they can be used to hold records from a database or to store information about contacts in an address book. In the contacts example, a struct will hold all of the information about a single contact for example name, address, phone number etc.

Defining structures

struct structName {

member definition;
member definition;

} structureVariables;

structName is the name of the entire type of structure which is optional and members are the variables within the struct, structureVariables are one or more structure variables which is optional.

struct Contacts {

char fristName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;

}contact;

Accessing Structure Members

The dot (.) operator is used to access any member of a structure. Dot operator is used between the structure variable name and the structure member that we are going to access. struct keyword is used to define variables of structure type.

#include <iostream>
#include <cstring>

using namespace std;

struct Contacts {

char firstName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;

};

int main( ) {

//Declaring Contact1 of type Contact
struct Contacts Contact1;

strcpy( Contact1.firstName, “Scott”);
strcpy( Contact1.lastName, “Tiger”);
strcpy( Contact1.emailAddress, “tiger@tutorialsgenie.com”);
Contact1.age = 28;
Contact1.contact_id = 1071;

//Printing Contacts
cout << “Contact1 firstName : ” << Contact1.firstName <<endl;
cout << “Contact1 lastName : ” << Contact1.lastName <<endl;
cout << “Contact1 emailAddress : ” << Contact1.emailAddress <<endl;
cout << “Contact1 age : ” << Contact1.age <<endl;
cout << “Contact1 id : ” << Contact1.contact_id <<endl;

return 0;

}

Output of the above program will be

Contact1 firstName : Scott
Contact1 lastName : Tiger
Contact1 emailAddress : tiger@tutorialsgenie.com
Contact1 age : 28
Contact1 id : 1071

typedef Keyword

The typedef Keyword can be used to define structures.

typedef struct {

char firstName[50];
char lastName[50];
char emailAddress[100];
int age;
int contact_id;

}Contacts;

Now Contacts can be used to directly define variables of Contacts type without using struct keyword.