C++ / C++ Arrays and Strings

Passing Arrays to Functions

In this tutorial, you will learn how to pass arrays to functions in C++. We will explore different ways of passing arrays and how to manipulate array data inside functions.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores working with arrays, multi-dimensional arrays, and string manipulation.

1. Introduction

In this tutorial, we will explore how to pass arrays to functions in C++. By the end of this tutorial, you will be able to pass arrays to functions, manipulate array data inside functions, and understand how array data works in a function.

Prerequisites: Basic understanding of C++ syntax, function, and arrays.

2. Step-by-Step Guide

In C++, arrays can be passed to functions in three different ways, namely:

  • Pass-by-value
  • Pass-by-reference
  • Pass-by-pointer

When we pass an array to a function as an argument, the function works with the original array. This is because the array's address, not the actual data, is passed - this is known as 'pass by reference'.

3. Code Examples

Example 1: Pass-by-value

In this example, we will pass an array to a function and print the array elements.

#include <iostream>
using namespace std;

// Function to print array elements
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, size); // Pass array to the function
    return 0;
}

This will output: 1 2 3 4 5

Example 2: Pass-by-reference

In this example, we will pass an array to a function and double the array elements.

#include <iostream>
using namespace std;

// Function to double array elements
void doubleArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        arr[i] *= 2;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    doubleArray(arr, size); // Pass array to the function
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

This will output: 2 4 6 8 10

4. Summary

In this tutorial, you have learned how to pass arrays to functions in C++. We have covered pass-by-value and pass-by-reference examples. You can now manipulate array data within functions and understand how this manipulation affects the original array.

5. Practice Exercises

  1. Write a function that takes an array as an argument and finds the maximum value in the array.
  2. Write a function that takes an array as an argument and reverses the array elements.

Solutions:

  1. Maximum value in the array:
#include <iostream>
using namespace std;

// Function to find maximum value in array
int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    cout << "Max value is: " << findMax(arr, size) << endl;
    return 0;
}
  1. Reverse array elements:
#include <iostream>
using namespace std;

// Function to reverse array elements
void reverseArray(int arr[], int size) {
    int start = 0, end = size - 1;
    while (start < end) {
        swap(arr[start], arr[end]);
        start++;
        end--;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    reverseArray(arr, size); // Reverse array
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

Keep on practicing and experimenting with different scenarios to strengthen your understanding. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

File Size Checker

Check the size of uploaded files.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

JSON Formatter & Validator

Beautify, minify, and validate JSON data.

Use tool

Random Number Generator

Generate random numbers between specified ranges.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help