Arrays in C++: A Comprehensive Guide

Introduction

Imagine you’re a teacher with 30 students, and you need to keep track of their grades. It would be a hassle to create a separate variable for each student, right? That’s where arrays come to the rescue! Arrays let us store multiple values in a single variable, making it easier to organize and access data.

In this article, we’ll explore the power of arrays, why we need them, how to use them, and real-life examples where arrays prove invaluable in solving common programming challenges. Get ready to master the art of working with arrays in C++!

Arrays in C++: A Comprehensive Guide

What is an Array in C++?

An array in C++ is like a container that can hold multiple values of the same data type. It’s like a row of boxes, where each box can store a value. With an array, you can store and access multiple values using a single variable. For example, if you have an array of integers, you can store a list of numbers in it. Arrays are great for organizing and working with collections of data efficiently in your C++ programs.

Syntax:

C++
int grades[30]; // This creates an array named 'grades' that can store 30 integers.

Here, ‘grade‘ is an array that can hold a maximum of 30 elements of ‘double‘ type.

In C++, the size and type of arrays cannot be changed after its declaration.

C++ Array Declaration

In C++, an array is a collection of elements of the same data type, stored in contiguous memory locations. To declare an array, you specify the data type of its elements followed by the array’s name and the number of elements enclosed in square brackets. For example, to declare an integer array named “numbers” with 5 elements:

Syntax:

C++
dataType arrayName[arraySize];

For example:

C++
int numbers[5];

Here,

  • int – type of element to be stored
  • numbers – the name of the array
  • 5 - the size of the array

Access Elements in C++ Array

Accessing elements in a C++ array means retrieving the values stored in specific positions within the array. You can do this by using the array’s index or position. Each element in an array is assigned a unique index number, starting from 0 for the first element and increasing by 1 for each subsequent element. To access an element, you simply use the array name followed by the index of the element you want to access, enclosed in square brackets.

For example, ‘arrayName[index]‘ retrieves the value of the element at the specified index. This way, you can retrieve and work with the values stored in different positions of the array.

Syntax:

C++
// syntax to access array elements
array[index];

Key points to remember when accessing elements in a C++ array:

  • Indexing Starts from 0: Array indexes begin at 0. The first element is accessed using index 0, the second with index 1, and so on.
  • Boundaries: Be cautious not to access elements beyond the array’s boundaries. This can lead to undefined behavior or program crashes.
  • Valid Index Range: Array indices range from 0 to (size – 1), where “size” is the total number of elements in the array.
  • Brackets for Access: Elements are accessed using square brackets []. For instance, myArray[2] accesses the third element in the array.
  • Looping Through: To iterate through all elements, use a loop. For example, you can use a for loop with the index varying from 0 to (size – 1).

C++ Array Initialization

Array initialization in C++ is the process of assigning initial values to the elements of an array. This helps set the initial state of the array before using it in your program. You can provide individual values or use a loop to assign values sequentially. Initializing arrays can make your code more organized and ensure that the array starts with the desired values.

In C++, it’s possible to initialize an array during declaration. For example,

C++
// declare and initialize and array
int x[5] = {12, 13, 3, 15, 9, 19};

Another method to initialize an array during declaration:

C++
// declare and initialize an array
int x[] = {12, 13, 3, 15, 9, 19};

In situations like this, where we haven’t specified the size of the array, the compiler figures out the size on its own.

C++ Array With Empty Members

In C++, arrays are used to store multiple elements of the same data type in a sequence. However, an array cannot have “empty” members. Each element in an array holds a value based on its data type. If you want to represent an “empty” value, you can use a special value like 0 or a sentinel value that indicates emptiness. Here’s a Code example:

C++
#include <iostream>
using namespace std;

int main() {
    const int size = 5;
    int numbers[size] = {10, 0, 25, 0, 42};

    for (int i = 0; i < size; i++) {
        if (numbers[i] == 0) {
            cout << "Empty" << endl;
        } else {
            cout << numbers[i] << endl;
        }
    }

    return 0;
}

