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.
What’s the easier code?
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.
“When a new variable is declared inside of a function, that variable’s name is only meaningful within that function.” Hi, I probably missed it but was this explicitly stated earlier in the tutorial? I also missed this completely…
“Main() then assigns that value to one of the variables it declared.” Presumably in sequence?
“what it’s name is” its name – sorry, born to be a grammar cop.
Thanks very much for this tutorial.
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 Allen & Alex. Again, I had the exact same confusion as Allen. Thanks guys.
void is displays no return value….. it is not mandatory
u should also write without void
example:
main()
{
int x,y,add;
cin>>x>>y;
add=x+y;
cout<<"add"<<add<<endl;
}
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.
Hi Alex,
For Problem 1, I actually used 3 “.cpp” files (main, readnumber and writeanswer) and created a header file to make the link. Everything is fine except (yeah I wouldn’t spam this blog if everything were really fine) that it doesn’t compile when I define WriteAnswer() this way:
#include "stdafx.h"
#include <iostream>
void WriteAnswer(int x)
{
using namespace std;
cout << "The sum is: " << x << endl;
}
You did that in chapter 1.8.
The error message I get:
—— Build started: Project: Addition, Configuration: Debug Win32 ——
Compiling…
WriteAnswer.cpp
c:\documents and settings\ben.beni\mes documents\visual studio 2008\projects\addition\addition\writeanswer.cpp(7) : error C3872: ‘0xa0′: this character is not allowed in an identifier
c:\documents and settings\ben.beni\mes documents\visual studio 2008\projects\addition\addition\writeanswer.cpp(7) : error C2065: ‘cout ’ : undeclared identifier
Build log was saved at “file://c:\Documents and Settings\Ben.BENI\Mes documents\Visual Studio 2008\Projects\Addition\Addition\Debug\BuildLog.htm”
Addition – 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
But it does compile if I just ask for the output
cout << x << endl;
Another question I’ve got, when I run this through Visual Studio 2008, it automatically pauses after it gave me the answer, asking me to press a touch to continue. But if I run that from the “.exe” created, it won’t stop and closes the window right after I enter the second integer (and press enter). How come?
Thanks.
I am a bit perplexed as to why it won’t compile for you. I copied your code into a WriteAnswer.cpp and it worked fine for me. Your error messages don’t make any sense for the code you copied above. Character 0xa0 is the ‘á’ character. You might look through your files and see if somehow one of your ‘a’ characters is actually an ‘á’ instead.
As for the pausing issue, Visual Studio intercepts the program’s termination and holds the output window open until you hit a key. This is a nice feature that it provides. When you run your program directly from the .exe, it exits immediately upon termination because that’s what it should do under normal circumstances. :)
That’s really weird. I managed to target the annoying part:
Because if I just ask for the value of “x”, it will work. So it probably doesn’t depend on the rest of my code.
I know my laptop keyboard is a bit messed up. It’s a Dell laptop with an English keyboard that they re-programmed (or just set up I don’t know what they did) in French. Ridiculous, nothing else but the basic keys (letters & numbers) correspond to what I press. Could it be a reason?
For example, I know I can’t print the code properly on your website even if I use the appropriate commands. It’s going to work this time because I used a different computer. Really weird.
Thanks for your help.
Nevermind, I finaly managed to make it work. Nothing was wrong, so I don’t really know what happened. Like if there was a mysterious character on that line that I couldn’t see.
like you I’m new to this but is it not the colon in that line, maybe if you try the answer is without the colon
I can’t get quiz 3 answer to compile. I use Code::Blocks 8.02. I copied and pasted exactly the same code from your post, and it gives the following error:
obj\Debug\main.o||In function `main’:|
C:\temp\CBProjects\IO_Separated_Files\main.cpp|5|undefined reference to `ReadNumber()’|
C:\temp\CBProjects\IO_Separated_Files\main.cpp|6|undefined reference to `ReadNumber()’|
C:\temp\CBProjects\IO_Separated_Files\main.cpp|7|undefined reference to `WriteAnswer(int)’|
||=== Build finished: 3 errors, 0 warnings ===|
I’m guessing you forgot to add io.cpp to your project, so it is not being compiled into your project.
I was struggling with the first question a bit, so I had a look at the answer. I didn’t really understand how it worked, but after compiling it myself, I figured it all out.
I’d have never thought to write it like that :P
I just want to say thank you, again, for all of this wonderful-ness!! :) The comments are great, too, for troubleshooting my work/problems and for avoiding problems in the future. I love this tutorial. I am an absolute beginner and I’m finding it fairly easy to grasp.
alex should be nominated as “best man on the net”. this guy like responds, AND COMPILES, everyones problems lol. thanks allexxxx!
Hallo alex,
I am practicing c++ under Linux ubuntu. till yet i compiled my files in the console with the g++ command. but now i dont know how to compile multible files that belong to one projekt. please is there any sugestion for me ?
If I remember correctly from my college days, I believe you can just type the names of all the files you want to compile:
g++ foo.cpp goo.cpp doo.cpp -o runme
Once you get into bigger projects, you may want to learn how to use makefiles (or maybe ant). Or easier, move to an IDE environment.
Whats the point of
I understand it’s a headergaurd, but I don’t get what defining IO_H does
nevermind, i didnt see that last #endif and i get it now
How does main.cpp know to include io.cpp if there’s no include statement for it?
main.cpp doesn’t include io.cpp. Rather, the linker takes both of them and combines them into a single program.
I made this code for the first question and this code also works.
But I wanted to know if my code is fine or not.
int x; int y; void ReadNumber() { using namespace std; cout << "Enter 1st No to be added" x << endl;; cout << "Enter 2nd No to be added" y <<endl; } int WriteAnswer() { return x + y; } int main() { using namespace std; ReadNumber(); cout << WriteAnswer() << endl; return 0; }For a program this simple it’s probably okay, but for more complex programs using global variables is a bad idea and should generally be avoided. I talk more about this in lesson 4.2 — Global variables.
Well I managed to do question 3 on my own, however I needed help on 2 and especially 1 :P
I keep forgetting when and when not to use a semi colon when declaring/defining functions :S
Also, it gets a bit confusing in the first answer where the ‘int x’ in the “WriteAnswer” function isn’t the same ‘x’ as in the “ReadNumber” or “main” functions…
I would suggest changing it to ‘t’ or something (t for total)
Hej Alex Admin, another question:
I took the innitiative to make a slightly different program after completing this test. But guess what? It doesn’t work. I will post the code because I can’t seem to figure it out.
the main cpp:
#include "stdafx.h" #include <iostream> #include "addsub.h" int main() { using namespace std; int a = add(); int b = add(); int c = sub(); int d = sub(); PrintAnswer(a+b-c-d); return 0; }the add and subtract cpp:
#include "stdafx.h" #include <iostream> int add() { using namespace std; cout << "Type a number to add: "; int a; cin >> a; return a; } int sub() { using namespace std; cout << "Type a number to subtract: "; int b; cin >> b; return b; } void PrintAnswer(int c) { using namespace std; cout << "The answer is: " << c << endl; }the add and subtract header file:
error codes:
1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(8) : error C2660: ‘add’ : function does not take 0 arguments
1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(9) : error C2660: ‘add’ : function does not take 0 arguments
1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(10) : error C2660: ’sub’ : function does not take 0 arguments
1>c:vs2005evencreatiefevencreatiefevencreatief.cpp(11) : error C2660: ’sub’ : function does not take 0 arguments
Thanx for looking it at, hope you see where I went wrong, I really like your tutorials, they make me learn a lot!
Code questions about what went wrong with your program are really better suited to be posted in the forums.
In this case though, the answer looks easy — your prototyped functions in addsub.h do not match the ones you declared in the .cpp files. The ones in the .cpp files have no parameters.
my question is is it possible to declare x and declare y
before he main function or i can only declare ReadNumber only once like this
#include <cstdlib> #include <iostream> using namespace std; int ReadNumber() { cout << "Enter a number" << endl; int x; cin >> x; return x; } void WriteNumber(int x) { cout << "WriteNumber(int x)" << x << endl; } int ReadNumber() { cout << "Enter a number" << endl; int y; cin >> y; return y; } void WriteNumber(int y) { cout << "WriteNumber(int y)" << x << endl; } int main() { int x = ReadNumber(); int y = ReadNumber(); cout << "WriteAnswer (x, y)" << (x+y) << endl; system("PAUSE"); return EXIT_SUCCESS; }I don’t quite understand the point of having the “io.cpp” file if I use an “io.h” file with the functions declared there instead.
What I did at first was to use just the two files io.h and main.cpp.
My io.h file looks exactly like the example io.cpp file minus the
which I took out because it’s called before the io.h file in my main.cpp file.
My main.cpp looks exactly the same. This works fine.
So why do I need to move the contents of io.h to io.cpp and put the forward declarations in io.h? It doesn’t seem necessary and it adds an extra file.
Hope that’s easier for you to read than it is for me. ;)
Putting your code in the .cpp file isn’t strictly necessary with these short little programs. However, it IS a good idea to do it anyway because once you get farther along (especially once you get to classes) you’ll realize that putting code in the headers really clutters up your headers and makes it hard to figure out the structure of your program.
So even though it’s not necessary now, it’s good to get in good habits now so you don’t have to break bad habits later. :)
ive got a problem… when i tried making the code to take 2 numbers and add them i think i did somthing wrong.. can anyone tell me what i did wrong??
#include
using namespace std;
int main()
{
int x;
cout << “can i have your first number please” <>x;
cout << “Thank you” << endl;
int y;
cout << “can i have your second number please” <>y;
cout << “thank you” << endl;
}
int add(int x, int y)
{
cout << “Compiling your numbers……” << endl;
int x + y = g
}
int read()
{
cout << “Your number added to gether is” <<g<< endl;
system(“PAUSE”);
return 0;
}
my error’s are 19 D:\Dev-Cpp\main.cpp expected primary-expression before “int”
19 D:\Dev-Cpp\main.cpp expected `;’ before “int”
D:\Dev-Cpp\Makefile.win [Build Error] [main.o] Error 1
hi, i answered and understood question 1, but when i split the functions into main and io.cpp for the forward declarations of ReadNumber() + WriteAnswer(), getting compile errors all over the place.
First split Main as in the tutorial…
Then added io.cpp into source file….
get the following errors
\projects\io\io\io.cpp(10) : error C2871: ’std’ : a namespace with this name does not exist
\projects\io\io\io.cpp(11) : error C2065: ‘cout’ : undeclared identifier
\projects\io\io\io.cpp(13) : error C2065: ‘cin’ : undeclared identifier
\projects\io\io\io.cpp(19) : error C2871: ’std’ : a namespace with this name does not exist
\projects\io\io\io.cpp(20) : error C2065: ‘cout’ : undeclared identifier
\projects\io\io\io.cpp(20) : error C2065: ‘endl’ : undeclared identifier
1>Generating Code…
1>firstown2 – 6 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
then i tried commenting out ‘//#include “stdafx.h”‘ in io.cpp
and i get….
\projects\io\io\io.cpp(24) : fatal error C1010: unexpected end of file while looking for precompiled header. Did you forget to add ‘#include “stdafx.h”‘ to your source?
1>firstown2 – 1 error(s), 0 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
dont understand what is going on here, all I did was split the files as in question 2, now it doesn’t work.
Please help me to understand, as I cant move on until I do.
You need to include the following in io.cpp:
Also, make sure that stdafx.h is the very first include.
Not sure I completely understand but now works by swapping #include “stdafx.h” with #include
now compiles fine
Just a heads up on the quiz three thing. I was unable to compile the code because my header file didn’t contain
Or id get an error stating something along the lines of: unresolved symbol something yadda yadda…
Question on linking .cpp files: I was unable, for question 2, to link the main.cpp with io.cpp. When I finally tried changing io.cpp to io.h, and left it in the same folder, it suddenly worked. I am using microsoft visual c++ 2008. I am wondering if there is a problem with #including .cpp files in .cpp files. By the way I love your site!
Generally it is inadvisable to include .cpp files in other .cpp files, as it’s easy for a .cpp to get included twice that way. for example, if A.cpp includes B.cpp, B.cpp may get included once from A.cpp and again by the project itself.
#include "stdafx.h" #include using namespace std; void Read() { int x; int y; cout <<"Enter a number: " <> x; cout <<"Enter a number: " <> y; } int Write(int x, int y) { return x+y; } int main() { Read(); cout << Write << endl; system("pause"); return 0; }I am terrible at this, just terrible. Time to start from the beginning.
Dont sweat it, it takes time sometimes. I started coding about 4 years ago and have been doing it to and fro. I am aiming to be a proffesional programmer after college, but I still have a long way to go!
I can’t even get this to work on Visual Studio Express 2008. Is it me or is there a glitch?
#include <stdafx.h> #include <iostream> int Main() { using namepsace std; cout << "Pick a number" << endl; return 0; }Ok, I got it figured out. However, why does capitalizing names create a bug…such as
int Main() versus int main?
Because C++ is case-sensitive, and thus for example Variable is not the same as variable or VaRiAbLe. :)
Keep coding. Use it for good.
it could also be the #include Try to put it without the angle brackets :P
Thank you for these great tutorials! I’m really enjoying all of this. :]
I wrote a different set of code where WriteAnswer() calls ReadNumber() twice in a sum operation
int WriteAnswer() //defines WriteAnswer() { int sum=ReadNumber()+ReadNumber(); //Makes one call to ReadNumber() getting 1st x value //and adding that to a second call to ReadNumber() that returns a second x value cout << "Your total is: " << sum << endl; return(0); }The main function only calls WriteAnswer() one time and the program works fine.
What I would like to know is how to be able to make the program print the return value for ReadNumber() the return is return(x);
Thanks so much for your help with learning this.
I could not have gotten interested without this website.
kinda curious about something, when i tried this i tried
#include <stdafx.h> #include <iostream> int ReadNumber(int x, int y) { return x + y; } void WriteAnswer(int x) { using namespace std; cout << x << endl; } int main() { using namespace std; cout << "Enter a number: "; int nX; cin >> nX; cout << "Enter another number: "; int nY; cin >> nY; cout << nX << " * " << nY << " = " << WriteAnswer(ReadNumber(nX,nY)) << endl; return 0; }kinda curious as to why WriteAnswer(ReadNumber(nX,nY)) does’nt work. When i look at it i see ReadNumber returning the value of nX + nY into WriteAnswer(int x). I know how to do this problem another way that works just still curious about this. plz and thx you :)
/*Looks like you’re trying to multiply(*) integer nX and integer nY, but you failed to tell ReadNumber to do so.
ReadNumber(nX,nY) should look like —> ReadNumber(nX * nY).
/*
When I try to build the first program, I get an error (Cube::Blocks) saying “expected initializer before ‘int’ on line 8.
Code:
#include #include “add.h” using namespace std; int add(int x, int y) int main() // This is the line that had the error { cout <> x; cout <> y; add(int x, int y) }Looking at the other comments, my code is way off and barely complete, but I should at least get this solved for future reference, right?
“int add(int x, int y)” is a forward declaration, which require a “;” at the end of.
The error was found in line 8 because it was expecting itself to be part of a prototype function, waiting for a {, causing the compiler to complain.
Your code doesn’t look too bad, but you should break it down some more.
Hi Alex,
Great tutorial. Is there a general rule for when to define a function with parameters or not? I’m a little fuzzy in that area.
I just finished an article about how to design your first programs. It contains some advice on this.
Great tutorials!
Am I right, that in the 1’st Quiz, a
must also be added to our
???
Edit: BLEH! Stupid me. It’s void, not int :p
Is this correct?
#include <iostream> using namespace std; int ReadNumber(int x, int y); int WriteAnswer(int x, int y); int main() { cout << "Please enter a number:" << endl; int num1; int num2; cin >> num1; cout << "Thank-you, and another:" << endl; cin >> num2; cout << "Thank-you..." << endl; cout << num1 << " + " << num2 << " = " << WriteAnswer(num1, num2) << endl; return 0; } int WriteAnswer(int x, int y) { return x + y; }Your int WriteAnswer prototype function should be above main. //Because when WriteAnswer is called in main(), it will not know what you’re referring to yet.
Also in your main function, “WriteAnswer(num1, num2)” should be “WriteAnswer(num1 + num2)”.//Without adding a symbol in there the variables will not give an argument.
Hey there…this is my first night on here, so beginner on c++ eh. But I thought I did everything correctly, but I am stuck with 1 error.
LINK : fatal error LNK1561: entry point must be defined
Here’s my 3 files:
=============================================================================================================
io.cpp:
#include
int ReadNumber()
{
using namespace std;
cout <> 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;
}
=============================================================================================================
I do think this is the best tutorial, I unbookmarked some others just because they were not nearly as useful as this…
Much Thanx,
Nick M.
Forgot to tell you I’m using V.S. 2008…if that helps any.
Your io.cpp needs #include heading it, because you are calling functions that require that library.
You’re not taking in a value from your int ReadNumber() function, so the compiler does not know where to start at.
/*BTW, that function should look like:
int ReadAnswer() { using namespace std; cout << "Input a value please: n" << endl; int x; cin >> x; return x; }/*
first of all thanks for this site, I really appreciate the step by step help.
My first thoughts when attempting the quiz was “how do i get WriteAnswer() to use the results from ReadNumber()…
Also I would have never thought that ReadNumber() could define only x and be used like this inside main.cpp
So i had to cheat to understand how to accomplish quiz 1.
quick question i got from the above responses. Is using
when using cin or cout ok?? I notice other have posted doing this.
Again thanks for the site, I am a total beginner but I can now see my goal of creating a task/timekeeper for work might actually be possible.
edit to the above poster i am jsut guessing but maybe your io.cpp
should be
but I am guessing
I believe when they are using “” it is typos, because my compiler complains when i try it.
That void function is tricky. I worked around it by asking the user for two inputs with different variables and then add them. It works as well, but it wasn’t the assignment.
#include "stdafx.h" #include <iostream> int som(int x, int y) { return x+y; } int main() { using namespace std; cout << "Enter a number: "; int x; cin >> x; cout << "Enter another number: "; int y; cin >> y; cout << "That adds up to: " << som(x,y) << endl; return 0; }I see the benefit now! There’s just one function that deals with the user input, in stead of asking input for every variable.
If I add another variable to main, it will ask for a third input automatically.
int main() { int x = ReadNumber(); int y = ReadNumber(); int z = ReadNumber(); WriteAnswer(x+y+z); return 0; }Funny, everyone seemed to be stumped by the same thing I was, the fact that WriteAnswer only had one int but main had two. Before reading posts about this or continuing with the test, I went back to the section on functions and figured it out, but this was a very tricky question to put on the test, since your examples were all (a,b) in both “main” and the “add” and “multiply” functions. I think you should go back to that section and add a blurb about the relationship between main and external functions, because though it all makes sense once you figure it out, this leads to unnecessary head-scratching for us fledgling coders. You could write a pared-down version of your response in an earlier post:
“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().”
Thank You Jason for your explaination…that really worked for me
hey, great site :)
im using visual c++ 2008
i keep getting this error:
1>—— Build started: Project: Firstquiz, Configuration: Debug Win32 ——
1>Compiling…
1>Firstquiz.cpp
1>Linking…
1>Firstquiz.obj : error LNK2019: unresolved external symbol “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) referenced in function _main
1>Firstquiz.obj : error LNK2019: unresolved external symbol “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) referenced in function _main
1>C:\Users\luke\Documents\Visual Studio 2008\Projects\Firstquiz\Debug\Firstquiz.exe : fatal error LNK1120: 2 unresolved externals
1>Build log was saved at “file://c:\Users\luke\Documents\Visual Studio 2008\Projects\Firstquiz\Firstquiz\Debug\BuildLog.htm”
1>Firstquiz – 3 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
any ideas what i can do to fix it?
Is it possible to return two integers with one function?
If so, please demonstrate how. Thanks.
#include "stdafx.h" #include <iostream> int som(int x, int y) { return x+y; } int main() { using namespace std; cout << "Enter a number: "; int x; cin >> x; cout << "Enter another number: "; int y; cin >> y; cout << "That adds up to: " << som(x,y) << endl; return 0; }Using the void is tricky.
Kaonashi did just as I did and it worked quite well.
I noticed that Alex’s code doesnt read the second input but simply prints the answer (the sum) immediately you input the second variable.
They both work anyway!
Thanks Alex.
i can’t get the solution of this programme.
my main.cpp is
int ReadNumber();
void WriteAnswer(int x);
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
io.cpp is
#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 <
error is
LINK : warning LNK4067: ambiguous entry point; selected ‘mainCRTStartup’
1>main.obj : error LNK2019: unresolved external symbol “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) referenced in function _main
1>C:UsersSanjayDocumentsVisual Studio 2008Projectsjyocpp programmingquiz1.11bDebugquiz1.11b.exe : fatal error LNK1120: 2 unresolved externals
1>Build log was saved at “file://c:UsersSanjayDocumentsVisual Studio 2008Projectsjyocpp programmingquiz1.11bquiz1.11bDebugBuildLog.htm”
1>quiz1.11b – 3 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
i can’t correct this error.pls give some idea.
Your two prototypes are very messed up.
Your int ReadNumber() should look like:
int ReadNumber() { using namespace std; cout << "Input value please: " << endl; int x; cin >> x; return x; }And your void WriteAnswer(int x) should look like:
void WriteAnswer(int x) { using namespace std; cout << "Your answer is: " << x << endl; }i can’t get the solution of this programme.
my main.cpp is
int ReadNumber();
void WriteAnswer(int x);
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
io.cpp is
#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 <LINK : warning LNK4067: ambiguous entry point; selected ‘mainCRTStartup’
1>main.obj : error LNK2019: unresolved external symbol “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) referenced in function _main
1>C:\Users\Sanjay\Documents\Visual Studio 2008\Projects\jyo\cpp programming\quiz1.11b\Debug\quiz1.11b.exe : fatal error LNK1120: 2 unresolved externals
1>Build log was saved at “file://c:\Users\Sanjay\Documents\Visual Studio 2008\Projects\jyo\cpp programming\quiz1.11b\quiz1.11b\Debug\BuildLog.htm”
1>quiz1.11b – 3 error(s), 1 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
i can’t correct this error.pls give some idea.
Look up ^^
At first, Thanks a lot for your wonderful and descriptive tutorial. It’s really amazing!
I use Turbo c++ 4.5 (windows version) for writing c++ program(My computer is so old and I can’t install visual studio on it). I write 3 piece of code as you said:
(1)main.cpp
#include "IO1.h" int main() { int x = ReadNumber(); int y = ReadNumber(); WriteAnswer(x+y); return 0; }(2)IO1.cpp
#include <iostream.h> int ReadNumber() { cout << "Enter a number: "; int x; cin >> x; return x; } void WriteAnswer(int x) { cout << "The answer is " << x << endl; }(3)IO1.h
I saved IO1.h in INCLUDE directory. but I don’t know what should else I do?!! There’s no place in tc4.5 like visual studio to add another file to my previous project or I don’t know where it’s. When I compile my main there are these errors :
Linker error : Undefined symbol WriteAnswer(int) in a module MAIN.CPP
Linker error : Undefined symbol ReadNumbera(int) in a module MAIN.CPP
No real problem here, you only forgot to add your namespaces in, well… everywhere.
Thanks for your reply. but the problem is that I can’t use “using namespace std”. If I put this phrase in my program I will get an error. I can compile and run my program without this phrase easily!!
hmm i couldnt do question 1 on my own, so i copied out your code in the answer, but it just flashes and goes away, i tryed putting in
system (“pause”); and stuff, but it still aint working for some reason :/
using DevC++
thanks
try this:
getch();
:D
What runtime is that in?
Take away the “return 0;” in int main().
i am really grateful for this wonderful tutorial, your response to people’s question has answered mine.
Kiitos!! it means thank you in finnish
Wow, I did it. Thank you so much! The only problem being the site loads up very slow sometimes :[ I understand this is because of how many people are there, but it’s lame :[[
Can some body please help me.
Why does this generate an answer of 2 ever single time (no matter what x,y are)
#include
using namespace std;
int readNumber(int x, int y, int z)
{ cout <> x;
cout <> y;
return z=x+y;
}
void writeAnswer(int z)
{cout << "The answer is : " << z;}
int main()
{
int x,y,z;
readNumber(x,y,z);
writeAnswer(z);
system ("pause");
return 0;
}
I’m pretty clueless mate, but, shouldn’t
cout x;
cout y;
be
cin >> x;
cin >> y;
?
#include
using namespace std;
int readNumber(int x, int y, int z)
{ cout <> x;
cout <> y;
return z=x+y;
}
void writeAnswer(int z)
{cout << "The answer is : " << z;}
int main()
{
int x,y,z;
readNumber(x,y,z);
writeAnswer(z);
system ("pause");
return 0;
}
hello i wrote this progam
// io.cpp : Defines the entry point for the console application.
//
#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
// main2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include
int ReadNumber();
void WriteAnswer(int x);
int main()
{
int x = ReadNumber();
int y = ReadNumber();
WriteAnswer(x+y);
return 0;
}
bt they r showin an error to this
like
1>—— Build started: Project: main2, Configuration: Debug Win32 ——
1>Linking…
1>main2.obj : error LNK2019: unresolved external symbol “void __cdecl WriteAnswer(int)” (?WriteAnswer@@YAXH@Z) referenced in function _main
1>main2.obj : error LNK2019: unresolved external symbol “int __cdecl ReadNumber(void)” (?ReadNumber@@YAHXZ) referenced in function _main
1>C:\Documents and Settings\HCL\My Documents\Visual Studio 2008\Projects\main2\Debug\main2.exe : fatal error LNK1120: 2 unresolved externals
1>Build log was saved at “file://c:\Documents and Settings\HCL\My Documents\Visual Studio 2008\Projects\main2\main2\Debug\BuildLog.htm”
1>main2 – 3 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
pl wt s da problem
Alright Alex?
Loving the guide so far, it’s really well written and very helpful and i’ve had no problems up untill now.
But i was wondering, is it bad that i couldn’t figure this out?
I spent nearly two hours trying different things, but didn’t really get close to figuring it out, the only thing i managed to do was build a program that did the same thing but didn’t obide by your rules.
But my question is, should i really know how to do this problem by now? Is it a bad thing that after me seemingly thinking i learned everything so far in your tutorial, i couldn’t put the pieces together and figure out this problem? :)
Thank you alex sir…. Excellent tutorials….
MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
why do i get this error whenever i type the code out myself, i have compared every little tidbit of code and i still get this… any help?
Also when doing problem #3 when trying to write the header guards it shows up that the directive is missing for #ifndef and it doesnt even recognize #endif
i dunno what im doing wrong :(
great and xplicit presentation, wonderful lessons, superb back/follow up quiz. this is just it.
THE BEST FREEEEEEEEE!!!! C++ TUTORIAL
THANKS ALEX, U’RE GREAT.
I’m having a problem, and I’m not sure what exactly is going on. I need to have #include “io.cpp” in my io.h file for my program to work. I’m not sure if that’s the way it should be, or if I made a mistake and that #include “io.cpp” is just shunting around the mistake. Here’s my code:
main.cpp
#include <iostream> #include "io.h" // add takes two integers as parameters, and returns the result of their sum // add does not care what the exact values of x and y are int main() { using namespace std; int first = ReadNumber(); int second = ReadNumber(); WriteAnswer(second + first); cin.clear(); cin.ignore(255, '\n'); cin.get(); return 0; }io.cpp
#include <iostream> int ReadNumber() { using namespace std; cout << "What's the number you want to add?"; int number; cin >> number; return number; } void WriteAnswer(int number) { using namespace std; cout << "When added, the answer is: " << number << endl; }and lastly, my header file, io.h:
I know this site went up a while ago, but hopefully someone still reads the comments. Thanks you!
i can’t compile your program even though i pasted it. in both #2 and #3 compiler complains that functions are not defined.
Solution 3 won’t work for me unless I put
#include “stdafx.h”
#include
before putting
#include “io.h”
how come?
I’m confused, in the main function where you declare
int x = ReadNumber(); int y = ReadNumber();Is that ReadNumber() a function call or a value? If it’s a value (which I assume) then I don’t see the part where there’s a call to ReadNumber() from main(), so it must be a call? But I didn’t know calls could be used as a variable value though? Has this been covered in a previous section or have I missed it?
HI, So can someone give me other quizzes too because sucked at these.