Question #22036

write a program that lets the user enter 50 elements in an array whose data type is integer. Locate the smallest and largest elements and display their corresponding value and location.

Expert's answer

#include <iostream>
using namespace std;
int main()
{
int minX,minXpos, maxX, maxXpos, i;
int n=5; //number of elements in the array

int * x = newint[n]; // get memory for the array x

// get datafrom the user
cout <<"Enter " << n << " values" << endl;
for(i=0;i<n; i++)
{
cout<< "x[" << i << "] = ";
cin>> x[i];
}

// look for themaximal and minimal elements and their positions
minX = maxX =x[0];
minXpos =maxXpos = 0;
for(i=1;i<n; i++)
{
if(x[i]<minX)
{
minX =x[i];
minXpos= i;
}
if (maxX<x[i])
{
maxX =x[i];
maxXpos= i;
}
}

// printresults
cout <<"Minimal element x[" << minXpos << "] = "
<< minX << endl;
cout <<"Maximal element x[" << maxXpos << "] = "
<< maxX << endl;

delete(x); //free memory
return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS