C++ Programing

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 53

C++ PROGRAMING

Difference between C and C++


 C++ was developed as an extension of C, and both languages have almost the same syntax.
 The main difference between C and C++ is that C++ support classes and objects, while C does
not

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:

 Every C++ statement ends with a semicolon ;.

Line 6:

 return 0; ends the main function.

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!";

 It is important that you end the statement with a semicolon ;


 If you forget the semicolon (;), an error will occur and the program will not run:
 Example
cout << "Hello World!"
[error: expected ';' before 'return']

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:

1. cout << "Hello World!";

2. cout << "Have a good day!";

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).

C++ Output (Print Text)


 The cout object, together with the << operator, is used to output values/print text:
 You can add as many cout objects as you want
 Example
#include <iostream>
using namespace std;
int main()

{
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;
}

 Another way to insert a new line, is with the endl manipulator:


 Example
#include <iostream>
using namespace std;
int main()

{
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}

 Both \n and endl are used to break lines.


 However, \n is most used.

But what is \n exactly?


 The newline character (\n) is called an escape sequence, and it forces the cursor to change its
position to the beginning of the next line on the screen.
 This results in a new line.
 Examples of other valid escape sequences are:

Escape Sequence Description


C++ PROGRAMING
\t creates a horizontal tab

\\ inserts a backslash character(\)

\" inserts a double quote character

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!";

 This example uses a single-line comment at the end of a line of code:


 Example

cout << "Hello World!"; // This is a comment

C++ Variables

 Variables are containers for storing data values.


 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 quotesbool - stores values with two states: true or false

Declaring (Creating) Variables


 To create a variable, specify the type and assign it a value:
 Syntax:type variableName = value;
 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.
C++ PROGRAMING

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)

C++ Declare Multiple Variables


Declare Many Variables
 To declare more than one variable of the same type, use a comma-separated list:

 Example
int x = 5, y = 6, z = 50;
cout << x + y + z;

One Value to Multiple Variables


 You can also assign the same value to multiple variables in one line:
 Example
int x, y, z;
x = y = z = 50;
cout << x + y + z;

C++ Identifiers
 All C++ variables must be identified with unique names.These unique names are
called identifiers.

The general rules for naming variables are:

 Names can contain letters, digits and underscores


 Names must begin with a letter or an underscore (_)
 Names are case-sensitive (myVar and myvar are different variables)
 Names cannot contain whitespaces or special characters like !, #, %, etc.
 Reserved words (like C++ keywords, such as int) cannot be used as names

C++ Variables Examples


Real-Life Examples
 In our examples, we simplify variable names to match their data type (myInt or myNum
for int types, myChar for char types, and so on). This is done to avoid confusion.
 Example
C++ PROGRAMING
 a program that stores different data about a college student:

// 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";

Calculate the Area of a Rectangle


 Create a program to calculate the area of a rectangle (by multiplying the length and width):
 Example
// Create integer variables
int length = 4;
int width = 6;
int area;
//Calculate the area of a rectangle
area = length * width;
// Print the variables
cout << "Length is: " << length << "\n";
cout << "Width is: " << width << "\n";
cout << "Area of the rectangle is: " << area << "\n";

C++ 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 (>>).
 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 (>>)

Creating a Simple Calculator


 In this example, the user must input two numbers.
 Then we print the sum by calculating (adding) the two numbers:
C++ PROGRAMING

 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;

C++ Data Types


 As explained in the Variables chapter, 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

data type size description


Boolean 1 byte stores true or false values.

Char 1 byte stores a single character/letters/numbers Or ASCII value

Int 2 or 4 byte stores whole numbers without decimals

Float 4 byte >stores fractional numbers,containing one or more decimals.

>Sufficient for storing 6-7 decimal digits.

Double 8 bytes >stores fractional numbers ,containing one or more decimals.

>sufficient for storing 15 decimal digits.

C++ Numeric Data Types


Numeric Types
 Use int when you need to store a whole number without decimals, like 35 or 1000,
 Float or double when you need a floating point number (with decimals), like 9.99 or 3.14515.

 int
int myNum = 1000;
cout << myNum;

 float
C++ PROGRAMING
float myNum = 5.75;
cout << myNum;

 double
double myNum = 19.99;
cout << myNum;

float vs. double


 The precision of a floating point value indicates how many digits the value can have after the
decimal point
 The precision of float is only six or seven decimal digits, while double variables have a precision
of about 15 digits.
 Therefore it is safer to use double for most calculations.

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;

C++ Boolean Data Types


Boolean Types
 A boolean data type is declared with the bool keyword and can only take the
values true or false

C++ Character Data Types


Character Types:
 The char data type is used to store a single character.
 The character must be surrounded by single quotes, like 'A' or 'c'.
 Alternatively, if you are familiar with ASCII, you can use ASCII values to display certain
characters:
 Example
char a = 65, b = 66, c = 67;
cout << a;
cout << b;
cout << c;
C++ PROGRAMING

C++ String Data Types


String Types
 The string type is used to store a sequence of characters (text).
 This is not a built-in type, but it behaves like one in its most basic usage.
 String values must be surrounded by double quotes:

C++ Data Types Examples


Real-Life Examples
 Example
 // Create variables of different data types
int items = 50;
double cost_per_item = 9.99;
double total_cost = items * cost_per_item;
char currency = '$';
 // Print variables
cout << "Number of items: " << items << "\n";

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)

 C++ divides the operators into the following groups:


 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators

Arithmetic Operators
C++ PROGRAMING
 Arithmetic operators are used to perform common mathematical operations.

Operators Name Description Examples


+ addition adds together two values x+y

- subtraction subtract one value from another x-y

* multiplication multiples two values x*y

/ division divides one value by other x/y

% modulus returns the division remainder x%y

++ increment increase the value of a variable by 1 ++x

-- decrement decrease the value of a variable by 1 --y

C++ Assignment Operators


Assignment Operators
 Assignment operators are used to assign values to variables.
 In the example below, we use the assignment operator (=) to assign the value 10 to a variable
called x:
 Example
int x = 10;

 The addition assignment operator (+=) adds a value to a variable:


 Example
int x = 10;
x += 5;

operator example same as


= x=5 x=5
+= x+=3 x=x+3
-= x-=3 x=x-3
*= x*=3 x=x*3
/= x/=3 x=x/3
%= x%=3 x=x%3
&= x&=3 x=x&3
|= x|=3 x=x|3
C++ PROGRAMING

^= x^=3 x=x^3
>>= x>>=3 x=x>>3
<<= x<<=3 x=x<<3

C++ Comparison Operators


Comparison Operators
 Comparison operators are used to compare two values (or variables).
 This is important in programming, because it helps us to find answers and make decisions.
 The return value of a comparison is either 1 or 0, which means true (1) or false (0).
 These values are known as Boolean values
 A list of all comparison operators:

Operator name example


== equal to x==y

!= not equal to x!=y

>. Grater than x>y

<. Less than x<y

>= greater than or equal to x>=y

<= lesser than or equal to x<=y

C++ Logical Operators


Logical Operators
 As with comparison operators, you can also test for true (1) or false (0) values with logical
operators.
 Logical operators are used to determine the logic between variables or values:

operator name description


&& logical and returns true if both statements are true
|| logical or returns true if one of the statement is true
! logical not reverse the result,returns false if the result
is true

C++ Strings
 A string variable contains a collection of characters surrounded by double quotes.
 string are used for storing text/characters.
C++ PROGRAMING

 For example, "Hello World" is a string.


 To use strings, you must include an additional header file in the source code,
the <string> library:
 Example
// Include the string library
#include <string>

C++ String Concatenation


String Concatenation
 The + operator can be used between strings to add them together to make a new string. This is
called concatenation:
 Example
string firstName = "John ";
string lastName = "Doe";
string fullName = firstName + lastName;
cout << fullName;

 to create a space between John and Doe on output:


string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << fullName;

C++ Numbers and Strings


