Arrays in C++
Have you ever seen books sitting neatly on a bookshelf?
Each book has its own special slot!
Imagine you have a bookshelf with 12 slots, and each slot can hold one book. You can put a book in any slot, take one out, or replace it with another. The slots are all lined up and numbered from 0 to 11 — starting from the left.
Arrays in C++ work just like that bookshelf.
In C++, an array is a way to keep a bunch of similar things (like numbers, names, or scores) together in one place — just like a bookshelf keeps all your books lined up in one row.
Each slot on the shelf is like a place in the array — we call that an “element.”
Each slot also has a number (called an “index”), starting from 0. So the first slot is index 0, the second is index 1, and so on.
You can easily find, add, or change what’s in any slot just by using its index number.
Suppose you want to store the scores of 12 basketball games. Instead of making 12 separate variables, you can simply use an array with 12 slots. Each slot will store the score for one game.
In short:
Arrays help you keep lots of related things in one place — just like a bookshelf helps you organize and manage all your books easily!
Declaring Arrays in C++
Imagine you're organizing a birthday party. You’ve invited 10 friends, and you decide to set aside one cupcake for each friend. So, you line up 10 plates on the table — one for each cupcake.
But before placing the cupcakes, you tell yourself:
"Okay, I need 10 plates — one for each person."
That’s exactly what you're doing when you declare an array in C++. You're saying, "Hey computer, I need a row of boxes to store things, and I know how many I need."
How Do You Declare an Array in C++?
Here’s the basic format:
type arrayName[size];
Let’s break it down:
- type – the kind of values you’ll store (like int for numbers, char for characters)
- arrayName – the name you give to your array (just like naming your cupcake plates!)
- size – how many items you want to store (just like how many plates you need)
Here are few example on how to declare an array:
1. Declaring an array of 5 integers:
int scores[5];
You’ve now told the computer:
"Give me 5 boxes where I can store integers (like test scores)."
2. Declaring an array of 10 characters:
char grades[10];
Now you're ready to store 10 letter grades, like 'A', 'B', 'C', etc.
3. Declaring and initializing at the same time:
int ages[3] = {12, 15, 14};
You just created an array named ages, and you already put in the ages of three kids.
In C++, arrays start counting from 0, not 1, which means the numbering begins a bit earlier than we usually expect.
So, the first element of the array is at index 0, the second at 1, and so on.
An index is just the position number of an element in the array — like a label that tells you where each item lives.
Think of it like shelf numbers in a library that help you find a book quickly!
"Here’s the secret sauce: When you type int marks[4], the computer goes ‘Got it!’ and carves out 4 boxes in its memory—all lined up like seats in a row. Somewhat like this:
Index | Box Name | What It Can Hold |
---|---|---|
0 | marks[0] | An integer |
1 | marks[1] | An integer |
2 | marks[2] | An integer |
3 | marks[3] | An integer |
Here’s the important stuff—think of it like rules for a game!
- The size of an array must be known at the time of declaration.
- Once you declare an array with a size, you can’t change it later.
- Array indexing starts at 0, not 1!
Initializing Arrays in C++
You’re getting ready for school and your mom says,
"Make sure you pack your books!"
So, you open your bag and start placing your books one by one:
- Math goes in first
- Then Science
- Then English, and so on...
Now, think of your school bag like an array. When you’re putting the books inside, you’re initializing it — you’re giving it actual values.
In programming, when you declare an array, it's like saying,
"I need space for my books."
And when you initialize it, you're saying,
"Here are the actual books I'm packing."
So, What is Initialization in C++?
Initialization simply means giving values to the array elements when you create it.
Here’s the basic idea:
int numbers[3] = {10, 20, 30};
You just created an array of 3 integers and immediately stored 10, 20, and 30 in it.
Different Ways to Initialize Arrays
1. Initialize All Elements at Once
int scores[4] = {90, 85, 78, 92};
Each value goes into the array in order:
Index | Value |
---|---|
0 | 90 |
1 | 85 |
2 | 78 |
3 | 92 |
2. Let the Compiler Count the Size
If you know the values but don’t want to count them yourself:
int ages[] = {12, 14, 13, 11, 15};
The compiler will automatically figure out that the size is 5.
3. Initialize Some Elements, Leave Others as Zero
int numbers[5] = {1, 2};
Here’s what happens:
Index | Value |
---|---|
0 | 1 |
1 | 2 |
2 | 0 |
3 | 0 |
4 | 0 |
If you don’t give values for some positions, C++ fills the rest with zeroes (for simple types like int).
4. Initialize Everything as Zero
You can write:
int marks[6] = {0};
This will make all 6 values zero!
What If You Don’t Initialize?
If you write:
int scores[3];
and don’t give it values, the array will hold garbage values (random numbers). So it's always safer to initialize it if you plan to use it right away.
Here’s an example table showing what you might see:
Index | Value (Garbage) |
---|---|
scores[0] | -858993460 |
scores[1] | 32767 |
scores[2] | 0 |
Note: These values are not fixed — they can be totally different each time you run the program or on a different machine. They're called garbage values because they come from whatever data was already sitting in that part of memory.
Here's a quick recap:
Syntax | What It Means |
---|---|
int a[3] = {1, 2, 3}; | Fill with values 1, 2, 3 |
int b[] = {4, 5}; | Let the compiler count the size (2) |
int c[4] = {7}; | First value is 7, rest are 0 |
int d[5] = {0}; | All values become 0 |
Accessing Array Elements in C++
Imagine you have a box of 6 chocolates, all lined up in a row. Now, each chocolate is in its own slot, and you can pick any one by saying,
"I want the 2nd one!" or
"Give me the 5th one!"
Arrays in C++ are like that chocolate box. Each item has a specific spot (called an index), and you can grab or change any item just by using that number.
Let’s Look at an Array First:
int chocolates[6] = {10, 20, 30, 40, 50, 60};
Here, the array chocolates has 6 items. Each number might represent how sweet or special each chocolate is.
How to Access an Element?
You use the array name and put the index inside square brackets:
cout << chocolates[2]; // This will print 30
Wait... why does it print 30 and not 20?
Important Rule: Array indexing in C++ starts from 0!
Index | Value |
---|---|
0 | 10 |
1 | 20 |
2 | 30 |
3 | 40 |
4 | 50 |
5 | 60 |
So:
- chocolates[0] is 10
- chocolates[1] is 20
- chocolates[2] is 30
...and so on.
Changing Values in the Array
Just like you can eat a chocolate and put a new one in its place, you can change values in an array.
chocolates[3] = 100;
Now, the chocolate at position 3 (which used to be 40) becomes 100!
So if you print:
cout << chocolates[3]; // This will now print 100
Looping Through All Elements
What if you want to look at every chocolate in the box? You don’t need to write 6 lines — just use a loop!
Looping through all elements is like peeking at every chocolate.
for(int i = 0; i < 6; i++) {
cout << chocolates[i] << " ";
}
Output:
10 20 30 100 50 60
The loop starts at index 0 and goes all the way to 5, printing each value.
In the same way, we can also input elements into the array using loops.
// Ask the user to enter 5 values for the 'numbers' array
cout << "Enter 5 numbers to store in the array: ";
for (int i = 0; i < 5; i++) {
// Store the input value at index i
cin >> numbers[i];
}
This loop repeats 5 times and fills the array from index 0 to 4.
Each time, the user enters a number, and it’s stored in the array.
What If You Try an Invalid Index?
Let’s say you try to do this:
cout << chocolates[6]; // Oops!
That’s dangerous! The index 6 doesn’t exist in an array of size 6 (remember: last index is 5). C++ might show garbage values or even crash your program.
This is undefined behavior — it depends on what's in memory at that moment. Sometimes it may crash, sometimes it may work "by accident", and sometimes it may silently give wrong values.
Moral of the story:
Always stay within the valid range of your array (0 to size-1), or you’ll risk unexpected bugs or crashes.
So always make sure your index is between 0 and size-1.
Here's a quick summary:
1. Use array[index] to get or set a value
2. Indexing starts at 0.
3. Be careful not to go out of bounds.
4. Loops make it easy to work with all elements.
How are Arrays stored in Memory in C++?
Imagine you're at school and there's a long row of lockers. Every student gets one locker. They’re all right next to each other, side by side, like a long train. Each locker has a number on it so you know where to go.
Arrays in memory work just like that row of lockers!
When you create an array in C++, the computer reserves a bunch of memory blocks right next to each other, like lockers. Each "locker" stores one item from the array, and each has a number (called an index) so you can easily find it.
A Simple Array Example:
int scores[4] = {90, 80, 70, 60};
When you create this array, the computer sets aside 4 memory blocks (because the array size is 4), and puts the values in order.
Let’s assume each int takes 4 bytes in memory.
Here’s what the memory might look like:
Memory Address | Index | Value |
---|---|---|
1000 | 0 | 90 |
1004 | 1 | 80 |
1008 | 2 | 70 |
1012 | 3 | 60 |
See how the addresses increase by 4 each time?
That’s because each integer takes 4 bytes.
Why Are They Stored Next to Each Other?
Because it makes it super fast for the computer to find any value.
Let’s say the array starts at memory address 1000. If you want the 3rd element (index 2), the computer just does a quick calculation:
Address of scores[2] = 1000 + (2 × 4) = 1008
Boom! Found in an instant.
You can find any element by using the starting address + index × size.
This is called random access — it means the computer can jump directly to any element in the array using its index, without checking each one before it.
Think of it like this:
You’re at a library and you want the 5th book on the shelf.
You don’t need to read the first 4 books to find it — you just go straight to the 5th spot and grab it. Super fast!
That’s exactly what the computer does with arrays.
Let’s say the array starts at memory address 1000, and each item takes 4 bytes.
If you want the element at index 3, it does this:
Address = Starting Address + (Index × Size of each item)
= 1000 + (3 × 4) = 1012
It doesn’t look at index 0, 1, or 2 — it just jumps right to index 3.
No searching, no delays. Just fast direct access.
What Happens in Memory If You Change a Value?
Let’s say you write:
scores[1] = 100;
Now, the value at index 1 changes from 80 to 100. The memory still looks like this:
Memory Address | Index | Value |
---|---|---|
1000 | 0 | 90 |
1004 | 1 | 100 |
1008 | 2 | 70 |
1012 | 3 | 60 |
Nothing moves. Just the value at that memory spot gets replaced. Super efficient!
Size of an Array
Imagine an array like a bookshelf, where each spot on the shelf can hold a book. If the bookshelf has 5 spots, it can hold exactly 5 books. The size of the array is simply the number of spots (or elements) it can hold.
For example, when we declare an array like this:
int chocolates[5];
The size of the array is 5 because it can hold 5 chocolate bars (or any kind of data). This means we have 5 spots on the "shelf" where we can store values. Each of those spots has a number (called an index) starting from 0 to 4.
In C++, if we want to find out how many spots or elements an array can hold, we can use the sizeof operator:
// Declaring an array of size 5
int chocolates[5] = {1, 2, 3, 4, 5};
int size = sizeof(chocolates) / sizeof(chocolates[0]);
Here’s what this does:
- sizeof(chocolates) tells us the total size (in bytes) of the array.
- sizeof(chocolates[0]) tells us the size of one element in the array (like the size of one chocolate bar).
- By dividing these two, we get the total number of spots in the array.
So, if you have an array like chocolates[5], the size will be 5, just like how a bookshelf with 5 spots can hold exactly 5 books.
Recap — Arrays in Memory:
- Arrays are stored in contiguous (side-by-side) memory blocks.
- You can find any element by using the starting address + index × size.
- This layout makes arrays super fast for accessing elements by index
Array Basics in C++ Try on Compiler
#include <iostream>
using namespace std;
int main() {
// -------------------------------------
// DECLARING AN ARRAY
// -------------------------------------
// Declare an array of 5 integers (can store 5 numbers)
int numbers[5];
// -------------------------------------
// INITIALIZING AN ARRAY
// -------------------------------------
// Method 1: Initializing values during declaration
int scores[4] = {90, 80, 70, 60};
// Method 2: Initializing some values, rest will be 0
int ages[5] = {10, 11}; // Remaining 3 will be 0
// Method 3: Initializing all values to 0
int marks[6] = {0}; // All elements will be 0
// -------------------------------------
// TAKING INPUT IN ARRAY USING LOOP
// -------------------------------------
// Ask the user to enter 5 values for the 'numbers' array
cout << "Enter 5 numbers to store in the array: ";
for (int i = 0; i < 5; i++) {
cin >> numbers[i]; // Store the input value at index i
}
// -------------------------------------
// ACCESSING ARRAY ELEMENTS
// -------------------------------------
// Print a specific value from the array
cout << "Value at index 2 in 'numbers': " << numbers[2] << endl;
// Update a value at a specific index
numbers[2] = 100; // Change the 3rd value to 100
// Print all elements using a loop
cout << "All values in 'numbers' array after update: ";
for (int i = 0; i < 5; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
Time Complexity: O(1)
In our code, we have two loops — one for taking input into the numbers array and one for printing its values. Both of these loops run exactly 5 times, since the array has 5 elements. We also have a single line where we access and update a specific element, and that operation takes constant time, or O(1). So overall, even though there are several operations happening, the only part that scales with the size of the array is the loops. Since these loops depend on the size of the array (numbers[5]), the total time complexity is O(5) — which we generally write as O(n), where n is the number of elements in the array.
Space Complexity: O(1)
Now let’s take a look at how much memory our program uses. We’ve declared a few arrays: one with 5 elements, another with 4, another with 5, and one more with 6. But all of these are fixed-size arrays — we’re not creating anything that grows or changes size during the program. This means the amount of space we need is determined from the beginning and doesn’t depend on user input. So, the space complexity is O(1) — constant space. Even though we’re storing several values, the space used stays predictable and small.