The instructions are:
Write a program that prompts the user for 2 numbers, finds the sum and finds the
difference for those numbers and displays a descriptive label for each calculation by calling
2 different functions.
• The 1st function should be called DisplaySumLabel and should print out the statement “ -
This is the Sum.”.
• The 2nd function should be called DisplayDifferenceLabel and should print out the
statement “ - This is the Difference: ”.
• The main function should prompt the user for the 2 numbers:
• Calculate and display the sum of the numbers, then call the function to display the correct label.
• Calculate and display the difference of the numbers, then call the function to display the correct label.
• Use Function Prototypes.
Output run 1: 100, 80.
Output run 2: 20, 250
Unless you want a value to be returned by the functions, instead of just cout'ing a message then void is all you need. In other words the function just does its job then finishes/returns without sending anything back.
Also the reason for the strange numbers is because you int in the function isn't defined so you just get undefined behavior i.e junk.
Try your code with the following and you should get a good idea of what is going on and why.
1 2 3 4 5 6
int DisplayDifferenceLabel()
{
int X = 789; // some number you choose
cout << ": " << "This is the difference" << endl;
return X;
}
the type of a function is what it returns.
that is a lot like the functions you studied in algebra:
y = f(x);
and looks just like that in code, variable = function(parameters);
your functions do NOT return any values, though. They just print on the screen.
cout << f(x)
^^ this will print the result of the function f with parameter x.
but if you say cout << displaywhatever() ... like an uninitialized variable, it prints junk.
if you say
displaywhatever() it calls the function and discards the returned value. In this case, the function now prints something, and it didn't return anything (useful) anyway.
so void is correct because you don't want a value returned. Void is a placeholder telling c++ compiler that no value is returned, again, which you want here.
you could do this:
string displaywhatever()
{
return "blah blah blah";
}
cout << displaywhatever(); //ok, the string is returned and cout processes that returned string.