0% found this document useful (0 votes)
31 views

220 Programming in C

Uploaded by

foyebov508
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

220 Programming in C

Uploaded by

foyebov508
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 143

Programming in C++

S e c t i o n 0 2 | M o d u l e 0 2
© Caendra Inc. 2019
All Rights Reserved
Table of Contents

Module 02 | Programming in C++

2.1 C++ IDE 2.6 Iteration & Conditional


Structures
2.2 Structure of C++
2.7 Pointers
Programs
2.8 Arrays
2.3 Variables & Types
2.9 Functions
2.4 Input / Output
2.10 Hera Lab: C++-assisted
2.5 Operators exploitation

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.2


Learning Objectives

By the end of this module, you should have a


better understanding of:

• C++ IDE
• C++ fundamentals: Variables, functions and basic
code constructs

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.3


2.1

C++ IDE

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.4


2.1 C++ IDE

Welcome to the Programming Section! Every Penetration


Tester should have basic programming skills.

In this module, we will cover basic concepts that will help


you write code in C++.

You can find all the C++ code samples used on the Resources drop-down
menu of this module.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.5


2.1 C++ IDE

Let’s start downloading and


installing an IDE (Integrated
Development Environment)
for C++.

We can download Dev-C++ at


the following link:
http://sourceforge.net/proje
cts/orwelldevcpp/
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.6
2.1 C++ IDE

The first step is to


create a new file
where we will insert
our source code.

To do that, click on
File>New>Source
File.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.7
2.1 C++ IDE

Here we see the


main panel where
we are going to
write our source
code.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.8


2.1 C++ IDE

Dev-C+ is a highly customizable IDE


and allows us to configure different
settings. Let’s now focus on the
most important features to compile
our first program.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.9


2.1 C++ IDE

Compiles the source code. If the source code


compiles successfully, a .exe file will be created.

Allows you to run the program you just


compiled.

Merges the previous two commands; it first


compiles your code and then runs it.

This button allows you to debug your source


code.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.10
2.2

Structure of C++
Programs

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.11


2.2 Structure of C++ Programs

In this chapter, you will see what a C++ program looks like.

Furthermore, you will learn how to write, compile and


execute your first program: Hello World!

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.12


2.2 Structure of C++ Programs

Here we see the code of Hello World, a super simple program


that we will compile to test the configuration of DevC++.

// This is my first Program in C++


#include <iostream>
using namespace std;
int main ()
{
cout << "Hello World!";
return 0;
}

Now, let’s go study it line by line.


PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.13
2.2 Structure of C++ Programs

// This is my first program in C++

The first line is a comment. All the


