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)

481 comments to 1.12 — Chapter 1 comprehensive quiz

  • Linyuan

    I think it might looks more elegant like this (the main function is more concise):

    In io.cpp:

    In io.h:

    In main.cpp:

    • N1ghtW0lf

      God where to start. You made your writeAnswer function parameter redundant. First of all you should really try to stick to what was said earlier of 1 task per function, now like i said your parameter became useless, it doesn't matter what you type into it, it'll get overwritten because you are assigning the result of input1 + input2 to it before printing it out to the screen.

      Either use #pragma once or #define, they both do the same thing so using both is redundant.  

      By declaring int answer there you just made it a global variable which is completely unnecessary and just a plain bad idea for this program.

      I see no point to "Begin here" and "End here".

      And again you missed the point of the exercise and failed to do what was asked

      is literally

      ,  the only reason you are getting the right output is because this

      right here is overriding that 0, and like i said the point was to use the parameter to print out to the screen like so

      which you failed to do, so don't take this the wrong way but maybe try to get your code right and working properly before trying to make it more "elegant".

      • Linyuan

        oh thank you so much to reply my code.

        well "begin here" and "end here" is just for me. Because i have wrote many codes in my own function main() in my computer, I just use those to let me know where to start in my debug window...here these two things make no sense...

        But for the rest part which u have talked about, u're right, thank you for pointing out where i was wrong.

  • Ali Dahud

    Hi Alex!

    could you please explain to me that code in detail:

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

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

    Because the rest is understoood 🙂

    p.s. and you're an awesome teacher

    • Alex

      This defines a function named readNumber that takes no parameters. When the function is called, the user will be asked to Enter a number:. An integer variable is defined to hold the user's input. The std::cin >> x actually gets the input from the console and puts it in variable x. This value is then returned back to the caller.

      This function takes an integer parameter, which it calls x. It then prints "The answer is " and the value of x (which is whatever the user passed in as the argument for x).

      • Ali Dahud

        and when are these parameters unnecessary and necessary?

        • Alex

          Parameters are necessary when you want to have the caller of a function supply data to that function to work with.

          In the case of readNumber(), the function gets data directly from the user, so the caller does not need to give it any. In the case of writeAnswer(), the caller is providing the value of x to be printed by the function.

          • Ali Dahud

            So if I use cin or getline I shouldn’t use parameters?

            • Alex

              Not necessarily. It's totally possible to write functions where the caller passes in some data, and then the function asks the user for more data. In that case, the function would both have parameters AND use cin or getline.

              • Ali Dahud

                could you please hit me up with some examples for both? my e-mail address is alidahud@gmail.com

                • Alex

                  We can just do it right here. We'll do all 3.

                  Caller passes in data:

                  User provides data:

                  Both:

  • Tyler S.

    Alex,

    On question one, I wrote my code almost identical to the answer before revealing it. However, visual studio 2017 was assigning random values to x and y in the main function until I did the following:

    I used the debugger with the original solution (once again, identical to the one in the answer you provided) and the variables just kept getting insane random numbers.

    Any idea what could be causing this?

    My full code NOW is

    It works flawlessly. But when I tried int x = readNumber(); is just kept giving random values. Very confused on that!

    • Alex

      I don't have the slightest idea. They should behave identically.

      • Tyler S.

        I see. Assuming the problem persists in further lessons, do you believe the set up I used is acceptable to the standards you're teaching us here?

        • Alex

          My best guess is that it will cause problems later, as const variables and references must be initialized, not assigned to. I still don't have a clue why you might be seeing what you're seeing. Try doing a clean build, or recreating your project from scratch?

  • merocom

  • Lim Jia Shiang

    #include <iostream>
    using namespace std;

    int readNumber();
    void writeAnswer();

    main()
    {
        cout << "Key in numbers!" << endl;

        writeAnswer();

        return 0;
    }

    readNumber()
    {
        int x;
        cin >> x ;

        return x ;
    }

    void writeAnswer()
    {
        cout << readNumber() + readNumber();
    }

    Is this correct for the first question ? It runs fine and does the task but its completely different from the posted answer above .

  • Reading through these comments are really useful also. Really enjoying this tutorial and hopefully i can get to grips with it. Thanks so far.
    Richard

  • Alex

    Hi Alex, thanks for the awesome tutorials has been very helpful to me 🙂

    I'm trying to understand why Function 1&2 are not valid.

    Function1:
    adding int x like so readNumber(int x) why is this wrong.

    Function1
    #########

    Function 2:
    not adding int x before std::cin >> x,why is it wrong
    Function2
    #########

    • Alex

      Functions should only have parameters when they expect the caller to pass them a value. In this case, function readNumber() is asking the user for a value (not expecting the caller to provide a value) so having a parameter forces the caller to pass a value that's just ignored.

  • readWrite.cpp

    int readNumber( )
    {
        int a;
        std::cin >> a;
        return a;
    }

    void writeAnswer(int a)
    {
        std::cout << a << std::endl;
    }

    readWrite.h

    #ifndef RDWR
    #define RDWR

    int readNumber( );

    void writeAnswer(int);

    #endif // RDWR

    main.cpp

    #include <iostream>
    #include "rdwr.h"

    int main()
    {
        std::cout<< writeAnswer(readNumber()+ readNumber()) << std::endl;
        return 0;
    }

    ||=== Build failed: 2 error(s), 1 warning(s) (0 minute(s), 2 second(s)) ===|

    Errors are:

    main.cpp|7|error: no match for 'operator<<' (operand types are 'std::ostream {aka std::basic_ostream<char>}' and 'void')|

    |602|error: forming reference to void|

    I Googled the error, it tells I have overloaded the operator! what does that mean? I know this topic has been covered in the coming chapters, but I just started the lessons today and I've been able to complete only till here for a day. So, as far as the knowledge till here, please lemme know how am I wrong and how can it be improved in the above written piece of code.

    • Alex

      The key parts of the error message are "no match for operator << and void". The problem here is that writeAnswer() returns void. But in main, you've written "std::cout << writeAnswer(...)". Operator<< doesn't know how to output a void return result (because it doesn't make sense), so you're getting an error here. Given the way you've structured your program, it probably makes sense to remove the std::cout in main and just call writeAnswer(). writeAnswer() can do it's own std::cout call and output the value itself. Main doesn't need to be involved.

  • Ivan

    I'm using Code::Blocks and I keep getting this error.

    D:\CodeBlocks\Chapter 1 Quiz\main.cpp|1|fatal error: ioh.h: No such file or directory|

    This is my code:

    main.cpp

    io.cpp

    ioh.h

    • Alex

      Since ios.h is a user-defined header file, it should be in double-quotes, not angled brackets. Try that and see if it fixes. If not, then it's likely you saved ios.h in some place that the system can't find it. If that's the case, you can try moving it to a different directory (e.g. the same directory that has your main.cpp).

      • Ivan

        Hey Alex,
        I've made the change to double-quotes.
        I still kept getting some error, but then I, umm... "de-compiled" and "de-linked" the header file. I don't know if the meaning of those words is clear. What I did is, in the "Properties of "ios.h"" under the "Build" tab, I unchecked "Compile File" and "Link file". Now the program works. I have no idea why though. If you could please explain.
        That was my mistake, it was unchecked by default, I checked it when I was figuring out why my code wasn't working.

        Here's the error that I was getting:

        Build log:

        --------- Build: Debug in Chapter 1 Quiz (compiler: GNU GCC Compiler)----------

        mingw32-g++.exe -Wall -fexceptions -g -std=c++14  -c "D:CodeBlocksChapter 1 Quizioh.h" -o ioh.h.gch
        mingw32-g++.exe  -o "binDebugChapter 1 Quiz.exe" objDebugio.o ioh.h.gch objDebugmain.o  

        ioh.h.gch: file not recognized: File format not recognized

        collect2.exe: error: ld returned 1 exit status

        Process terminated with status 1 (0 minute(s), 0 second(s))
        1 error(s), 0 warning(s) (0 minute(s), 0 second(s))

        Build messages:

        ||=== Build: Debug in Chapter 1 Quiz (compiler: GNU GCC Compiler) ===|
        ||error: ld returned 1 exit status|
        ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

        • Alex

          I'm not sure why compiling a header file would cause a problem. There shouldn't be anything in there that the compiler doesn't like.

          But speaking generally, we typically only compile code files, not header files. This is because header files are included into other files, which are then compiled. There's no need to compile the header file by itself, because the stuff that's in a header file typically isn't useful on its own. It's just connective tissue that helps the compiler understand other things that it's seeing.

  • Alex,
    I got stuck on 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).

    Please tell me how could I do with DEV-C++.
    Thank you.

    • Alex

      There is a provided solution if you can't figure out how to solve the quiz question yourself. If you're asking how to add files to DEV-C++, I have no idea. That's something you'll have to figure out with help from Google search.

  • Marius

    Hello, Alex!
    I just took notice of some missing open and closed parentheses on the first line under question 2:

    This:
    "Modify the program you wrote in exercise #1 so that readNumber and writeAnswer()"

    Should be:
    "Modify the program you wrote in exercise #1 so that readNumber() and writeAnswer()"

    🙂

  • Gurdeep Singh

    Dear C++ Techer,

    In the first question I called main() inside the main functon before the return statement, so that I can use it for more than once. When It asked for input, instead of integer value I entered "c", it starts to print some value again and again like a loop and never stoped. Why

    • Alex

      First, it's not a good idea to have main() call itself. Second, when you use std::cin to get integer input but then enter a bad input, std::cin goes into failure mode and stops accepting input until you clear it. I discuss this phenomena, and how to fix it, in chapter 5.10.

  • himanshu

    HEY ALEX!
    IS IT RIGHT
    #include<iostream>
    using namespace std;

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

    void writeAnswer(int result)
    {
        cout << "\nthe answer is:"<< result;
    }
    int main()
    {

    int result=readNumber()+readNumber();
    writeAnswer(result);
        return 0;
    }

    • Alex

      Yes, it's fine. Personally I don't favor using a function that asks for user input in the middle of an arithmetic expression, but I can't think of a particular reason it wouldn't work.

  • Eduardo RM

    What about this code concerning question1...

    Some enhancements suggestions???

  • Hi, I am relatively new to C++ and brand new to this site I got the link from stack exchange.

    I am finding this an excellent resource for learning C++ (I am a PHP developer) and notice that PHP and C++
    share a similar syntax.

    My question is related to Question 3 and the correct way to code the header file, I am currently using
    Visual Studio 2017 Community Edition and have noticed that in the newly created header file there is the line:-

    I had a look around on stack exchange and there seems to be a bit of controversy over whether to use that or header guards or both, so I opted to use both as follows:-

    Will this actually break anything it seems to build and run fine.

    • Alex

      If you try to run this on a compiler that doesn't support #pragma once, it will likely error when it encounters that line.

      That said, if you have a header guard, using #pragma once is redundant, so you might as well remove it altogether at that point.

      I wish #pragma once was supported by all compilers because it's a superior solution to header guards (easier and less error-prone).

      • Thank you for the quick reply Alex, 🙂

        I will keep that in mind and will probably leave the code in place but commented out and keep the header guard, as I understand it

        is now fully supported by gcc but will have to try that out  when I boot into Linux next
        Jon.

  • Hacker

    Hi, is this correct way to solve the first problem? 🙂

  • Jerry

    io.h

    Tips or feedback? After reading the instructions it just make more sense to me to do it this way... What do you think? Any do's or don'ts here? Thank you for your time.

    • Alex

      Yup. Looking at main the first thing I see is a call to writeAnswer(). That strikes me as odd, because what answer is being written? I haven't entered any data yet. It's only when I look at how writeAnswer is written that I realize it calls realNumber(), and then it clicks. It's not obvious at all, and it violates the "functions should do one thing" rule (your writeAnswer both writes the answer and calls the function that gets the input).

      It would be better to have main call realNumber() (which needs a better name) and then pass that to writeAnswer(). Then it will read more logically.

      • Jerry

        Thank you, I have to get out of this functions calling other functions habit... even if it complies… So do you know of any place that has more practice quizzes like this? Maybe you could add more for each chapter or something. Just a suggestion. Love this.

    • coder_king

      write this too after including iostream so that you dont need to write std again and again.

      #include<iostream>
      using namespace std;

  • Lucas

    Hello when i try to compile the first part it just gives me this error:

    And here is the actual code i wrote

    • Lucas

      I just noticed that <iostream> isnt shown to be included here but it is included

    • Derik

      Hi Lucas,

      I found a few small problems with your code. You get the overall picture, but you seem to have trouble with proper syntax, which is causing problems with compiling. Here is a small list of solutions to make the code run:

      - You're putting semicolons after the arguments when defining your functions, which is incorrect syntax.

      - You need to declare the variable of "X" before you use it to store an input (std::cin). Just insert "int X;" above the line "std::cin >> X;"

      - After you define/declare your functions and variables, you no longer need to put "int" or "void" before you call or refer to them.

      After correcting those small issues, this is what I came up with:

      I'd recommend printing a prompt for the user to enter numbers in your readNumber function and printing something like "Result: " in your writeAnswer function.

  • John

    In Question 2, if main.cpp was changed to include an output line, i.e.

    Now <iostream> must be included at two locations, in main.cpp and in io.cpp (as you showed in section 1.8). But it looks a bit unnecessary, the same code inserted two times, into the same executable. Is this correct?

    Thanks for a great site. /John

    • Alex

      You are correct: if main.cpp were to output (or input) anything, you'd need to #include iostream at the top of main.cpp.

      Since the iostream header is only declarations (so the compiler can do type checking), this won't bloat the size of your code (it will just make it take slightly longer to compile). The iostream code itself (that is precompiled as part of the C++ standard library) will only get included once regardless of how many times the iostream header is included in a program.

  • DNA

    Hello Sir. I want to begin by thanking you for this service to society as this is a prime example of enriching the world in a positive way. I now have my own question. Please see the code I wrote below and let me know why this is bad form. It compiles and it even runs if you press ignore.

    #include "stdafx.h"
    #include <iostream>

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

    void writeAnswer(int x)
    {
        std::cout << "These equate to: " << x << std::endl;
    }

    int main()
    {
        std::cout << "What numbers would you like to add?" << std::endl;

        int x;
        int y;
        
        x = readNumber(x);
        y = readNumber(x);

        writeAnswer(x + y);
        
    }

    • Jim Smith

      The function readNumber() doesn't need a parameter. A better way is:

    • Alex

      Two bits of feedback here.

      First, readNumber shouldn't take a parameter. Parameter x should be defined as a local variable, like this:

      Otherwise, the caller is forced to pass a value into readNumber(), but that value is ignored.

      Second, you could consolidate these four lines:

      Into these two lines:

  • Eric

    I'm having an odd problem, if anyone can offer some help I'd appreciate it.
    I'm receiving this error message:
          1>c:\users\eric\documents\visual studio 2017\projects\test ride\test ride\source.cpp(1): fatal error C1010: unexpected end of file while looking for precompiled header. Did you
          forget to add '#include "stdafx.h"' to your source?
    But I DIDN'T forget to #include "stdafx.h" as the first line of both files. I'm stumped here.

    And the second file:

    • Alex

      I don't see anything wrong here. Are there any other files in your project that it might be complaining about? You could also try creating a new project and adding these two files to it, to see if it's something else weird happening (maybe your stdafx.h file is corrupted?).

      As a workaround if you can't figure this out, you could try turning off precompiled headers. It'll make compiling a little bit slower but at least it won't block you.

  • BOBONA

    This is a suggestion:
    I think the quizzes where you ask to write code are very useful and that maybe more should be added throughout the lessons.

  • Theo

    Dear Teacher ,
    i keep getting the error = prog.cpp:8:2: error: expected ';' before 'int'
      int writeNumbers()
      ^
    program i designed below.

    [//include "stdafx.h" if using visual studio
    //this is going to be a test program
    #include <iostream>
    using namespace std

    //function to get an input from user
    int writeNumbers()
    {
         cout << "chosse 2 int to be sum";
         int x;
         cin >> x;
         return x;
    }

    //function that outputs the sum
    void writeAnswer(int x)
    {
         cout << "the answer is :" << x << endl;
    }

    //main function
    int main()
    {
        int x = writeNumbers();
        int y = writeNumbers();
        writeAnswer(x + y);
        return 0;
    }]

  • David

    Did everything from memory! Thanks for the quizzes. They're real confidence boosters. Now I know I'm ready for the next chapter.

  • James Ray

    I don't know if this has been covered in the comment threads, but I had a working solution for all three questions. However, when I looked at the solutions, I modified my solution accordingly, and now I get unidentified errors for each function in main. I've added io.cpp to my project, it shows under source files below the main.cpp. I #included "stdafx.h" and <iostream> in main and io.cpp, as well as io.h in main.

    I'm using Microsoft Visual Studio 2015 on Windows 10.

    Any ideas?

    • James Ray

      io.cpp

      io.h:

      main.cpp:

    • Alex

      #include "stdafx.h" needs to be the first include. Put the io.h include below it.

  • Joshua

    I just want to say thanks, Alex. I completed all 3 tasks first attempt. I think that speaks to the quality of these tutorials. It's also amazing to see you are still here answering questions.

    Thanks Again,
    Joshua

  • Rhys

    Question 3 attempt, won't compile.

    • Alex

      What error are you getting?

      • Rhys

        Too many arguments to function 'void writeAnswer()'

        • Alex

          The only thing I can think of is that you have some other definition for writeAnswer somewhere that's confusing the compiler. I'd maybe try recreating your project and these specific files, and see if that resolves the issue.

        • Kris

          I may very well be far too late, but it is not necessary to include "io.h" in the source file that the very same header creates forward declarations for. I'm personally not sure, but I'd assume that perhaps the inclusion of io.h conflicts with the declaration of the respective functions?

  • Yay got through with the quiz. Funny thing was that I had already created a multiply program for fun that I could implement into this.
    Turns out it was not as simple. I actually was forced to rewrite the whole thing because it did not follow the guideline of this task.

    I went back to read about the parameters etc to find out how to call a function twice. Really made me think outside the box.
    The only thing I did differently was that I did not use writeAnswer(x + y); but instead I used writeAnswer(x, y); and did the math inside void writeAnswer(int x, int y)

    Either way it worked and was happy with it. After that was done everything else went as smoothly as it could.

    Really I think reading some of the comments here people kinda step ahead on what has been practiced so far. While other solutions are good as well I think the point of this quiz is to just remember what you've learned and not learn new things to overcome the problem you are facing.

  • My dear c++ Teacher,
    Please let me say, this is your program! I only changed variables name, and type "int" to "double".
    With regards and friendship.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]