-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy path10_largest_smallest.c
60 lines (47 loc) · 1.26 KB
/
10_largest_smallest.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// // Find out the largest and smallest element from an array that is created using dynamic memory allocation in C.
// // Header Files
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#define MAX 50
// // Main Function Start
int main()
{
const int n;
int *ptr, smallest, largest;
printf("\nHow Many Elements You Want to Enter (MAX %d) => ", MAX);
scanf("%d", &n);
// // Invalid Input
if (n < 1 || n > MAX)
{
puts("\n!!! Invalid Input...\n");
exit(0);
}
// // Allocate memory dynamically
ptr = (int *)malloc(n * sizeof(int));
if (!ptr)
{
puts("\nUnable to Allocate Memory Dynamically...\n");
exit(0);
}
// // Input Numbers
printf("\nEnter %d Numbers => ", n);
for (int i = 0; i < n; i++)
scanf("%d", &ptr[i]);
smallest = largest = ptr[0];
// // Find Largest and Smallest Element
for (int i = 1; i < n; i++)
{
if (ptr[i] > largest)
largest = ptr[i];
if (ptr[i] < smallest)
smallest = ptr[i];
}
printf("\nSmallest Element => %d\nLargest Element => %d", smallest, largest);
// // Free Dynamically Allocated Memory
free(ptr);
putch('\n');
getch();
return 0;
}
// // Main Function End