From a5c5ec5079d13c9f0dadd6a69946020375bf3e5d Mon Sep 17 00:00:00 2001 From: Shreya Gautam Date: Fri, 8 Oct 2021 18:51:18 +0530 Subject: [PATCH] C program to find sum of array elements using Dynamic Memory Allocation --- ...y elements using Dynamic Memory Allocation | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 C program to find sum of array elements using Dynamic Memory Allocation diff --git a/C program to find sum of array elements using Dynamic Memory Allocation b/C program to find sum of array elements using Dynamic Memory Allocation new file mode 100644 index 0000000..a2a35e1 --- /dev/null +++ b/C program to find sum of array elements using Dynamic Memory Allocation @@ -0,0 +1,40 @@ +#include +#include + +int main() +{ + int* ptr; //declaration of integer pointer + int limit; //to store array limit + int i; //loop counter + int sum; //to store sum of all elements + + printf("Enter limit of the array: "); + scanf("%d", &limit); + + //declare memory dynamically + ptr = (int*)malloc(limit * sizeof(int)); + + //read array elements + for (i = 0; i < limit; i++) { + printf("Enter element %02d: ", i + 1); + scanf("%d", (ptr + i)); + } + + //print array elements + printf("\nEntered array elements are:\n"); + for (i = 0; i < limit; i++) { + printf("%d\n", *(ptr + i)); + } + + //calculate sum of all elements + sum = 0; //assign 0 to replace garbage value + for (i = 0; i < limit; i++) { + sum += *(ptr + i); + } + printf("Sum of array elements is: %d\n", sum); + + //free memory + free(ptr); //hey, don't forget to free dynamically allocated memory. + + return 0; +}