Search

1.12 — Chapter 1 comprehensive quiz

Question 1

Write a single-file program (named main.cpp) that reads two separate integers from the user, adds them together, and then outputs the answer. The program should use three functions:

  • A function named “readNumber” should be used to get (and return) a single integer from the user.
  • A function named “writeAnswer” should be used to output the answer. This function should take a single parameter and have no return value.
  • A main() function should be used to glue the above functions together.

Hint: You do not need to write a separate function to do the adding (just use operator+ directly).
Hint: You will need to call readNumber() twice.
Hint: If you’re using visual studio with precompiled headers, don’t forget to #include “stdafx.h”.

Show Solution

Question 2

Modify the program you wrote in exercise #1 so that readNumber() and writeAnswer() live in a separate file called “io.cpp”. Use a forward declaration to access them from main().

Hint: If you’re having problems, make sure io.cpp is properly added to your project so it gets compiled (see lession 1.8 -- programs with multiple files for more information on how to do this).

Show Solution

Question 3

Modify the program you wrote in #2 so that it uses a header file (named io.h) to access the functions instead of using forward declarations directly in your code (.cpp) files. Make sure your header file uses header guards.

Show Solution

2.1 -- Fundamental variable definition, initialization, and assignment
Index
1.11a -- Debugging your program (watching variables and the call stack)

