One Dimensional Array part 3 (Passing Array To Function)

Estimated reading: 6 minutes 154 Views

In C++, you can pass an array to a function, and this is a fundamental concept when working with arrays. When you pass an array to a function, you’re essentially allowing that function to operate on the array’s elements or modify the array if needed.

Here’s an explanation of how to pass an array to a function in C++:

Array Declaration in a Function

Array Parameters: To pass an array to a function, you need to declare the function parameter as an array. You can declare it in two ways:

  • Using a Fixed Size: If you know the size of the array in advance, you can specify the size in the function parameter, like this:
void functionName(int arr[5]) {
    // Code to work with the array
}
  • Using a Pointer: You can also declare the function parameter as a pointer to the array’s elements without specifying the size, like this:
void functionName(int *arr, int size) {
    // Code to work with the array
}

In this case, you pass the size of the array as a separate argument.

Passing the Array to the Function

Calling the Function: When you call the function, you provide the array as an argument. If you declared the function parameter with a fixed size, you pass the array directly. If you used a pointer, you pass the array and its size as arguments.

Example with a fixed-size array parameter:

int myArray[5] = {1, 2, 3, 4, 5};
functionName(myArray);

Example with a pointer parameter:

int myArray[5] = {1, 2, 3, 4, 5};
functionName(myArray, 5);

Using the Array in the Function

Working with the Array: Inside the function, you can access and manipulate the elements of the array as needed. You can use array indices (e.g., arr[0], arr[1]) to access individual elements, and you can use loops to iterate through the elements.

Example of accessing array elements:

void functionName(int arr[5]) {
    for (int i = 0; i < 5; i++) {
        // Access and manipulate arr[i]
    }
}

Here is a demonstration of passing an array to functions for setting values in the array and then printing those values:

#include <iostream>
using namespace std;

void set(int arr[], int s)
{
    for (size_t i = 0; i < s; i++)
    {
        cout << "Enter array value: ";
        cin >> arr[i];
    }
}

void print(int arr[], int s)
{
    for (size_t i = 0; i < s; i++)
    {
        cout << arr[i] << " ";
    }
}

int main()
{
    int a[5];
    set(a, 5);
    print(a, 5);

    return 0;
}

The set function allows the user to set values in the array, and the print function prints the values stored in the array. It’s a practical example of how to work with arrays and functions in C++.

Modifying the Array

Example 1:

This code shows an implementation of the “Bubble Sort” algorithm. Bubble Sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares adjacent elements, and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, indicating that the list is sorted. Here’s a breakdown of the code:

#include <iostream>
using namespace std;

int main()
{
    int vector[] = {6,5,4,1,2};
    int t = 0;
    
    // Bubble Sort algorithm
    for (size_t i = 0; i < 5 - 1; i++)
    {
        for (size_t j = 0; j < 5 - i - 1; j++)
        {
            if (vector[j] > vector[j + 1])
            {
                t = vector[j];
                vector[j] = vector[j + 1];
                vector[j + 1] = t;   
            }
        }
    }
    
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << endl;
    }

    return 0;
}
  1. int vector[] = {6, 5, 4, 1, 2};:
    An integer array vector is initialized with unsorted values.
  2. int t = 0;:
    An integer variable t is declared to be used for swapping elements during the sorting process.
  3. Bubble Sort Algorithm:
    The nested for loops are used to implement the Bubble Sort algorithm. The outer loop (i) controls the number of passes, and the inner loop (j) compares adjacent elements and swaps them if they are out of order.
  4. If the element at index j is greater than the element at index j + 1, a swap is performed to put them in ascending order.
  5. Printing the Sorted Array:
    After sorting is complete, the code uses a for loop to print the sorted elements in ascending order.

The output of this code will be the sorted array in ascending order, which is the result of applying the Bubble Sort algorithm to the initial unsorted array. Bubble Sort is not the most efficient sorting algorithm for large data sets, but it’s easy to understand and implement.

Example 2:

This code performs the sorting of an integer array using the Bubble Sort algorithm. It sorts the array in ascending order and then prints the sorted values. Let’s break down the code step by step:

#include <iostream>
using namespace std;

const int s = 5;
void sort(int arr[])
{
    int t = 0;
    for (size_t i = 0; i < 5 - 1; i++)
    {
        for (size_t j = 0; j < 5 - i - 1; j++)
        {
            if (arr[j] > arr[j + 1])
            {
                t = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = t;   
            }
        }
    }
}

void print(int vector[])
{
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << endl;
    }
}

int main()
{
    int vector[] = {0,-1,55,-5,-100};
    sort(vector);
    print(vector);
    return 0;
}

The output of this code will be the sorted array in ascending order, which is the result of applying the Bubble Sort algorithm to the initial unsorted array.

Example 3:

This code demonstrates how to reverse the elements of an integer array using a reversArray function. It reverses the array in-place and then prints the reversed array:

#include <iostream>
using namespace std;

void reversArray(int arr[], int s)
{
    for (size_t i = 0; i < s / 2; i++)
    {
        swap(arr[i], arr[s - i - 1]);
    }
}

int main()
{
    int vector[] = {3,2,4,5,6};
    reversArray(vector, 5);
    for (size_t i = 0; i < 5; i++)
    {
        cout << vector[i] << " ";
    }

    return 0;
}

The output of this code will be the reversed array, where the elements are reversed in place. This is achieved by swapping the first element with the last element, the second element with the second-to-last element, and so on. It’s a simple and efficient way to reverse the order of elements in an array.

 

Note:

If you don’t want to modify your array you can initial its value as a constant in the function. Example:

void print(const int arr[], int s)
{
    //body of the function
}

This way any try to modify the array will produce an error.

Share this

One Dimensional Array part 3 (Passing Array To Function)

Or copy link

CONTENTS
English