×

C Programs

C Basic & Conditional Programs

C Looping Programs

C String Programs

C Miscellaneous Programs

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

Dynamic Memory Allocation Example: In this C program, we will declare memory for array elements (limit will be at run time) using malloc(), read element and print the sum of all elements along with the entered elements.

This program is an example of Dynamic Memory Allocation, here we are declaring memory for N array elements at run time using malloc() - which is used to declare memory for N blocks at run time, we will read N elements, will print them and also print the sum of all elements.

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

Consider the program:

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

Output

Enter limit of the array: 5
Enter element 01: 100
Enter element 02: 200
Enter element 03: 300
Enter element 04: 400
Enter element 05: 500

Entered array elements are:
100
200
300
400
500
Sum of array elements is: 1500

C Advance Programs »

Related Programs

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.