In: Computer Science
Design a modular program which asks the user to enter a list of numbers. The numbers must be stored in an array. The program then finds the index of the first occurrence of the smallest element in the array and the last occurrence of the largest element in the array. The program displays the position and value of each of these items.
Answer:
#include<iostream>
using namespace std;
int smallest(int[],int);
int largest(int[],int);
int main()
{
int a[20],i,n,si,li; /* a is an array, i is counter
variable, n is the number of elements, si is smallest number index,
li is largest number index*/
cout<<"Enter the number of elements to be
entered into the array:";
cin>>n; /* Taken the number of elements of the
array*/
cout<<"Enter the array elements one by
one\n";
for(i=0;i<n;i++)
cin>>a[i]; /* Takes the n elements into array a
one by one from the keyboard*/
cout<<"The elements of the array are\n";
for(i=0;i<n;i++)
cout<<a[i]<<" "; /* Displays the array
elements one by one */
si=smallest(a,n); /* Function call to smallest(), the
arguments are array's base address and number of elements n*/
cout<<"\nThe index of the first occurrence of
the smallest element of the array is:"<<si;
li=largest(a,n); /* Function call to largest(), the
arguments are array's base address and number of elements n*/
cout<<"\nThe index of the last occurrence of the largest
element of the array is:"<<li;
return 0;
}
int smallest(int a[],int n)
{
int i,min;
min=a[0]; /* Treat the first element as minmum*/
for(i=1;i<n;i++) /* Comparision for minimum element
of the array starts at index 1 i.e from the second element*/
{
if(a[i]<min) /* if the ith index
element is less than minimum then make a[i] as minimum*/
{
min=a[i];
}
}
cout<<"\nThe Minimum element of the array
is:"<<min; /* Displays the minimum element of the
array*/
for(i=0;i<n;i++)
{
if(a[i]==min) /* Once we find the
minimum element compare it to every element to get the first
occcurrence of that element*/
break; /* Once min matches with ith
index element it stops comparision and exits from the loop*/
}
return i; /* returns ith index value (i value) to the main()
function*/
}
int largest(int a[],int n)
{
int i,max,index;
max=a[0]; /* Treat the first element as
maximum*/
for(i=1;i<n;i++) /* Comparision for maximum element
of the array starts at index 1 i.e from the second element*/
{
if(a[i]>max) /* if the ith index
element is greater than maximum then make a[i] as maximum*/
{
max=a[i];
}
}
cout<<"\nThe Maximum element of the array
is:"<<max; /* Displays the maximum element of the
array*/
for(i=0;i<n;i++)
{
if(a[i]==max) /* Once we find the
maximum element compare it to every element to get the last
occcurrence of that element*/
{
index=i; /*
Finally last occurrence of maximum element's index will be stored
in index*/
}
}
return index; /* returns ith index value (index value) to the
main() function*/
}
Output: