Write a program to find the smallest and largest element in
a given array in c language
Answer Posted / hari prasad perabattula
#include<stdio.h>
#include<stdlib.h>
int main() {
int n, *arr, i, min, max, tmin, tmax, start=2;
printf("How many elements:");
scanf("%d", &n);
arr = (int *) malloc(sizeof(int) * n);
printf("Enter %d Elements:", n);
for (i=0; i<n; i++)
scanf("%d", &arr[i]);
if(arr[0] < arr[1]) { // 1 comparison
min = arr[0];
max = arr[1];
} else {
min = arr[1];
max = arr[0];
}
tmin = min;
tmax = max;
if(n%2) {
if(arr[2] < min)
min = arr[2];
if(arr[2] > max)
max = arr[2];
start = 3;
}
for(i=start; i < n; i+=2) //
(n-2)/2 elements
{
if(arr[i] < arr[i+1]) { // 1 comparison
min = arr[i];
max = arr[i+1];
} else {
min = arr[i+1];
max = arr[i];
}
if(tmin < min) // +1
min = tmin;
if(tmax > max) // +1 = 3
max = tmax; // Total
comparisons = 3(n-2)/2
}
printf("Min: %d \nMax: %d\n", min, max);
}
Note: This gives a slightly better running time.
| Is This Answer Correct ? | 21 Yes | 34 No |
Post New Answer View All Answers
What are the differences between Structures and Arrays?
When was c language developed?
can we change the default calling convention in c if yes than how.........?
How many keywords are there in c?
What is the difference between a free-standing and a hosted environment?
What is the 'named constructor idiom'?
a function gets called when the function name is followed by a a) semicolon (;) b) period(.) c) ! d) none of the above
What does %c mean in c?
What are pragmas and what are they good for?
What is void pointers in c?
what do u mean by Direct access files? then can u explain about Direct Access Files?
Can i use “int” data type to store the value 32768? Why?
What is the right way to use errno?
What is the use of f in c?
How can I invoke another program (a standalone executable, or an operating system command) from within a c program?