Sum of integer array – Computer Sir Ki Class
  

Login
[lwa]



Solved Problem #CPP#3088 siteicon   siteicon   siteicon  

Problem Statement - Sum of integer array

Write a program to collect 5 integer values from user in an integer array and then pass this array to a function along with its size. Return the sum of the array members from the function and print its value in the main routine.

Solution

TC++ #3088

#include <iostream.h>
#include <conio.h>
int sumarr(int [],int);
int main()
{
clrscr();
int arr[5];
for(int i=0;i<5;++i)
{
cout<<"Give array member "<<i+1<<" : ";
cin>>arr[i];
}
cout<<endl;
cout<<"Members in given array are : "<<endl;
for(int i=0;i<5;++i) cout<<arr[i]<<" ";
int sa=sumarr(arr,5);
cout<<endl<<"Array sum = "<<sa<<endl;
getch();
return 0;
}

int sumarr(int a[],int size)
{
int sum=0;
for(int i=0;i<size;i++) sum+=a[i];
return sum;
}
#include <iostream>
using namespace std;
int sumarr(int [],int);
int main()
{
int arr[5];
for(int i=0;i<5;++i)
{
cout<<"Give array member "<<i+1<<" : ";
cin>>arr[i];
}
cout<<endl;
cout<<"Members in given array are : "<<endl;
for(int i=0;i<5;++i) cout<<arr[i]<<" ";
int sa=sumarr(arr,5);
cout<<endl<<"Array sum = "<<sa<<endl;
return 0;
}

int sumarr(int a[],int size)
{
int sum=0;
for(int i=0;i<size;i++) sum+=a[i];
return sum;
}

Test it !
  Related (?) :

Run Output

Give array member 1 : 12
Give array member 2 : 11
Give array member 3 : 10
Give array member 4 : 9
Give array member 5 : 8

Members in given array are :
12 11 10 9 8
Array sum = 50

Notes

  • It is important to pass the size of array to a function as array is always passed by a reference. For this reason only the address of first member is passed and there is no way to find array boundary unless the array size is passed. However when strings are passed as reference array boundary can be determined by null termination point and length of string need not be passed.

Common Errors

  • Most common error student do is in understanding that array member filling has to start from 0 and not from 1 but the user has to be asked to fill member number 1, 2 and so on.


Share

sunmitra| Created: 27-Jan-2018 | Updated: 27-Jan-2018|






Back