Education logo

C++

HOW C++ WORKS & USES PART-2

By Shri ValsanPublished about a year ago 20 min read
1

C++ Array Size

Get the Size of an Array

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 data type it contains:

Example

int myNumbers[5] = {10, 20, 30, 40, 50};

int getArrayLength = sizeof(myNumbers) / sizeof(int);

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.

However, by using the sizeof() approach from the example above, we can now make loops that work for arrays of any size, which is more sustainable.

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:

Example

int myNumbers[5] = {10, 20, 30, 40, 50};

for (int i = 0; i < sizeof(myNumbers) / sizeof(int); i++) {

cout << myNumbers[i] << "\n";

}

Note that, in C++ version 11 (2011), you can also use the "for-each" loop:

Example

int myNumbers[5] = {10, 20, 30, 40, 50};

for (int i : myNumbers) {

cout << i << "\n";

}

It is good to know the different ways to loop through an array, since you may encounter them all in different programs.

C++ Multi-Dimensional Arrays

Multi-Dimensional Arrays

A multi-dimensional array is an array of arrays.

To declare a multidimensional array, define the variable type, specify the name of the array followed by square brackets which specify how 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.

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"

Remember that: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

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

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.

The following example outputs all elements in the letters array:

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

}

}

}

Why Multi-Dimensional Arrays?

Multi-dimensional arrays are great at representing grids. This example shows a practical use for them. 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

numberOfTurns++;

}

cout << "Victory!\n";

cout << "You won in " << numberOfTurns << " turns";

C++ Structures (struct)

C++ Structures

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.

After the declaration, specify the name of the structure variable (myStructure in the example below):

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:

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:

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:

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:

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

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

return 0;

}

C++ References

Creating References

A reference variable is a "reference" to an existing variable, and it is created with the & operator:

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 from the previous page, 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.

To access it, use the & operator, and the result will represent where the variable is stored:

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.

And why is it useful to know the memory address?

References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you the ability to manipulate the data in the computer's memory - which can reduce the code and improve the performance.

These two features are one of the things that make C++ stand out from other programming languages, like Python and Java.

C++ Pointers

Creating Pointers

You learned from the previous chapter, that we can get 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 pointerv however, is a variable that stores the memory address as its value.

A pointer variable points to a data type (like int or string) of the same type, and is created with the * operator. The address of the variable you're working with is assigned to the pointer:

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 example from the previous page, 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 a declaration (string* ptr), it creates a pointer variable.

• When not used in a declaration, it acts 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. You will learn more about return values later in the next chapter

inside the function (the body), add code that defines what the function should do

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)

void myFunction() { // declaration

// the body of the function (definition)

}

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(). This will make the code better organized and easier to read:

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

}

The following example has a function that takes a string called fname as parameter. When the function is called, we pass along a first name, which is used inside the function to print the full name:

Example

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

Inside the function, you can add as many parameters as you want:

Example

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.

Note that 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)

This example returns the sum of a function with two parameters:

Example

int myFunction(int x, int y) {

return x + y;

}

int main() {

cout << myFunction(5, 3);

return 0;

}

// Outputs 8 (5 + 3)

You can also store the result in a variable:

Example

int myFunction(int x, int y) {

return x + y;

}

int main() {

int z = myFunction(5, 3);

cout << z;

return 0;

}

// Outputs 8 (5 + 3)

C++ Functions - Pass By Reference

Pass By Reference

In the examples from the previous page, 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;

}

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

You can also pass arrays to a function:

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

trade schoolteacherstudentinterviewhow tohigh schooldegreecoursescollege
1

About the Creator

Shri Valsan

Reader insights

Be the first to share your insights about this piece.

How does it work?

Add your insights

Comments

There are no comments for this story

Be the first to respond and start the conversation.

Sign in to comment

    Find us on social media

    Miscellaneous links

    • Explore
    • Contact
    • Privacy Policy
    • Terms of Use
    • Support

    © 2024 Creatd, Inc. All Rights Reserved.