#include<iostream>
using namespace std;
/*Function Prototype*/
int getMaxIndex(int arr[], int size); //function for getting index of max number in the array passed
int main()
{
int values[50], //defining array of large size(50)
size,index;
cout << "Enter the array size: ";
cin >> size; //getting size of array
while(size<1||size>50) //checking if the size entered is in the range of 1 through 50
{
cout << "Wrong input(should be between 1to50)!"
<< "\nEnter again: ";
cin >> size;
}
for( int i=0 ; i<size ; i++ ) //for getting input in array
{
cout << "Enter element "
<< (i+1)
<< ": ";
cin >> values[i]; //getting array individual elements
}
index=getMaxIndex(values,size); //calling function by passing array and its size
cout << "The largest elemnt is "
<< values[index]
<< " and its index is: "
<< index
<< ".\n";
return 0;
}
/*Function definition*/
int getMaxIndex(int arr[],int size)
{
int index=0, //initializing index with 0
large=arr[0]; //inititalizing large(for largest value) with first element
for( int i=0 ; i<size ; i++ ) //for checking eash element
{
if( arr[i]>large ) //testing each element if it is larger than 'large'
{
large=arr[i]; //assigning larger element to large
index=i; //assigning the index of larger element to 'index'
}
}
return index; //returning the index of largest element
}
No comments:
Post a Comment