1) Write a program that reads two numbers from the user, adds them together, and then outputs the answer. The program should use two functions: A function named ReadNumber() should be used to get an integer from the user, and a function named “WriteAnswer” should be used to output the answer. You do not need to write a function to do the adding.
2) Modify the program you wrote in #1 so that the function to read a number from the user and the function to output the answer are in a separate file called “io.cpp”. Use a forward declaration to access them from your main() function, which should live in “main.cpp”.
3) Modify the program you wrote in #2 so that it uses a header file to access the functions instead of forward declarations. Make sure your header file uses header guards.
Quiz solutions
1) Show Solution
#include <iostream>
int ReadNumber()
{
using namespace std;
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void WriteAnswer(int x)
{
using namespace std;
cout << "The answer is " << x << endl;
}
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
2) Show Solution
io.cpp:
#include <iostream>
int ReadNumber()
{
using namespace std;
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void WriteAnswer(int x)
{
using namespace std;
cout << "The answer is " << x << endl;
}
main.cpp:
int ReadNumber();
void WriteAnswer(int x);
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
3) Show Solution
io.cpp:
#include <iostream>
int ReadNumber()
{
using namespace std;
cout << "Enter a number: ";
int x;
cin >> x;
return x;
}
void WriteAnswer(int x)
{
using namespace std;
cout << "The answer is " << x << endl;
}
io.h:
#ifndef IO_H
#define IO_H
int ReadNumber();
void WriteAnswer(int x);
#endif
main.cpp:
#include "io.h"
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
you haven’t mentioned what void is yet
[ It was covered in a first look at functions. "A return type of void means the function does not return a value". -Alex ]
When you say two numbers from the user it make it sound like 2 different numbers from the user not adding 1 number to itself by putting it into two variables.
[ I am not sure I follow. The intent is to read in 2 different numbers from the user. Sample program #1 does just that by reading one value into x, and one value into y. These are then added together and sent to the function that writes the answer. -Alex ]
There’s a much easier code for Question 1:
[ Code removed so as not to give hints as to how to solve the problem ]
Juiceh, the point of the exercise isn’t to write the easiest or most efficient code. The exercises are worded to encourage people to use various concepts that have been covered in the preceding sections.
thx for the tutorial, it really helps
Show me what I’m missing. Why don’t you need to declare “int y” as part of the “int ReadNumber()” function? It would seem that this is necessary since in the main function, both “int x” and “int y” are called. How can “int y” be called if it has not been expressly declared? When the function “int ReadNumber()” was declared at the top of the program, only “int x” was included as part of the declaration. Please explain.
Hmmm. When we say “int x” or “int y”, we’re telling the program that we’re defining a new variable, and we’re telling the program what type the variable is and what it’s name is. When a new variable is declared inside of a function, that variable’s name is only meaningful within that function. As a result, it is perfectly permissible to reuse the same variable name within multiple functions. This does not imply any kind of linkage between these variables.
Within main(), we declare two variables: x and y. These variables only exist within main(). We need two variables here because we have to hold two inputs.
Within ReadNumber(), we also declare one variable named x. This x has no relationship to the x we declared within main(). In fact, ReadNumber() doesn’t even know that another variable with the same name exists within main(). This is a good thing because it means we don’t have to worry about naming collisions.
We do not declare a variable y within ReadNumber() because ReadNumber() only needs one variable to do it’s job. Once ReadNumber() is finished executing, it passes it’s value back to the caller (main()). Main() then assigns that value to one of the variables it declared.
It might help you understand conceptually if you rename the x variable inside of ReadNumber() to “z”, or some other name that is not reused by main().
Got it, thanks.
About the function “void WriteAnswer(int)” in question 1):
Since in the main function, the statement:
does return a value for the addition of x plus y , why does “WriteAnswer” have a type of “void”? Can you provide more clarity on when a function can be of type “void” and return a value such as it does in this case?
Thanks
WriteAnswer() actually does not return anything. When the program reaches the
WriteAnswer(x+y)line, the first thing that happens is that x+y is evaluated and resolved to an integer. After that happens, then WriteAnswer() is called. The value of x+y is passed as a parameter of WriteAnswer(). This is why WriteAnswer has a parameter of type “int” — because the caller is passing it a parameter of type int. WriteAnswer() doesn’t return anything back to the caller, which is why it has a return type of void.Hi, Alex!
I just wanted to let you know that quiz question one says to write a function called
ReadInteger(), however all of the solutions sayReadNumber()instead.Once again, I think this is a great tutorial.
[ Thanks for letting me know! It's fixed. -Alex ]
I made a few changes to this program. I took the asking for a number part out of the ReadNumber function, so that i can ask for a first and second number explicitly. I also had the program print the word OK after the user entered a number. Throughout this tutorial, I have been observing the effects of typing in numbers, letters, and even expressions, when it is expecting an integer. You have yet to explain what it does in these cases or how to validate proper inputs. I usually validate inputs in my programs. This is my first low-ish level language, usually deal with higher stuff like MATLAB. I’m sure this all will be explained in later sections. I want to tell you what happens though.
I enter the letter s for the first number. it prints OK to the screen, since there isn’t any validation, it always does. It asks for the second number. But it answers itself with the word OK, and prints the answer as 0. How does s + OK equal 0? we should clear the input buffer every function then?
Chad, I’m just starting to write the sections on I/O (chapter 13), where I will discuss I/O in more detail. Unfortunately, there is no easy way to do numerical validation in C++ when using the standard I/O operators (at least that I know of). As you’ve noted, the >> operator does funny things when the user input is not formatted as expected. There are some other functions that perform more consistently, which I will cover in chapter 13.2 (which should be up sometime this week).
However, perhaps the best way I’ve found is to read everything into a string, because a string will treat numbers, letters, and whitespace uniformly. Then, you can parse the string to see whether it meets your validation criteria. However, this is somewhat beyond the scope of these introductory tutorials.
I am trying to wirte a simple program using on Function, but I am getting following error about stdafx.h.
Please let me now where I am making mistake.
fatal error C1083: Cannot open include file: ’stdafx.h. I will appreciate your help.
stdafx.h is a file that Microsoft Visual Studio expects to be the first line in all of your .cpp files. For each .cpp file in your project, make sure you include stdafx.h.
I did the first one and to test it I tried compiling it, and at first i thought i was doing something wrong but I can’t compile your code either, I can run it though, and it prints out the solution as expected. I figure I must have forgot something?
If you’re running the code, then it’s getting compiled. If you try to run the code when it hasn’t been compiled, the compiler should automatically compile for you before running.
mmmm I found the problem, I was using “void Readnumber()” instead of int and somehow when i copied the solution code I did the same thing on the solution. So much for
Thanks for the timely response though, and your guide is already helping me get ahead of school which is much appreciated.
I can’t get solution 3 to build.
This is my main ccp (test8.cpp):
// Test8.cpp : Defines the entry point for the console application. #include "stdafx.h" #include "io.h" int main() { int x = ReadNumber(); int y = ReadNumber(); WriteAnswer(x+y); return 0; }This is my io.cpp:
#include "stdafx.h" #include int ReadNumber() { using namespace std; cout <> x; return x; } void WriteAnswer(int x) { using namespace std; cout << "The answer is: " << x << endl; }And this is my io.h:
This is the error I get:
c:vcpp2008projectstest8test8io.h(8) : fatal error C1070: mismatched #if/#endif pair in file ‘c:vcpp2008projectstest8test8io.h’
(I’m putting #include iostream with at each side or iostream at the top of io.cpp here and there isn’t supposed to be space between the << after the cout in io.cpp here either, but it won’t display correctly. Slashes won’t show up in the error message either.)
It’s okay: problem solved.
#ifdef IO_H should be @define IO_H
Silly me.
Good job on chapter 1. I’ve really been struggling with stuff like pointers and arrays so I’m going through this whole tutorial slowly. Hopefully the advanced stuff will be as good as this. Thanks for the tutorials!
Can I just put what you have in io.h in stdafx.h? Would that not remove some of the difficulty?
Stdafx.h should be used only for stuff that is very unlikely to ever change. Typically stdafx.h #includes other header files that meets this criteria.
Very useful!!
/* Program of add two number like example 1 */
#include <iostream.h>
#include <conio.h>
int ReadNumber(int x,int y)
{
int z;
z = x + y;
return z;
}
void WriteAnswer(int x)
{
cout << "\n The Answer is " << x;
}
void main()
{
int x,y,z;
clrscr();
cout << "\n Enter the first Number : ";
cin >> x;
cout << " \n Enter the second Number : ";
cin >> y;
z = ReadNumber(x,y);
WriteAnswer(z);
getch();
}
/*End of Program */
This one was very helpful. Thanks. Those tutorials give me some hands on experience (I learn a lot faster that way). Thanks again for the great tutorial.