Adding Numbers and Strings
 C++ uses the + operator for both addition and concatenation. Numbers are added.
 Strings are concatenated. If you add two numbers, the result will be a number:
 Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer)

 If you add two strings, the result will be a string concatenation:


 Example
string x = "10";
string y = "20";
string z = x + y; // z will be 1020 (a string)

 If you try to add a number to a string, an error occurs:


 Example
C++ PROGRAMING
string x = "10";
int y = 20;
string z = x + y;

C++ String Length


String Length
 To get the length of a string, use the length() function:

C++ Access Strings


Access Strings
 You can access the characters in a string by referring to its index number inside square
brackets [].
 This example prints the first character in myString:
 Example
string myString = "Hello";
cout << myString[0];
// Outputs H

 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

Change String Characters


 To change the value of a specific character in a string, refer to the index number, and use single
quotes:

C++ Special Characters


Strings - Special Characters
 Because strings must be written within quotes, C++ will misunderstand this string, and generate
an error:
 string txt = "We are the so-called "Vikings" from the north.";
 The solution to avoid this problem, is to use the backslash escape character.
 The backslash (\) escape character turns special characters into string characters:

Escape character Result Description

\’ ‘ single quotes

\” “ double quotes
C++ PROGRAMING
\\ \ backslash

 The sequence \" inserts a double quote in a string:


 Example
 string txt = "We are the so-called \"Vikings\" from the north.";
 The sequence \' inserts a single quote in a string:
 Example
string txt = "It\'s alright.";

 The sequence \\ inserts a single backslash in a string:


 Example
 string txt = "The character \\ is called backslash.";
 Other popular escape characters in C++ are:

Escape sequence Result

\n new line

\t tab

C++ User Input Strings


User Input Strings
 It is possible to use the extraction operator >> on cin to store 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

 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++ C-Style Strings


C-Style Strings
 C-style strings are created with the char type instead of string.
 the C language, which, unlike many other programming languages, does not have a string type
for easily creating string variables.
 Instead, you must use the char type and create an array of characters to make a "string" in C.
 As C++ was developed as an extension of C, it continued to support this way of creating strings
in C++:
 Example
string greeting1 = "Hello"; // Regular String
char greeting2[] = "Hello"; // C-Style String (an array of characters)

C++ Math
 C++ has many functions that allows you to perform mathematical tasks on numbers.

Max and min


 The max(x,y) function can be used to find the highest value of x and y:
 Example
cout << max(5, 10);
 the min(x,y) function can be used to find the lowest value of x and y:
 Example
cout << min(5, 10);

C++ <cmath> Library


 Other functions, such as sqrt (square root), round (rounds a number) and log (natural
logarithm), can be found in the <cmath> header file:
 Example
// Include the cmath library
#include <cmath>
cout << sqrt(64);
cout << round(2.6);
cout << log(2);

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).

C++ Boolean Expressions


Boolean Expression
 A Boolean expression returns a boolean value, which is either 1 (true) or 0 (false).
 This is useful for building logic and finding answers.the greater than (>) operator, to find out if
an expression (or variable) is true or false:
 Example
int x = 10;
int y = 9;
cout << (x > y); // returns 1 (true), because 10 is higher than 9

Real Life Example


 use the >= comparison operator to find out if the age (25) is greater than OR equal to the voting
age limit, which is set to 18:
 Example
int myAge = 25;
int votingAge = 18;
cout << (myAge >= votingAge); // returns 1 (true), meaning 25 year olds are allowed to vote!

C++ If ... Else


C++ Conditions and If Statements
 C++ supports the usual logical conditions from mathematics:
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to :a == b
 Not Equal to: a != b
 these conditions to perform different actions for different decisions.

C++ has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is true

 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

 Use switch to specify many alternative blocks of code to be executed

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++ Short Hand If Else


Shot Hand If...Else (Ternary Operator)
 There is also a short-hand if else, which is known as the ternary operator because it consists of
three operands.
 It can be used to replace multiple lines of code with a single line, and is often used to replace
simple if else statements:
 Syntax
