Write a program to find the smallest and largest element in
a given array in c language
Answer Posted / 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 View All Answers
What is the basic structure of c?
If the size of int data type is two bytes, what is the range of signed int data type?
hi to every one .. how to view table pool after creating the pooled table? plz help me.. if any knows abt this ..
Can we compile a program without main() function?
Why do we use c for the speed of light?
Where can I get an ansi-compatible lint?
my project name is adulteration of chille powder.how can i explain it to the hr when he asks me about the project?
Are negative numbers true in c?
Which is not valid in C a) class aClass{public:int x;}; b) /* A comment */ c) char x=12;
What is f'n in math?
What are the advantages of the functions?
What is static and volatile in c?
what is ur strangth & weekness
I need testPalindrome and removeSpace
#include
Explain what is the most efficient way to store flag values?