We will practice using arrays in this article. With the help of examples, we will learn how to declare, initialize, and access array elements in C++ programming.
It is a collection of variables of comparable data kinds that are referred to by a single element. Its elements are kept in a single memory location.
The array’s size should be specified when it is declared. Array elements are always counted beginning with zero (0).
The position of an array element in the array can be used to access it. The dimensions of an array can be one or more.
- The array data structure in C++ stores a fixed-size sequential collection of elements of the same type.
- A collection of data is stored in an array, although it is generally more convenient to conceive of an array as a collection of variables of the same type.
- Instead of declaring individual variables such as number0, number1,…, and number99, you declare one array variable such as numbers and represent individual variables with numbers[0], numbers[1,…, numbers[99]. An index is used to access a specific element in an array.
- All arrays are made up of contiguous memory regions. The first element refers to the lowest address, and the last element corresponds to the highest address.
- An array is a variable in C++ that can hold numerous instances of a single kind of data. For instance,
- An array is a collection of related data objects stored in contiguous memory locations that may be accessed randomly using array indices in C/C++ or any programming language.
- They can be used to hold a collection of primitive data types of any type, such as int, float, double, char, and so on.
In addition, an array in C/C++ can store derived data types such as structures, pointers, and so on.
Let’s say there are 27 students in the class, and we need to keep their grades altogether. We may simply build an array rather than 27 different variables:
double grade[27];
Here, a grade is an array with a maximum capacity of 27 double-type entries.
After an array is declared, its size and type cannot be altered in C++.
Contents
array declaration in C++
dataType arrayName[arraySize];
For example:
int x[6];
Here,
- type of element to be saved in int
- x – the array’s name
- 6 is the array’s size.
Access Elements for Arrays in C++
Each element of an array in C++ has a corresponding number. The value is referred to as an array index. By employing those indexes, we can get at the items of an array.
// syntax to access array elements array[index];
Think about the array x that we saw earlier.
A Few Things to Keep in Mind
- The array’s indexes begin at 0. Meaning that the first item saved at index 0 is x[0].
- The final element of an array with size n is kept at index (n-1). This example’s final element is x[5].
- An array’s elements have sequential addresses. Consider the scenario where x[0beginning ]’s address is 2120.
- The address of the subsequent element, x[1], will then be 2124, followed by x[2], 2128, and so forth.
- Each element in this case has a four-fold increase in size. This is due to the fact that int has a 4-byte capacity.
C++ Array Initialization
An array can be initialized during declaration in C++. For instance,
// declare and initialize and array int x[6] = {19, 10, 8, 17, 9, 15};
An additional approach to initializing an array during declaration
// declare and initialize an array int x[] = {19, 10, 8, 17, 9, 15};
We haven’t indicated the array’s size here. In such circumstances, the compiler computes the size automatically.
C++ Array With Empty Members
In C++, if an array has a size of n, we can store up to n elements in it. However, what happens if we store fewer than n elements?
For example,
// store only 3 elements in the array int x[6] = {19, 10, 8};
The array x has a size of 6 in this case. However, we’ve only given it three elements to begin with.
The compiler assigns random values to the remaining locations in such circumstances. This random value is frequently simply 0.
What is the syntax for inserting and printing array elements?
int mark[5] = {19, 10, 8, 17, 9} // change 4th element to 9 mark[3] = 9; // take input from the user // store the value at third position cin >> mark[2]; // take input from the user // insert at ith position cin >> mark[i-1]; // print first element of the array cout << mark[0]; // print ith element of the array cout >> mark[i-1];
Example 1: Displaying Array Elements
#include <iostream> using namespace std; int main() { int numbers[5] = {7, 5, 6, 12, 35}; cout << "The numbers are: "; // Printing array elements // using range based for loop for (const int &n : numbers) { cout << n << " "; } cout << "\nThe numbers are: "; // Printing array elements // using traditional for loop for (int i = 0; i < 5; ++i) { cout << numbers[i] << " "; } return 0; }
Output
The numbers are: 7 5 6 12 35
The numbers are: 7 5 6 12 35
A for loop was used to iterate from I = 0 to I = 4. We have printed numbers[i] in each iteration.
To print the array’s elements, we once again utilized a range-based for loop. Check to see C++ Ranged for Loop to understand more about this loop.
Note that we used const int &n as the range declaration in our range-based loop rather than int n. The const int &n, on the other hand, is recommended because Each repetition of int n simply transfers the arrays of elements to the variable n. This is not memory-friendly. &n, on the other hand, uses the arrays elements’ memory addresses to access their data without duplicating it to a new variable. This is memory-saving. We’re just printing the array elements, not changing them. As a result, we utilize const to avoid mistakenly changing the array’s values.
Example 2: Take Inputs from User and Store Them in an Array
#include <iostream> using namespace std; int main() { int numbers[5]; cout << "Enter 5 numbers: " << endl; // store input from user to array for (int i = 0; i < 5; ++i) { cin >> numbers[i]; } cout << "The numbers are: "; // print array elements for (int n = 0; n < 5; ++n) { cout << numbers[n] << " "; } return 0; }
Output
Enter 5 numbers:
11
12
13
14
15
The numbers are: 11 12 13 14 15
We used a for a loop once again to iterate from I = 0 to I = 4. In each loop, we took a user input and stored it in numbers[i].
We then used another for loop to print out all of the array elements.
Example 3: Display Sum and Average of Array Elements Using for Loop
#include <iostream> using namespace std; int main() { // initialize an array without specifying size double numbers[] = {7, 5, 6, 12, 35, 27}; double sum = 0; double count = 0; double average; cout << "The numbers are: "; // print array elements // use of range-based for loop for (const double &n : numbers) { cout << n << " "; // calculate the sum sum += n; // count the no. of array elements ++count; } // print the sum cout << "\nTheir Sum = " << sum << endl; // find the average average = sum / count; cout << "Their Average = " << average << endl; return 0; }
Output
The numbers are: 7 5 6 12 35 27
Their Sum = 92
Their Average = 15.33334
This program includes:
We created double arrays called numbers but did not specify their size. In addition, three double variables were declared: total, count, and average.
In this case, total Equals 0 and count = 0.
The array elements were then printed using a range-based for loop. In each loop iteration, we add the current arrays entry to the total.
We also increment the value of count by one in each iteration, so that by the end of the for loop, we have the size of the arrays.
We print the sum and average of all the numbers after publishing all of the items. Average = sum/count gives the average of the numbers.
We utilized a ranging for loop instead of a standard for loop.
A standard for loop asks us to define the number of iterations, which is determined by the size of the array.
A ranging for loop, on the other hand, does not require such constraints.
C++ Array Out of Bounds
If we declare a 10-element array, the arrays will have elements from 0 to 9.
However, attempting to access the element at index 10 or higher will result in Undefined Behaviour.
You may Like:
C++ Programming Default Arguments (Parameters) with Example
Recursion In C++ Language (Basic Recursion Example)
https://theudaipurstore.com/maharana-pratap/
Pingback: Multiple Multilevel Hierarchical and Inheritance In C++