C++ Intro

Hi, everyone. So my professor gave the class an assignment and what it had to do is basically have the compiler say:

Enter two numbers: x y
x "plus" y "equals: "

using a function and int main.
and we could not use any cout in the function.

how can i get it to print out the added numbers in the function from int main?
what i have is:


#include <iostream>
using namespace std;

int x = 0;
int y = 0;
void add()
{
x+y;
}

int main()
{
cout << "Enter two numbers: ";
cin >> x;
cin >> y;
cout << x << " plus " << y << " equals: ";
add();
cout << "\n";
return 0;
}


when i call the function it will not print out from int main though. thanks a lot.

A function can return a value. For instance your main() returns an int.
Your add() function should return the sum of x and y.

1
2
3
4
int add()
{
    return x + y;
}


Then you simply put the call to add() in the cout after "equals: ", so that its return value is displayed.
If you are forced to use a void add function than u could do:

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;

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

int main()
{
	int x,y;
	cout<<"add x value"<<'\n';
	cin>>x;	
	cout<<"add y value"<<'\n';
	cin>>y;

	add(x,y);

	cout<<"x+y = "<<x;

	cin.get();
	cin.get();
	return 0;
}


For the example I presented you should know about pointers http://www.cplusplus.com/doc/tutorial/pointers/ .

But Catfish2 example is what you need :)
Topic archived. No new replies allowed.