N numbers are entered from the input. Determine and print the maximum number entered.
Answers
Answer:
The smallest and the largest element can be found out in a single traversal of an array. i .e . in O(N) . The idea is to use two variables min and max that keeps track of the minimum and maximum element found till a particular index in the array respectively.Initially we can initialize min to an arbitrary large number and max to a smaller number. Then as we traverse the array , if we find an element lesser than min or larger than max we can keep track of them and finally print out the results. Below is the C code for the same
#include<stdio.h>
#include<limits.h>//for INT_MIN and INT_MAX
int a[10000];//array to store the numbers
int main(){
int min,max,n,i;
min = INT_MAX;//will store the minimum element
max = INT_MIN;//will store the maximum element
printf("Enter the value of n :");
scanf("%d",&n);
printf("Enter n numbers:");
for(i = 0 ; i < n ; i++){
scanf("%d",a+i);
if( a[i] < min )
min = a[i];
if( a[i] > max)
max = a[i];
}
printf("Minimum Element = %d\nMaximum Element = %d",min , max);
return 0;
}
Hope it helps :)
Explanation: