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
a sequence of bytes with one to one corrspondence to those in the external device a) sequential addressing b) address c) byte code d) none
Is boolean a datatype in c?
c programs are converted into machine language with the help of a) an interpreter b) a compiler c) an operatinf system d) none of the above
What is a 'null pointer assignment' error?
What's the right way to use errno?
Explain what is wrong with this statement? Myname = ?robin?;
What is indirection?
Can an array be an Ivalue?
What is || operator and how does it function in a program?
What is a structure and why it is used?
Explain continue keyword in c
Which is best linux os?
simple program of graphics and their output display
In C programming, what command or code can be used to determine if a number of odd or even?
What is the difference between Printf(..) and sprint(...) ?