Skip to content

Commit 5557d41

Browse files
Create dynamic_allocation.c
1 parent a60fd31 commit 5557d41

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

dynamic_allocation.c

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
int main()
5+
{
6+
int* ptr; //declaration of integer pointer
7+
int limit; //to store array limit
8+
int i; //loop counter
9+
int sum; //to store sum of all elements
10+
11+
printf("Enter limit of the array: ");
12+
scanf("%d", &limit);
13+
14+
//declare memory dynamically
15+
ptr = (int*)malloc(limit * sizeof(int));
16+
17+
//read array elements
18+
for (i = 0; i < limit; i++) {
19+
printf("Enter element %02d: ", i + 1);
20+
scanf("%d", (ptr + i));
21+
}
22+
23+
//print array elements
24+
printf("\nEntered array elements are:\n");
25+
for (i = 0; i < limit; i++) {
26+
printf("%d\n", *(ptr + i));
27+
}
28+
29+
//calculate sum of all elements
30+
sum = 0; //assign 0 to replace garbage value
31+
for (i = 0; i < limit; i++) {
32+
sum += *(ptr + i);
33+
}
34+
printf("Sum of array elements is: %d\n", sum);
35+
36+
//free memory
37+
free(ptr); //hey, don't forget to free dynamically allocated memory.
38+
39+
return 0;
40+
}

0 commit comments

Comments
 (0)