lines starting with double slashes
( // ) are considered comments and do
not have any effect on the program.
The compiler will ignore them.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.14


2.2 Structure of C++ Programs

#include <iostream>

All lines starting with the hash ( # )


character are directives. In this example,
it instructs the compiler to include the
code of the iostream library in our
program. The iostream library provides
input and output functionalities. A
library is a collection of routines that a
program can use.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.15
2.2 Structure of C++ Programs

Using namespace std;

Namespaces are used to group a set


of classes, functions etc. under a
name. Since all the elements in the
standard C++ library (such as
iostream) are declared within the std
namespace, we need this command to
access its functionalities.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.16
2.2 Structure of C++ Programs

Using namespace std;

Please note the semicolon ( ; ) at the


end of the command; this is part of the
syntax, and it is called a terminator. It
tells the compiler that it has reached
the end of a command.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.17


2.2 Structure of C++ Programs

int main ()

Here is the declaration of the main


function of our program. The main
function is where our program
execution starts. In other words,
wherever the main function is
declared in our source code, it will
be the first code to be executed.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.18
2.2 Structure of C++ Programs

{
instructions here
}

The two curly brackets ‘ { } ’ contain


the body of the main function. The
brackets determine where the main
function code starts and ends.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.19


2.2 Structure of C++ Programs

cout << “Hello World!”;

cout is the name of the standard output.


Most of the time, the standard output is
the console. The cout << statement tells
the compiler to put a sequence of
characters, ‘Hello World!’ in our example,
onto the standard output stream (the
console). In other words, it prints the
string ‘Hello World!’ on the screen.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.20
2.2 Structure of C++ Programs

return 0;

This last statement causes the main


function to end. As we will see later in
the function section, the return
statement can have different values. In
our case the value is ‘0’, and it means
that the program has completed its
execution without any errors.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.21
2.2 Structure of C++ Programs

Now that we have written


our first program let’s try to
compile it and see what
happens. To do that, we will
use the button ( ) shown
before. So now we can start!

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.22


2.2 Structure of C++ Programs

If the program is
successfully compiled we
should see a window like
the following; this window
tells us that the compiler
is done and that no errors
or warnings were
generated.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.23


2.2 Structure of C++ Programs

A new file named


“helloworld.exe” has
been created in the same
directory of our source
code. Now, we can open
a CMD prompt and run it!

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.24


2.2 Structure of C++ Programs

We can also use the Dev-C++ button to run our compiled


program.

Please note that a program terminates as soon as it


completes its operations; this means that running our
program will open a terminal window for less than a
second.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.25


2.2 Structure of C++ Programs

In order to avoid the console closing automatically, we can


use different commands.

For example, insert one of the two following commands


right before the “return 0;” statement and then compile and
run ( ) the program within Dev-C++:
• system(“PAUSE”);
• cin.ignore();

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.26


2.2 Structure of C++ Programs

You should now be able to run the program and see the
console output.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.27


2.3

Variables & Types

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.28


2.3 Variables & Types

Now that we are more confident about the IDE, let’s see
how we can define variables with different types.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.29


2.3 Variables & Types

The “Hello World” example was very simple.

Variables are portions of memory where values are stored.


Each variable is recognizable by a human (the programmer)
through a symbolic name (or identifier). In other words, this
identifier is the way we can reference the stored value.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.30


2.3 Variables & Types

Since we are going to store these values in the computer’s


memory, we have to specify the type of data we are going
to store in it. For this reason, when we declare a new
variable, we have to define its type.

Now, let’s look at some examples to clarify these concepts.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.31


2.3 Variables & Types

In this example, we declared three


variables (a, b, sum) and then we
changed their values. The program
prints the sum of the variables a and b.

The first time we print the value of


sum (through cout), it is 2, while the
second time it is 5. This happens
because we change the value of the
variable a during the execution of the
program.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.32
2.3 Variables & Types

Here we declare the three variables,


and we assign a value to each of
them.

As you can see in the code, each


variable has its type, which is an
integer (int) in our case. We can also
declare and assign the value in the
same line.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.33


2.3 Variables & Types

This line prints the value of the sum


variable. In this case, it prints the
following string:

“The value of variable sum is: 2”

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.34


2.3 Variables & Types

Here we assign a new value to the


variable a.

The previous value (0) is overwritten


with the new one (3).

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.35


2.3 Variables & Types

We assign a new value to the variable


sum.

Since the value of the variable a is


changed, the value of the sum is now
5 (3+2).

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.36


2.3 Variables & Types

short
Short integer (2 bytes)
short int
There are many int Integer (4 bytes)
different data long
Long integer (4 bytes)
long int
types we can use. bool Boolean (1 byte)
float Floating point number (4 bytes)

Here is a short list. double


Double precision floating point number (8
bytes)
char Character (1 byte)

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.37


2.3 Variables & Types

Before we see the Iteration and Conditional Structures


section, there is one last thing you need to know!

Each variable we are going to use must be declared


somewhere in the source code. Depending on the position
where it is declared it has a different scope: global or local.
We’ll now explain this concept with an example.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.38


2.3 Variables & Types

A global variable is declared in the


body of the source code (it is not
in a function) and can be referred
from anywhere.

In the first instruction in the main


function, we can print the value of
the variable named global_variable and the output is “Value of
global_variable: 4”.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.39
2.3 Variables & Types

Local variables are variables


declared inside a function body
or block enclosed in curly
brackets “{}” (main function in
our case) and their scope is
limited to the block where they
are declared.

In this case, the second cout prints the following string: Value of
global_variable: 2
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.40
2.3 Variables & Types

So the scope of the


global_variable is different.
Global scope

If we use global_variable in
another function, its value will be
4, no matter if we have already
Local Scope
executed the instruction
“int global_variable = 2;”

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.41


2.4

Input / Output

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.42


2.4 Input / Output

In the previous examples, we used a function that allows us


to print a message on the screen. We can expand it and see
how we can interact with the user and get his input from
the keyboard.
Do you remember this line of code?

cout << "The value of variable sum is: " << sum << endl;

Let’s split it and analyze each part.


PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.43
2.4 Input / Output

The cout statement represents the standard output.

Since our default output is the console, cout tells our


program to print the following code to the console:

cout << "The value of variable sum is: " << sum << endl;

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.44


2.4 Input / Output

The << operator tells the program to insert the next data
into the stream. Since we use cout, it puts the data in the
standard output stream. This operator can be used multiple
times, and it is useful when we want to print a combination
of strings and variables. In this case, we want the string
“The value of variable sum is:” followed by the value of the
variable sum.

cout << "The value of variable sum is: " << sum << endl;

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.45


2.4 Input / Output

endl inserts a ‘new line character’ and flushes the buffer;


"
this ensures that the next output prints in the next line.

cout << "The value of variable sum is: " << sum << endl;

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.46


2.4 Input / Output

Similarly, we can use the cin function followed by the


operator >> in order to get the user’s input.

In this case, the standard input is the keyboard.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.47


2.4 Input / Output

In this example, we first


declare the variable where the
user input is stored
(uservalue), and then we print
some messages to the user.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.48


2.4 Input / Output

With the cin >> uservalue;


statement, we instruct the program
to get the input from the standard
input ( the keyboard) and save it in
the uservalue variable.

As you can see in the next two


lines, we first print the value
provided by the user and then we
print out the value plus 10.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.49
2.4 Input / Output

When the user inserts their value


and presses enter (return) on the
keyboard, the return value goes
into the buffer.

When we run the program, in order


to keep the console opened, we
need to clean this buffer with the
first cin.ignore() statement and
then with the second cin.ignore()
we can prevent the console from
closing.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.50
2.4 Input / Output

In other words, the first


cin.ignore() reads the return
value and the second waits
for a new input, keeping the
console on the screen.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.51


2.4 Input / Output

Here we can see what our


program looks like.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.52


2.5

Operators

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.53


2.5 Operators

In C++ there are four main classes of operators:

Arithmetic Relational Logical Bitwise

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.54


2.5 Operators

variable_name = expression;

The assignment operator can be used within any valid


expression, and we can see the general form above.

The target (the left part – variable name) of the assignment


must be a variable or a pointer (we will see later what
pointers are) and can’t be a function or a constant.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.55
2.5 Operators

variable_name = expression;

In C++ literature, you will see these two terms: lvalue and
rvalue.
• lvalue is any label that appears on the left side of an
assignment statement; in other words, we can say it is the
variable name.
• rvalue refers to expressions/value on the right side of an
assignment and simply means the value that will be
assigned to the variable.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.56
2.5 Operators

In the following example, the first statement assigns the


value 10 to the variable named variable1.
variable1 = 10;

b = variable1;

The second statement assigns the value contained in


variable1 to variable b. At this point, the value of variable b
will be 10.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.57
2.5 Operators

The following table summarizes the arithmetical operators.

Operator Action
- Subtraction
+ Addition
* Multiplication
/ Division
% Modulus

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.58


2.5 Operators

a = a + 1; is the same as ++a;

a = a - 1; is the same as --a;

In addition to the previous operators, C++ includes an


increment operator (++) and a decrement operator (--)
where:
• ++ adds 1 to its operand
• -- subtracts 1 from its operand
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.59
2.5 Operators

x = 10; x = 10;
y = ++x; Set y to 11 y = x++;
Set y to 10 and x to 11

Both the increment and decrement operators may precede (++x)


or follow (x++) the operand. The difference between them is that
when the operator precedes its operand, the increment or
decrement operation is performed before obtaining the value of
the operand, while if the operator follows its operand, the value is
obtained before incrementing or decrementing it.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.60


2.5 Operators

Operator Action
Relational
> Greater than
>= Greater than or equal
Operator Action
< Less than Logical
<= Less than or equal && AND

== Equal || OR

!= Not equal ! NOT

Relational operators define a relationship between two values.

Logical operators define how previous relationships must be


connected.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.61
2.5 Operators

The idea of true and false is the basic concept of relational


and logical operators. In C++, true is any value other than
zero. False is zero. Expressions that use relational or logical
operators return 0 for false and 1 for true.

For this purpose, in C++ we can use the bool data type and
the Boolean constants true and false. So a 0 value
automatically converts to false while a non-zero value
automatically converts to true.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.62
2.5 Operators

Operation Value
Relational operators are used ( 10 > 1 ) True
in order to evaluate a ( 10 >= 10 ) True
comparison between two ( 10 < 5 ) False
expressions. The result is a ( 5 <= 10 ) True
Boolean value. ( 1 == 1 ) True
( 1 != 1 ) False

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.63


2.5 Operators

Logical operators define how previous relationships must


be connected.
x y x && y x || y !x
0 0 0 0 1
0 1 0 1 1
1 1 1 1 0
1 0 0 1 0

The first line may be read as the following: when x is false (0) and y is false (0) the result
of x AND y (x && y) is false (0), the result of x OR y is false, and the inverse of x is true

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.64


2.5 Operators

The logical operator ! has only one operand (at its right) and
it inverses this value (false if its operand is true, and true if
its operand is false). The logical operator && and || evaluate
two expressions in order to obtain a relational result.
• && (AND) results true if both operands are true and
false otherwise
• || (OR) results true if either one of its operands is true,
false when both are false
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.65
2.5 Operators

C++ supports many Operator Action


operations that can be done & AND
in assembler, including | OR
operations on bits. ^ Exclusive OR (XOR)
~ One’s complement (NOT)
Bitwise operations refer to >> Shift right
testing, setting or shifting the << Shift left
actual bits in a byte or word.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.66


2.5 Operators

The following program executes a bitwise AND, a bitwise OR and


then shifts the value of x.

Bitwise AND
11001110 & 206 &
10011000 = 152 =
10001000 136

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.67


2.6

Iteration & Conditional


Structures

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.68


2.6 Iteration & Conditional Structures

Let’s see how we can define control structures.

These structures are useful to instruct the program to


execute or to repeat a specific operation when some
condition is matched.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.69


2.6 Iteration & Conditional Structures

A statement is part of our program that can be executed


and specifies an action. In this section, we are going to see
three main groups of statements.
SELECTION ITERATION JUMP

• if • while • break
• switch • for • continue
• do-while • goto
• return

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.70


2.6 Iteration & Conditional Structures

The general form of the if statement is:

if (expression)
statement;
else
statement;

Where a statement may consist of a single statement, a block of


statements (but they must be enclosed in curly brackets ), or
nothing (in case of an empty statement). The else clause is
optional.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.71
2.6 Iteration & Conditional Structures

if (expression)
statement;
If the expression evaluates to
else true, the statement or block of
statement;
statements that form the target
of if is executed; otherwise, the statement or block that is
the target of else will be executed.

Only the code associated with if or the code associated


with else executes, never both.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.72
2.6 Iteration & Conditional Structures

The above program contains an example of an if - else


statement. The program simply checks if the number provided is
greater or less than 10. Depending on the value, the program will
print different messages.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.73
2.6 Iteration & Conditional Structures

A nested if is an if contained in the body of a parent if. In a


nested if, the else statement refers to the nearest if
statement in the same block that is not already associated
with another else.
if(x)
{
if(a) statement 1;
if(b) statement 2; /* this if is associated */
else statement 3; /* with this else */
}
else statement 4; /* associated with if(x) */

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.74


2.6 Iteration & Conditional Structures

C++ implements a multiple- switch (expression){


branch selection statement, case constant1:
called switch, which tests, in statement sequence
order, the value of an expression break;
against a list of values. case constant2:
statement sequence
break;
Only the block of operations .
.
associated with the matching .
expression is executed. Note default
that the value must be an statement sequence
integer or a constant. }

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.75


2.6 Iteration & Conditional Structures

The value of the expression is sequentially tested against


the values specified in the case statements. When a match
is found, the statement block associated is executed until
the break statement, or the end of the switch is reached.
The default statement is executed if no matches are found.

Note that default is optional, so if it is not defined, there is


no action if all matches fail.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.76
2.6 Iteration & Conditional Structures

The break statement is one of switch (expression){


case constant1:
C++’s jump statements. You statement sequence
can use it in loops as well as in break;
the switch statement. case constant2:
statement sequence
break;
When break is encountered in a .
.
switch, the execution “jumps” .
default
to the line of code following the statement sequence
switch statement. }

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.77


2.6 Iteration & Conditional Structures

The following
example shows a
menu selection.

This simple
program displays a
menu, gets the
user input and calls
the proper
procedures.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.78
2.6 Iteration & Conditional Structures

ITERATION

Iteration statements, also called loops, allow a set of


instructions to be executed repeatedly for a fixed number of
times or until a certain condition is reached.

While in for loops the condition is predefined, in do-while


loops are open-ended.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.79
2.6 Iteration & Conditional Structures

The general form of a for statement is:


for(initialization;condition;increment) {
statement;
}

Where:
• initialization is an assignment statement that sets the starting
value of the loop control variable
• condition determines when the loop must end
• increment defines how the control variable changes for each
iteration
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.80
2.6 Iteration & Conditional Structures

Start with a = 2

Until a is less or equal to 50


Increment a by 2 in each loop

The for loop continues as long as the condition is true. Once the
condition fails, the program executes the statement right after
the for. In the above program, the for loop is used to print all the
multiples of 2 until 50 is reached.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.81
2.6 Iteration & Conditional Structures

The for statement is also used for infinite loops.

Since initialization, condition, and increment of the for loop


are not required, we can make an infinite loop by leaving
them empty:
for( ; ; ){
statement;
}

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.82


2.6 Iteration & Conditional Structures

When the conditional expression is left empty, it is


processed as true. Note that the for( ; ; ) construct can exit
from an infinite loop through a break statement present
anywhere in the body of the loop. The break statement
causes the termination of the loop, and the program control
resumes from the next instruction following the loop.

You may be wondering though, why one would want to use


an infinite loop.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.83
2.6 Iteration & Conditional Structures

As shown in the code above, an infinite loop used with a break statement can be
useful to keep the console alive until the user chooses to exit. The program
terminates only if the user inserts the number 2; otherwise, they will see the menu
over and over again.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.84
2.6 Iteration & Conditional Structures

In the same way as with other statements, for loops can be


nested. Nested loops are very common in programming
since they add power and flexibility to complex algorithms.

Let’s take a look at an example of how nested loops can be


used.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.85


2.6 Iteration & Conditional Structures

Given two numbers (base


and height), let’s say we
want to draw a rectangle
using the char ‘*’.

What we can do is use


nested loops to iterate
columns and rows, as we
see here in the code on the
left.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.86
2.6 Iteration & Conditional Structures

The second loop available in C++ is the while loop. Its general
form is:
while(condition) {
statement;
}
Where:
• statement is either an empty statement, a single
statement, or a block of statements
• condition may be any expression, and true is any non-zero
value
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.87
2.6 Iteration & Conditional Structures

while(condition) {
The loop continues while the statement;
condition evaluates to true. }

When the condition evaluates to false, the program control


goes to the line of code right after the loop.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.88


2.6 Iteration & Conditional Structures

Similar to the previous


example (infinite for
loop), this program will
continue until the user
inserts 3 (the condition
(user_value != 3)
becomes false).

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.89


2.6 Iteration & Conditional Structures

Since the user_value is set


to 0, in the first iteration the
condition is evaluated to
true, and the loop begins.

Each time we insert a value


the condition is tested
again. Once we insert 3, the
condition becomes false,
and the loop terminates.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.90


2.6 Iteration & Conditional Structures

Unlike for and while loops, which test the condition at the
beginning of the loop, the do-while loop checks its
condition at the end of the loop; a do-while loop always
executes at least once.

The general form of the do{


do-while loop is: statement;
}while(condition);

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.91


2.6 Iteration & Conditional Structures

The do-while loop iterates


until the condition
evaluates to false.

The program on the left


will first get the user input,
and then it will stop only
when the condition
becomes false.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.92
2.6 Iteration & Conditional Structures

You have all the skills needed to write a program that prints
out a simple Xmas tree. Given a number, write a program
that will display a triangle made of * chars, which has as
many lines as the number provided.

*
Let’s type in 5; the program ***
should print something like this: *****
*******
*********
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.93
2.6 Iteration & Conditional Structures

There are many


different ways to
do it. This code is
one of them.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.94


2.6 Iteration & Conditional Structures

JUMP STATEMENT

C++ has four statements that can change the normal


execution flow: return, goto, break and continue.

While return and goto are mostly used anywhere in your


program, break and continue statements are often used in
conjunction with any of the loop statements seen before.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.95
2.6 Iteration & Conditional Structures

The return statement is used to return from a function. It


may or may not have a value associated with it.

The general form of a return statement is:

return expression;

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.96


2.6 Iteration & Conditional Structures

The expression must be used


return expression; only if the function has a
returning value. In this case, the
value of the expression will become the return value of the
function and can be associated with a variable.

We can use as many return statements as we like within a


function. However, the function stops executing as soon as
it encounters the first return.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.97
2.6 Iteration & Conditional Structures

The main concern about the goto is that it makes the


programs unreadable. It can be used to jump to a specific
statement, such as jumping out of a set of deeply nested
loops.

Its general form is: goto label;




label:

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.98


2.6 Iteration & Conditional Structures

goto label; The goto statement requires a label. A




label is an identifier followed by a
label: colon.

Note that the label must be in the same block of


statements as the goto that uses it, so we cannot jump
between functions.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.99


2.6 Iteration & Conditional Structures

The break statement has two uses:


• Terminates a case in the switch statement
• Forces the termination of a loop, bypassing the
normal loop conditional test.

When we use the break statement within a loop, the loop


terminates, and the program control resumes at the
statement after the loop.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.100
2.6 Iteration & Conditional Structures

This program prints numbers from


0 to 10.

Even if the loop should continue


until x is 100, it terminates because
the break causes the loop to
terminate, overriding the
conditional test x < 100.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.101
2.6 Iteration & Conditional Structures

The continue statement works similarly to the break


statement. Instead of forcing termination, it forces the code
to continue to the next iteration of a loop, skipping any code
in between.

So, in a for loop, continue causes an increment of the


control variable and a new iteration.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.102


2.6 Iteration & Conditional Structures

This program checks how


many numbers are odd and
how many are even. As you
can see, if the number is even
(if(user_value % 2 == 0) ) the
program encounters the
continue statement. In this
case, the odd variable will not
be incremented.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.103


2.7

Pointers

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.104


2.7 Pointers

A pointer is a variable that holds a memory address. This


address is the location of another object in memory.

For example, if one variable (a) contains the address of


another variable (b), a is said to point to b.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.105


2.7 Pointers

The following image shows


the situation where one
variable points to another.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.106


2.7 Pointers

If a variable is a pointer, it must be declared in a different way.


We will write an * and the variable name. The general form is:

type *name;

Where:
• type is the base type of the pointer (int, char…);
• name is the name (identifier) of the pointer variable

Type defines the type of variable the pointer can point to.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.107
2.7 Pointers

There are two special pointer operators: * and &. The &
returns the memory address of the variable. For example:

x = &y;

Put the memory address of the variable y into x. This


address is the computer’s internal location of the variable.
It is not the value of y but its address. In other words, the &
operator returns “the address of”. Therefore, the above
statement means “x holds the address of y”.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.108
2.7 Pointers

The second pointer operator, *, is the complement of &. It


returns the value located at the address of the following
operator. For example:
x = *y;

places the value in memory pointed by y, into x. So if y


contains the memory address of another variable, let us say
counter, x will have the value of counter.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.109
2.7 Pointers

This program shows how


the two pointer operators
work. In the indicated
statement, p1 points to
the memory address of
the variable x.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.110


2.7 Pointers

With this statement, p2


points to the same memory
address of p1, meaning
that p2 now points to the
memory address of x.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.111


2.7 Pointers

The next statement assigns


to variable y, the value
located at the memory
address pointed by p2. In
other words, y now contains
the value of the variable x.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.112


2.7 Pointers

With this last statement, we


assign 5 to the value
located at the memory
address pointed by p2.
Remember that p2 was
pointing to the memory
address of x, so the value
of x is now 5.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.113


2.8

Arrays

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.114


2.8 Arrays

An array is a collection of variables of the same type. A


specific element in an array is accessed by an index.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.115


2.8 Arrays

An array may have several dimensions. The general form is:

type var_name[size];
Where:
• type declares the type of the array (the type of each element in the
array)
• size defines the length of the array (how many elements the array can
contain)

All arrays have 0 as an index of the first element. Therefore, if we declare an


array of 10 elements its index goes from [0] to [9].
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.116
2.8 Arrays

The program creates an


integer array of 20 elements. Array declaration
The for loop places numbers
from 0 to 19 inside the array.
Element accessed by
indexing the array name
Remember that an array is
accessed by indexing the
array name. This is done by Print array elements with
placing the index of the index from 0 to 20
element we want to access
within square brackets.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.117
2.9

Functions

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.118


2.9 Functions

Functions are blocks of statements defined under a name.


In other words, it is a group of statements that get executed
when this name is called in the program.

Functions perform a given operation and often return a


result.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.119


2.9 Functions

The general form of a function is:


type function_name(paramenter1, parameter2,…){
statements;
}

Where:
• type specifies the type of data that the function returns
• function_name is the identifier used to call that function
• parameters is a comma-separated list of variables and their
associated types. Those variables receive the values when the
function is called.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.120
2.9 Functions

type function_name(){
statements;
}

Note that functions may have no parameters, but they still


require parentheses ‘()’.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.121


2.9 Functions

Function definition
Here is an example of a
function that takes two
numbers from the user,
sums them and returns
the result of the Function call
operation.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.122


2.9 Functions

Formal parameters

Since this function uses two


arguments, we have to declare two variables (int x, int y)
that will accept the values from the caller. These variables
are called formal parameters of the function. They are like
any other local variable inside the function, and they are
declared when the function is called and destroyed when
the function returns.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.123
2.9 Functions

Let’s see how this


program works step by
step.

As usual, the first


instruction to be executed
is the one within the main
function.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.124
2.9 Functions

a = 5;
The program will then b = 3;
ask the user to insert two
values: a and b.

Let’s say that we insert


the following values: 5
and 3.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.125


2.9 Functions

Here the function sum is a = 5; b = 3;


called, and the control is lost
by main, and it is passed to sum( a , b )
sum.
sum(int x, int y)

The value of both arguments


in the caller function (a, b)
are copied into the local
variables (int x, int y) of the
function sum.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.126
2.9 Functions

x = 5; y = 3;
The execution now occurs
in the sum function. z = x + y;
z = 5 + 3;
Here a new variable is z = 8;
declared and the operation
z = x + y is executed.

Since the actual value of x


and y are 5 and 3, z will be 8
(5+3).

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.127


2.9 Functions

The return statement z = 8;


finalizes the function and return(z);
returns the control back to
result = 8
the caller function (in this
case main).

The program then


resumes execution at the
line of code following the
function call.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.128
2.9 Functions

z = 8;
return(z);
Since the function result = 8
returned a value (z), this
will be copied in the
variable result: the value
of the result will then be 8.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.129


2.9 Functions

This instruction prints the


values of the variables.
As we can see from the
console the result is 8.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.130


2.9 Functions

In almost any programming language there are two ways in


which we can pass arguments to a function.

By value By reference

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.131


2.9 Functions

The first method, call by value, copies the value of an


argument into a parameter. In this case, changes made to
the parameter do not affect the argument.

By default, C++ uses call by value; this means that the code
in the function does not alter the arguments used by the
caller.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.132


2.9 Functions

Similar to the previous example, in


in this program, the value of the
argument sum(), 5, is copied into
the parameter x ( within sum() ).

When the assignment x = 10 + x


takes place, only the local variable x (within the function) is
modified. The variable x in the main function used to call
sum() still holds the value of 5.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.133
2.9 Functions

Remember that it is a copy of the value of the argument


passed into the function.

What occurs inside the function has NO EFFECT on the


variable provided by the caller.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.134


2.9 Functions

The second method, call by reference, passes arguments in


a different way. With this method, the address of an
argument (not the value) is copied into the parameter.
Inside the function, the address is used to access the actual
argument used in the call, so changes made to the
parameter affect the argument.

We can create a call by reference by passing a pointer to an


argument instead of the argument itself.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.135
2.9 Functions

In the declaration of the


function, the type of each
parameter is followed by an void swap(int& x, int& y)
{
ampersand sign that specifies int temp;
that their corresponding temp = *x;
arguments are to be passed by *x = *y;
*y = temp;
reference; this means that we }
are passing the variable itself
and not its value.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.136
2.9 Functions

The swap function exchanges


the values of the two
variables i and j because we
pass the variables and not
just their values.

Any modification to local


variables in the swap function
will have an affect on the
variables passed as
argument (&i and &j).
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.137
2.10

Hera Lab
C++-assisted exploitation

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.138


2.10 Lab – C++-assisted exploitation

Let’s try to use C++ in order to create simple tools that


could be used during your penetration testing activities.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.139


2.10 Lab – C++-assisted
exploitation

C++-assisted exploitation
In the lab, you will:
• Create a simple keylogger
program
• Create a simple data stealing
program
• Exfiltrate stolen data via a
network connection

*Labs are only available in Full or Elite Editions of the course. To upgrade, click HERE. To access, go to the course
in your members area and click the labs drop-down in the appropriate module line or to the virtual labs tabs on
the left navigation.
PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.140
References

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.141


References
This concludes our basic C++ tutorial. If you want to dig deeper
in this programming language, here are some references that
you can use:

C++ tutorial
http://www.cplusplus.com/doc/tutorial/

The C++ Programming Language (3rd Edition)


http://www.amazon.com/The-Programming-Language-3rd-Edition/dp/0201889544

Sams Teach Yourself C++ in One Hour a Day


http://www.amazon.com/Sams-Teach-Yourself-One-Hour/dp/0672335670/

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.142


Labs
C++-assisted exploitation
In the lab, you will:
• Create a simple keylogger program
• Create a simple data stealing program
• Exfiltrate stolen data via a network connection

*Labs are only available in Full or Elite Editions of the course. To upgrade, click HERE. To access, go to the course in your
members area and click the labs drop-down in the appropriate module line or to the virtual labs tabs on the left navigation.

PTSv4: Section 2, Module 2 - Caendra Inc. © 2019 | p.143

You might also like