Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Friday, 22 December 2017

C program to find sum of n elements entered by user

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int num,i,*ptr,sum=0;
    printf("Enter number of elements: ");
    scanf("%d", &num);
    ptr = (int*) malloc(num * sizeof(int));  //dynamic memory allocation
    if(ptr==NULL)                   
    {
        printf("Sorry!! memory not allocated.");
        exit(0);
    }
    printf("Enter elements of array: ");
    for(i=0;i<num;i++)
    {
        scanf("%d",ptr+i);
        sum=sum + *(ptr+i);
    }
    printf("Sum = %d", sum);
    free(ptr);
    return 0;
}
x

No comments:

Post a Comment