Skip to content

Commit 78bd48f

Browse files
committed
add: DMA 10
1 parent 6b0b121 commit 78bd48f

File tree

2 files changed

+61
-2
lines changed

2 files changed

+61
-2
lines changed

19_dynamic_memory_allocation/00_questions.txt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,4 @@ and free.
2424
09. Write a program to allocate memory dynamically of the size in bytes entered by the
2525
user. Also handle the case when memory allocation is failed.
2626

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.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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

0 commit comments

Comments
 (0)