×

C++ array to function

Arrays in C++ :

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable.

An array can be declared by specifying the variable type, then the array and then the square brackets that would store the number of elements in the array.

Syntax:

var_type array[no_of_elements]

Example –

String colors[3] = {“red”, “blue”, “green”}

The above example shows an array of colors having 3 colors namely red, blue and green.

Functions in C++ :

A function is a code block that only executes when it is invoked.

The Parameters are data that may be sent into a function.

Functions are used to accomplish certain tasks and are essential for code reuse: Once the code is defined, it may be reused numerous times.

Syntax:

void func(){
	//the piece of code that is to be executed
}

Example –

void func(){
	cout << “This is executed”
}
int main(){
	func(); // function called
	Return 0;
}

Output:

This is executed

In this example, we created a function called func(), which when called in main gave us the required output that it is executed.

Passing Arrays to Function in C++ :

Arrays can be passed as arguments to functions in C++. We can also return arrays from functions.

Make sure you understand C++ Arrays and C++ Functions before learning about providing arrays as a function argument.

Syntax :

returnType functName(datatype arr[size]){
	// code block
}

Example –

int sum(int score[4]) {
	// code block
}

In this Example, the method sum has been supplied an int type array named score(). The array has a size of 4.

C++ Array to Function

1D Array to a Function:

In the C++ language, a one-dimensional array is the most basic type of array. A one-dimensional array is simple to define, initialise, and modify. A one-dimensional array can be used as a function argument and so on.

Example -

// C++ Program to show score of 4 students


#include <iostream>
using namespace std;


// declaring function to show score
//1d array taken as parameter
void show(int s[4]) {
    cout << "Showing marks: " << endl;


    // showing elements of the array    
    for (int k = 0; k < 4; ++k) {
        cout << "Person " << k + 1 << ": " << s[k] << endl;
    }
}


int main() {


    // call and initialize array
    int score[4] = {77,98,91,69};
    
    // call show func
    // pass array as arg
    show(score);


    return 0;
}

Output :

Showing score:
Person 1: 77
Person 2: 98
Person 3: 91
Person 4: 69

In this example,

1. Only the name of the array is used when calling a function with an array as a parameter.

show(score);

The memory location of the first member of array score[4] is represented by the parameter score.

2. However, take note of the show() function's argument.

void show(int s[4])

In this case, we utilise the whole array declaration in the function argument, including the square brackets [].

3. The int s[4] function argument is converted to int* s;. This corresponds to the same address as the array score. This indicates that we're actually modifying the original array score when we manipulate s[4] in the method body.

This is how C++ handles sending an array to a function to save memory and time.

Multi-dimensional Array to Function :

Multidimensional arrays may be simply defined as an array of arrays in C/C++. Tabular format is used to store data in multidimensional arrays (in row-major order).

Multidimensional arrays can also be sent as an argument to the function. As an example

Example –

// C++ Program to display the elements of two
// dimensional array by passing it to a function


#include <iostream>
using namespace std;


// define func 
// pass 2D array as parameter
void show(int no[][2]) {
    cout << "Showing Values: " << endl;
    for (int k = 0; k < 3; ++k) {
        for (int l = 0; l < 2; ++l) {
            cout << "number[" << k << "][" << l << "]: " << no[k][l] << endl;
        }
    }
}


int main() {


    // initializing the 2D array
    int number[3][2] = {
        {1, 2},
        {3, 4},
        {5, 6}
    };


    // call the func
    // pass 2D array as arg
    show(number);


    return 0;
}

Output:

Showing Values:
number[0][0]: 1
number[0][1]: 2
number[1][0]: 3
number[1][1]: 4
number[2][0]: 5
number[2][1]: 6

In this example, we've defined a function called show() in the previous program. The function accepts a two-dimensional array as an input, int no[][2], and outputs the array's elements.

We merely supply the name of the two-dimensional array as the function parameter display when invoking the function (number).

The number of rows in the array does not have to be specified. The number of columns, on the other hand, should always be stated. We used int no[][2] for this reason.

As a function parameter, we may also send arrays with more than two dimensions.


Related Topics

C++ Tricks for Competitive Programming

If you are interested in Computer science or Information technology, you must have heard about competitive programming. Competitive programming is a way to improve your problem-solving skills. There are various...

7 minutes read.

Differences between #define & const in C/C++

 Differences between #define & const in C/C++ A preprocessor directive is #define. The preprocessor replaces things defined by #define prior to starting compilation. In this chapter, we'll learn about the member, variable,...

3 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

Reverse a Number in C++

In this tutorial, you'll learn how to utilize a C++ program to reverse a number entered by a user at runtime. Because there are various ways to write a C++...

3 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Function overloading in C++

Function overloading in C++ As we know that C++ works on the OOP Concepts, that are abstraction, encapsulation, and data hiding, it also uses the other important feature of OOP, which...

8 minutes read.

C++ Queue

C++ queue: Queue in C++ is also a container adapter with the functionality of a queue. Queue is just the opposite of the stack in C++ because stack works on...

4 minutes read.

C++ Encapsulation

The following two essential components are present in all C++ programmes: Functions are the parts of a programme that perform actions, and they are termed programme statements (code).Program data is the...

4 minutes read.

Approach in C++

Object oriented programming languages like Java or C++ use a bottom-up approach that identifies each object first.  In the bottom-up approach, we create a small problem first, and try to...

6 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

How to Reverse a String in C++ using For Loop

For Loop: We may loop through a certain section of C++ code repeatedly using the for loop. A for loop is carried out if the test expression yields a true result. The...

4 minutes read.

Counting Frequencies of Array Elements in C++

We have an array of integer items with duplicate values, and our objective is to compute the frequencies of the different elements in the array. Methods: Methods that can be used to...

3 minutes read.

Armstrong Number Program in C++

Let's first define Armstrong number before writing the C++ program to check whether the number is Armstrong or not. The sum of the cubes of its digits is equal to the...

2 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute read.

C++ Range-based For Loop

In C++ language, the range-based for loop was added, which is far superior than the ordinary For loop. The implementation of a range-based for loop doesn't really need much code. It's a...

4 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.