Array in C++

In our series “Learn C++ Step by Step,” we have covered loops and basic variables. But what happens when your data grows from one single number to a thousand? In this guide, we dive into Arrays—a fundamental data structure that allows you to manage large amounts of data without losing your mind in a sea of variable names.

Definitions

Before we explore the logic, let’s define the core concepts simply:

Term  Definition
Array A single variable name that can hold more than one value of the same type.
Derived/Compound Data Type A data type built using existing ones.
Declaration Telling the computer the type, name, and size of your array.
Initialization The process of putting actual values into the array, either while writing the code or while the program is running.
Index The “address” or position of a value inside the array, which always starts at zero.
Contiguous Memory How the computer stores array items side-by-side in one straight block.

The “Why”: Why Do We Need Arrays?

Imagine you want to store a single roll number. You simply write int a = 5;. But what if you have 60 students in a class? Creating 60 separate variables (a, b, c… or roll1, roll2…) is nearly impossible to manage.
Now, imagine a business with 1,000 customers. Writing a thousand variable names is not just tedious—it’s bad programming. We need a way to store all these values under a single variable name. This is exactly what an array does.

Relatable Daily Life Example: The Apartment Building

Think of an array like an apartment building with a single name (e.g., “Sunshine Apartments”).
  • Single Name: Every resident lives in “Sunshine Apartments.”
  • Multiple Units: Inside that one building, there are many different rooms (units).
  • Same Type: In our programming world, every “room” in this building must hold the same thing—for example, only integers or only characters.

What is an Array?

An array is a collection of elements of the same data type.
  • You can store multiple integers in one array, but you cannot mix an integer with a float or a character in the same array.
  • It is often called a Data Structure because it organizes data in a specific way in your computer’s memory.

Declaring and Defining Arrays

To create an array, you need to tell C++ three things: the Data Type, the Array Name, and the Array Size.
The Syntax:
data_type array_name[array_size];
Example:
int roll_number[3]; //Declearation of an integer array
string name [3] = {"Ali", "Hamza", "Kashif"}; //Declearation + Definition of a string type array
char grades[3]; // Declearation of a character type array 
grades[0] = 'A'; // Assignment of value to the first index of array
grades[1] = 'B'; // Assignment of value to the second index of array
grades[2]= 'A'; //  Assignment of value to the third index of array

Crucial Rules for Sizes:

  1. Positive Constants: The size must be a positive number. You cannot have an array of size -5.
  2. Fixed Size: Once you set the size (like 60), you cannot change it while the program is running.
  3. Memory Allocation: When you define an array, the computer immediately reserves memory. For 60 integers (where each int is 4 bytes), the computer reserves 240 bytes (60 * 4). It will automatically deallocate the memory once the program is terminated.

Initialization: Putting Values in the “Boxes”

There are two main ways to fill your array with data:

A. Compile-Time Initialization (In your code)

You can fill the array as you write it using curly braces {}, as shown in the above example.
  • Known Size: int a[5] = {1, 2, 3, 4, 5};
  • Unknown Size: If you provide the list, you don’t need the number in the brackets: int a[] = {10, 20, 30};. C++ will count them and realize the size is 3.
  • Partial Filling: If you have an array of size 10 but only provide 5 numbers, the remaining 5 slots will automatically be filled with 0.

B. Run-Time Initialization (From the user)

If you want the user to type in the values while the program is running, you use a loop. Since array positions (indices) always start from 0, your loop should look like this:
#include <iostream>
using namespace std;
int main() {
    int roll_number[5];
    // Asking user for 5 roll numbers
    for (int i = 0; i < 5; i++) {
        cout << "Enter roll number of student "<<i+1<<": ";
        cin >> roll_number[i]; // i is the index (0, 1, 2, 3, 4)
    }
    return 0;
}

Interactive Elements: Try It Yourself!

  1. The “Zero” Mystery: Why does the array index always start from 0 instead of 1?. (Hint: It has to do with how the computer calculates memory addresses).
  2. Challenge 1: Try to declare an array with a negative size, like int test[-5];. What error does your compiler show you?.
  3. Challenge 2 (The Assignment): How can you initialize an array of size 100 so that every single value is the number 1, without typing “1” a hundred times?.
  4. Reflection Prompt: Why do we call arrays “wasteful” if we declare a size of 60 but only use 15 slots?.
  5. Logic Test: If an array is declared as int a[10], what is the index of the very last element?

Engagement Boost: Let’s Chat!

  • What is your biggest C++ fear? Is it keeping track of all these “boxes” in memory?
  • Question for the comments: In your daily life, besides an apartment building, what is another example of a “collection of the same thing” that could be an array?

Take the Next Step

Arrays are the building blocks of almost every complex program. For official technical documentation on data structures, visit the ISO C++ official resource.
Happy Coding!
Video Tutorial