BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Passing Array to Function in C++

By Chaitanya Singh | Filed Under: Learn C++

You can pass array as an argument to a function just like you pass variables as arguments. In order to pass array to the function you just need to mention the array name during function call like this:

function_name(array_name);

Example: Passing arrays to a function

In this example, we are passing two arrays a & b to the function sum(). This function adds the corresponding elements of both the arrays and display them.

#include <iostream>
using namespace std;
/* This function adds the corresponding
 * elements of both the arrays and
 * displays it.
 */
void sum(int arr1[], int arr2[]){
   int temp[5];
   for(int i=0; i<5; i++){
      temp[i] = arr1[i]+arr2[i];
      cout<<temp[i]<<endl;
   }
}
int main(){
   int a[5] = {10, 20, 30, 40 ,50};
   int b[5] = {1, 2, 3, 4, 5};
   //Passing arrays to function
   sum(a, b);
   return 0;
}

Output:

11
22
33
44
55

Example 2: Passing multidimensional array to function

In this example we are passing a multidimensional array to the function square which displays the square of each element.

#include <iostream>
#include <cmath>
using namespace std;
/* This method prints the square of each
 * of the elements of multidimensional array
 */
void square(int arr[2][3]){
   int temp;
   for(int i=0; i<2; i++){
      for(int j=0; j<3; j++){
        temp = arr[i][j];
        cout<<pow(temp, 2)<<endl;
      }
   }
}
int main(){
   int arr[2][3] = { 
       {1, 2, 3},
       {4, 5, 6}
   };
   square(arr);
   return 0;
}

Output:

1
4
9
16
25
36
❮ PreviousNext ❯

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

C++ Tutorial

  • C++ Tutorial
  • First C++ Program
  • C++ Variables
  • C++ Data types
  • C++ Operators

Flow Control

  • C++ If-else
  • C++ Switch Case
  • C++ for loop
  • C++ while loop
  • C++ do-while loop
  • C++ Continue
  • C++ break
  • C++ goto

Functions

  • C++ Functions
  • Default Argument in Function
  • C++ Recursion

Arrays

  • C++ Arrays
  • Multidimensional Arrays
  • C++ Array to Function
  • C++ Strings

Pointers

  • C++ Pointers
  • "this" Pointer

OOPs Concepts

  • C++ OOPs
  • C++ Constructor
  • C++ Destructor
  • C++ Structure
  • Struct and Function
  • C++ Enum
  • C++ Inheritance
  • C++ Polymorphism
  • C++ Function Overloading
  • C++ Function Overriding
  • Function Overloading vs Overriding
  • C++ Virtual Function
  • Encapsulation
  • Abstraction
  • C++ Interfaces
  • Friend Class and Function

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap