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

what is the difference between c and java?

1 Answers  


What is a C array and illustrate the how is it different from a list.

1 Answers   Amazon,


write a program to display numbers from 1 to 10 and 10 to 1?

2 Answers  


Write a C++ program to give the number of days in each month according to what the user entered. example: the user enters June the program must count number of days from January up to June

0 Answers  


What is data structure in c programming?

0 Answers  


What are volatile variables?

1 Answers   Mind Tree,


What is the difference between char a[] = "string"; and char *p = "string"; ?

14 Answers   Adobe, Honeywell, TCS,


Explain which function in c can be used to append a string to another string?

0 Answers  


How do you write a program which produces its own source code as output?

0 Answers  


Can a pointer point to null?

0 Answers  


implement OR gate without using any bitwise operator.

1 Answers   Alcatel, Wipro,


What the advantages of using Unions?

0 Answers   TISL,


Categories