Tuesday, January 19, 2010

SUM OF ARRAY ELEMENTS

#include
#include
void main()
{
clrscr();
int asum(int a[],int l);
int a[50],i,sum,n,count=0,l,c=0;
cout<<"Enter the maximum limit of array";
cin>>l;
cout<<"\nEnter the elements";
for(i=0;i<=l-1;i++)
{
cin>>a[i];
}
do
{
cout<<"\n1:sum with simple method\n2:sum using recursion\n3:exit\n";
cin>>n;
switch(n)
{
case 1:
{
sum=0,count=0;
for(i=0;i<=l-1;i++)
{
sum=sum+a[i];
count++;
}
cout<<"sum of all the elements of array using simple addition="< cout<<"\nloop was executed "< c=0;
break;
}
case 2:
{
sum=asum(a,l);
cout<<"sum of all elements of array using resursive method="< cout<<"\nrecursion was performed "< c=0;
break;
}
case 3:
{
c++;
}
}
}while(c==0);
}
int asum(int a[],int l)
{
int sum=0,count=0;
int m=l-1;
if(m<0)
{
count++;
}
else
{
sum=a[m]+asum(a,m);
count++;
}
return(sum);
}

No comments: