C++ RE-Exam Document
C++ RE-Exam Document
1. Introduction to C++
Program (Software)
Assembly Language
❖ Machine dependent.
❖ Program written in a high-level language is called source code or source program code.
1
1. Introduction to C++
C++ is a powerful, high-level programming language that supports both procedural and object-
oriented programming. It was developed by Bjarne Stroustrup as an extension of the C language.
C++ is widely used for developing system software, games, and applications due to its efficiency
and flexibility.
2. Key Features of C++
• Object-Oriented: Supports concepts like classes, objects, and inheritance.
• Fast Execution: Optimized for performance and speed.
• Modular Programming: Supports functions and reusable code.
• Platform Independent: Can be used on various operating systems.
• Rich Library Support: Includes the Standard Template Library (STL) for data structures
and algorithms.
What is C++?
2
int main() {
Example explained
Line 1: #include <iostream>is a header file library that lets us work with input and output
objects, such as cout(used in line 5). Header files add functionality to C++ programs.
Line 2: using namespace stdmeans that we can use names for objects and variables from the
standard library.
Line 3: A blank line. C++ ignores white space. But we use it to make the code more readable.
Line 4: Another thing that always appear in a C++ program, is int main(). This is called a
function. Any code inside its curly brackets {}will be executed.
3
Line 5: cout(pronounced "see-out") is an object used together with the insertion operator
(<<) to output/print text. In our example it will output "Hello World".
Line 7: Do not forget to add the closing curly bracket}to actually end the main function.
The cout object, together with the <<operator, is used to output values/print text: Example
#include <iostream>
using namespace std;
int main() {
You can add as many coutobjects as you want. However, note that it does not insert a new line at
the end of the output:
C++ New Lines
int main() {
return 0; }
4
Another way to insert a new line, is with the endl manipulator:
Example
#include <iostream>
using namespace std;
int main() {
return 0;}
Both \nand endl are used to break lines. However, \nis used more often and is the preferred
way.
C++ Comments
Comments can be used to explain C++ code, and to make it more readable. It can also be used to
prevent execution when testing alternative code. Comments can be singled-lined or multi-lined.
Single-line Comments
// This is a comment
/* The code below will print the words Hello World! to the screen, and it is amazing */
5
2. C++ Variables
In C++, there are different types of variables (defined with different keywords), for example:
❖ int - stores integers (whole numbers), without decimals, such as 123 or -123
❖ double - stores floating point numbers, with decimals, such as 19.99 or -19.99
❖ char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
❖ string - stores text, such as "Hello World". String values are surrounded by double quotes
❖ bool - stores values with two states: true or false
Syntax
Where type is one of C++ types (such as int), and variableName is the name of the variable (such
as x or myName). The equal sign is used to assign values to the variable.
Example
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign the value later: Example
int myNum;
myNum = 15;
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
6
Example
Display Variables
To combine both text and a variable, separate them with the <<operator: Example
To declare more than one variable of the same type, use a comma-separated list:
int x = 5, y = 6, z = 50; cout << x + y + z;
C++ Identifiers
❖ All C++ variables must be identified with unique names. These unique names are called
identifiers.
❖ Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
❖ Note: It is recommended to use descriptive names in order to create understandable and
maintainable code:
The general rules for naming variables are:
7
3. User Input
You have already learned that cout is used to output (print) values. Now we will use cin to get
user input.
Cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).
In the following example, the user can input a number, which is stored in the variable x. Then we
print the value of x:
Example
int x;
cout << “Type a number: “; // Type a number and press enter cin >> x; // Get user input from the
keyboard
cout << “Your number is: “ << x; // Display the input value
Good To Know
❖ cout is pronounced “see-out”. Used for output, and uses the insertion operator (<<)
❖ cin is pronounced “see-in”. Used for input, and uses the extraction operator (>>)
cout << “Type a number: “; cout << “Sum is: “ << sum;
8
4. C++ Data Types
As explained in the Variables topic, a variable in C++ must be a specified data type:
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99; // Floating point number
double myDoubleNum = 9.98; // Floating point number
char myLetter = 'D'; // Character
bool myBoolean = true; // Boolean
string myText = "Hello"; // String
The data type specifies the size and type of information the variable will store
Use int when you need to store a whole number without decimals, like 35 or 1000, and float or
Double when you need a floating point number (with decimals), like 9.99 or 3.14515.
9
C++ Boolean Data Types
A boolean data type is declared with the boolkeyword and can only take the values trueor
False. When the value is returned, true= 1and false= 0.
Example
bool isCodingFun = true;
bool isFishTasty = false;
cout << isCodingFun; // Outputs 1 (true)
cout << isFishTasty; // Outputs 0 (false)
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
Example
char myGrade = 'B';
cout << myGrade;
10
C++ User Input Strings
It is possible to use the extraction operator >>on cinto display a string entered by a user:
Example
string firstName;
cout << "Type your first name: ";
cin >> firstName; // get user input from the keyboard
cout << "Your name is: " << firstName;
// Type your first name: John
// Your name is: John
However, cinconsiders a space (whitespace, tabs, etc) as a terminating character, which means
that it can only display a single word (even if you type many words):
5. C++ Operators
11
Arithmetic operators
Example
Int x = 1000;
Int y = 1000;
cout << x + y;
Comparison operators
Note: The return value of a comparison is either true (1) or false (0).
12
Example
Int x = 1000;
Int y = 2000;
cout << x > y; // returns 1 (true) because 2000 is greater than 1000
Assignment operators
Example
Int x = 1000;
x += 1000;
cout << x;
Logical operators
Logical operators are used to determine the logic between variables or values:
13
Chapter 2 DECISION MAKING
1. Conditions
The if Statement
Use the ifstatement to specify a block of C++ code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
❖ Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
In the example below, we test two values to find out if 20 is greater than 18. If the condition is
true, print some text:
Example
if (20 > 18) {
cout << "20 is greater than 18";
}
We can also test variables:
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
}
Example explained
In the example above we use two variables, x and y, to test whether x is greater than y (using the
>operator). As x is 20, and y is 18, and we know that 20 is greater than 18, we print to the screen
that "x is greater than y".
14
The else Statement
Use the elsestatement to specify a block of code to be executed if the condition is false.
Syntax
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (20) is greater than 18, so the condition is false. Because of this, we
move on to the else condition and print to the screen "Good evening". If the time was less than
18, the program would print "Good day".
15
The Else If Statement
Use the else ifstatement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
}
else if (time < 20) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
// Outputs "Good evening."
Example explained
In the example above, time (22) is greater than 10, so the first condition is false. The next
condition, in the else ifstatement, is also false, so we move on to the elsecondition since
condition1 and condition2 is both false- and print to the screen "Good evening".
However, if the time was 14, our program would print "Good day."
16
2. C++ Switch Statements
Use the switchstatement to select one of many code blocks to be executed.
Syntax switch(expression) { case x:
// code block
break; case y:
// code block break; default:
// code block
}
This is how it works:
❖ The switchexpression is evaluated once
❖ The value of the expression is compared with the values of each case
❖ If there is a match, the associated block of code is executed
❖ The breakand defaultkeywords are optional
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4; switch (day) { case 1:
case 2:
case 3:
case 4:
17
The break Keyword
When C++ reaches a break keyword, it breaks out of the switch block. This will stop the
execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more
testing.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the
code in the switch block.
The default Keyword
The defaultkeyword specifies some code to run if there is no case match:
Example
int day = 4;
switch (day) {
case 6:
cout << "Today is Saturday"; break;
case 7:
cout << "Today is Sunday"; break;
default:
cout << "Looking forward to the Weekend";
}
// Outputs "Looking forward to the Weekend"
Note: The default keyword must be used as the last statement in the switch, and it does not need
a break.
18
Chapter Three: - Loops, Arrays and Functions
C++ Loops
➢ Often when you write code, you want the same block of code to run over and over again
in a row. Instead of adding several almost equal code-lines in a script, we can use
loops to perform a task like this.
➢ In C++, we have the following looping statements:
➢ while - loops through a block of code as long as the specified condition is true
➢ do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
➢ for - loops through a block of code a specified number of times
The C++ while Loop
➢ The while loop executes a block of code as long as the specified condition is true.
Syntax
➢ while (condition) {
// code block to be executed
}
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++; }
The C++ do...while Loop
➢ The do/while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the
condition is true.
Syntax do {
// code block to be executed
}
while (condition);
Example
➢ int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
The C++ for Loop
➢ When you know exactly how many times you want to loop through a block of code, use
the for loop instead of a while loop:
19
Syntax
➢ for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}
C++ Arrays
➢ Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
➢ To declare an array, define the variable type, specify the name of the array followed
by square brackets and specify the number of elements it should store
➢ string cars[4];
➢ We have now declared a variable that holds an array of four strings. To insert values to
it, we can use an array literal - place the values in a comma-separated list, inside
curly braces:
➢ string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
Access the Elements of an Array
➢ You access an array element by referring to the index number inside square brackets [].
20
b) Functions in C++
A function is a block of code that performs a specific task. Functions help in breaking down a
program into smaller, reusable components. Example:
#include <iostream>
using namespace std;
void greet() {
cout << "Hello, Welcome to C++!";
}
int main() {
greet();
return 0;
}
class Car {
public:
string brand;
void display() {
cout << "Brand: " << brand;
21
}
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.display();
return 0;
}
7. Comparison of C and C++
Feature C Language C++ Language
Programming Paradigm Procedural Object-Oriented + Procedural
Data Security Less secure More secure (Encapsulation)
Function Overloading Not supported Supported
Standard Input/Output scanf(), printf() cin, cout
8. Importance of C++ in Modern Programming
C++ is widely used in developing:
• Operating systems (e.g., Windows, Linux)
• Game engines (e.g., Unreal Engine)
• Web browsers (e.g., Google Chrome, Mozilla Firefox)
• Financial applications and databases
Conclusion
C++ is a fundamental programming language that provides a strong foundation for software
development. Learning C++ helps in understanding core programming concepts and prepares
developers for advanced programming challenges.
22