Simple addition funtcion

I'm new to functions and I'm trying to add 2 numbers. Where am I going 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
25
26
27
  #include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int add(int a);


int main()
{
	int a, p, q;
	cout << "Enter a number : " << endl;
	cin >> p;
	cout << "Enter a 2nd number : " << endl;
	cin >> q;
	cout << add(a) << endl;
}

int add (int a)
{
	int p, q, add;
	  
	  add = p + q;
	
	return add;
}
You're not passing p and q from main into your add() function. Instead, inside the function, you're creating new local variables p and q, which you never initialise or assign values to.

You're also passing a mysterious variable a into the function. You never assign a value to this variable in main, and you don't use it ad all in add().
Last edited on
closed account (48T7M4Gy)
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);

int main()
{
    int p = 0;
    int q = 0;
    int total_in_main = 0;
    
    cout << "Enter a number : " << endl;
    cin >> p;
    
    cout << "Enter a 2nd number : " << endl;
    cin >> q;
    
    
    total_in_main = add(p, q);
    
    cout << "Total is: " << total_in_main << endl;
}

int add (int x, int y)
{
    int total = x + y;
    return total;
}



Enter a number : 
5
Enter a 2nd number : 
8
Total is: 13
Program ended with exit code: 0


Send the two numbers p and q to the add function - via the bracketed numbers - they replace x and y. The add function does the addition and sends back its total which is stored as total_in_main when returned. Printing follows.
Last edited on
Topic archived. No new replies allowed.