CS Engineering Gyan

Arrays in C++

When a program needs to work with a single value, a regular variable does the job perfectly well. But real-world applications rarely deal with just one piece of information at a time. Whether it is a list of exam scores, a set of daily video views, or a collection of temperature readings, programs often need to store and manage multiple related values together. This is exactly the kind of problem arrays are designed to solve.

An array in C++ is a data structure that allows you to store multiple values of the same type under a single variable name. Instead of creating separate variables for every individual value, an array groups them together and lets you access each one using a numeric position, known as an index.

In this tutorial, you will learn how to declare and initialize arrays, how to access and modify their elements, how multidimensional arrays work, how to pass arrays to functions, and how to perform common operations such as finding sums, averages, and maximum values.


What is an Array in C++?

An array is a fixed-size collection of elements, all of the same data type, stored in contiguous memory locations. Once an array is created, its size cannot be changed, although the values stored inside it can be freely updated.

Example

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    int weeklyViews[5] = {1200, 1500, 1800, 2100, 2400};

    cout << channel << " views on day 3: " << weeklyViews[2] << endl;

    return 0;

}

Output

CS Engineering Gyan views on day 3: 1800

In this example, weeklyViews is an array holding five integer values. Notice that array indexing in C++ starts from zero, so the third day's views are accessed using index 2, not index 3.


Declaring and Initializing Arrays

Declaring an array in C++ requires specifying its data type, name, and size. Values can either be assigned individually after declaration, or provided all at once at the time of declaration.

Syntax

dataType arrayName[size];

dataType arrayName[size] = {value1, value2, value3};

Example

#include <iostream>

using namespace std;

int main() {

    int subscriberCounts[5];

    subscriberCounts[0] = 40000;

    subscriberCounts[1] = 42000;

    subscriberCounts[2] = 45000;

    cout << "First recorded count: " << subscriberCounts[0] << endl;

    return 0;

}

Output

First recorded count: 40000

When an array is declared without being initialized, its elements may contain unpredictable leftover values from memory, so it is good practice to assign values before using them in any calculation.


Initializing Arrays Without Specifying Size

C++ also allows you to declare and fill an array with values at the same time, without needing to specify the size manually. The compiler automatically determines the size based on how many values are provided.

Example

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    string playlists[] = {"C++ Basics", "OOPs Concepts", "DSA", "Operating Systems", "Placement Prep"};

    int totalPlaylists = sizeof(playlists) / sizeof(playlists[0]);

    cout << channel << " first playlist: " << playlists[0] << endl;

    cout << channel << " total playlists: " << totalPlaylists << endl;

    return 0;

}

Output

CS Engineering Gyan first playlist: C++ Basics

CS Engineering Gyan total playlists: 5

Since C++ arrays do not store their own size directly, the expression sizeof(playlists) / sizeof(playlists[0]) is a common technique used to calculate how many elements the array actually contains.


Accessing and Modifying Array Elements

Every element inside an array can be accessed or updated using its index, which always starts at zero for the first element and goes up to one less than the array's total size.

Example

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    int videoLikes[3] = {320, 450, 500};

    cout << channel << " likes on video 2: " << videoLikes[1] << endl;

    videoLikes[1] = 600;

    cout << channel << " updated likes on video 2: " << videoLikes[1] << endl;

    return 0;

}

Output

CS Engineering Gyan likes on video 2: 450

CS Engineering Gyan updated likes on video 2: 600

Unlike some languages, C++ does not automatically check whether an index is valid before accessing it. Attempting to access an index outside the array's bounds does not necessarily cause an immediate error, but it results in undefined behavior, which can lead to unpredictable results or program crashes.


Traversing an Array Using a for Loop

Since arrays often contain many values, loops are commonly used to process every element without writing repetitive code for each individual index.

Example

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    int weeklyUploads[5] = {2, 3, 1, 4, 2};

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

        cout << channel << " uploads in week " << (i + 1) << ": " << weeklyUploads[i] << endl;

    }

    return 0;

}

Output

