ARRAYS IN C++ LANGUAGE
Introduction: What are arrays in C++ and why are they important?
For example, if you want to store exam results for a group of 50 students, instead of creating 50 individual variables, you can use an array with 50 elements, which simplifies the code and makes it easier to manipulate the data.
Why are arrays important?
✅ Fast Access – Thanks to indexing, accessing any element takes the same time, regardless of the array size.
✅ Code Efficiency – Enables more compact code and easier data manipulation compared to individual variables.
✅ Foundation for Advanced Structures – Many complex data structures, such as vectors, matrices, stacks, and queues, are based on the array concept.
In this article, we will explore the fundamental concepts of arrays in C++, including their declaration, initialization, element access, working with multidimensional arrays, and practical examples. We will also compare traditional C++ arrays with modern approaches such as std::array and std::vector from the Standard Library (STL).
Example of using an array in C++
Let's consider the following task: We need to input grades for n subjects and determine the highest grade.
We allocate memory for the grades data and then use a for loop to input n grades (e.g., n = 5):
int grade, n = 5; // Array input for (int i = 0; i < n; i++) {cout << "Enter grade " << (i + 1) << ":"; cin >> grade;}
int grades[n];
…
The name of the array is: ratings. The preceding expression reserves memory for n integers, because the value in the square brackets is actually the dimension of the array.
grades[2]=5;
Evo kako bi izgledalo stanje u memoriji u tom slučaju:
int grades[5], n = 5; // Array input for (int i = 0; i < n; i++) {cout << "Enter grade " << (i + 1) << ":"; cin >> grades[i];}
Test your code in the editor!
Determining the maximum value of an array (maximum)
int max = grades[0];
First, an integer variable is defined to represent the maximum grade, and it is assumed to be equal to the first grade in the array, i.e., its initial value is `grades[0]`. Next, a `for` loop is used to iterate through the array, accessing each grade in order as `grades[i]`. In each iteration, we check if the new grade is greater than the current maximum, and if so, that value becomes the new maximum. This process looks like this:
for (int i = 0; i < n; i++) {if (grades[i] > max) {}max = grades[i];}
max
represents the highest grade.
Određivanja maksimalne sume uzastopnog podniza
Within a one-dimensional array of numbers, it is necessary to find the subarray of consecutive numbers that has the highest sum.
For example, given the array:
3, 5, -10, -34, 16, 2
the subarray with the highest sum is 16, 2 , which equals 18 .
For a complete explanation and an animation illustrating the algorithm, visit the page:
Maximum Subarray Sum.
|
Declaring and defining arrays
Definition of an array of 10 integers (this also allocates memory for the array):
int array[10];
This will allocate memory space for 10 integers. If we try to access the 11th element of the array, the program will terminate at that point due to an error.
A drawback of arrays is that when we do not know in advance how many elements the array will contain, we must allocate more space than expected, just in case. Some of that space will likely remain unused, but the program will not crash because of it.
The ability to allocate exactly as much space as needed is solved by using collections, but that topic is covered in an advanced course.
Defining a real sequence of numbers
An array of real numbers is defined similarly to an array of integers, except that instead of int you use double or float.
float array[10]; // or double array[10];
Assigning values to the members of an array
double a[5]; a[0] = 1.1; a[1] = 12.0; a[2] = 22.0; a[3] = -1.6; a[4] = 3.3;
Assigning values to the members of an array when they are known in advance
If we know the values of the array elements in advance, then the array is initialized together with its definition. The previous array is initialized as follows:
double a[] = {1.1, 2.0, 2.5, -1.6, 3.3};
A more detailed explanation of array syntax in C++
1. Array declaration
An array is declared by first specifying the data type, then the name of the array, and then in square brackets [] the number of elements the array can contain.
Syntax:
data_type array_name[size];
2. Array initialization
- Initialization during declaration:
int numbers[5] = {1, 2, 3, 4, 5}; // All elements are explicitly defined
- Automatic array sizing:
If you specify all values explicitly, you can omit the size:
int brojevi[] = {10, 20, 30}; // Veličina niza je automatski određena na 3
- Partial initialization:
If you specify a smaller number of values, the other elements will be set to 0 (for basic data types).
int numbers[5] = {1, 2}; // The remaining elements will be 0
3. Accessing array elements
int numbers[3] = {5, 10, 15}; cout << numbers[0]; // Prints 5
4. Entering and printing an array using a loop
int grades[5]; // Array declaration for (int i = 0; i < 5; i++) { cout << "Enter grade: "; cin >> grades[i]; } cout << "The entered grades are: "; for (int i = 0; i < 5; i++) { cout << grades[i] << " "; }
5. Common errors that appear when working with arrays
If you try to access an element that doesn't exist, you'll get unpredictable results.
int numbers[3] = {1, 2, 3}; // Declaration and initialization of the array cout << numbers[5]; // Error - index 5 does not exist
The array size must be a constant value at declaration.
int n; cin >> n; int numbers[n]; // Error in older C++ versions (use `std::vector` instead)
Examples of using arrays:
Example 1: Inputting an array and determining the positive numbers.
First, the value of n needs to be input in order to define the array, as n represents the dimension of the array.
int n; cout << "Enter the number of elements in the array" << endl; cin >> n;
int array[n]; // Defining an array of n elements
// Loading the array for (int i = 0; i < n; i++) {cout << "Enter " << (i + 1) << ". element of the array"; cin >> array[i];}
// Printing the array for (int i = 0; i < n; i++) {cout << array[i] << " ";}
// Determining the number of positive elements int numPositive = 0; for (int i = 0; i < n; i++) {if (array[i] > 0) {} cout << "Number of positive elements = " << numPositive << endl;numPositive++;}
Example 2: Inputing an array and determining the largest element
First we need to define an array.
int n; cin >> n; int a[n];
- Suppose an array of 5 elements is loaded and the values are loaded as in the image below
- Assume that the maximum is the first element of the array
double max; max = a[0];
- Then, through the for loop, the current element of the array is changed and checked if it is greater than the assumed maximum. If so, that element becomes the maximum.
for (int i = 0; i < n; i++) {if (a[i] > max) {} cout << "max=" << max << endl;max = a[i];}
double min; // Initialize min with the first element of the array min = a[0]; for (int i = 0; i < n; i++) {if (a[i] < min) {} // Output the minimum value cout << "min=" << min << endl;// Update min if a smaller value is found min = a[i];}
Example 3: Reversing an array
#include <iostream> int main() { int numbers[] = {1, 2, 3, 4, 5}; // Declaration and initialization of the array std::cout << "Array in reverse order:" << endl; // Prints the title for (int i = 4; i >= 0; i--) { // Loop to reverse the array std::cout << numbers[i] << " "; // Prints the elements of the array in reverse order } return 0; // End of the function }
Reverse sequence: 5 4 3 2 1
Example 4: Counting occurrences of an element
#include <iostream> int main() { int numbers[] = {1, 2, 3, 2, 4, 2, 5}; // Array of numbers int number = 2; // Element to count int count = 0; // Counter to store the number of occurrences for (int i = 0; i < 7; i++) { // Loop through the array if (numbers[i] == number) { // Check if the current element is equal to the number count++; // If yes, increment the count } } std::cout << "Element " << number << " appears " << count << " times in the array.\\n"; // Print the result return 0; // End of the function }
Element 2 appears 3 times in the array.
Modern C++ concepts
Using std::vector
instead of static arrays
While traditional C++ arrays are useful, they have limitations, such as fixed size. Modern C++ developers often use std::vector
, which allows dynamic allocation and memory management.
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
numbers.push_back(6); // Adds a new element
cout << "First element: " << numbers[0] << endl;
}
You can read more about std::vector
here.
Two-dimensional arrays and matrices
Arrays can have multiple dimensions, which is useful for representing matrices and data tables.
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
cout << "Element matrix[1][2]: " << matrix[1][2] << endl; // Prints 6
For a detailed explanation of two-dimensional arrays, visit this page.
Passing arrays as function arguments
If we want to pass an array to a function, we use a pointer or reference.
void printArray(int array[], int size) {
for (int i = 0; i < size; i++)
cout << array[i] << " ";
cout << endl;
}
int main() {
int numbers[] = {10, 20, 30, 40};
printArray(numbers, 4);
}
For more details on dynamic arrays and passing arrays through functions, check here.
Additional Resources:
- Pointers in C++ Programming - A detailed explanation of pointers and their application in programming.
- Array Examples in C++ - Specific examples demonstrating array manipulation in C++.
- Two-Dimensional Arrays in C++ Programming - Explanation and examples of working with two-dimensional arrays in C++.
- TutorialsPoint - C++ Programming - Detailed guides on basic and advanced C++ programming concepts.
- LearnCpp.com - Interactive online guide to learning C++ with examples and exercises.
- GeeksforGeeks - C++ Programming - Detailed explanations of C++ language with practical examples and code.
- Udemy - C++ Programming for Beginners - Online course for beginners who want to learn C++ programming.
- Stack Overflow - C++ Questions - Platform for solving problems and sharing knowledge related to C++ programming.
Previous
|< Nested loops in C++ |
Next
Vectors in c++ >| |