variable = (condition) ? expressionTrue : expressionFalse;

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)

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.

The default Keyword


 The default keyword 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"

C++ While Loop


C++ Loops
 Loops can execute a block of code as long as a specified condition is reached.
 Loops are handy because they save time, reduce errors, and they make code more readable.

C++ While Loop


 The while loop loops through a block of code as long as a specified condition is true:
 Syntax
C++ PROGRAMING
while (condition) {
// code block to be executed
}

 Do not forget to increase the variable used in the condition, otherwise the loop will never end!

C++ Do/While Loop


The 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);

 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);

C++ While Loop Examples


Real Life Example
 To demonstrate a practical example of the while loop, we have created a simple "countdown"
program:
 Example
int countdown = 3;
while (countdown > 0) {
cout << countdown << "\n";
countdown--;
}
cout << "Happy New Year!!\n";

C++ For Loop


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:
 Syntax
C++ PROGRAMING
 for (statement 1; statement 2; statement 3) {
// code block to be executed
}
 Statement 1 is executed (one time) before the execution of the code block.
 Statement 2 defines the condition for executing the code block.
 Statement 3 is executed (every time) after the code block has been executed.
 The example below will print the numbers 0 to 4:
 Example
for (int i = 0; i < 5; i++) {
cout << i << "\n";
}

 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.

C++ Nested Loops


Nested Loops
 It is also possible to place a loop inside another loop. This is called a nested loop.
 The "inner loop" will be executed one time for each iteration of the “outer loop”:
 Example
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}

The foreach Loop


 There is also a "for-each loop" (also known as ranged-based for loop), which is used exclusively
to loop through elements in an array (or other data structures):
 Syntax
for (type variableName : arrayName) {
// code block to be executed
}

 Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}

C++ For Loop Examples


C++ PROGRAMING

Real Life Example


 we create a program that only print even numbers between 0 and 10 (inclusive):
 Example
for (int i = 0; i <= 10; i = i + 2) {
cout << i << "\n";
}

C++ Break and Continue


C++ Break
 The break statement can also be used to jump out of a loop.

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.

Break and Continue in While Loop


 You can also use break and continue in while loops:
 Break Example
int i = 0;
while (i < 10) {
cout << i << "\n";
i++;
if (i == 4) {
break;
}
}

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};

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
C++ PROGRAMING
string cars[4] = {"Volvo", "BMW", "Ford", "Mazda"};
cout << cars[0];
// Outputs Volvo

Loop Through an Array


 loop through the array elements with the for loop.
 Example
// Create an array of strings
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
// Loop through strings
for (int i = 0; i < 5; i++) {
cout << cars[i] << "\n";
}

loop through an array of integers:


 Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}

output all elements in an array using a "for-each loop":


 Example
 Loop through integers:
// Create an array of integers
int myNumbers[5] = {10, 20, 30, 40, 50};
// Loop through integers
for (int i : myNumbers) {
cout << i << "\n";
}
 Example
 Loop through strings:
// Create an array of strings
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
// Loop through strings
for (string car : cars) {
cout << car << "\n";
}

C++ Omit Array Size


Omit Array Size
 In C++, you don't have to specify the size of the array.
 The compiler is smart enough to determine the size of the array based on the number of
inserted values:
 Example
C++ PROGRAMING
string cars[] = {"Volvo", "BMW", "Ford"}; // Three array elements
 The example above is equal to:
string cars[3] = {"Volvo", "BMW", "Ford"}; // Also three array elements
 However, the last approach is considered as "good practice", because it will reduce the chance
of errors in your program.

Omit Elements on Declaration


 It is also possible to declare an array without specifying the elements on declaration, and add
them later:
 Example
string cars[5];
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
 If you don't specify the array size, an error occurs:
 Example
string cars[]; // Array size is not specified
cars[0] = "Volvo";
cars[1] = "BMW";
cars[2] = "Ford";
cars[3] = "Mazda";
cars[4] = "Tesla";
// error: array size missing in 'cars'

Fixed Size (Arrays) vs. Dynamic Size (Vectors)


 This is because the size of an array in C++ is fixed, meaning you cannot add or remove elements
