In: Computer Science
c++ please
1. Write and test the function maximum that is passed an array of n pointers to integers and returns the maximum value among the n integers. The function must use the travellingpointer(1stversion) notation to traverse the array. The function has the following prototype.
int maximum ( int *p [ ], int n);
2. Implement the function psum( )that is passed an array of n floats and returns a pointer to the sum of such an array. Print the address of the returned sum and its value in the main program.
float *psum (float *p, int n); // function prototype
void main ( ){
float pfs[3] = {5.5, 10.5, 20.3};
for (int j = 0; j < 3; j++)
cout << pfs[j] << endl;
float* rp = psum (pfs, 3);
cout << “The address of the sum: “ << rp << endl;
cout << “The value of the sum: “<< (*rp) << endl;
}
float* psum (float* p , int n){ // A function that returns a pointer
}
1.
#include<iostream> // C++ Standard Header file
int maximum ( int *p[ ], int n); //Function Prototype
using namespace std;
int main()
{
int arr[]={1,2,3,4,5};
int *p = arr; //Pointer to array of n integers.
int max,n=5;
cout<<"Elements in the array: ";
for(int i=0;i<n;i++)
cout<<p[i]<<"\t";
cout<<endl;
max=maximum(&p,n); //Function call, remember, int
*p[] is converted into int **p at compile-time
cout<<"\n\nmaximum value of integers is:
"<<max;
return 0;
}
int maximum ( int *p[ ], int n) //Function Definition
{
int max = *p[0]; //Initialising max with first
array element
for(int i=0;i<n;i++)
{
if(max < *p[i]) //Condition
to find the maximum element
max =
*p[i];
}
return max;
}
2.
#include<iostream>
float *psum (float *p, int n); // function prototype
using namespace std;
int main ( )
{
float pfs[3] = {5.5, 10.5, 20.3}; //An array of float values
for (int j = 0; j < 3; j++) //Displaying the
elements in the array
cout << pfs[j] <<
endl;
float* rp = psum (pfs, 3); //Function call
cout << "The address of the sum: " << rp << endl;
cout << "The value of the sum: "<< (*rp) <<
endl;
return 0;
}
float* psum (float* p , int n){ // Function Definition
static float sum=0;
//A static variable to store sum, as sum will be used further in
the program
for(int i=0;i<n;i++) //Loop to
calculate the sum of elements in the array
sum += p[i];
return ∑ //Returning the
address of sum
}
Sample Run: