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

main() { clrscr(); } clrscr();

6 Answers   ME, Wipro,


What is storage class?

0 Answers  


How can I generate floating-point random numbers?

0 Answers  


What is a pointer in c plus plus?

0 Answers  


What are the features of the c language?

0 Answers  






main() { int ptr[] = {1,2,23,6,5,6}; printf("%d",&ptr[3]-&ptr[0]); }

8 Answers   Vector,


what are the stages of compilation

1 Answers   Bosch,


What is hashing in c?

0 Answers  


Is a house a shell structure?

0 Answers  


What is the need of structure in c?

0 Answers  


Main must be written as a.the first function in the program b.Second function in the program c.Last function in the program d.any where in the program

19 Answers   CTS, HCL, TCS,


What are logical errors and how does it differ from syntax errors?

0 Answers  


Categories