Introduction to C++ | Arrays

C++ Arrays

An array in C++ is a collection of variables of the same type, stored in contiguous memory locations. Arrays allow you to store multiple values under a single variable name and access them using an index. Arrays are very useful when you need to handle large amounts of data that share a common data type.

An array is a fixed-size sequence of elements of the same data type. The size of the array is defined at the time of declaration and cannot be changed during runtime. Each element of the array is stored in contiguous memory locations, making it easier to access and manipulate data efficiently.

The array's elements are indexed, starting from 0 for the first element, 1 for the second element, and so on. This is known as zero-based indexing. In C++, arrays are homogeneous, meaning they store elements of the same data type (e.g., integers, characters, floats).

Syntax

syntax of Passing Array to Function


             functionname(arrayname); //passing array to function    
                    

Pass Arrays as Function Parameters

Code Example: Pass Array


            #include <iostream>
            using namespace std;
                                
                void myFunction(int myNumbers[5]) {
                for (int i = 0; i < 5; i++) {  
                cout << myNumbers[i] << "n";    
                } 
            }
            
            int main() {  
                int myNumbers[5] = {10, 20, 30, 40, 50};  
                myFunction(myNumbers);
                return 0;
            }  
                
                    

Output

10 20 30 40 50

C++ Passing Array to Function Example: Print minimum number

Code Example: Print minimum number


            #include <iostream>
            using namespace std;
                
            void printMin(int arr[5]);
                        
            int main() {
                int arr1[5] = {30, 10, 20, 40, 50};  
                int arr2[5] = {5, 15, 25, 35, 45};  
                    
                printMin(arr1); // Passing array to function  
                printMin(arr2); 
                    
                return 0;
            }
                
            void printMin(int arr[5]) {
                int min = arr[0];  
                for (int i = 1; i < 5; i++) { // Fixed the loop condition to `i < 5`
                        if (arr[i] < min) {
                            min = arr[i];
                        }
                    }  
                    cout << "Minimum element is: " << min << "n";  
                }

                    

Output

Minimum element is: 10 Minimum element is: 5

Accessing Array Elements

Array elements can be accessed using their index. The first element is at index 0, the second at index 1, and so on. You can access and modify array elements directly by using the index:

Example: If you want to change the value of the third element, you would use numbers[2] = 100; (note that indexing starts from 0).

Multi-Dimensional Arrays

C++ also supports multi-dimensional arrays. These arrays can represent tables, matrices, or grids, where elements are stored in more than one dimension.

Syntax for a 2D Array

        dataType arrayName[rows][columns];
            

A two-dimensional array, or 2D array, has rows and columns. The total number of elements is the product of the number of rows and columns. You can access elements in a 2D array using two indices: the row index and the column index.

Example of a 2D Array

The following example shows how to declare and initialize a 2D array:

Code Example: 2D Array


                        {% raw %}
        #include <iostream>
        using namespace std;
        
        int main() {
            // Declare and initialize a 2D array (matrix)
            int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
        
            // Accessing elements in a 2D array
            cout << "Element at [0][1]: " << matrix[0][1] << endl;
            cout << "Element at [1][2]: " << matrix[1][2] << endl;
        
            return 0;
        }
        {% endraw %}
                    

Output

Element at [0][1]: 2
Element at [1][2]: 6

Array Initialization Methods

C++ allows different methods of initializing arrays. These methods give flexibility depending on your needs:

Example of Array Initialization Methods

The following example shows different types of array initialization:

Code Example: Different Initialization Methods


                        {% raw %}
        #include <iostream>
        using namespace std;
        
        int main() {
            // Static initialization
            int arr1[5] = {1, 2, 3, 4, 5};
            
            // Partial initialization
            int arr2[5] = {10, 20}; // Remaining elements will be 0
            
            // Default initialization
            int arr3[5]; // Values are uninitialized
        
            // Display values of arr1
            cout << "arr1: ";
            for (int i = 0; i < 5; i++) {
                cout << arr1[i] << " ";
            }
        
            cout << "narr2: ";
            for (int i = 0; i < 5; i++) {
                cout << arr2[i] << " ";
            }
        
            cout << "narr3: ";
            for (int i = 0; i < 5; i++) {
                cout << arr3[i] << " ";
            }
        
            cout << endl;
            return 0;
        }
        {% endraw %}
                    

Output

arr1: 1 2 3 4 5
arr2: 10 20 0 0 0
arr3: (garbage values) // Depends on the environment

Arrays in Functions

In C++, arrays can be passed to functions. When passing an array to a function, the array name is passed as a reference, which means that changes to the array elements inside the function will affect the original array.

Syntax for Passing Arrays to Functions

        void functionName(dataType arrayName[], int size) {
            // Function body
        }
            

Here, arrayName represents the array to be passed, and size is the number of elements in the array. You must pass the array size explicitly since C++ does not store the size of an array automatically when passed to a function.

Example: Passing Arrays to Functions

Here is an example of passing an array to a function:

Code Example: Passing Arrays to Functions


                        {% raw %}
        #include <iostream>
        using namespace std;
        
        void printArray(int arr[], int size) {
            for (int i = 0; i < size; i++) {
                cout << arr[i] << " ";
            }
            cout << endl;
        }
        
        int main() {
            int numbers[5] = {1, 2, 3, 4, 5};
            printArray(numbers, 5); // Passing the array to the function
        
            return 0;
        }
        {% endraw %}
                    

Output

1 2 3 4 5

Conclusion

Arrays are an essential concept in C++ programming. They enable efficient storage and access of multiple elements of the same type. Understanding array declaration, initialization, access, and passing arrays to functions will help you efficiently manage collections of data and solve a variety of problems in your programs.