C++ Final Exam Document
C++ Final Exam Document
C++ Final 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
What is C++?
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.
2
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; }
3
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 */
4
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:
5
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:
6
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;
7
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.
8
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;
9
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
10
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).
11
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:
12
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".
13
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".
14
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."
15
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:
16
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.
17
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:
18
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 [].
This statement accesses the value of the first element in cars:
Example
#include <iostream> "Ford", "Mazda"};
#include <string> cout << cars[0];
using namespace std; return 0;
int main() { }
string cars[4] = {"Volvo", "BMW",
C++ Functions
A function is a block of code which only runs when it is called.
You can pass data, known as parameters, into a function.
Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.
19
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code.
But you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function,
followed by parentheses ():
Syntax
void myFunction() {
// code to be executed
}
Call a Function
Declared functions are not executed immediately. They are "saved for later use",
and will be executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a
semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is
called
Function Declaration and Definition
A C++ function consist of two parts:
void myFunction() { // declaration
// the body of the function (definition)
}
Example
#include <iostream> int main() {
using namespace std; myFunction();
void myFunction() { return 0;
cout << "I just got executed!"; }
}
C++ Function Parameters
Information can be passed to functions as a parameter. Parameters act as variables
inside the function.
Parameters are specified after the function name, inside the parentheses. You can add as
many parameters as you want, just separate them with a comma
20
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Inside the function, you can add as many parameters as you want:
Example
#include <iostream> int main() {
using namespace std; myFunction("Liam", 3);
void myFunction(string fname, int age) { myFunction("Jenny", 14);
cout << fname << " Refsnes. " << age myFunction("Anja", 30);
<< " years old. \n"; return 0;
} }
Return Values
The void keyword, used in the previous examples, indicates that the function should not
return a value.
If you want the function to return a value, you can use a data type (such as int, string, etc.)
instead of void, and use the return keyword inside the function.
Example
#include <iostream> int main() {
using namespace std; cout << myFunction(3);
int myFunction(int x) { return (0);
return 5 + x; }
}
21
Chapter 4: - C++ OOP
C++ What is OOP?
OOP stands for Object-Oriented Programming.
Procedural programming is about writing procedures or functions that perform operations on the
data, while object-oriented programming is about creating objects that contain both data and
functions.
Object-oriented programming has several advantages over procedural programming:
OOP is faster and easier to execute
OOP provides a clear structure for the programs
OOP helps to keep the C++ code DRY "Don't Repeat Yourself", and makes the code easier
to maintain, modify and debug
OOP makes it possible to create full reusable applications with less code and shorter
development time
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You
should extract out the codes that are common for the application, and place them at a single place
and reuse them instead of repeating it.
C++ What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented programming. Look at the
following illustration to see the difference between class and objects:
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and functions from the
class.
C++ Classes/Objects
C++ is an object-oriented programming language.
Everything in C++ is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.
Attributes and methods are basically variables and functions that belongs to the class.
These are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works as an object
constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the class keyword:
Example
Create a class called "MyClass":
class MyClass { // The class public: // Access specifier
int myNum; // Attribute (int variable) string myString; // Attribute (string variable)
};
22
Example explained
The class keyword is used to create a class called MyClass.
The public keyword is an access specifier, which specifies that members (attributes and
methods) of the class are accessible from outside the class. You will learn more about access
specifiers later.
Inside the class, there is an integer variable myNum and a string variable myString. When
variables are declared within a class, they are called attributes.
At last, end the class definition with a semicolon ;.
Create an Object
In C++, an object is created from a class. We have already created the class named MyClass,
so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name.
To access the class attributes (myNum and myString), use the dot syntax (.) on the object:
Example
Create an object called "myObj" and access the attributes:
23