LAB week 9 (i): sum of elements of array (dynamic allocation of memory using malloc( ))

/*code is slightly modified by bhayyA after taking it from S.chand text book
 'Introduction to Programming' authored by KV SAmbasivarao & DAvuluri sunita*/
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n,*arrptr,total=0;
printf("\n enter no of elements in the array:");
scanf("%d",&n);
//dynamically allotinng memory for the array begins
arrptr=(int *)malloc(n*sizeof(int));
printf("\n memory alloted =%d",sizeof(arrptr));
if(arrptr==NULL)
{
  printf("\n memory allocation failed");
  exit(0); //the no. is an indication of the type of error
     }
     else
     {
      printf("\n enter the elements of the array:\n");
      for(i=0;i<n;i++)
      {
      printf("\n enter the element arrptr[%d]:",i);
      scanf("%d",&arrptr[i]);
      total=total+arrptr[i];
      }
   
     }
     free(arrptr); //frees the dynamically allocated memory
     printf("\n sum of the array elements=%d",total);
}
తెరమీద
enter no of elements in the array:4
enter the element arrptr[0]:1
enter the element arrptr[1]:2
enter the element arrptr[2]:3
enter the element arrptr[3]:5
sum of the array elements=11

కామెంట్‌లు

ఈ బ్లాగ్ నుండి ప్రసిద్ధ పోస్ట్‌లు

100% C prog to write content into a file and then read it back onto the console

Spic macay

శ్రీరస్తు.. రామలింగ 18-1-24 (సూరసాని వారి ఆహ్వానము)