add is work but minus doesnt work

hi
this is my code with function, it works when adding numbers but when i change line 27 to minus (like this sum-=a[i])answer is 0

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

int add(int[]);

int main(){
	
	int num[3];
	
	for(int i=0;i<3;i++){
		
		cout<<"enter number: ";
		cin>>num[i];
	}
	
	cout<<add(num);
	
	return 0;
}

int add(int a[]){
	
	int sum;
	for(int i=0;i<3;i++){
		
		sum+=a[i];
	}
	return sum;
}
Last edited on
You forgot to initialize sum.
The problem is in line 23:
int sum;
You need to initialize it before you can use it;
thank you so much
but i didnt understand
where should i initialize sum?
Best is to do it when you declare it: int sum = 0;
i have changed to this
sorry for my amateur question
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
#include <iostream>
using namespace std;

int min(int[]);

int main(){
	
	int num[3];
	
	for(int i=0;i<3;i++){
		
		cout<<"enter number: ";
		cin>>num[i];
	}
	
	cout<<min(num);
	
	return 0;
}

int min(int a[]){
	
	int sum=0;
	for(int i=0;i<3;i++){
		
		sum-=a[i];
	}
	return sum;
}
it doesnt work
Worsk fine for me.

Input: 5,6,7
output: -18.

input: 2,2,2
output: -6
im gonna calculate 10-1-1=8
thanks
Then maybe you should change your code so it doesn't minus everything.

sum-=a[i];

Every number that is in the array will be reversed. If it is 5, -5 will go into sum. So change your code to make it do what you want. Which apparently is to not reverse the first number, but only the second and third.
thanks for helping
im little confused
i dont know how to minus these numbers
You are already minusing them? But right now you're minusing all 3. You want to minus only the last 2 digits, not the first one.
thanks
yes im gonna minusing them
understood
so how can i minus last 2 numbers?
Your code already minuses 3 numbers. Now take a thinker and make it minus 2 numbers instead of 3, it should not be very hard if you actually try, which you are not right now. Work on it yourself and you'll learn more.
i think more
thanks for answering
Note that if you use += you can calculate 10-1-1 by inputting the numbers 10, -1 and -1.
This works for you?

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

int add( int a[] ) ;

int main()
{	
	int num[3] ;
	
	for( int i = 0; i < 3; ++i)
	{	
		std::cout << "enter number: " ;
		std::cin >> num[i] ;
	}
	
	std::cout << add( num ) ;
	
	return 0 ;
}

int add( int a[] )
{
	int sum = a[0] ;
	
	for( int i = 1; i < 3; ++i )
	{
		sum -= a[i] ;
	}
	
	return sum ;
}
Last edited on
@elalelph is right.
Topic archived. No new replies allowed.