0% found this document useful (0 votes)
11 views5 pages

Passing Arrays To Functions

Cpp learning

Uploaded by

For Business
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views5 pages

Passing Arrays To Functions

Cpp learning

Uploaded by

For Business
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Fundamentals of Computer

Programming
(CS-110)
Course Instructors:
Dr. Momina Moetesum
Ms. Shakeela Bibi

1
Passing Arrays to Functions

• In C++, we can pass arrays as


an argument to a function.
• We can return arrays from a
function as well. However,
the actual array is not
returned. Instead, the
address of the first element
of the array is returned with
the help of pointers (We will
cover this topic later)

2
Example:
A Function that returns the average of elements in an array
#include <iostream>
using namespace std;
double getAverage(int arr[], int size)
{ // function declaration:
int i, sum = 0; double getAverage(int arr[], int size);
double avg;
int main () {
// an int array with 5 elements.
for (i = 0; i < size; ++i) int balance[5] = {1000, 2, 3, 17, 50};
{ double avg;
sum += arr[i];
} // pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
avg = double(sum) / size;
return avg; // output the returned value
} cout << "Average value is: " << avg << endl;
return 0;
3
}
Example:
A Function that returns the largest element in an array
#include<iostream>
#include<chrono>
int findLarge(int a[], int s) using namespace std;
{ int findLarge(int [], int);
int main()
int i, m; {
m = a[0]; const int size=10;
for(i=1; i<s; i++) int arr[size], larg, i;
srand(time(0));
{ for(i=0; i<size; i++)
if(m<a[i]) arr[i]=rand()%100;
cout<<"Array Elements: ";
m = a[i]; for(i=0;i<size;i++)
} cout<<arr[i]<<" ";
return m; larg = findLarge(arr, size);
cout<<"\nLargest Number = "<<larg;
} cout<<endl;
return 0;
} 4
Acknowledgment

• Content of these slides are taken from:


• https://www.geeksforgeeks.org/
• https://www.tutorialspoint.com/
• https://www.programiz.com/
• https://www.w3schools.com/

You might also like