help in adding n numbers using function

can someone help me with my codes I'm new to function. what is wrong with my codes?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
  #include<iostream>

int addition(int);
using namespace std;

int main ()
{
    int arr[20];
    int sz,temp,j, i;
    int sum= 0;

    cout<<"How many numbers you want to be added? \n";
    cin>>sz;
    cout<< "Enter "<<sz<< " numbers: \n"<<endl;

    for(int i= 0; i<sz; i++)
    {
        cin>>arr[i];
    }
    for(i=0,j=sz-1;i<sz/2;i++,j--)
	{
		temp=arr[i];
		arr[i]=arr[j];
		arr[j]=temp;
	}

    cout<< "The reverse of the inputed numbers is: "<<endl;

    sum= addition(sz);
    double average= sum/sz;

    for(int i= 0; i<sz; i++)
    {
        cout<<arr[i]<< " ";
    }
    cout<<endl<< "The total sum of the number you inputed is: \n"<<sum<<endl;
    cout<<endl<< "The total average of the numbers you inputed is: \n"<<average<<endl;

    return 0;
}
int addition(int size)
{
    int a[20];
    int sum;
    int j;
    for(int j= 0; j<size; j++)
    {
        sum+=a[j];
    }
    return sum;
}
Last edited on
(1) You don't actually pass the array that you want to add to the addition() function;
- change lines 3 and 41 to include a parameter int a[];
- change line 29 to pass the array (here called arr);
- then you can delete line 43

(2) You don't initialise sum in function addition(); change line 44 to
int sum = 0;

(3) You are going to suffer from integer division in working out the average on line 30 (int/int always gives an int, truncated toward zero if necessary, irrespective of the double variable they will be put in on the LHS); to avoid this you will have to cast one of the items on the RHS to a double. Whatever I suggest somebody will take issue with, so choose your favourite method of casting.

(4) You don't need to declare int j on line 45; it won't be used as a new int j will take over for the duration of the loop on line 46.

(5) You don't actually have to swap the array round just to write things in reverse order. (This depends on what you were actually asked to do.)
Last edited on
Lets look at your function:
1
2
3
4
5
6
7
8
9
10
11
int addition( int size )
{
    int a[20]; // 20 integers. What are their values now?
    int sum; // what is the value of sum now?
    int j;
    for ( int j= 0; j<size; j++ ) // you look at size values. What if 20<size?
    {
        sum += a[j];
    }
    return sum;
}

thank you @lastchance it works! :)
Topic archived. No new replies allowed.