after it is created.
 Arrays - Fixed Size Example
// An array with 3 elements
string cars[3] = {"Volvo", "BMW", "Ford"};
// Trying to add another element (a fourth element) to the cars array will result in an error
cars[3] = "Tesla";

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

C++ Array Size


 To get the size of an array, you can use the sizeof() operator:
 Example
int myNumbers[5] = {10, 20, 30, 40, 50};
cout << sizeof(myNumbers);
Result:
20

 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

Loop Through an Array with sizeof()


 In the Arrays and Loops Chapter, we wrote the size of the array in the loop condition (i
< 5). This is not ideal, since it will only work for arrays of a specified size.
 Example:
 Instead of writing:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
 It is better to write:
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < sizeof(myNumbers) / sizeof(myNumbers[0]); i++) {
cout << myNumbers[i] << "\n";
}
 the "for-each" loop, which is even cleaner and simpler:
 Example
int myNumbers[5] = {10, 20, 30, 40, 50};
for (int i : myNumbers) {
cout << i << "\n";
}
C++ PROGRAMING

C++ Arrays Real-Life Examples


Real Life Example
 create a program that calculates the average of different ages:
 Example
// An array storing different ages
int ages[8] = {20, 22, 18, 35, 48, 26, 87, 70};
float avg, sum = 0;
int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Loop through the elements of the array
for (int age : ages) {
sum += age;
}
// Calculate the average by dividing the sum by the length
avg = sum / length;
// Print the average
cout << "The average age is: " << avg << "\n";
 create a program that finds the lowest age among different ages:
 Example
// An array storing different ages
int ages[8] = {20, 22, 18, 35, 48, 26, 87, 70};

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";

C++ Multi-Dimensional Arrays


Multi-Dimensional Arrays
 A multi-dimensional array is an array of arrays.
 To declare a multi-dimensional array, define the variable type, specify
the name of the array followed by square brackets which specify how
C++ PROGRAMING
many elements the main array has, followed by another set of square
brackets which indicates how many elements the sub-arrays have:
string letters[2][4];
 As with ordinary arrays, you can insert values with an array literal - a
comma-separated list inside curly braces. In a multi-dimensional
array, each element in an array literal is another array literal.
 Example:

string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

 Each set of square brackets in an array declaration adds another dimension to an


array. An array like the one above is said to have two dimensions.
 Arrays can have any number of dimensions. The more dimensions an
array has, the more complex the code becomes. The following array
has three dimensions:
 string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};

Access the Elements of a Multi-Dimensional Array


 To access an element of a multi-dimensional array, specify an index number in each of
the array's dimensions.
 This statement accesses the value of the element in the first row (0) and third column
(2) of the letters array.
 Example

string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2]; // Outputs "C"

Change Elements in a Multi-Dimensional Array


 To change the value of an element, refer to the index number of the element in each of
the dimensions:
 Example
C++ PROGRAMING

string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";

cout << letters[0][0]; // Now outputs "Z" instead of "A"

Loop Through a Multi-Dimensional Array


 To loop through a multi-dimensional array, you need one loop for each of the
array's dimensions.

 Example
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};

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


for (int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}

 This example shows how to loop through a three-dimensional array:


 Example
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};

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


for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
cout << letters[i][j][k] << "\n";
}
}
}
C++ PROGRAMING

 In the following example we use a multi-dimensional array to represent a small game of


Battleship:
 Example
