Write a program to find the smallest and largest element in
a given array in c language

Answers were Sorted based on User's Feedback



Write a program to find the smallest and largest element in a given array in c language..

Answer / 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

More C Interview Questions

Write a program to accept a character & display its corrosponding ASCII value & vice versa?

9 Answers  


Which of these statements are false w.r.t File Functions? i)fputs() ii)fdopen() iii)fgetpos() iv)ferror() A)ii B)i,ii C)iii D)iv

6 Answers   Accenture,


what is output of the following statetment?Printf(“%x”, -1<<4); ?

5 Answers  


to get a line of text and count the number of vowels in it

3 Answers   Satyam,


Can one function call another?

0 Answers  






the portion of a computer program within which the definition of the variable remains unchanged a) mode b) module c) scope d) none

0 Answers  


main() { enum _tag{ left=10, right, front=100, back}; printf("%d, %d, %d, %d", left, right, front, back); }

1 Answers   Accenture, Vector,


Write a program that an operator and two operands read from input operand operator on the implementation and results display.

0 Answers  


how does the C compiler interpret the following two statements p=p+x; q=q+y; a. p=p+x; q=q+y b. p=p+xq=q+y c. p=p+xq; q=q+y d. p=p+x/q=q+y

2 Answers   TCS, Tech Synergy,


What is the difference between typedef struct and struct?

0 Answers  


When would you use a pointer to a function?

0 Answers  


Which is better pointer or array?

0 Answers  


Categories