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 |
Explain indirection?
What are dangling pointers? How are dangling pointers different from memory leaks?
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
how can write all 1to 100 prime numbers using for loop,if and break ?
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 .
Write a program to print factorial of given number using recursion?
What is logical error?
who is the founder of c
19 Answers College School Exams Tests, HP,
Lists the benefits of c programming language?
Explain demand paging.
write a c programs to do multiplication of two numbers with out using arithmatic operator ??????????
How to write in a function declaration and in function call in which the function has 'n' number of varible or arguments?