C++ Programing
C++ Programing
C++ Programing
C++ Syntax
Line 1:
#include <iostream> is a header file library. Header file add functionality to C++ program.
That lets us work with input and output objects, such as cout (used in line 5).
Line 2:
using namespace std means that we can use names for objects and variables from the standard
library.
Line 3:
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.
Line 4:
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 5:
Line 6:
Line 7:
Do not forget to add the closing curly bracket } to actually end the main function.
Omitting Namespace
some C++ programs that runs without the standard namespace library.
The using namespace std line can be omitted and replaced with the std keyword, followed by
the :: operator for some objects:
Example
#include <iostream>
int main()
{
std::cout << "Hello World!";
return 0;
}
C++ PROGRAMING
C++ Statements
In a programming language, these programming instructions are called statements.
Example
cout << "Hello World!";
Many Statements
The statements are executed, one by one, in the same order as they are written:
Example
1. cout << "Hello World!";
2. cout << "Have a good day!";
3. return 0;
Example explained
From the example above, we have three statements:
3. return 0;
The first statement is executed first (print "Hello World!" to the screen).
Then the second statement is executed (print "Have a good day!" to the screen).
And at last, the third statement is executed (end the C++ program successfully).
{
cout << "Hello World!";
return 0;
}
New Lines
C++ PROGRAMING
To insert a new line, you can use the \n character:
Example
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
You can also use another << operator and place the \n character after the text, like this:
Example
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!" << "\n";
cout << "I am learning C++";
return 0;
}
{
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
C++ Comments
Single-line Comments
Single-line comments start with two forward slashes (//).
Any text between // and the end of the line is ignored by the compiler (will
not be executed).
This example uses a single-line comment before a line of code:
Example
// This is a comment
cout << "Hello World!";
C++ Variables
Other Types
A demonstration of other data types:
Example
int myNum = 5; // Integer (whole number without decimals)
double myFloatNum = 5.99; // Floating point number (with decimals)
char myLetter = 'D'; // Character
string myText = "Hello"; // String (text)
bool myBoolean = true; // Boolean (true or false)
Example
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.
// Student data
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// Print variables
cout << "Student ID: " << studentID << "\n";
cout << "Student Age: " << studentAge << "\n";
cout << "Student Fee: " << studentFee << "\n";
cout << "Student Grade: " << studentGrade << "\n";
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 (>>)
Example
int x, y;
int sum;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
sum = x + y;
cout << "Sum is: " << sum;
int
int myNum = 1000;
cout << myNum;
float
C++ PROGRAMING
float myNum = 5.75;
cout << myNum;
double
double myNum = 19.99;
cout << myNum;
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 = 35e3;
double d1 = 12E4;
cout << f1;
cout << d1;
cout << "Cost per item: " << cost_per_item << "" << currency << "\n";
cout << "Total cost = " << total_cost << "" << currency << "\n";
C++ Operators
Operators are used to perform operations on variables and values. the + operator to add
together two values:
Example
int x = 100 + 50;
Although the + operator is often used to add together two values, like in the example above, it
can also be used to add together a variable and a value, or a variable and another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Arithmetic Operators
C++ PROGRAMING
Arithmetic operators are used to perform common mathematical operations.
^= x^=3 x=x^3
>>= x>>=3 x=x>>3
<<= x<<=3 x=x<<3
C++ Strings
A string variable contains a collection of characters surrounded by double quotes.
string are used for storing text/characters.
C++ PROGRAMING
Note: String indexes start with 0: [0] is the first character. [1] is the second character, etc.
This example prints the second character in myString:
Example
string myString = "Hello";
cout << myString[1];
// Outputs e
\’ ‘ single quotes
\” “ double quotes
C++ PROGRAMING
\\ \ backslash
\n new line
\t tab
Example[error]
string fullName;
cout << "Type your full name: ";
cin >> fullName;
cout << "Your name is: " << fullName;
// Type your full name: John Doe
// Your name is: John
From the example above, you would expect the program to print "John Doe", but it only prints
"John".
That's why, when working with strings, we often use the getline() function to read a line of text.
It takes cin as the first parameter, and the string variable as second:
Example
string fullName;
cout << "Type your full name: ";
C++ PROGRAMING
getline (cin, fullName);
cout << "Your name is: " << fullName;
// Type your full name: John Doe
// Your name is: John Doe
C++ Math
C++ has many functions that allows you to perform mathematical tasks on numbers.
C++ Booleans
Very often, in programming, you will need a data type that can only have one of two values,
like:
YES / NO
C++ PROGRAMING
ON / OFF
TRUE / FALSE
For this, C++ has a bool data type, which can take the values true (1) or false (0).
Use else to specify a block of code to be executed, if the same condition is false
Use else if to specify a new condition to test, if the first condition is false
The if Statement
C++ PROGRAMING
Use the if statement 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.
C++ Else
The else Statement
Use the else statement 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
}E
lse{
// block of code to be executed if the condition is false
}
C++ Else If
The else if Statement
Use the else if statement 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.";
C++ PROGRAMING
}
// Outputs "Good evening."
C++ Switch
C++ Switch Statements
Use the switch statement 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 switch expression 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 break and default keywords are optional, and will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
Example
int day = 4;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
C++ PROGRAMING
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
}
// Outputs "Thursday" (day 4)
Do not forget to increase the variable used in the condition, otherwise the loop will never end!
The loop will always be executed at least once, even if the condition is false, because the code
block is executed before the condition is tested:
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
Example explained
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is
true, the loop will start over again, if it is false, the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
C++ Continue
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
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"};
To create an array of three integers, you could write:
int myNum[3] = {10, 20, 30};
Vectors
C++ provides vectors, which are resizable arrays.
The size of a vector is dynamic.
Vectors are found in the <vector> library, and they come with many useful functions to add,
remove and modify elements:
Vectors - Dynamic Size Example
// A vector with 3 elements
vector<string> cars = {"Volvo", "BMW", "Ford"};
// Adding another element to the vector
cars.push_back("Tesla");
C++ PROGRAMING
Why did the result show 20 instead of 5, when the array contains 5 elements?
It is because the sizeof() operator returns the size of a type in bytes.
You learned from the Data Types chapter that an int type is usually 4 bytes, so from the
example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
To find out how many elements an array has, you have to divide the size of the array by
the size of the first element in the array:
Example
int myNumbers[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(myNumbers) / sizeof(myNumbers[0]);
cout << getArrayLength;
Result:
5
int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Create a variable and assign the first array element of ages to it
int lowestAge = ages[0];
// Loop through the elements of the ages array to find the lowest age
for (int age : ages) {
if (lowestAge > age) {
lowestAge = age;
}
}
// Print the lowest age
cout << "The lowest age is: " << lowestAge << "\n";
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2]; // Outputs "C"
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";
Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
Structures (also called structs) are a way to group several related variables into one
place. Each variable in the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, string, bool,
etc.).
Create a Structure
To create a structure, use the struct keyword and declare each of its members inside
curly braces.
Syntax
struct { // Structure declaration
int myNum; // Member (int variable)
string myString; // Member (string variable)
} myStructure; // Structure variable
struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3; // Multiple structure variables separated with commas
struct {
string brand;
string model;
int year;
} myCar1, myCar2; // We can add variables by separating them with a comma here
// Put data into the first structure
myCar1.brand = "BMW";
myCar1.model = "X5";
myCar1.year = 1999;
// Put data into the second structure
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
Named Structures
By giving a name to the structure, you can treat it as a data type. This means that you
can create variables with this structure anywhere in the program at any time.
To create a named structure, put the name of the structure right after
the struct keyword:
Syntax:
To declare a variable that uses the structure, use the name of the structure as the data
type of the variable:
Syntax:
myDataType myVar;
Example
Use one structure to represent two cars:
myCar1.model = "X5";
myCar1.year = 1999;
// Create another car structure and store it in myCar2;
car myCar2;
myCar2.brand = "Ford";
myCar2.model = "Mustang";
myCar2.year = 1969;
// Print the structure members
cout << myCar1.brand << " " << myCar1.model << " " << myCar1.year << "\n";
cout << myCar2.brand << " " << myCar2.model << " " << myCar2.year << "\n";
enum Level {
LOW,
MEDIUM,
HIGH
};
return 0;
}
C++ PROGRAMING
Change Values
As you know, the first item of an enum has the value 0. The second has the value 1, and so
on.
Example:
enum Level {
LOW = 25,
MEDIUM = 50,
HIGH = 75
};
int main() {
enum Level myVar = MEDIUM;
cout << myVar; // Now outputs 50
return 0;
}
Note that if you assign a value to one specific item, the next items will update their
numbers accordingly:
Example:
enum Level {
LOW = 5,
MEDIUM, // Now 6
HIGH // Now 7
};
enum Level {
LOW = 1,
MEDIUM,
HIGH
};
int main() {
enum Level myVar = MEDIUM;
switch (myVar) {
case 1:
cout << "Low Level";
break;
case 2:
cout << "Medium level";
break;
case 3:
cout << "High level";
break;
}
C++ PROGRAMING
return 0;
}
C++ References
Creating References
A reference variable is a "reference" to an existing variable, and it is created with
the & operator:
Example:
string food = "Pizza"; // food variable
string &meal = food; // reference to food
Now, we can use either the variable name food or the reference name meal to refer to
the food variable:
Example
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
Note: The memory address is in hexadecimal form (0x..). Note that you may not get the
same result in your program.
C++ Pointers
Creating Pointers
the memory address of a variable by using the & operator:
Example
string food = "Pizza"; // A food variable of type string
cout << food; // Outputs the value of food (Pizza)
cout << &food; // Outputs the memory address of food(0x6dfed4)
A pointer is a variable that stores the memory address as its value.
C++ PROGRAMING
A pointer variable points to a data type (like int or string) of the same type, and is
created with the * operator.
Example
string food = "Pizza"; // A food variable of type
string
string* ptr = &food; // A pointer variable, with the name ptr, that stores the address
of food
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
Example explained
Create a pointer variable with the name ptr, that points to a string variable, by using the
asterisk sign * (string* ptr). Note that the type of the pointer has to match the type of
the variable you're working with.
Use the & operator to store the memory address of the variable called food, and assign
it to the pointer.
Now, ptr holds the value of food's memory address.
Tip: There are three ways to declare pointer variables, but the first way is preferred:
string* mystring; // Preferred
string *mystring;
string * mystring;
C++ Dereference
Get Memory Address and Value
In the previous example , we used the pointer variable to get the memory address of a
variable (used together with the & reference operator).
However, you can also use the pointer to get the value of the variable, by using
the * operator (the dereference operator):
Example
string food = "Pizza"; // Variable declaration
string* ptr = &food; // Pointer declaration
// Reference: Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";
// Dereference: Output the value of food with the pointer (Pizza)
cout << *ptr << "\n";
Note that the * sign can be confusing here, as it does two different things in our code:
When used in declaration (string* ptr), it creates a pointer variable.
C++ PROGRAMING
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
}
Example Explained
myFunction() is the name of the function
void means that the function does not have a return value.
inside the function (the body), add code that defines what the function should do
C++ PROGRAMING
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:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
A function can be called multiple times:
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
// I just got executed!
// I just got executed!
// I just got executed!
However, it is possible to separate the declaration and the definition of the function -
for code optimization.
You will often see C++ programs that have function declaration above main(), and
function definition below main().
Example
// Function declaration
void myFunction();
// The main method
int main() {
myFunction(); // call the function
return 0;
}
// Function definition
void myFunction() {
cout << "I just got executed!";
}
Example
C++ PROGRAMING
When a parameter is passed to the function, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
// Call the function, which will change the values of firstNum and secondNum
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
Instead of defining two functions that should do the same thing, it is better to overload
one.
In the example below, we overload the plusFunc function to work for
both int and double:
Example
int plusFunc(int x, int y) {
return x + y;
}
double plusFunc(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFunc(8, 5);
double myNum2 = plusFunc(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
Multiple functions can have the same name as long as the number and/or type of
parameters are different.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function:
Example
void myFunction() {
// Local variable that belongs to myFunction
int x = 5;
// Print the variable x
cout << x;
}
int main() {
myFunction();
return 0;
}
void myFunction() {
// Local variable that belongs to myFunction
int x = 5;
}
int main() {
myFunction();
// Print the variable x in the main function
cout << x;
return 0;
}
C++ PROGRAMING
C++ PROGRAMING
C++ PROGRAMING
C++ PROGRAMING
C++ PROGRAMING
C++ PROGRAMING
C++ PROGRAMING
C++ PROGRAMING
C++ PROGRAMING