adding funnction

hey guys
i have a problem with this function
answer is wrong


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
using namespace std;

int add(int , int);

int main(){
	
	int num,sum;
	
	for(int i=0;i<5;i++){
		
		cout<<"enter number: ";
		cin>>num;
	}
	
	cout<<add(num,sum);
	return 0;
}

int add(int num,int sum){
	
	return sum+=num;
	
}
1) What value do you think sum has when you call your add function?

2) Why do you ask the user to input 5 numbers, when your code only ever uses the last one that they input?

should i use array for getting 5 numbers?
im gonna add 5 numbers with function
An array would probably be a good way of storing the 5 numbers. A vector would be even better.

In this case, though, you don't actually need to store all five of the numbers. Just use them one by one.

You did notice how many questions I asked you, right?
Do you know what your For loop is doing?
Every time your code is reading a number, it is overwriting your previous read. so basically your num variable will only hold the last value entered. For example try this code (which is from your original code) below and see the output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

#include <iostream>
using namespace std;


int main(){
	
	int num;
	
	for(int i=0;i<5;i++){
		
		cout<<"enter number: ";
		cin>>num;
	}
	
	
	//print only num
	cout<<endl<<num;
	return 0;
}





Now compare your original code with this solution - can you see the difference?

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
#include <iostream>
using namespace std;

//initialise 
int sum = 0;
	
//function
int add(int n){
	
	return sum = sum + n;
	
}

int main(){
	
	int num;

	
	for(int i=0;i<5;i++){
		//prompt for user input
		cout<<"enter number: ";

                //read user input
		cin>>num;

               //call function to cumulative sum
		add(num);
		
	}
	
	cout<<sum;
	return 0;
}


Last edited on
@RonnieRahman:

Now you're using a global variable, and that's not a good habit to get into.
Oops!
Coming from SQL Server database background and learning C++. I bet you're right. Cheers matey @MikeyBoy
thanks everyone
understood
One solution:

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
#include <iostream>

int add(int num, int sum);

int main(){
	
	int num, sum = 0;
	
	for(int i = 0; i < 5; ++i) {
		
		std::cout << "enter number: ";
		std::cin >> num;
		sum = add(num, sum);
	}
	
	std::cout << sum << std::endl;
	
	return 0;
}

int add(int num, int sum){
	
	return sum += num;
	
}
Last edited on
Another:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

int main(){
	
	int num, sum = 0;
	
	for(int i = 0; i < 5; ++i) {
		
		std::cout << "enter number: ";
		std::cin >> num;
		sum += num;
	}
	
	std::cout << sum << std::endl;
	
	return 0;
}
thanks for answer
Topic archived. No new replies allowed.