View Full Version: How to do certain things in C++

C++ Learning Community > C++ Tips > How to do certain things in C++


Title: How to do certain things in C++


Dragon - June 23, 2003 02:06 AM (GMT)
The program below shows how to do many things. It teaches how to use a macro, declare variables, take input from the user, do simple addition, subtraction, multiplication, and divison. It also teaches how to use 'system("PAUSE");' and call your own functions.

#include <iostream>
using namespace std;

//This is a macro.
#define EXP(EXP, ANS) \
cout << EXP << " = " << ANS << endl;

//AddFunc() shows how to add two integers.
int AddFunc()
{
int val1, val2, add;
cout << "Enter first integer:" << endl;
cin >> val1;
cout << "Enter second integer:" << endl;
cin >> val2;
add = val1 + val2;
EXP("val1 + val2", add);
system("PAUSE");
}

//SubFunc() shows how to subtract two integers.
int SubFunc()
{
int val1, val2, sub;
cout << "Enter first integer:" << endl;
cin >> val1;
cout << "Enter second integer:" << endl;
cin >> val2;
sub = val1 - val2;
EXP("val1 - val2", sub);
system("PAUSE");
}

//MulFunc() shows how to multiply two integers.
int MulFunc()
{
int val1, val2, mul;
cout << "Enter first integer:" << endl;
cin >> val1;
cout << "Enter second integer:" << endl;
cin >> val2;
mul = val1 * val2;
EXP("val1 * val2", mul);
system("PAUSE");
}

//SubFunc() shows how to divide two integers.
int DivFunc()
{
int val1, val2, div;
cout << "Enter first integer:" << endl;
cin >> val1;
cout << "Enter second integer:" << endl;
cin >> val2;
div = val1 / val2;
EXP("val1 / val2", div);
system("PAUSE");
}

//Main function.
int main()
{
AddFunc();
SubFunc();
MulFunc();
DivFunc();
}

Oh, yeah, and if anyone was wondering who I was, I am r168 on the GM forum.

ih8censorship - June 23, 2003 05:43 PM (GMT)
what is EXP and ANS?

Dragon - June 23, 2003 06:21 PM (GMT)
You can see this near the top of the code:

#define EXP(EXP, ANS) \
cout << EXP << " = " << ANS << endl;

Here I defined a macro called EXP with EXP and ANS as arguments. I know I should have used different names for the name of the macro and the argument, but oh well. What this macro does is take an expression and the answer and display it using "cout." So every time I want to use cout to display an expression used in this program, I can just use:

EXP("1+2",3);

Or you can use variables, like I did in the code.




* Hosted for free by InvisionFree