Q:

C program to read a one dimensional array, print sum of all elements along with inputted array elements using Dynamic Memory Allocation.

0

C program to read a one dimensional array, print sum of all elements along with inputted array elements using Dynamic Memory Allocation.

In this program we will allocate memory for one dimensional array and print the array elements along with sum of all elements. Memory will be allocated in this program using malloc() and released using free().

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

/*C program to read a one dimensional array, 
print sum of all elements along with inputted array 
elements using Dynamic Memory Allocation.*/
 
#include <stdio.h>
#include <stdlib.h>
 
int main()
{
    int *arr;
    int limit,i;
    int sum=0;
     
    printf("Enter total number of elements: ");
    scanf("%d",&limit);
     
    /*allocate memory for limit elements dynamically*/
    arr=(int*)malloc(limit*sizeof(int));
     
    if(arr==NULL)
    {
        printf("Insufficient Memory, Exiting... \n");
        return 0;
    }
     
    printf("Enter %d elements:\n",limit);
    for(i=0; i<limit; i++)
    {
        printf("Enter element %3d: ",i+1);
        scanf("%d",(arr+i));
        /*calculate sum*/
        sum=sum + *(arr+i);
    }
     
    printf("Array elements are:");
    for(i=0; i<limit; i++)
        printf("%3d ",*(arr+i));
     
     
    printf("\nSum of all elements: %d\n",sum);
     
    return 0;    
}
    Enter total number of elements: 5
    Enter 5 elements:
    Enter element 1: 11
    Enter element 2: 22
    Enter element 3: 33
    Enter element 4: 44
    Enter element 5: 55
    Array elements are: 11 22 33 44 55
    Sum of all elements: 165

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now