Dynamic Memory Allocation

QUESTION

Write a program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using malloc() function.

“TESTCASE_1”: “5\n1 2 3 4 5\n###—###SEPERATOR—###—\nSum=15”, “TESTCASE_2”: “7\n5 5 5 5 5 1 1\n###—###SEPERATOR—###—\nSum=27”, “TESTCASE_3”: “3\n2 2 2\n###—###SEPERATOR—###—\nSum=6”, “TESTCASE_4”: “0\n###—###SEPERATOR—###—\n0”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <stdlib.h>
#include<stdio.h>
int main()
{
  int n,i,*ptr,sum=0;
  scanf("%d",&n);
  ptr=(int*)malloc(n*sizeof(int));  
  if(ptr==NULL){
        	
        	exit(0);
    	}
  for(i=0;i<n;++i){
        	scanf("%d",ptr+i);
        	sum+=*(ptr+i);
    	}	
 
    	printf("Sum=%d\n",sum);
    	free(ptr);
    	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.