CS Engineering Gyan uploads in week 1: 2

CS Engineering Gyan uploads in week 2: 3

CS Engineering Gyan uploads in week 3: 1

CS Engineering Gyan uploads in week 4: 4

CS Engineering Gyan uploads in week 5: 2

Using a loop to traverse an array keeps the code short and consistent, regardless of how many elements the array actually contains, as long as the loop's condition matches the array's size correctly.


Traversing an Array Using a Range-Based for Loop

Modern C++ also supports a range-based for loop, which simplifies traversal further by removing the need to manage an index manually, similar to a for-each style loop found in other languages.

Example

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    string topics[] = {"Arrays", "Pointers", "Functions", "OOPs"};

    cout << channel << " upcoming topics:" << endl;

    for (string topic : topics) {

        cout << "- " << topic << endl;

    }

    return 0;

}

Output

CS Engineering Gyan upcoming topics:

- Arrays

- Pointers

- Functions

- OOPs

The range-based for loop is ideal when you only need to read through each element in order, without requiring the index value itself for any calculations.


Common Array Operations

Beyond simple traversal, arrays are often used to perform calculations such as finding a total, an average, or the largest and smallest values within a dataset.

Example: Finding the Sum and Average

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    int dailyViews[5] = {1500, 1800, 2100, 1950, 2200};

    int total = 0;

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

        total += dailyViews[i];

    }

    double average = static_cast<double>(total) / 5;

    cout << channel << " total weekly views: " << total << endl;

    cout << channel << " average daily views: " << average << endl;

    return 0;

}

Output

CS Engineering Gyan total weekly views: 9550

CS Engineering Gyan average daily views: 1910

Example: Finding the Maximum Value

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    int dailyViews[5] = {1500, 1800, 2100, 1950, 2200};

    int maxViews = dailyViews[0];

    for (int i = 1; i < 5; i++) {

        if (dailyViews[i] > maxViews) {

            maxViews = dailyViews[i];

        }

    }

    cout << channel << " highest daily views: " << maxViews << endl;

    return 0;

}

Output

CS Engineering Gyan highest daily views: 2200

These kinds of operations, summing values, calculating averages, and finding maximums or minimums, form the basis of many real-world programs that analyze collections of data.


Multidimensional Arrays

C++ also supports multidimensional arrays, which are especially useful for representing data that naturally fits into a grid or table format, such as rows and columns.

Syntax

dataType arrayName[rows][columns];

Example

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    int monthlyViews[2][3] = {

        {1200, 1400, 1600},

        {1800, 2000, 2200}

    };

    cout << channel << " views for month 2, week 3: " << monthlyViews[1][2] << endl;

    return 0;

}

Output

CS Engineering Gyan views for month 2, week 3: 2200

Here, monthlyViews represents two months, each containing three weekly values. The first index selects the month, while the second index selects the specific week within that month.


Traversing a Multidimensional Array

Processing every element inside a multidimensional array typically requires nested loops, where the outer loop moves through each row and the inner loop moves through each column within that row.

Example

#include <iostream>

using namespace std;

int main() {

    string channel = "CS Engineering Gyan";

    int monthlyViews[2][3] = {

        {1200, 1400, 1600},

        {1800, 2000, 2200}

    };

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

        cout << channel << " month " << (month + 1) << " weekly views:" << endl;

        for (int week = 0; week < 3; week++) {

            cout << "  Week " << (week + 1) << ": " << monthlyViews[month][week] << endl;

        }

    }

    return 0;

}

Output

CS Engineering Gyan month 1 weekly views:

  Week 1: 1200

  Week 2: 1400

  Week 3: 1600

CS Engineering Gyan month 2 weekly views:

  Week 1: 1800

  Week 2: 2000

  Week 3: 2200

This nested structure mirrors how the data itself is organized, making it a natural fit for working with tables, grids, or any information that has two related dimensions.


Passing Arrays to Functions

Arrays can be passed to functions, allowing calculations to be performed on a collection of values inside a separate, reusable block of code. Since arrays do not carry their size information automatically, the size is usually passed as an additional parameter.

