Write a program to find sum of n elements entered by the user. To write this program, allocate memory dynamically using malloc() / calloc() functions or new operator.




#include<iostream.h>
#include<conio.h>
class sum
{
int *a;
int n;
public:
sum();
~sum();
int s();
};
sum::sum()
{
cout<<"enter the number of elements you want to add"<<endl;
cin>>n;
cout<<"allocating memory via new"<<endl;
a=new int[n];
cout<<"enter the elements"<<endl;
for(int i=0;i<n;i++)
cin>>a[i];
}
sum::~sum()
{
cout<<"deallocating memory using delete"<<endl;
delete a;
}
int sum::s()
{
int sum=0;
for(int i=0;i<n;i++)
sum=sum+a[i];
return(sum);
}
void m()
{
sum obj;
int k=obj.s();
cout<<"The sum is "<<k<<endl;
}
void main()
{
clrscr();
m();
getch();
}


Output:-

Comments