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

Explain indirection?

0 Answers  


What are dangling pointers? How are dangling pointers different from memory leaks?

1 Answers  


Which of the following about the C comments is incorrect ? a.commentscan go over multiple lines b.comments can start any where in the line c.a line can contain comments with out any language statements d.comments can occur within comments

6 Answers   TCS,


how can write all 1to 100 prime numbers using for loop,if and break ?

2 Answers   TCS,


Rapunzel walks into the forest of forgetfullness. She meets a Lion who lies on Monday Tuesdays and Wednesdays and meets a rabbit who lies on Thurs fridays and saturdays . On that day both say that "I lied yesterday". What day is it .

3 Answers   TCS,






Write a program to print factorial of given number using recursion?

0 Answers  


What is logical error?

0 Answers  


who is the founder of c

19 Answers   College School Exams Tests, HP,


Lists the benefits of c programming language?

0 Answers  


Explain demand paging.

1 Answers   Agilent,


write a c programs to do multiplication of two numbers with out using arithmatic operator ??????????

7 Answers   Infosys, TCS,


How to write in a function declaration and in function call in which the function has 'n' number of varible or arguments?

2 Answers  


Categories