function prototype

I am a beginner in C++.I need to project the sum but it will not project. Please help.

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

//function prototype
void calcSum(int &n1, int &n2, int &n3);

int main()
{
	int num1 = 0;
	int num2 = 0;
	int num3 = 0;
	
	cout << "Enter the first number: ";
	cin >> num1;
	cout << "Enter the second number: ";
	cin >> num2;
	
	return 0;
}	//end of main function

//*****function definitions*****
void calcSum(int &n1, int &n2, int &n3)
{
	n3 = n1 + n2;
	cout << "Sum: " << n3 << endl;
}//end of calcSum function 
you did not actually CALL the function. you must call it!

1
2
3
4
5
6
7
8
9
10
11
12
13
14

int main()
{
	int num1 = 0;
	int num2 = 0;
	int num3 = 0;
	
	cout << "Enter the first number: ";
	cin >> num1;
	cout << "Enter the second number: ";
	cin >> num2;
	calcSum(num1, num2, num3);
	return 0;
}




as a side note this is a bit odd.
most would do one of 3 things here.

int calcSum(int a, int b) //calculates and returns, letting main decide to print or use it..
{
return a+b;
}
//in main, num3 = calcSum(num1, num2);

or maybe this, removing the somewhat useless 3rd input, printing it here
void calcSum(int a, int b)
{
cout << a+b<< endl;
}


and a somewhat strange 3rd option (return in c, main handles result)

void calcSum(int a, int b, int &c)
{
c = a+b;
}

Nothing you have is wrong, beyond forgetting to call it.

Thank you, i have corrected and it worked.

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

//function prototype
void calcSum(int &n1, int &n2, int &n3);

int main()
{
	int num1 = 0;
	int num2 = 0;
	int num3 = 0;
	
	cout << "Enter the first number: ";
	cin >> num1;
	cout << "Enter the second number: ";
	cin >> num2;
	calcSum(num1, num2, num3);
	return 0;
}	//end of main function

//*****function definitions*****
void calcSum(int &n1, int &n2, int &n3)
{
	n3 = n1 + n2;
	cout << "Sum: " << n3 << endl;
}//end of calcSum function 
So... since you didn't address jonnin's issues, I'll ask the obvious question:

Why are you passing n1 and n2 into calcSum by reference?
Last edited on
Topic archived. No new replies allowed.