Skip to main content

Arrays/Vectors

Arrays and Functions

Functions - we already did this topic right! Then why again? 🤔

Well, so far we have only studied simple variables being used or passed as arguments in functions but now we will study how we can use arrays in functions.

Let's revise how functions worked:

#include <iostream>
using namespace std;
 
// function to add two numbers
int add(int x, int y) {
    int sum = x + y;
    return sum;
}
 
int main() {
  
    int number1 = 12;
    int number2 = 14;
 
    // function call
    int ans = add(number1, number2);
    cout << "Sum: " << ans;
  
    return 0;
}

Output

Sum: 26

In this program, the function add takes two parameters - x and y and returns their sum as output. Now just like x and y we can also pass array elements and even arrays as function arguments. Let's see how!

Array elements as arguments

Suppose we have an array:

arr[4] = {3, 7, 12, 5};

Now don't forget that the elements of this array like 3, 7, 12 or 5 are also integers. This implies that we can also pass them as arguments in the function example (add function) discussed above.

Remember while accessing array elements, we use their index (position) values like to access 2nd element (7), we accessed it using arr[1]. Similarly, we can also pass them as arguments.

Example

Write a C++ program that finds the sum of the 1st and 4th elements of the above array using the same add function as discussed initially.

Input

arr[4] = {3, 7, 12, 5};

Output

Sum: 8

Hint

Pass the 1st and 4th element of the array as arguments to function add

Solution

Try yourself

#include <iostream>
using namespace std;

// Function to find the sum of the 1st and 4th elements
int add(int x, int y) {
    int sum = x + y;
    return sum;
}

int main() {
    // Given array
    int arr[] = {3, 7, 12, 5};

    // Calculate the sum of the 1st and 4th elements using the add function
    int sum = add(arr[0], arr[3]);

    // Print the sum of the 1st and 4th elements
    cout << "Sum of the 1st and 4th elements of array arr: " << sum << endl;

    return 0;
}

Try on compiler


Quiz

What is the output of the following code?

#include <iostream>
using namespace std;

void find_square(int n) {
    cout << n * n;
}

int main() {

    int arr[5] = {6, 8, 2};

    find_square(arr[3]);
 
    return 0;
}

Array as Function argument

Now let's take the same problem again i.e. I want to write a program that outputs the sum of 1st and 4th elements of array. But now I don't want to select and pass the 1st and 4th elements again and again. Instead, I want the function to do that work for me too. In that case, we would be required to pass the array itself as an argument to the function add so that it could select the required elements and return their sum. Now let's see how can we achieve this:

Example

Write a C++ program that finds the sum of the 1st and 4th elements of the above array using an add function.

Input

arr[4] = {3, 7, 12, 5};

Output

Sum: 8
💡
Don't forget to add a condition in the function that will check if the array has >= 4 elements or not. If array has less than 4 elements then simply return 0.

Solution

Try yourself

#include <iostream>
using namespace std;

// Function to find the sum of the 1st and 4th elements
int add(int arr[], int size) {
    // Check if the array has at least 4 elements
    if (size < 4) {
        cout << "Array should have at least 4 elements." << endl;
        return 0;
    }
    int sum = arr[0] + arr[3];
    return sum;
}

int main() {
    int arr[4] = {3, 7, 12, 5};

    // Calculate the size of the array
    int size = sizeof(arr) / sizeof(arr[0]);
 
    /* To understand the calculation of size of an array, break it down into 
    numerator and denominator
    Numerator = Size of array arr in bytes 
    Denominator = Size of an element of arr basically an integer in bytes
    Hence, this division will provide us with the no. of integers in array arr or 
    in other words, the size of arr */

    // Call the add function to find the sum of the 1st and 4th elements
    int result = add(arr, size);

    // Print the sum of the 1st and 4th elements
    cout << "Sum of the 1st and 4th elements: " << result << endl;

    return 0;
}

Try on compiler


Quiz

What is the correct way to call a function func with vowels array as an argument?


Problem

Write a C++ program to find and print the sum of all array elements for array arr = {4.5, 6.3, 2.1, 3.7} using functions.

Input

arr[4] = {4.5, 6.3, 2.1, 3.7};

Output

Sum: 16.6

Try yourself

Solution
#include <iostream>
using namespace std;

// Function to calculate the sum of array elements
double calculate_sum(double arr[], int size) {
    double sum = 0;

    for (int i = 0; i < size; i++) {
        sum += arr[i];
    }

    return sum;
}

int main() {
    double arr[] = {4.5, 6.3, 2.1, 3.7};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array

    // Call the function to calculate the sum
    double sum = calculate_sum(arr, size);

    // Print the sum of the array elements
    cout << "Sum of the array elements: " << sum << endl;

    return 0;
}

With this, we have covered the concepts of functions and arrays in this article. I hope you understood it and had fun while learning it. In case, of any confusion, do give it a re-read : )