// We put "1" to indicate there is a ship.
bool ships[4][4] = {
{ 0, 1, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
};
// Keep track of how many hits the player has and how many turns they have played in these
variables
int hits = 0;
int numberOfTurns = 0;
// Allow the player to keep going until they have hit all four ships
while (hits < 4) {
int row, column;
cout << "Selecting coordinates\n";

// Ask the player for a row


cout << "Choose a row number between 0 and 3: ";
cin >> row;
// Ask the player for a column
cout << "Choose a column number between 0 and 3: ";
cin >> column;
// Check if a ship exists in those coordinates
if (ships[row][column]) {
// If the player hit a ship, remove it by setting the value to zero.
ships[row][column] = 0;
// Increase the hit counter
hits++;
// Tell the player that they have hit a ship and how many ships are left
cout << "Hit! " << (4-hits) << " left.\n\n";
} else {
// Tell the player that they missed
cout << "Miss\n\n";
}
// Count how many turns the player has taken number Of Turns++;
}
cout << "Victory!\n";
cout << "You won in " << numberOfTurns << " turns";

C++ Structures (struct)


C++ Structures
C++ PROGRAMING

 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

Access Structure Members


 To access members of a structure, use the dot syntax (.):
 Example
 Assign data to members of a structure and print it:
// Create a structure variable called myStructure
struct {
int myNum;
string myString;
} myStructure;
// Assign values to members of myStructure
myStructure.myNum = 1;
myStructure.myString = "Hello World!";
// Print members of myStructure
cout << myStructure.myNum << "\n";
cout << myStructure.myString << "\n";

One Structure in Multiple Variables


 You can use a comma (,) to use one structure in many variables:
 Syntax:

struct {
int myNum;
string myString;
} myStruct1, myStruct2, myStruct3; // Multiple structure variables separated with commas

 This example shows how to use a structure in two different variables:


 Example
 Use one structure to represent two cars:
C++ PROGRAMING

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:

struct myDataType { // This structure is named "myDataType"


int myNum;
string myString;
};

 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:

// Declare a structure named "car"


struct car {
string brand;
string model;
int year;
};
int main() {
// Create a car structure and store it in myCar1;
car myCar1;
myCar1.brand = "BMW";
C++ PROGRAMING

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";

C++ Enumeration (enum)


C++ Enums
 An enum is a special type that represents a group of constants (unchangeable
values).
 To create an enum, use the enum keyword, followed by the name of the enum, and
separate the enum items with a comma:
 Syntax:

enum Level {
LOW,
MEDIUM,
HIGH
};

 It is not required to use uppercase, but often considered as good practice.


 Enum is short for "enumerations", which means "specifically listed".
 To access the enum, you must create a variable of it.
 Inside the main() method, specify the enum keyword, followed by the name of the enum
(Level) and then the name of the enum variable (myVar in this example):
 Example:
enum Level myVar;
 Now that you have created an enum variable (myVar), you can assign a value to it.
 The assigned value must be one of the items inside the enum (LOW, MEDIUM or HIGH):
enum Level myVar = MEDIUM;
 By default, the first item (LOW) has the value 0, the second (MEDIUM) has the value 1, etc.
 If you now try to print myVar, it will output 1, which represents MEDIUM:
 Example:
int main() {
// Create an enum variable and assign a value to it
enum Level myVar = MEDIUM;
// Print the enum variable
cout << myVar;

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 in a Switch Statement


 Enums are often used in switch statements to check for corresponding values:

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

C++ Memory Address


Memory Address
 In the example , the & operator was used to create a reference variable.
 But it can also be used to get the memory address of a variable; which is the location of
where the variable is stored on the computer.
 When a variable is created in C++, a memory address is assigned to the variable. And
when we assign a value to the variable, it is stored in this memory address.
 Example
string food = "Pizza";
cout << &food; // Outputs 0x6dfed4

 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

 When not used in declaration, it act as a dereference operator.

C++ Modify Pointers


Modify the Pointer Value
 You can also change the pointer's value. But note that this will also change the value of
the original variable:
 Example
string food = "Pizza";
string* ptr = &food;
// Output the value of food (Pizza)
cout << food << "\n";
// Output the memory address of food (0x6dfed4)
cout << &food << "\n";
// Access the memory address of food and output its value (Pizza)
cout << *ptr << "\n";
// Change the value of the pointer
*ptr = "Hamburger";
// Output the new value of the pointer (Hamburger)
cout << *ptr << "\n";
// Output the new value of the food variable (Hamburger)
cout << food << "\n";
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.

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!

Function Declaration and Definition


 A C++ function consist of two parts:
 Declaration: the return type, the name of the function, and parameters (if any)
 Definition: the body of the function (code to be executed)
 Example:
void myFunction() { // declaration
// the body of the function (definition)
}
C++ PROGRAMING

 Note: If a user-defined function, such as myFunction() is declared after


the main() function, an error will occur:
 Example
int main() {
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error

 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!";
}

C++ Function Parameters


Parameters and Arguments
 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:
 Syntax

void functionName(parameter1, parameter2, parameter3) {


// code to be executed
}

 Example
C++ PROGRAMING

void myFunction(string fname) {


cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

 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.

C++ Default Parameters


Default Parameter Value
 You can also use a default parameter value, by using the equals sign (=).
 If we call the function without an argument, it uses the default value ("Norway"):
 Example
void myFunction(string country = "Norway") {
cout << country << "\n";
}
int main() {
myFunction("Sweden");
myFunction("India");
myFunction();
myFunction("USA");
return 0;
}
// Sweden
// India
// Norway
// USA
 A parameter with a default value, is often known as an "optional parameter". From the
example above, country is an optional parameter and "Norway" is the default value.

C++ Multiple Parameters


Multiple Parameters
 Example
C++ PROGRAMING

void myFunction(string fname, int age) {


cout << fname << " Refsnes. " << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
 when you are working with multiple parameters, the function call must have the same
number of arguments as there are parameters, and the arguments must be passed in
the same order.

C++ The Return Keyword


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
int myFunction(int x) {
return 5 + x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs 8 (5 + 3)

C++ Functions - Pass By Reference


Pass By Reference
 we used normal variables when we passed parameters to a function. You can also pass
a reference to the function. This can be useful when you need to change the value of
the arguments:
 Example
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
C++ PROGRAMING

}
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;
}

C++ Pass Array to a Function


Pass Arrays as Function Parameters
 Example
void myFunction(int myNumbers[5]) {
for (int i = 0; i < 5; i++) {
cout << myNumbers[i] << "\n";
}
}
int main() {
int myNumbers[5] = {10, 20, 30, 40, 50};
myFunction(myNumbers);
return 0;
}
 Example Explained
 The function (myFunction) takes an array as its parameter (int myNumbers[5]), and
loops through the array elements with the for loop.
 When the function is called inside main(), we pass along the myNumbers array, which
outputs the array elements.
 Note that when you call the function, you only need to use the name of the array when
passing it as an argument myFunction(myNumbers). However, the full declaration of
the array is needed in the function parameter (int myNumbers[5]).

C++ Function Examples


Real Life Example
 To demonstrate a practical example of using functions, let's create a program that
converts a value from fahrenheit to celsius:
 Example
C++ PROGRAMING

// Function to convert Fahrenheit to Celsius


float toCelsius(float fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}
int main() {
// Set a fahrenheit value
float f_value = 98.8;
// Call the function with the fahrenheit value
float result = toCelsius(f_value);
// Print the fahrenheit value
cout << "Fahrenheit: " << f_value << "\n";
// Print the result
cout << "Convert Fahrenheit to Celsius: " << result << "\n";
return 0;
}

C++ Function Overloading


Function Overloading
 With function overloading, multiple functions can have the same name with different
parameters:
 Example
int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)
 Consider the following example, which have two functions that add numbers of
different type:
 Example
int plusFuncInt(int x, int y) {
return x + y;
}
double plusFuncDouble(double x, double y) {
return x + y;
}
int main() {
int myNum1 = plusFuncInt(8, 5);
double myNum2 = plusFuncDouble(4.3, 6.26);
cout << "Int: " << myNum1 << "\n";
cout << "Double: " << myNum2;
return 0;
}
C++ PROGRAMING

 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.

C++ Variable Scope


 it is important to learn how variables act inside and outside of functions.
 In C++, variables are only accessible inside the region they are created. This is
called scope.

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;
}

 A local variable cannot be used outside the function it belongs to.


 If you try to access it outside the function, an error occurs:
 Example
C++ PROGRAMING

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

You might also like