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

  • Nicholas

    This is a really good way to learn C++. I likethese tutorials man great work. I hope you get paid a lot for what you’ve done for this generation of programmers.

  • Austin

    Hi, having a problem. It seems as if when I save it code blocks, it never saves the project file. It saves other files, but there is no project or work space files. When I try to put in the .cpp files individually, it won’t let me change the properties of the files. So it says “undefined reference” to all my io.h defines. Or maybe it’s not define but when you put “void blahblah(int x)” at the beginning of code.

  • Nat

    I have copied and pasted your code exactly as it is just to check for the flawlessness of task 2 and 3. I have included both the header and the io.cpp in the source files.
    However the compiler keeps telling me that there is an error, "an identifier not found" for the both functions.
    What must I have done wrong?

    • Alex

      I can’t help you debug this without an exact error message. Can you paste in the full error message so we can see what identifier it’s complaining about?

      • Nat

        Thanks for reply! Does that provide more info on the errors?

        Error    1    error C3861: ‘readNumber’: identifier not found    c:\users\nat\documents\visual studio 2013\projects\main.cpp\main.cpp\main.cpp.cpp    6    1    Main.cpp
        Error    2    error C3861: ‘readNumber’: identifier not found    c:\users\nat\documents\visual studio 2013\projects\main.cpp\main.cpp\main.cpp.cpp    7    1    Main.cpp
        Error    3    error C3861: ‘writeAnswer’: identifier not found    c:\users\nat\documents\visual studio 2013\projects\main.cpp\main.cpp\main.cpp.cpp    8    1    Main.cpp
            4    IntelliSense: identifier "readNumber" is undefined    c:\Users\Nat\Documents\Visual Studio 2013\Projects\Main.cpp\Main.cpp\Main.cpp.cpp    6    10    Main.cpp
            5    IntelliSense: identifier "writeAnswer" is undefined    c:\Users\Nat\Documents\Visual Studio 2013\Projects\Main.cpp\Main.cpp\Main.cpp.cpp    8    2    Main.cpp

  • itamar elbaz

    My writeAwnser function got out a bit different but it works great.

  • Josh

    My code compiled and runs properly, but for question 3 I was under the impression you did not want forward declarations at all, so my io.h includes the functions for readNumber() and writeAnswer() rather than a .cpp with them and forward declarations for them in main(). i.e., I have no forward declarations. Is it better to do the way you have for any reason? Or is including the functions in the header better? Or is one just better practice?

    • Alex

      As noted in lesson 1.9 -- Header files, you should generally avoid putting your function definitions inside header files (see that lesson for some comments about why). Header files are intended to be used to propagate declarations.

      I updated the quiz text slightly to be more clear about what I’m looking for in question 3.

  • Rahul

    The code for my last program gives me this error

    Undefined symbols for architecture x86_64:

    main.cpp

    io.cpp

    io.h

    • Rahul

      NVM I hadn’t included the io.cpp in io.h is it necessary to include even if the filenames are same?

      • Devashish

        No it’s not necessary. In fact we should avoid #including .CPP files whenever possible. I run your code in my 32 bit machine and everything goes fine. So, I couldn’t spot the problem out there. Alex may help. But I would like to give some advices:
        Make your writeAnswer() function return void because it is only printing out result and caller won’t expect any return value (int) from this. Remove Don’t #include iostream in your .h file. That’s redundant. Well, main function will also work without #including iostream but generallygenerally we should include this in main().

      • Alex

        You should never #include .cpp files. It’s bad form, and can easily lead to duplicate definitions in your program.

    • Alex

      Did you remember to add io.cpp to your project?

  • jason paulaskas

    // ConsoleApplication1.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    int add(int x, int y) {
        return x + y;
    }
    int main(){
        int x, y;
        cout << "put two numbers" << endl;
        cin >> x >> y;
        cout <<"the answer is  ="<<" "<< add(x, y) << endl;
        return 0;
            
    }
    //i made it in an other way ;is that a bad programming ?

    • Alex

      Nope, this is okay, outside of the use of the “using namespace std” declaration in the global scope. You should move that line inside of main().

  • Thomas Keith

    You got it!  readnumber (not readNumber) in my header file was not helpful.  Compiled after correcting that.  I should have caught that.  After all, Visual Studio was telling me that my variable was not defined.  I won’t make that mistake again. <crosses fingers>
    Thanks again!

  • Thomas Keith

    Alex,

    I’m puzzled (again.)

    I got through questions 1 an 2 ok, but on question 3, even though my files look identical to yours (except for some remarks), whenever I try to compile main.cpp, io.cpp or io.h, I get an error complaining that readNumber is undefined, though it is clearly defined in io.cpp.  When I look at main.cpp, the first use of readNumber() is flagged and upon scroll-over, it says "identifier readNumber is undefined", but the second time I call it (to initialize y,) isn’t flagged and neither is writeAnswer (also defined in io.cpp.)  I currently can’t compile any of these files because "readNumber is undefined."  I can post my code if you like, but you’ll find it very familiar, I think.

    Thanks for the help.

    • Alex

      This one sounds tricky to diagnose.

      A few things to check:
      1) Make sure all 3 files are added to your project.
      2) Make sure main.cpp #includes io.h
      3) Make sure the capitalization is all correct (readNumber, not ReadNumber)

      If none of that helps, contact me from the contact form in the support section of the website and we’ll try and diagnose this one offline.

  • Joseph

    So I have make this multi file project, it is suppose to have two file.
    main.cpp

    io.cpp

    I built and ran, which led to to errors numbering into lines > 500.
    I clicked one of those errors which subsequently led to a file named ostream
    which very much resembles iostream.

    • Alex

      The problem is this line:

      writeValue is a function that does not return a value (the return type is void), but you’re trying to send the return value of the function to std::cout.

      Even if this did work, you’d have a recursive function that would loop forever, as writeValue is calling itself.

      You probably intended this:

  • Aroma

    Hi Alex, below is my answer to each of the 3 questions, everything compiled and linked fine!, Any comment on my code to help me improve?

    (Question 1)main.cpp[
    #include<iostream>
    using namespace std;

    int readNumber()
    {
        cout<< " please enter a number ";
    int a;
    cin>> a;                                 //First user input
    cout << "please enter another number";
    int b;
    cin>> b;                                 //second user input

        return a + b ;
    }

    void writeAnswer(){                      // A function to output the final result
        cout<< "the sum of the two numbers is "<< readNumber() ;}

    int main()
    {
        writeAnswer();
    return 0;
    }]

    (Question 2)io.cpp
    [#include<iostream>
    using namespace std;

    int readNumber()
    {
        cout<< " please enter a number ";
    int a;
    cin>> a;                                 //First user input
    cout << "please enter another number";
    int b;
    cin>> b;                                 //second user input

        return a + b ;
    }

    void writeAnswer(){                      // A function to output the final result
        cout<< "the sum of the two numbers is "<< readNumber() ;}

    ]

    (main.cpp) where the function "writeAnswer" was forward declared for question two
    [int main()
    {
       int writeAnswer();
    return 0;
    }
    ]

    (Question 3)io.h [#include<iostream>
    #ifndef io_h
    #define io_h

    using namespace std;

    int readNumber()
    {
        cout<< " please enter a number ";
    int a;
    cin>> a;                                 //First user input
    cout << "please enter another number";
    int b;
    cin>> b;                                 //second user input

        return a + b ;
    }

    void writeAnswer(){                      // A function to output the final result
        cout<< "the sum of the two numbers is "<< readNumber() ;}

    #endif // io_h
    ]

    main.cpp file which included the io.h as header file

    [#include <iostream>
    using namespace std;
    #include "io.h"
    int main()
    {
        writeAnswer();
    return 0;
    }
    ]

    • Alex

      In question 1, it’s weird to have a function named readnumber() read two numbers and return the sum. Either break this into multiple functions or rename your function to indicate what it actually does.
      In question 2/3, it’s weird to have writeanswer() call readnumber(). If you didn’t know what writeanswer() did, would you expect a function named writeanswer() to ask the user for input? Probably not. readnumber() should be called in main and passed to writeanswer(), which should only do the writing.

      You seem to understand the syntax of the language okay. Work on understanding the proper use of functions (a function should have one job) and use variable passing to achieve that.

  • Kemikals

    This is how I did it.

  • Joao Lopes

    This is how I solved 5#

    main.cpp

    io.cpp

    io.h

  • r00kie

    Alex,

    Is there any past lesson in the previous chapters where I can read more and understand how the values inside () are passed in by the caller ?

    I understand perfectly how it works inside {} and this is why I sticked to variables inside {} in my program , but I don’t quite understand how the function parameters work inside () ?

  • r00kie

    Don’t worry about the first function in my program "readNumber" , I am not sure why some data didn’t get copied corectly, my readNumber is written correct , like this and it works…just explain to me why sometimes you declare int X inside () , instead of {} and why on your program if you do it inside {} it doesn’t work…

    int readNumber()
    {
        std::cout << "Enter a number: ";
        int x;
        std::cin >> x;
        return x;
    }

    • Alex

      If you put a variable inside the (), it’s considered a function parameter, and the value must be passed in by the caller.
      If you put a variable inside the {}, it’s considered a local variable, and the value must be defined by the function itself.

      In the case of function writeAnswer(), the function caller supplies the value to write, so x must be a function parameter, not a local variable.

      Make sense?

  • r00kie

    Alex,

    I have been checking your solution for quiz no 1 and I do not understand why the void is like this :

    void writeAnswer(int x)
    {
        std::cout << "The answer is " << x << std::endl;
    }

    If I write your void function like bellow, the program gives me this error :

    error C2660: ‘writeAnswer’ : function does not take 1 arguments

    void writeAnswer()

    {

         int x;

        std::cout << "The answer is " << x << std::endl;
    }

    What’s the deal with int x, and why the program only works if you declare it like this :

    void writeAnswer (int x)

    and not inside the void function ?? inside { }

    with readNumber it goes the other way around, if you try to initialize X like this readNumber(int x) it doesn’t work …please explain why some X gets initialized inside () and others inside {}

    To stay away from things I do not understand, I wrote my code like this and it worked perfectly , but please explain what’s the deal with X and why you have it initialized sometimes in () and sometimes in {}

    As you can see , I am initializing x only inside {} , but I would love to know why you do it sometimes in ()

    int readNumber()
    {
    std::cout <> x;
    return x;
    }

    void writeAnswer()
    {

    int x;

    x = readNumber() + readNumber();

    std::cout << "The answer is " << x << std::endl;

    }

    int main()
    {

    writeAnswer();
    return 0;
    }

  • Tyler

    I was none-too pleased when I had to do it over again because I put writeAnswer(readNumber()); and had to have 3 forward declarations to support it.

  • BobZ

    Hi, Alex:
    I have been fighting with Question 3 for over a week and after try this try that, making no progress.  At present I have 7 errors and 8 warnings.  

    My main.cpp is:

      my io.cpp is:

    and my io.h is

    • Alex

      At a glance, your main.cpp and io.cpp look good.

      It’s your io.h that’s going to give you problems and is probably causing all your errors.

      First off, io.h shouldn’t include stdafx.h or iostream, because it doesn’t need/use either. Header files should only include other headers that they directly reference.

      Second, your header guards are incorrect. Your only need one set of header guards per header file, and everything should be inside the guards. The guards should also be named after the filename as a best practice:

      Third, you don’t need to #define your functions in this way. It doesn’t make sense, and it’s confusing the compiler. Instead, what you want to do here is put your forward declarations:

      That way, when main.cpp (or any other file) #includes io.h, the forward declarations from io.h will be copied into main.cpp.

      I hope that’s helpful.

  • SS

    how is this peice of code:

    #include <iostream>
    using namespace std;

    int readNumber()
    {
        int a, b;
        cout << "Enter a number: " ;
        cin >> a;
        cout << "Enter another number: ";
        cin >> b;
        return a + b;
    }

    int writeAnswer()
    {
        return readNumber();
    }

    int main()
    {
        cout << "The sum is: " << writeAnswer() << endl;
        system("pause");
    }

    • Alex

      Needs some work. 🙂
      First, writeAnswer actually doesn’t do anything. You might as well just call readNumber.
      Second, readNumber is misnamed. It should be called something like readAndAddNumbers based on the way you’ve written it.
      Third, it’s bad form to use system(“pause”).
      Fourth, it’s bad form to use “using namespace std;” outside of a function.

      But it would really be better if readNumber just read in a single number, and writeAnswer did the writing, and main did the adding of the numbers read in from readNumber. That way your functions each have one job.

  • Marta

    I just wanted to post a thank you message for you. This tutorial is amazing and I feel I’m learning fast and well. Thanks!

  • Root

    Hey Alex, can u please explain the "return x" part in an int function. i mean in the previous functions i realized that if we take an input (lets say x), then in the end of the int function we end with "return x". i tried return zero for everything and the whole calculation part went wrong as no matter what,it just assumed 0.
    What if we take more than one input in a function other than main()?what should we end it with?
    also if we expect the answer like 2.5 , what should we include for it to display this number?

    • Alex

      Functions can only return one value, and the type of that value is determined by the return type (which so far, has only been int).

      If you need to return more than one value to the caller, there are ways to do that but none of those are simple, so I don’t talk about that until later.

      If you expect a non-integer return value, then you should use something other than int as your return type. In the next chapter, I talk about floating point types, which are used to handle fractional values (such as 2.5).

  • inkboy12345

    Hey, this code i wrote works completely fine as far as I can tell, but i’m curious as to whether i’m using any bad form, or wrong/unnecessary syntax (i know i’ve written iostream and stdafx.h twice, because sometimes it gives me weird syntax errors so I put it in there for the sake of paranoia)  

    main.cpp

    io.cpp

    READ_N_WRITE.h

    • Alex

      My suggestions:
      * READ_N_WRITE.h should be named io.h, so that io.h pairs with io.cpp.
      * It’s weird to have writeAnswer read in numbers. I’d call readNumber() twice from main, and pass both the values into writeAnswer as parameters.
      * writeAnswer should be given a better name, like writeSum().
      * Don’t “use namespace std” outside of a function. Put it inside each function that needs it.

      Other than that, seems fine for where you are at this point in the tutorial. 🙂

  • MD jYa

    Thanks to U all for helping me out….Thank U MasterCreator
    Its a Great Tutorial..
    Thank U Sir Alex…

  • Dominus

    Wow, i already made this exact program while going through the tutorials! Great work by the way, im really getting into C++ thanks to you!

  • MD jYa

    where i am wrong,plz tell me???

    • MasterCreator

      In line 14, you’re trying to call the function writeAnswer() in itself. Instead, try the following

  • Meowmeow_Prince

    what the point of using the "Using namespace std;" twice in the io.cpp where you could just put it in the header and have it there for the whole scope of the file because everything there uses it

    • Alex

      The point of declaring “using namespace std” inside of a given function is that we limit the effects of the using statement to just that function. That allows us to get the benefit of the using statement (not having to repeatedly type std::), while minimizing the risk that our code has a naming conflict with something inside the std library.

      Using “using” statements outside of individual functions (_especially_ inside header files) should be avoided, as it significantly increases the chance of having a naming collision with something in the namespace.

  • Hey Alex,

    Below you will find the code for a programme I am making just for practice in Xcode. Im up to chapter 1.12 and I need a bit of help with a few things.

    I may be asking a bit too much, but you don’t ask you don’t get.

    - How can make it so that the user can enter a gun name without using a capital letter at the start and still be show the if statement that is linked to it?

    - How can I make it so that each gun has a different minimum bid?

    #include <iostream>

    int main()
    {
        //welcome();
        using namespace std;
        cout << "Welcome to WhichGun?, the home of the best weapons the world has to offer. " << endl;
        
        //whichGun();
        cout << "We have 4 guns up for auction tonight, the names are: Bloco, Remin, Selor, and Sonit. "<< endl;
        cout << "Please type the name of the gun you would like to bid for. (including capital letter) " << endl;
        char word [80];
        cin >> word;

        //commentOnGun();
        string bloco ("Bloco");
        string remin ("Remin");
        string selor ("Selor");
        string sonit ("Sonit");
        
        if (word == bloco)
        {
            cout << "Ahhh so you want to bid for the Bloco Pistol. Wise choice for someone who is looking for a personal weapon to carry around with them. " << endl;
        }
        if (word == remin)
        {
            cout << "There are only 3 Remin Sub-Machs in the world. " << endl;
        }
        if (word == selor)
        {
            cout << "I have one of these myself. It is a very useful hunting rifle. " << endl;
        }
        if (word == sonit)
        {
            cout << "Only those who are looking to cause major damage would purchase the Sonit 104 Launcher. " << endl;
        }
        //howMuch();
        cout << "How much would you like to bid for the " << word << endl;
        int x;
        x = 0;
        cin >> x;
        if (x < 10000)
        {
            cout << "Sorry the minimum bid for any wepaon is £10,000. " << endl;
        }
        else
        {
            cout << "Brilliant take a seat, I will confirm your bid and you will be called to the front if you are the winning bidder. " << endl;
        }
        //thankYou();
        cout << "Thank you for partcipating in the 5th annual WhichGun? auction, Please spread the word and come again next year. " << endl;

    }

  • Daniel

    Hello Alex,

    Just a few questions after having completed the quiz and tried some extra bits to further my understanding.

    I have a program that takes 2 inputs from user via one function called twice, it then uses a function to add the two inputs to define a third variable which is then divided using a function & printed using std::cout.

    All functions are defined in seperate .cpp files with a header file containing all declarations. (all compiles correctly)

    I was just wondering about the header files, does one need a seperate header file for each function e.g add.h, divide.h getInput.h.

    It seems it would get really messy quickly having loads of header files for every function. But I can kind of wrap my head around why it may make more sense on huge programs/projects.

    Also, on all of my .cpp’ created it says in brackets (global scope), is this correct in the context of these tutorials?

    I hope my question makes sense.

    kind regards

    Daniel

    • Alex

      Hi Daniel.

      You don’t need a separate header file for each function (as you note, it would get messy quickly). Typically both code files and their header file counterparts are divided into logical groups. For example, if you have a bunch of function to deal with vector math, you might have a vector.cpp that defines a bunch of functions, and a vector.h that includes the prototypes for all of the functions in vector.cpp. That way, if any of your programs need to use the vector functionality, you #include and make sure vector.cpp is compiled into your project, and you’re good to go.

      As for the (global scope), I’m not sure what that is in reference to. It doesn’t sound like anything to be concerned about at this point though.

  • Souvik Pal

    Mah answer to Question 1 :

    #include<iostream>
    int readNumber()
    {  
    int n;
    using namespace std;
    cin>>n;
    return n;
    }
    int writeAnswer(int ans)
    {
    using namespace std;
    cout<<"The addition is="<<ans;  
    }
    int main()
    {
    using namespace std;
    cout<< "Enter the first number :"<<endl;
    int x1= readNumber();
    cout<< "Enter the second number :"<<endl;
    int x2= readNumber();
    int ans=x1+x2;
    writeAnswer(ans);
    return 0;
    }
    Is it ok Mr. Alex.

    • Alex

      Mostly correct. Two minor issues:
      * writeAnswer should be void since it doesn’t return a value.
      * There’s no need to use “int ans=x1+x2”. Just pass the expression “x1+x2” as a parameter to writeAnswer.

Leave a Comment

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