In this tutorial you will learn about the C++ Programs to Pass Array In Function and its application with practical example.
C++ Programs to Array In Function
In this tutorial, we will learn to create a C++ program that will Pass Array In Function using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- For loop in C++ Programming.
- Functions in C++ Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
STEP 1: START STEP 2: INITIALIZE arr[] = { 1, 2, 3, 4, 5 } STEP 3: length= sizeof(arr)/sizeof(arr[0]) STEP 4: PRINT ARRAY NORMAL STEP 5: REVERSING ARRAY STEP 6: PRINT "REVERSE ORDER OF ARRAY IS AS FOLLOWS" STEP 7: RETURN 0. STEP 8: END. |
Program to pass Array In Function:-
As we all know array is a collection of similar data type elements. we can perform many different operations on arrays in c++ programming. In today’s program, we will reverse a given array using a user-defined function. Bypassing that array to a function.
Program Code:-
Pass Array In Function To Reverse Array Element Using Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include <algorithm> using namespace std; // Utility function to print contents of an array void print(int arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } } // Utility function to reverse elements of an array void reverse(int arr[], int n) { reverse(arr, arr + n); } int main() { //declaring the variables for the program. int arr[] = { 1, 2, 3, 4, 5 }; //finding the size of array. int n = sizeof(arr)/sizeof(arr[0]); //Printing the normal array. cout << "Elements in array " ; for (int i = 0; i < n; i++) { cout << arr[i] << " " <<endl; } //passing the array to the reverse function reverse(arr, n); //Printing the out array cout << "Reverse Elements in array " ; print(arr, n); return 0; } |
Output:-
In the above program, we have first initialized the required variable
- arr = it will hold the elements in an array.
- n = it will hold the number of elements in an array.
- i = it will hold the integer value to control the array.
Printing elements of the array
Calling of user-defined function in the program.
Program Code for reverse function & Print function.