Output:

C++
10
Empty
25
Empty
42

Explanation:

  • The code creates an array named “numbers” with a size of 5 elements.
  • The value 0 is used in the array to indicate “empty” or uninitialized elements.
  • A loop iterates through each element of the array.
  • Inside the loop, it checks if the current element is equal to 0.
  • If the element is 0, it prints “Empty.” Otherwise, it prints the value of the element.

How to insert and print array elements?

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    const int size = 5; // Define the size of the array
    int numbers[size]; // Declare an array of integers

    // Insert elements into the array
    cout << "Enter " << size << " numbers:\n";
    for (int i = 0; i < size; i++) {
        cout << "Enter number " << i + 1 << ": ";
        cin >> numbers[i];
    }

    // Print the array elements
    cout << "Array elements are:\n";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }

    return 0;
}

Explanation:

  • We declare an array ‘numbers‘ of size 5 to store integers.
  • Using a loop, we input values from the user for each element of the array.
  • Another loop is used to print the elements of the array.

Output:

C++
Enter 5 numbers:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50
Array elements are:
10 20 30 40 50

Real-Life Example of Using Arrays

An array is like a row of lockers in a school corridor. All the lockers are identical and lined up in a single row. Each locker can hold one thing – a book, a lunchbox, or a bag. Importantly, each locker has a unique number, starting from 0 and going up to the total number of lockers minus one.

Let’s say we have 5 lockers, so the lockers will be numbered from 0 to 4. This is very similar to how arrays work in C++. You can store a value in each ‘locker’ (array element), and you can access or change the value by referring to the locker number (array index).

Code Example:

C++
#include<iostream>
using namespace std;

int main() {
    int locker[5]; // Creating an array of 5 lockers

    locker[0] = 10; // Putting a '10' in the first locker
    locker[1] = 20; // Putting a '20' in the second locker
    locker[2] = 30; // Putting a '30' in the third locker
    locker[3] = 40; // Putting a '40' in the fourth locker
    locker[4] = 50; // Putting a '50' in the fifth locker

    // Printing the content of each locker
    for (int i = 0; i < 5; i++) {
        cout << "Locker " << i << " contains: " << locker[i] << endl;
    }

    return 0;
}

Output:

C++
Locker 0 contains: 10
Locker 1 contains: 20
Locker 2 contains: 30
Locker 3 contains: 40
Locker 4 contains: 50

Explanation:

  • Array Concept: In this code, ‘locker‘ represents an array, like a row of lockers, capable of holding 5 integers.
  • Storing Values: Each locker (array element) can hold a value. We store values in each array element, simulating putting things in each locker.
  • Printing Contents: We access and print the contents of each locker by looping through the array elements.
  • Array Indexing: Similar to using a locker number to open a specific locker, we use array indices to access specific elements. In C++, array indices start from 0, not 1.
  • Zero-Based Indexing: Remember, arrays in C++ start from index 0. The first locker is ‘locker[0]‘, the second is ‘locker[1]‘, and so on.

Problem Statement and Uses

Problem Statement:

In a class, a teacher asks students to write down their favorite numbers. Now, the teacher wants to know the average of these favorite numbers and the highest number among them.

Write a C++ program to help the teacher with this. The teacher will enter the favorite number of each student, one by one. There are 5 students in the class.

Use arrays to store the favorite numbers, and then write functions to calculate the average and find the highest number.

Guide:

  • Create an array to store the numbers.
  • Use a loop to take input from the teacher.
  • Write a function to calculate the average of the numbers.
  • Write a function to find the highest number.

Note: Please make sure you handle the scenario of the teacher entering less than 5 numbers. For instance, if the teacher only enters 3 numbers, your program should still be able to calculate the average and find the highest number.

Hint:

  • You can use a loop to take inputs and populate the array.
  • To calculate the average, you might want to sum up all the elements and then divide by the number of elements.
  • To find the highest number, consider initializing a variable to the first element of the array, then compare this variable with all other elements in the array. If you find a number greater than your variable, update the variable with this new number.

