Arrays help us store many values of the same type together in one place. This makes it easy to organize and use data efficiently.
0
0
Why arrays are needed in C++
Introduction
When you want to keep a list of student scores in a test.
When you need to store daily temperatures for a month.
When you want to remember multiple names or words.
When you want to process a group of numbers together, like adding them all.
When you want to quickly access any item by its position.
Syntax
C++
class ArrayExample { public: int elements[5]; // array of 5 integers void setValues() { elements[0] = 10; elements[1] = 20; elements[2] = 30; elements[3] = 40; elements[4] = 50; } void printValues() { for (int i = 0; i < 5; i++) { std::cout << elements[i] << " "; } std::cout << std::endl; } };
Arrays store multiple values of the same type in a fixed size.
Each value is accessed by its position, starting from 0.
Examples
Simple array of 3 integers with values assigned.
C++
int numbers[3]; // array with 3 integers numbers[0] = 5; numbers[1] = 10; numbers[2] = 15;
Edge case: array with zero size, usually not useful.
C++
int emptyArray[0]; // array with zero size (not useful but valid in some compilers)
Array with only one element, useful for simple cases.
C++
int singleElement[1] = {100}; // array with one element
Accessing the last element by its index.
C++
int lastElement = numbers[2]; // access last element in a 3-element array
Sample Program
This program creates an array of 5 integers inside a class, sets values, and prints them.
C++
#include <iostream> class ArrayExample { public: int elements[5]; void setValues() { elements[0] = 10; elements[1] = 20; elements[2] = 30; elements[3] = 40; elements[4] = 50; } void printValues() { std::cout << "Array elements: "; for (int i = 0; i < 5; i++) { std::cout << elements[i] << " "; } std::cout << std::endl; } }; int main() { ArrayExample myArray; myArray.setValues(); myArray.printValues(); return 0; }
OutputSuccess
Important Notes
Accessing array elements by index is very fast (constant time).
Arrays have fixed size; you cannot change their size after creation.
Common mistake: accessing outside the array size causes errors (out of bounds).
Use arrays when you know the number of items in advance and want fast access.
Summary
Arrays store multiple values of the same type together.
They allow easy access to each value by position.
Arrays have fixed size and are useful for organizing related data.