There are three ways to pass an array to a function. Each way and its program examples are give below:
Here i am sharing a simple program that will initialize and array and then will send that array to a function which will make square of elements of that array.
These three method include passing array to function using pointers. Passing array to function simply with name, And passing array to function with size.
Method 1:
#include <iostream>using namespace std;
void function(int arr[]);
int main()
{
int arr[10];
for(int i=0; i<10; i++)
arr[i]=i+1;
function(arr);
// New Values of Array
for(int i=0; i<10; i++)
cout<<arr[i]<<endl;
return 0;
}
void function(int arr[])
{
for(int i=0; i<10; i++)
arr[i]= arr[i] * arr[i];
}
Method 2:
#include <iostream>using namespace std;
void function(int *arr);
int main()
{
int arr[10];
for(int i=0; i<10; i++)
arr[i]=i+1;
function(arr);
// New Values of Array
for(int i=0; i<10; i++)
cout<<arr[i]<<endl;
return 0;
}
void function(int *arr)
{
for(int i=0; i<10; i++)
arr[i]= arr[i] * arr[i];
}
Method 3:
#include <iostream>using namespace std;
void function(int *arr, int size);
int main()
{
int arr[10];
for(int i=0; i<10; i++)
arr[i]=i+1;
function(arr, 10);
// New Values of Array
for(int i=0; i<=9;i++)
cout<<arr[i]<<endl;
return 0;
}
void function(int *arr, int size)
{
for(int i=0; i<size; i++)
arr[i]= arr[i] * arr[i];
}
I found nice article in your blog thank you
ReplyDeletevisit
web programming tutorial
welookups.com
Thanks for sharing about passing array Private Tutor Gilbert
ReplyDeleteGood explanation Special Needs Tutor Scottsdale
ReplyDeleteThanks for this amazing guidance Private Tutor Greater Heights
ReplyDeleteA detailed informative article Private Tutor Chandler
ReplyDeleteThe way u tell everything about the function is amazing Private tutor Naples
ReplyDeleteThanks for making ti easy for undertsand Private tutor Tampa
ReplyDeleteYou have mentioned everything in detail Private tutor Ocala
ReplyDelete