391 comments to 1.12 — Chapter 1 comprehensive quiz

  • Blackshire

    I am terrible at this, just terrible. Time to start from the beginning.

    • csvan

      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!

  • Mike

    Not sure what I did wrong. It compiles just fine. But when I enter the two numbers, I get random asnwers.

    • Alex

      There are multiple problems here:
      1) Inside of Read(), you’re declaring variables x and y. These are local function Read() and get destroyed when the call to Read() is finished.
      2) You can’t mix a call to cout with a call to cin.
      3) On line 20, you’re printing the address of the function Write, not actually making a function call to Write(). Don’t forget that function calls need a parameter list, enclosed in ().

  • Kevin

    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.

  • Andre

    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…

  • Chris

    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, since you’re using Visual Studio, make sure that stdafx.h is the very first include.

      • BobZ

        Hi, Alex

        I am fighting now with question 2.  You say above:

        "You need to include the following in io.cpp:……."

        I just discovered that.  Does "#include <iostream>" need to be included BOTH io.cpp and main.cpp?  I thought that instructs the preprocessor.  Do we need to tell it twice?  Or can I omit it from main.cpp? (I still have other errors so it is not easy for me to try a controlled experiment.)

        Thanks,

        BobZ

  • Corey

    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.

      Furthermore, if you put code in the headers and then have to change that code, you’ll have to not only recompile that header, but everything that includes it too. That means one little change can have a cascading effect on what needs to be recompiled, which can really slow down compilation times.

      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. ๐Ÿ™‚

  • Leonora A Quarcoo, US

    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

    • Alex

      This program won’t compile because you’ve got multiple definitions for both functions ReadNumber() and WriteNumber().

      Remember that variables declared in a function are local to that function -- the x and y you’re declaring in main() are different than the ones in ReadNumber() or WriteNumber().

  • 19bk87

    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:

    the add and subtract cpp:

    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 elsewhere.

      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.

  • Julian

    Well I managed to do question 3 on my own, however I needed help on 2 and especially 1 ๐Ÿ˜›

    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)

  • Karan

    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.

  • Tony

    How does main.cpp know to include io.cpp if there’s no include statement for it?

  • PoisonedV

    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

  • sami

    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.

  • daniel

    alex should be nominated as “best man on the net”. this guy like responds, AND COMPILES, everyones problems lol. thanks allexxxx!

  • 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.

  • Seltox

    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 ๐Ÿ˜›

  • Luciana

    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 ===|

  • Ben

    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. ๐Ÿ™‚

      • Ben

        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.

        • Ben

          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.

  • Vikram

    Very useful!!

  • Arocalex

    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.

  • John

    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!

  • Stuart

    I can’t get solution 3 to build.

    This is my main ccp (test8.cpp):

    This is my io.cpp:

    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.)

  • Ralph

    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.

      • Ralph

        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.

  • John

    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.

  • Chad Bernier

    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.

  • Allen01

    About the function “void WriteAnswer(int)” in question 1):

    Since in the main function, the statement:

    WriteAnswer(x+y);

    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.

      • Brian

        Hi Allen & Alex. Again, I had the exact same confusion as Allen. Thanks guys.

      • BobZ

        Hi, Alex

        I have been struggling with the first quiz question for more than a week (I have not cheated by viewing any of the answers) and now I am even confuseder by your January 20 2008 explanation here.  You are saying that WriteAnswer does not return anything, but the value of x+y is passed as a parameter of WriteAnswer.  That seems contradictory.  What is the difference between passing and returning? (I don’t think we are discussing football.)  I have to laugh so I do not cry.

        • Alex

          You should re-review the material covered in lessons 1.4 -- A first look at functions and 1.4a -- A first look at function parameters and arguments.

          In short:
          * passing in = the caller sending data to the function via arguments and parameters.
          * returning = the function returning data back to the caller via the return value.

          WriteAnswer’s job is to print stuff, but it needs to know _what_ to print. So WriteAnswer is declared with a parameter, allowing the caller (in this case, main) to pass in data to it via an argument. WriteAnswer doesn’t need to return anything back to the caller (main), so it has no return type.

          ReadNumber’s job is to get something from the user. ReadNumber doesn’t need anything from the caller (main) so it has no parameters. However, after getting a value from the user, it needs to return this to the caller (main). It uses a return value to do so.

          Make sense?

          • BobZ

            Thanks a lot, Alex
            Wow I thought I would never sort out this one…….but my code for the first question ran on first attempt with no errors.  I think the key was that I made up a variable name "karkle" for readNumber ๐Ÿ™‚  Now I need to start on the second question; give me another few weeks.  ๐Ÿ™

  • Allen01

    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().

      • Allen01

        Got it, thanks.

      • Brian

        “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.

  • brandon

    thx for the tutorial, it really helps

  • 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.

      • Trophy

        I’m sorry to reply to your comment even though this has nothing to do with it, but I can’t figure out how to comment without replying. Anyway, there’s a problem with your code. Basically you’re telling the compiler to go to main.cpp to io.h and then to io.cpp, but that isn’t how the compiler reads it, the compiler reads it as main.cpp to io.h to main.cpp which causes the compiler to stop before “ReadNumber()” and “WriteAnswer()” are defined, even though they’ve been declared. I kept getting “undefined reference” error, because of the way the program was set up, so I put ‘#include “io.cpp”‘ in the header file and it worked again, which revealed the problem. Am I wrong, or is my compiler just not set up correctly?

        • Alex

          My code is fine. Make sure you’ve added io.cpp to your project so it gets compiled in.

          It’s bad form to #include a .cpp file.

        • Daniel Ricci

          The linker should detect both your cpp files (main and io) and will sandwich them both together along with some other dependency libraries.

          If you wanted to write a header file then there would be no need for a forward declaration in your Main.cpp, you would just #include "io.h" and the .cpp file would be sandwiched during compilation.  Both ways work, but normally having a seperate .h file will allow us to avoid forward declarations in our Main, since including the header would just do that for us automagically.

      • shakey2

        My code ended up almost identical to your solutions >.< the only difference is I didn’t use "using namespace std"(because people keep going on about name collisions), and I put "the sum of those numbers is: " inside main() instead of writeAnswer(). I felt it’d be better if I wanted to call writeAnswer() for a different purpose and didn’t want that extra text.
        I’m kinda curious now what the "easier" method was.

        PS your site rocks! I’d pay for this in book form if I had the money x.x(hopefully learning C++ will solve the money problem)

        • Alex

          He didn’t call writeAnswer(), he just did it all within main().

          Which is totally legitimate, just missing the point of the exercise. ๐Ÿ™‚

  • me

    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 ]

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter