File tree Expand file tree Collapse file tree 2 files changed +61
-2
lines changed
19_dynamic_memory_allocation Expand file tree Collapse file tree 2 files changed +61
-2
lines changed Original file line number Diff line number Diff line change @@ -24,5 +24,4 @@ and free.
24
24
09. Write a program to allocate memory dynamically of the size in bytes entered by the
25
25
user. Also handle the case when memory allocation is failed.
26
26
27
- 10. Find out the largest and smallest element from an array using dynamic memory allocation
28
- in C.
27
+ 10. Find out the largest and smallest element from an array that is created using dynamic memory allocation in C.
Original file line number Diff line number Diff line change
1
+ // Find out the largest and smallest element from an array that is created using dynamic memory allocation in C.
2
+
3
+ // Header Files
4
+ #include <stdio.h>
5
+ #include <conio.h>
6
+ #include <malloc.h>
7
+
8
+ #define MAX 50
9
+
10
+ // Main Function Start
11
+ int main ()
12
+ {
13
+ const int n ;
14
+ int * ptr , smallest , largest ;
15
+ printf ("\nHow Many Elements You Want to Enter (MAX %d) => " , MAX );
16
+ scanf ("%d" , & n );
17
+
18
+ // Invalid Input
19
+ if (n < 1 || n > MAX )
20
+ {
21
+ puts ("\n!!! Invalid Input...\n" );
22
+ exit (0 );
23
+ }
24
+
25
+ // Allocate memory dynamically
26
+ ptr = (int * )malloc (n * sizeof (int ));
27
+
28
+ if (!ptr )
29
+ {
30
+ puts ("\nUnable to Allocate Memory Dynamically...\n" );
31
+ exit (0 );
32
+ }
33
+
34
+ // Input Numbers
35
+ printf ("\nEnter %d Numbers => " , n );
36
+ for (int i = 0 ; i < n ; i ++ )
37
+ scanf ("%d" , & ptr [i ]);
38
+
39
+ smallest = largest = ptr [0 ];
40
+
41
+ // Find Largest and Smallest Element
42
+ for (int i = 1 ; i < n ; i ++ )
43
+ {
44
+ if (ptr [i ] > largest )
45
+ largest = ptr [i ];
46
+
47
+ if (ptr [i ] < smallest )
48
+ smallest = ptr [i ];
49
+ }
50
+
51
+ printf ("\nSmallest Element => %d\nLargest Element => %d" , smallest , largest );
52
+
53
+ // Free Dynamically Allocated Memory
54
+ free (ptr );
55
+
56
+ putch ('\n' );
57
+ getch ();
58
+ return 0 ;
59
+ }
60
+ // Main Function End
You can’t perform that action at this time.
0 commit comments