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
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 |
find a number whether it is even or odd without using any control structures and relational operators?
22 Answers Microsoft, Shashank Private Limited,
Define a structure to store roll no, name and marks of a student. Using the structure of above write a ‘C’ program to create a file “student.dat”. There must be one record for every student in the file. Accept the data from the user.
What is zero based addressing?
how to solve "unable to open stdio.h and conio.h header files in windows 7 by using Dos-box software
How is a macro different from a function?
How can I sort more data than will fit in memory?
Write a program in c to replace any vowel in a string with z?
what is difference between #include<stdio.h> and #include"stdio.h"
find out largest elemant of diagonalmatrix
What are enums in c?
What are pointers? What are stacks and queues?
write a c program to find the probability of random numbers between 1-1000