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

  • My dear c++ Teacher,
    Please comment following program regarding question 1:

    With regards and friendship.

  • ppippi

    Hi Alex, can I not globally declare a variable in io.h to be used in io.cpp and main.cpp, instead of declaring it twice?

    This is what I have and it doesn’t compile. 🙁

    io.h:

    io.cpp:

    main.cpp:

    Thanks!

    • Alex

      Putting global variables in header files is a really bad practice. Don’t do it.

      In this case, both main.cpp and io.cpp will get a copy of variable addAnswer. By default, non-const global variables have something called external linkage (a concept we explain in chapter 4). The end-result of this is that when the linker goes to link main.o and io.o, it sees that both have a variable of the same name, and doesn’t know how to reconcile this.

      There are quite a few ways to fix this, but the best way is to not do anything like this in the first place. You really shouldn’t be using global variables at all in this case.

      • ppippi

        I understand it a lot better now, thanks. I just read the following sub-chapter and I see why it’s bad practice. Since I learned C first and my professor encouraged global initializations, I assumed it would be good practice here too. Thank you!

  • Mohammad

    thank you so much!

  • Vlad

    Hi I have a problem too.At second question,I wrote this code inside a project(note that there are only these files in that project):
    io.cpp
    #include<iostream>
    using namespace std;
    int readNumber()
    {
      cout<<"enter a number:"<<endl;
      int x;
      cin>>x;
      return x;

    }
    void writeAnswer(int x)
    {
      cout<<"the result is:"<<x;
    }
    main.cpp
    #include<iostream>
    using namespace std;
    int readNumber();
    void writeAnswer(int x);

    int main()
    {
        int a = readNumber();
        int b = readNumber();
        writeAnswer(a + b);
        return 0;
    }
    I keep getting multiple definition of ‘main’ error even if I have only one main function inside the project.Any tips on solving this problem?
    note:I apologize if I have any grammatical errors,English is not my native language

    • Alex

      Somehow your compiler is compiling two main() functions, which means you have a second main function either in main.cpp, io.cpp, or some other file that’s getting compiled into your project by accident. My bet is on the latter.

  • Jared

    I know that this isn’t too important, but why does "std::cin >> x;" act as a endl at the end? What if I wanted to say "
    std::cout << ‘Print two Numbers: ‘;
    std::cin >> x;
    std::cout " and ";
    std::cout >> y;" I want it to print "Print two numbers: x and y" yet it prints "Print two numbers: x
    *endl* and y" Sorry for bad formatting in code 😛

    • Alex

      std::cin waits for you to hit enter before trying to extract a value to your variable. Hitting enter causes a newline.

      There are 3rd party libraries available that allow you to do input without require the user hit enter, such as the curses I/O library.

  • Sav

    Hello,

       I am using Visual Studio 2015, and i have included the io.h and the io.cpp in my main.cpp file but when i compile it it still throws the error of identifier not found for the readNumber and writeAnswer. I have copied the answer given letter for letter and it is still not working. What did I do wrong?

    io.h:

    io.cpp:

    main.cpp:

    And as I stated before the io.cpp and the io.h are added in their respective areas in the solution explorer. Any insight would be appreciated.

    (this may seem silly but how am i supposed to use the code tags? I typed them in at the beginning and end of the code exactly how they are written and it did not seem to work)
    Thanks

    • Alex

      I don’t see anything wrong with your code. Are you getting a compiler error or linker error? If linker error, maybe io.cpp isn’t getting compiled as part of your project.

      Try copying the readNumber() and writeAnswer() prototypes from io.h and put it at the top of main and see if that compiles. If so, then something is going on with io.h. Maybe your header guards are having a naming conflict with something else?

      You use the code brackets like this:

      [code]
      Your code here
      [/code]

  • Olvin Lizama

    I was getting a compilation error, something that I thought was weird is that the io.cpp file must include the iostream library, my code will not work if not done so,

    io.h

    io.cpp

    main.cpp

    That was not commented I think so in the chapter 1.8 — Programs with multiple files, but I think anyone with a little common sense can realize it.

    Thanks for this great Course!!

  • I have the same problem as Lauren. I have the exact same code used for solution 3 with 3 different files. Somehow the compiler (using Microsoft Visual Studio 2015) doesn’t find io.h when going through main.cpp.

    It throws undefined errors by the way.

  • Lauren

    Hmm, so I’m a little confused about what I should put in a header file: is it better to put just the forward declarations in the header file or to define the functions in the header file? And why?

    I also have a second, unrelated question: for some reason when I make a io.h file (analogous to your solution) with

    including "io.h" in main, the compiler throws an error and tells me it can’t find writeAnswer

    When I keep the exact same files, and just change io.h to

    which is what CodeBlocks automatically fills in for the name of the header, it works. Any ideas why case 1 doesn’t work?

    Sorry if these were covered elsewhere and I somehow missed it. And thank you for these tutorials, they’re fantastic!

    • Alex

      You should generally only put declarations in a header file. If you put a definition in the header file, that definition will be propagated to every code file that includes that header, which can lead to duplicate definition problems.

      It sounds like somehow IO_H is getting #defined more than once, so the contents of your io.h header file aren’t being included in your main code file. I’m not sure where this would be happening though.

  • Aaron

    It’s great how much this bit of practice helps!!! Thanks for this quiz…it helps to condense everything in chapter one into 3 questions 😉

  • Abhishek

    Hi Alex,
    I modified my code to answer the 3rd question without seeing the solution (i modified only the io.h file the rest is same as yours) and i came up with this:
          In io.h

    #ifndef READNUMBER_H
    #define READNUMBER_H

    int readNumber();

    #endif // READNUMBER_H

    #ifndef WRITEANSWER_H
    #define WRITEANSWER_H

    void writeAnswer(int x);

    #endif // WRITEANSWER_H

    I compiled it and it works fine. I wanted to know if this is the correct way to code or efficient way to code or i should follow as you have mentioned. Thanks.

    • Alex

      If these are both in io.h, then no, this is not the right way to do things. The header guards should include the entire contents of the header.

  • [#include "stdafx.h"
    #include <iostream>
    int readnumber()
    {
        int x = 0;
        std::cout << "please enter a number" << std::endl;
        std::cin >> x;
        return x;
    }
    int writeanswer(int y )
    {
        std::cout << y << std::endl;
        return 0;

    }
    int main()
    {
        int y = 0;
        int input1 = readnumber();
        int input2 = readnumber();
        y = input1 + input2;
        std::cout << y << std::endl;
    }
    ]
    is this one correct like for 1st answer it is not matching I did not void anywhere because I basically did not understand its usage but is this correct
    Thanks a lot

    • Alex

      It produces the correct output, but writeanswer() should have a return type of void and no return statement, otherwise your code is a bit misleading.

  • Malavika

    Hello,
    This question isn’t exactly related to this quiz. Whenever I use the command "return 0;" outside of the main function, in an int function, I find that the program actually prints the number 0 on-screen before proceeding. But if I make the function a void or char one, this doesn’t happen.

    Is this supposed to happen? Or am I missing something?

    By the way, this is my first time commenting here, and I’m glad to see you’re still here responding to every comment 🙂

    • Alex

      Returning a value simply passes that value back to the caller of the function. The caller can print that value if they wish, but that’s not required. The simple act of returning a value does not print anything in and of itself.

  • Jatin

    Hi Alex, for question 2 I used the following code
    io.cpp

    main.cpp

    but the compiler is showing me errors like
    Roughio.cpp|4|error: ‘cout’ is not a member of ‘std’|
    Roughio.cpp|4|error: ‘endl’ is not a member of ‘std’|
    When I #include in io.cpp it runs fine .Why it is happening

    • Alex

      io.cpp uses std::cout and std::cin, which are defined in header file iostream, so io.cpp needs to #include iostream. The fact that you’ve included it in main.cpp only allows the code in main to use that functionality, not other files.

  • brent

    if your still reading these, I wanted to say thank you for the time and effort you put into this for me to have access to lessons of this type, and your work here, so far has been outstanding !!
    I’m very grateful you found the time to teach others, like myself.
    great work !
    thank you sir.
    peace hope love
    Doc

  • John

    I’ve been using this site purely on the whim in the hope that I might be able to learn something new quite casually in my spare time. So far (just got to the end of chapter 1!) I’ve found the style incredibly accessible and easy to follow. I have zero background in programming or anything particularly "codey" outside of being reasonable in Excel!  I hope the remaining content matches what I’ve seen so far!

    Great stuff so far!

  • Nyap

    I did it differently for exercise 1. Is this still correct?

    • Nyap

      nvm, writeAnswer is supposed to have only one parameter
      back to the drawing board then

      edit: done, finished the test. Looking forward to chapter 2 😀

    • Alex

      It’s not wrong. But there are a few things to watch out for here:
      1) Nesting function calls inside of other function calls can be confusing.
      2) C++ doesn’t indicate whether functions should evaluate their parameters left to right or right to left. In this case, it doesn’t matter because your left and right parameters are identical. However, if you had a readNumber1() and readNumber2(), they might execute in different orders on different machines.

      I think it’s clearer if you split out the two readNumber() calls into their own statements. That way you have explicit control over the ordering, and each statement is simpler.

  • Rhys

    My question 1 attempt so far, won’t compile. Where am I going wrong? (haven’t looked at the answer yet)

    • Rhys

      Sorry, it DOES compile, just doesn’t work

    • Nyap

      semantic error (line 21)
      edit: I’m not sure actually, you’ve confused me aswell xD

    • Alex

      Your compiler should tell you exactly what’s wrong. When I compiled this, I got:

      1>...\consoleapplication1.cpp(29): error C4700: uninitialized local variable 'X' used
      

      And there it is. You’re passing the value of X to a function without having given it a value first.

    • Rhys

      If I like declare X = 1 first in main(), it stays as 1 and doesn’t get updated when it gets passed to readNumber & back. Like here’s my most recent version:

      • Alex

        When you pass variable X to function readNumber(), parameter A in readNumber becomes a copy of X, which you then overwrite with the user’s input. So first off, you should not pass X to readNumber(). Instead, readNumber() should not take a parameter and instead should declare its own local variable.

        Second, you return the user’s input from readNumber(), but you’re not doing anything with it, so it’s being discarded. You should assign this back to X (or Y as appropriate).

    • Rhys

      Third attempt, runs, but gives wrong answer.

      • Alex

        This program shouldn’t compile, as function readNumber() is expecting a parameter, but the calls to readNumber() do not supply an argument.

        Variable X should be defined inside the function body (as a local variable) rather than a function parameter, as we should not expect the caller to pass in a value for this variable.

  • gowtham

    Thank you for your response. So can we generalise the function of header guards as a method to prevent errors due to definition duplication (while compiling)?

  • gowtham

    I don’t understand the use of header guards. I did this exercise without header guards and it compiled just fine. I know i’m missing the point but just can’t figure out what it is!

    • Randall L

      I’ll try to answer this to test my own understanding. 🙂

      Header guards won’t make a noticeable difference when you only have a single header file you’re including, but it should be done anyway because it’s part of establishing good habits while programming. If you were including multiple files, there’s a chance (and probably a pretty good one) you would include the same files over and over through inheritance. (myProgram.cpp includes myMath.h and myConstants.h, however myConstants.h includes myMath.h too - This leads to code bloat).

      • Alex

        Code bloat is actually the lesser problem we’re trying to solve.

        The bigger problem is the fact a given identifier can only be defined once. If you try to define it twice, then the compiler will give you an error.

        So consider the case where you have a definition (of any kind) in A.h. B.h #includes A.h. main.cpp #includes both A.h and B.h. Without header guards, you’ll get two copies of the definition in main.cpp (one from A.h, and one from B.h, which it got from A.h). That will cause a compile error.

  • Randall L

    Alex! Thank you so much! Finally someone who can teach C++ the way my brain wants to learn it! You have no idea how much this site means to me. Maybe you do. You state something in a paragraph, and my brain starts to think "well, what about this other possiblity?" You then proceed in the very next sentence to address the question I was just thinking about.  This whole process makes so much more sense than it ever has any other time I’ve tried to learn C++. Honestly, thank you so much!!

  • Grampa Grump

    Hello! I’m not sure if you are still looking through these, but I wanted some feedback regarding what I put in main()

    The readNumber and writeAnswer functions were the same, but I noticed that I did the last part differently than what I had seen in the solutions and comments. What I did worked correctly, at least it asked for two numbers and then added them correctly.

    int main()
    {
        writeAnswer(readNumber() + readNumber());
        return 0;
    }

    Should I have done it like you did in the example by creating two new variables in main and passing those into writeAnswer instead of just calling the input function twice and using the return in the middle of calling the write function? I’m not sure if the way I did it or the way you did it would be more efficient for larger programs

    Also, thank you very much for the tutorials, they are very helpful!

    • Alex

      The way you did it is fine. Personally, I prefer having functions that ask for user input in their own individual statements, rather than nested inside another function call. To me, it reads cleaner, and makes the order that things execute in a little more obvious.

  • Garrett

    Whew, got through chapter 0-1 in one night, its 12 PM.. really tired, found this guide SUPER helpful though! Thank you!!!

  • Sharaf

    main.cpp

    io.h

    io.cpp

    i didn’t use header guard but it still got compiled so plzz explain point header guard here?

    • Alex

      It looks like you used a header guard in io.h, since you have #ifndef io.h. It’s also a little weird to have your main function in io.cpp instead of main.cpp.

      But to answer your question, header guards prevent a header file from being #included multiple times into a given file (to prevent problems with redeclarations). Since your io.h only gets #included once, the header guard isn’t technically needed (but it’s still good practice to include it, since for more complicated programs you’ll want the header guards).

  • Brady

    I was able to answer all three problems.  But had a couple questions about ordering and efficiency.  In mine I put int x as the first line in readNumber().  I’m guessing doing this in larger programs could cause poor performance by using unnecessary RAM?  And so it is more efficient to do it your way where x is filled and destroyed as quickly as possible to when it is created?
    Also, in main() I tried two different ways that both worked.  I was wondering if one of the three (my two ways and your solution) is better than the other two and why?  Here’s what I did:

    I just commented out one to try the other.
    Thanks!

    • Alex

      The ordering of the lines doesn’t really matter in terms of efficiency. The “define a variable as close to its first use as possible” is to reduce complexity, not affect performance. In both cases, the variable is created at the start of the function and destroyed at the end.

  • X

    Hello, Alex. I have a question.
    In "Solution 1, line 11", what’s the meaning of ‘int x’ within ‘void writeNumber(int x)’?? I can not understand it, even if I use ‘int s’ to instead of ‘int x’, the code can be executed successfully…..

    • Alex

      int x is a function parameter. It tells the compiler that function writeNumber() takes one parameter of type integer, with name x. So when we call writeNumber(), we need to pass it an argument (e.g. writeNumber(5)), and this argument will be assigned to parameter x when the function starts.

      Please re-review the lesson on function arguments and parameters.

  • Oeleo

    Hello,
    I want to help you with allowing AdBlock on your site, but when I go on the homepage and pause or disabling AdBlock "on this domain" I always don’t see adds. However, I see them when I put a shortcut on my desktop and in this case I see them. Any idea to solve that ?

  • Nic

    Hi, I seem to have trouble with the code even though the syntax is correct(I think).
    main.cpp

    io.cpp

    Header.h

    I get the error:

    What does that mean?

  • Olha meu resultado aí, em pleno 2015.

    #include <iostream>
    #include <cstdlib>

    //Declara uma função para fazer uma leitura
    int readNumber();

    //Declara uma função para mostrar o resultado
    int writeAnswer(int y);

    int main()
    {
        int n1 = readNumber();
        int n2 = readNumber();
        writeAnswer(n1 + n2);
        system("pause");
    }

    int writeAnswer(int y)
    {
        std::cout << "O resultado é: " << y << std::endl;
    }

    int readNumber()
    {
        std::cout << "Insira um número inteiro:";
        int x;
        std::cin >> x;
        return x;
    }

  • Arjen

    Hi,

    As a java developer, I really LOVE your tutorial and of course, besides of the different syntax, it’s quite ease to implement until now.. 😉

    I even wrote the solution on question 2 already in the first question.. and tried the one liner version to see if that worked, which it did! 🙂

    You explain it very well!

    Will continue on this one the coming days!

    Thanks & regards,
    Arjen

Leave a Comment

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