Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

C program to find sum of array elements using Dynamic Memory Allocation #27

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <stdio.h>
#include <stdlib.h>

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;
}