Example

#include <iostream>

using namespace std;

int calculateTotal(int views[], int size) {

    int total = 0;

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

        total += views[i];

    }

    return total;

}

int main() {

    string channel = "CS Engineering Gyan";

    int weeklyViews[5] = {1500, 1800, 2100, 1950, 2200};

    int total = calculateTotal(weeklyViews, 5);

    cout << channel << " total weekly views: " << total << endl;

    return 0;

}

Output

CS Engineering Gyan total weekly views: 9550

When an array is passed to a function in C++, it is effectively passed as a pointer to its first element, meaning any changes made to the array's contents inside the function will also affect the original array back in the calling code.


Arrays and Strings in C++

C++ provides two common ways to represent text: character arrays, which come from the underlying C language, and the more modern string class from the standard library. Understanding both is useful, since older codebases and certain low-level operations still rely on character arrays.

Example

#include <iostream>

using namespace std;

int main() {

    char channelChars[] = "CS Engineering Gyan";

    string channelString = "CS Engineering Gyan";

    cout << "Character array: " << channelChars << endl;

    cout << "String object: " << channelString << endl;

    return 0;

}

Output

Character array: CS Engineering Gyan

String object: CS Engineering Gyan

While a character array behaves like a fixed-size array of individual characters ending with a special null character, the string class offers far more convenient built-in methods for tasks like concatenation, comparison, and searching.


Advantages and Limitations of Arrays

Advantages Limitations
Allows efficient storage and access of multiple related values. Size is fixed once the array is created and cannot be resized.
Elements can be accessed quickly using their index. All elements must be of the same data type.
Works well with loops for processing large sets of data. C++ does not automatically check for out-of-bounds access.

Best Practices While Using Arrays


Common Mistakes Beginners Make

Mistake Correct Practice
Accessing an index equal to or greater than the array's size. Remember that valid indexes range from 0 to size minus 1.
Assuming array size can be changed after creation. Create a new array with the required size if more space is needed.
Forgetting that array indexing starts at zero. Always treat the first element as index 0, not index 1.
Forgetting to pass the array size when passing an array to a function. Always pass the size explicitly, since arrays do not track their own size.

Frequently Asked Interview Questions

  1. What is an array in C++?
    An array is a fixed-size collection that stores multiple values of the same data type under a single variable name.
  2. What index does array numbering start from in C++?
    Array indexing in C++ always starts from zero, not one.
  3. What happens if you access an invalid array index in C++?
    C++ does not automatically check bounds, so accessing an invalid index results in undefined behavior.
  4. Can the size of an array be changed after it is created?
    No, once an array is created, its size remains fixed for its entire lifetime.
  5. How can you calculate the number of elements in an array?
    By dividing the total size of the array by the size of a single element, using the sizeof operator.
  6. What is the difference between a one-dimensional and a multidimensional array?
    A one-dimensional array stores a single list of values, while a multidimensional array stores data arranged in rows and columns.
  7. Why is the array size passed separately when passing arrays to functions?
    Because arrays in C++ do not carry information about their own size once passed to a function.
  8. What is the difference between a character array and the string class?
    A character array is a fixed-size sequence of characters, while the string class offers dynamic sizing and built-in text-handling methods.

Summary

Arrays provide an efficient way to store and manage multiple related values in C++, whether you are working with simple numeric data or collections of text. By understanding how to declare, initialize, access, and modify arrays, you gain the ability to organize data in a structured and predictable way.

Combined with loops, arrays become even more powerful, allowing you to process large sets of data with just a few lines of code. Multidimensional arrays further extend this capability, letting you represent grid-like data such as tables and matrices naturally within your programs, while passing arrays to functions allows this logic to remain organized and reusable.

With a solid understanding of arrays, you are now ready to explore pointers in C++, which work closely with arrays and provide direct control over memory addresses and dynamic memory allocation.


← Previous: Functions in C++ Next: Pointers in C++ →

Home Visit Our YouTube Channel