Friday 19 July 2013

07. Write a C++ program to find both the largest and smallest number in a list of integers.

#include<iostream>
using namespace std;

void minmax(int a[],int n,int &min,int &max)    //Call by Reference mechanism to get back the modified result
{
int i;
for(i=0;i<n;++i)       //we are scanning each and every element of array to measure Min and Max
{
if(a[i]<min)             //any element less than min is saved as min (over writing old with new )
         min=a[i];
else if(a[i]>max)     //any element greater than max will be max
         max=a[i];
}
}

int main()
{
    int a[50];
    int n,i,min=a[0],max=a[0];    //Assuming that the first element is Min and Max for comparison
    cout<<"enter the number of integers in list";
    cin>>n;                                //Number of element we want to store in array.......
    cout<<"\nenter the values in list";
    for(i=0;i<n;++i)
        cin>>a[i];                          //Reading each element into array
    cout<<"\ngiven values in list";
    for(i=0;i<n;++i)
        cout<<"\n"<<a[i];               //Displaying the element in the Array (Verification)

    minmax(a,n,min,max);             //Function that evaluate Min and Max values
    cout<<"\nminimum value is : "<<min<<"\nmaximum value is : "<<max;
    return 0;
}

No comments:

Post a Comment