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++ 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 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. Continue reading C++ Multi-Dimensional Arrays

C++ Arrays Real-Life Examples

Real Life Example

To demonstrate a practical example of using arrays, let’s 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";

And in this example, we create a program that finds the lowest age among different ages: Continue reading C++ Arrays Real-Life Examples

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. Continue reading C++ Array Size

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:

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. Continue reading C++ Omit Array Size

C++ Arrays and Loops

Loop Through an Array

You can loop through the array elements with the for loop.

The following example outputs all elements in the cars array:

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

This example outputs the index of each element together with its value: Continue reading C++ Arrays and Loops

C++ Arrays

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 : Continue reading C++ Arrays

C++ Break and Continue

C++ Break

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to “jump out” of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  cout << i << "\n";
}

Continue reading C++ Break and Continue

C++ For Loop Examples

Real Life Example

To demonstrate a practical example of the for loop, let’s create a program that counts to 100 by tens:

Example

for (int i = 0; i <= 100; i += 10) {
  cout << i << "\n";
}

In this example, we create a program that only print even numbers between 0 and 10 (inclusive): Continue reading C++ For Loop Examples

C++ The foreach Loop

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
}

The following example outputs all elements in an array, using a “for-each loop”: Continue reading C++ The foreach Loop