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);
}
'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
కామెంట్లు
కామెంట్ను పోస్ట్ చేయండి
దయచేసి మీ సలహాలను సూచనలను స్పష్టంగా పేర్కొనగలరు. plz see that ur comments are 'acceptable' in a value based society.