Expected Output:

The output should display the average of the favorite numbers and the highest favorite number.

Examples of Arrays in C++

Example 1

C++
#include <iostream>
using namespace std;

int main() {
    int size;
    cout << "Enter the size of the array: ";
    cin >> size;

    int arr[size];

    cout << "Enter " << size << " elements:" << endl;
    for (int i = 0; i < size; i++) {
        cin >> arr[i];
    }

    cout << "Elements in the array:" << endl;
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }

    return 0;
}

Output:

C++
Enter the size of the array: 5
Enter 5 elements:
10 20 30 40 50
Elements in the array:
10 20 30 40 50

Explanation:

  • The user is asked to provide the size of an array.
  • The program creates an array with the specified size.
  • The user is prompted to input elements for the array.
  • The program stores the input values in the array.
  • Finally, the entered values are displayed back to the user.

Example 2

C++
#include <iostream>
using namespace std;

int main() {
    const int size = 5; // Size of the array
    int arr[size] = {10, 20, 30, 40, 50}; // Array elements
    int sum = 0; // Variable to store the sum

    // Calculating the sum of array elements
    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }

    // Calculating the average
    float average = static_cast<float>(sum) / size;

    // Displaying the sum and average
    cout << "Sum of array elements: " << sum << endl;
    cout << "Average of array elements: " << average << endl;

    return 0;
}

Output:

C++
Sum of array elements: 150
Average of array elements: 30

Explanation:

  • The code creates an array of integers with 5 elements.
  • It uses a for loop to iterate through the array and calculate the sum of all elements.
  • After calculating the sum, it converts the sum to a float and divides it by the number of elements to find the average.
  • The calculated sum and average are then displayed using the “cout” statement.
  • The program concludes by returning 0, indicating successful execution.

Advantages and Disadvantages of Using Arrays in C++

AdvantagesDisadvantages
Allows storage of multiple values in a single variableWasted memory if the array size is larger than needed
Efficient access to elements using indexRequires contiguous memory allocation
Simplifies iteration and processing of dataDifficult to insert or delete elements in the middle of the array
Facilitates sorting and searching operationsWasted memory if array size is larger than needed
Enables implementation of other data structuresCannot directly return an array from a function
Advantages and Disadvantages of Using Arrays in C++

Key Takeaways

  • Storage for Multiple Values: Arrays allow you to store multiple values of the same data type in a single variable, making data management more efficient.
  • Index-Based Access: Each value in the array is associated with an index, starting from 0. You can access array elements using their indices.
  • Fixed Size: Arrays have a fixed size declared at the beginning. Once defined, the size cannot be changed during runtime.
  • Sequential Storage: Array elements are stored sequentially in memory, making them easy to access in a linear manner.
  • Limitations: Arrays have limitations like fixed size and lack of dynamic resizing, which might not suit all scenarios. Other data structures can be more appropriate for specific tasks.

Conclusion

Becoming proficient with arrays in C++ is a significant stride toward mastering programming. As a fundamental component, arrays empower you to tackle diverse challenges. By developing your array of skills, you’ll gain the ability to solve a group of problems effectively. So, practice consistently and you’ll swiftly attain knowledge in using arrays, improving your programming skills. Happy Coding!

FAQs

Q. What is an array in C++?

An array in C++ is a variable that can store multiple values of the same type.

Q. Why do we need arrays in C++?

Arrays allow us to store multiple values in a single variable, which makes our code cleaner and easier to manage.

Q. Can the values in an array be of different types?

No, all the values in an array have to be of the same type.

Q. Can the size of an array be changed after it’s created?

No, the size of an array is fixed. Once you create an array, you can’t change its size.

Q. What are some limitations of arrays in C++?

Arrays in C++ have to be of the same type, their size is fixed, and they don’t have built-in functions like push or pop.

Deepak Vishwakarma

Founder

RELATED Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.