6. a) Write C++ code for a loop that simultaneously computes both the maximum and minimum of an array.
b) What is wrong with the following loop?
int values[10];
for (int i = 1; i <= 10; i++)
{
values[i] = i * i;
}
Explain two ways of fixing the error.
Answer 6a:
#include <iostream>
using namespace std;
int main()
{
int arr[]={10,2,5,6,3,9};
int minN=arr[0]; //assuming 0th element as min
int maxN=arr[0];//assuming 0th element as max
for(int i=0;i<6;i++){
//checking if current element is less than min than make current
element as min
if(arr[i]<minN)
minN=arr[i];
//checking if current element is greater than max than
make current element as max
if(arr[i]>minN)
maxN=arr[i];
}
cout<<"Min element: "<<minN<<endl;
cout<<"Max element: "<<maxN<<endl;
return 0;
}
Answer 6b:
issue indexes of array starts from 0 to length -1 so here we should iterate till 0 to 9
Correct Code:
for (int i = 0; i < 10; i++)
{
values[i] = i * i;
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me
Get Answers For Free
Most questions answered within 1 hours.