1.10 — Developing your first program

The preceding lessons have introduced a lot of terminology and concepts that we’ll use in just about every program we create. In this lesson, we’ll walk through the process of integrating this knowledge into our first simple program.

Multiply by 2

First, let’s create a program that asks the user to enter an integer, waits for them to input an integer, then tells them what 2 times that number is. The program should produce the following output (assume I entered 4 as input):

Enter an integer: 4
Double that number is: 8

How do we tackle this? In steps.

Best practice

New programmers often try to write an entire program all at once, and then get overwhelmed when it produces a lot of errors. A better strategy is to add one piece at a time, make sure it compiles, and test it. Then when you’re sure it’s working, move on to the next piece.

We’ll leverage that strategy here. As we go through each step, type (don’t copy/paste) each program into your compiler, compile, and run it.

First, create a new console project.

Now let’s start with some basic scaffolding. We know we’re going to need a main() function (since all C++ must have one), so if your IDE didn’t create a blank one when you created a new project, let’s create one:

We know we’re going to need to output text to the console, and get text from the user’s keyboard, so we need to include iostream for access to std::cout and std::cin.

Now let’s tell the user that we need them to enter an integer:

At this point, your program should produce this result:

Enter an integer:

and then terminate.

Next, we’re going to get the user’s input. We’ll use std::cin and operator >> to get the user’s input. But we also need to define a variable to store that input for use later.

Time to compile our changes… and…

Uh oh! Here’s what the author got on Visual Studio 2017:

1>------ Build started: Project: Double, Configuration: Release Win32 ------
1>c:\vcprojects\double\double.cpp(8): error C2678: binary '<<': no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)
1>c:\vcprojects\double\double.cpp: note: could be 'built-in C++ operator<<(bool, int)'
1>c:\vcprojects\double\double.cpp: note: while trying to match the argument list '(std::istream, int)'
1>Done building project "Double.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

We ran into a compile error!

First, since the program compiled before we made this latest update, and doesn’t compile now, the error must be in the code we just added (lines 7 and 8). That significantly reduces the amount of code we have to scan to find the error. Line 7 is pretty straightforward (just a variable definition), so the error probably isn’t there. That leaves line 8 as the likely culprit.

Second, this error message isn’t very easy to read. But let’s pick apart some key elements: The compiler is telling us it ran into the error on line 8. That means the actual error is probably on line 8, or possibly the preceding line, which reinforces our previous assessment. Next, the compiler is telling you that it couldn’t find a ‘<<‘ operator that has a left-hand operand of type std::istream (which is the type of std::cin). Put another way, operator<< doesn’t know what to do with std::cin, so the error must be either with our use of std::cin or our use of operator<<.

See the error now? If you don’t, take a moment and see if you can find it.

Here’s the program that contains the corrected code:

Now the program will compile, and we can test it. The program will wait for you to enter a number, so let’s enter 4. The output should look like this:

Enter an integer: 4

Almost there! Last step is to double the number.

Once we finish this last step, our program will compile and run successfully, producing the desired output.

There are (at least) 3 ways we can go about this. Let’s go from worst to best.

The not-good solution

In this solution, we use an expression to multiply num by 2, and then assign that value back to num. From that point forward, num will contain our doubled number.

Why this is a bad solution:

  • Before the assignment statement, num contains the user’s input. After the assignment, it contains a different value. That’s confusing.
  • We overwrote the user’s input by assigning a new value to the input variable, so if we wanted to extend our program to do something else with that input value later (e.g. triple the user’s input), it’s already been lost.

The mostly-good solution

This solution is pretty straightforward to read and understand, and resolves both of the problems encountered in the worst solution.

The primary downside here is that we’re defining a new variable (which adds complexity) to store a value we only use once. We can do better.

The preferred solution

This is the preferred solution of the bunch. When std::cout executes, the expression num * 2 will get evaluated, and the result will be double num‘s value. That value will get printed. The value in num itself will not be altered, so we can use it again later if we wish.

This version is our reference solution.

Author's note

The first and primary goal of programming is to make your program work. A program that doesn’t work isn’t useful regardless of how well it’s written.

However, there’s a saying I’m fond of: “You have to write a program once to know how you should have written it the first time.” This speaks to the fact that the best solution often isn’t obvious, and that our first solutions to problems are usually not as good as they could be.

When we’re focused on figuring out how to make our programs work, it doesn’t make a lot of sense to invest a lot of time into code we don’t even know if we’ll keep. So we take shortcuts. We skip things like error handling and comments. We sprinkle debugging code throughout our solution to help us diagnose issues and find errors. We learn as we go -- things we thought might work don’t work after all, and we have to backtrack and try another approach.

The end result is that our initial solutions often aren’t well structured, robust (error-proof), readable, or concise. So once your program is working, your job really isn’t done (unless the program is a one-off/throwaway). The next step is to cleanup your code. This involves things like: removing (or commenting out) temporary/debugging code, adding comments, handling error cases, formatting your code, and ensuring best practices are followed. And even then, your program may not be as simple as it could be -- perhaps there is redundant logic that can be consolidated, or multiple statements that can be combined, or variables that aren’t needed, or a thousand other little things that could be simplified. Too often new programmers focus on optimizing for performance when they should be optimizing for maintainability.

Very few of the solutions presented in these tutorials came out great the first time. Rather, they’re the result of continual refinement until nothing else could be found to improve. And in many cases, readers still find plenty of other things to suggest as improvements!

All of this really to say: don’t be frustrated if/when your solutions don’t come out wonderfully optimized right out of your brain. That’s normal. Perfection in programming is an iterative process (one requiring repeated passes).

Author's note

One more thing: You may be thinking, “C++ has so many rules and concepts. How do I remember all of this stuff?”.

Short answer: You don’t. C++ is one part using what you know, and two parts looking up how to do the rest.

As you read through this site for the first time, focus less on memorizing specifics, and more on understanding what’s possible. Then, when you have a need to implement something in a program you’re writing, you can come back here (or to a reference site) and refresh yourself on how to do so.

Quiz time

Question #1

Modify the solution to the “best solution” program above so that it outputs like this (assuming user input 4):

Enter an integer: 4
Double 4 is: 8
Triple 4 is: 12

Show Solution

1.x -- Chapter 1 summary and quiz
1.9 -- Introduction to expressions

66 comments to 1.10 — Developing your first program

  • BeanSprugget

    Why is the "mostly-good" solution not preferred? You say that the only once used variable adds "complexity", but I'm confused as to what is meant by "complexity"? Is initializing a new variable less efficient?

    Because, to me, initializing a new variable is closer to how my mind thinks of the problem: that the number is doubled, and then printed - as opposed to being doubled while it's being printed.

    • nascardriver

      `doublenum` isn't used anywhere after being printed, but it still exists, taking up memory and preventing the name from being reused for another variable.
      Doing this can also be slower, as we'll explain later (A lot later, when we talk about move semantics). This isn't relevant for integers, but can have adverse effects when the types get larger.

  • Math

    I used dev c++ before finding this website but then I switched to visual studio
    so far it has been working fine but one thing I noticed was that it doesn't give me warnings like dev c++ did
    in one program I used the single quotations like this '= '
    and didn't realize that there was a space
    it compiled fine but when I ran my program it gave me undefined behavior I couldn't figure out why so I tried it on dev c++ and it immediately showed me that there was the extra space on '= ' and then the program worked and ran as expected on both IDEs
    what I want to ask is , can I make visual studio show me warnings like these??
    If there is please tell me how I would really appreciate your help :)

  • Zatch

    include <iostream>

    int main()

        std::cout << "enter your number: ";
        int X{};

        std::cin >> X;
        int Z{ X*2 };

        std::cout << "Double that of number is: " << Z << '\n';

        std::cout << "Triple of that number is: ";
        int A{Z*2};
        std::cout << A;
         return 0;

  • Khalis

    when I slightly change the "The mostly-good solution" and does not give the int num an initial value, I get the result 32 every time. I want to know if there is a special reason that my coumputer gives an initial value of 32 to the int num aoutomatically. Here is my slightly changed code:

    And here is the result I get on CMD:

    Enter an integer: 4
    Double that number is: 32

    Process returned 0 (0x0)   execution time : 0.786 s
    Press any key to continue.

    • Flkob

      The reason is num isn't initialized with a number, so it contains a random number (32 in your case).
      You also multiply num when intialize doublenum, before you have read the number from cin.

      The code is executed line by line, so you will have to move the int doublenum{ num * 2 } after std::cin >> num for get it to work.

  • Jim Guth

    Another dumb question.  How are we supposed to enter the data to start this lesson (1.10) in code blocks and add more files.  I have file C:/CBProjects...main cpp with Hello World enclosed in it.  Do I just delete the data inside main.cpp. Or make a new file using the CB Main Menu File>New (Or make a new Project, Or What ?).

    However this need to done. Will I have to save this fill with a new (XXX.cpp) name.  I don't know how to enter a screen shot here, but main.cpp is in the CB management window.

    I'd like to save all my work if I can, a least for a while so I can go back and look at it again.

  • mohamed

    why we have to use int main()
    not just main() all along why we have to make type integer ?

    • karmazynowypiekarz

      main is a function and all functions need to have a type, you could make it a void but then you'd strip yourself from the chance to return a value different than usual were things to go wrong.

  • In the below code snippet (which is referred in this Tutorial),
    1. doublenum is initialised with what value ?
    2. how doublenum becomes twice of num ?

    3. does the Compiler converts the below statement
    int doublenum{ num * 2 };
    into something similar to below two equivalent statements
    doublenum{ 0 };
    doublenum = num * 2;

    • nascardriver

      We talk more about initialization later.

      • Thanks for the response, nascardriver.

        My doubt was not about the statement "int doublenum{ num * 2 };" in general.

        My doubt was about the initialisation of the variable doublenum based on run-time value supplied to another variable num:
        1. doublenum is initialised with what value ?
        2. how doublenum becomes twice of num ?

        Sorry, I could not find out the discussion about such special initialisation case in this discussion thread based on which my doubt would get clarified.

        • nascardriver

          It's initialized with the value of `num` times 2. That's what


          • Hi nascardriver,
            Compiler generates the machine level code of variable initialization at compile time.
            So how does compiler know in the machine level code being generated during compilation, the variable doublenum will be initialised with what value.

            Does in machine level code, the content of doublenum memory location refers to the de-refencing of the address of num memory location which is multiplied by 2 ?

  • John

    Regarding the last author's note, it basically means that I don't need to remember what a specific concept means, for example what is undefined behavior, etc. I need to focus on coding, I don't need to remember what a specific concept means, I can come back to it whenever I want?

  • José

    I keep getting the error LNK1168 and can't solve it, no matter what I do, I have to restart the pc for it to work, but since it happens every 2 minutes, well

  • Ed


    I noticed after executing the example above using the Preferred option, that immediately after a number is entered, it just closes. I'm new to all of this, can you tell me what is missing or what I did wrong? I'm using Visual Studio 2019. Here is the code I have, there weren't any errors or warnings informed?


    #include <iostream>

    int main()
        std::cout << "Welcome Mathmetician! Please enter an integer!" << std::endl;

        int num{ 0 };
        std::cin >> num;

    std::cout << "Now double that number: " << num * 2 << '\n';

        return 0;

  • Arthas

    I practice the example above, my complier doesn't report any error nor bug, and the program came out with the correct result when I found I missed the last statement 'return 0;' of the main() function. Does the 'return 0;' statement really matter in all program/function? Thanks.
    My complier is Visual Studio 2019.

    • nascardriver

      It's optional in `main` (`main` is the only function that automatically returns a value). It should be added for consistency anyway.

  • Nico

    I found an error

    #include <iostream>

    [code] int main()
        std::cout << "Enter an integer: ";

        int num{ 0 }; // define variable num as an integer variable
        std::cin << num; // get integer value from user's keyboard

        return 0;
    } [code]

    The cin should be >> instead of <<

  • Ryan

    Hi! I found a couple typos, and had a question to ask. In this chapter, it says "multiple" instead of "multiply" in "we use an expression to multiple num by 2". There is also an unnecessary "a" in "This solution is a pretty straightforward to read and understand". A couple chapters back, in 1.8 "Introduction to literals and operators", it says "flip" instead of "flips" in "takes literal operand 5 and flip its sign".

    In the following two examples, would there be *any* difference in performance to any theoretical extent? Especially if done to some exaggerated extreme amount of times? Or do they evaluate to the exact same thing in compilation; and the first would be preferred for organizational purposes?

    • nascardriver

      Thanks for pointing out the spelling mistakes, all fixed!

      Version 2 is faster. `std::cout`'s address has to be loaded into a register (A fast variable on the CPU). In version 1, it has to be loaded twice, whereas version 2 loads it just once, otherwise they're the same. You're not going to notice this, especially since we're talking about IO, which is slow in general.

  • Vitaliy Sh.

    Hi Sires!

  • #include <iostream>
    int main()
        std::cout << "Enter an Integer: ";
        int {user_value = 0};
        std::cin >> user_value;
        std::cout << "Double your integer is: " << user_value * 2 << std::endl;
        std::cout << "Triple your integer is: " << user_value * 3 << std::endl;
        return 0;

    I programmed this, but I'm not sure which category this would fall under ( the not-good solution, the ok solution, or the preferred solution).

    • nascardriver

      The untested solution.

      Also, don't use `std::endl` unless you need to. '\n' should be preferred, as noted in lesson 1.5.

      You can highlight your code in the comments by using code tags:
      your code here
      Without the -

    • Apaulture

      is preferred.
      But since user_value may be replaced anyway,

      will also work.

  • Ryan

    Would it be a good habit to initialise like int num{}; or int num{ 0 };

    • nascardriver

      If you use the initial value (0), explicitly initialize to 0

      If you don't use the value, use value-initialization.

      They both do the same, but the first version is easier to understand if the value is used.

  • Jake

    (Please forgive my getting ahead by "using namespace"; also multiple definitions on a line; I's jest set in me ways. :-)
    I decided to get a a bit mathematical and added a hypotenuse calculation. Surprising result..


    The result should have been 17 or something VERY close to that. What have I missed?

    • `^` is not power. It's a logical XOR (Chapter O (That's an o, not a zero)). If you want power, use `std::pow` from the `<cmath>` header.

      EDIT: "header" means you have to add `#include <cmath>`.

  • Shubham Maske

    I am having an issue with code Block software

    after running the program the Black screen appears

    it says Enter an Integer :
    when I type any integer 1 or 2 or say 5
    and press enter
    the black screen disappears and the result is not shown.

    can anyone help me fix this?

  • 4STR4L_3N3MY

    #include <iostream>
    /* I read the first 2 paragraphs and wanted to see if i could do it myself, so i quickly wrote this silly little program. Wasn't confident at first but it turned out pretty good! *\

    int main()
        int inP{};
        std::cout << "Enter A Number You Want To Double: ";
            std::cin >> inP;
            std::cout << "\n" << "*CPU powering up* AAAND x2!!!! ~~~ " << (inP * 2);

            return 0;


    // im sure i can use the \n more effectively tho. i think its time to move on.

    • Crateer

      Hope that helps

  • George

    Using the site to refresh my C++ skills - it's very well organised and written with a lot of relevance. Really liked the following author's note:

    "Short answer: You don’t. C++ is one part using what you know, and two parts looking up the rest."

    Very true! :)

  • Chayim

    Why is it need to use 2 output operators <<  << left ands right of expressions to output? is it because it's and expression and not a statement? and to distinguish and indentidfy expression from statement?

    • You start with a stream object, `std::cout`.
      When you call `operator<<` on that stream, it prints whatever you gave it, and returns the stream object.

      `<<` always applies to the result of the previous `<<` (Unless it's the first).

      • Chayim

        It's not clear, the first operator prints out what's written after like << "Hello", why is it needed another << for << "nascardriver\n"?

        std::cout << "Double that number is: " << num << '\n'; ------ why does num and '\n' need a seporate << operator??

  • Zoe

    Hi. I am using clang on codeblocks with c++14 and when i entered this code:

    I get this error :
    warning: generalized initializer lists are incompatible with C++98 [-Wc++98-compat].
    I have no idea how to get rid of it. Any help would be appreciated.

  • Thomas

    The best solution is not the best solution, but maybe the preferred solution since nothing fancy is going on.
    Best practice is to always think before you talk, or you may end up being embarrassed by an error since you are talking without thinking.

  • ooepewwerew

    How do I fix this code?

    • VichTrogdor

      When you are asking for help with code, you  need to give the reader more information about what you want to fix. You can't just say, "fix this code." A more helpful statement would be something like, "I just added lines x through y to my code, which is intended to do this, but instead, it is doing this and I'm getting this error code. What error did I make?" Even if what you say isn't all of the information necessary for someone to help you, it at least will be enough that someone will try.

  • Hunter Coleman

    Why is it int num { 0 } instead of int num = 0;?

    Is it changes to C++ this year or was the { } an assignator for a flexible variable ready to change?

    • Hi!

      This was part of a C++ update in 2011. It's covered in lesson 1.4.

      • Hunter Coleman

        Hello nascardriver,

        I reviewed 1.4 and found out why you guys included the { }.  Now, it makes more sense.  In my previous class of Programming Fundamentals II, my teacher taught copy assignments, and did not emphasize the use of the uniform initialization.

        The code process would have been as followed:

        For the rest of our class, we used copy assignemnts all over.  I never knew about the { } except for [] which is assigned to arrays.

        I need to continue my path of becoming a VR developer, and in order to do that, I need to update myself with practicing more often.

  • 3.14

    In the author notes, the word "maintainability" is spelled wrongly

  • Jorge Guimaraes

    Question #1

    Modify the solution to the “best solution” program above so that it outputs like this (assuming user input 4):

    One std::cout assignment can output multiple lines, no need (other than educational) to assign cout multiple times:

    #include <iostream>

    int main() {
        std::cout << "Enter an integer: ";
        int num{ 0 };
        std::cin >> num;
    //std::cout appears
        std::cout << "Double of " << num << " is " << num * 2 << ".\nTriple of " << num << " is " << num * 3 << "\n";
        return 0;

  • Gurankas

    In the last Author's note, second last paragraph, I think you meant to say "readers still find plenty of other things to suggest as improvements!" rather than " readers still plenty of other things to suggest as improvements!". Thanks for these tutorials!

  • Iury

    "First, since the program compiled before we made this latest update, and doesn’t compile now, the error must be in the code we just added (lines 7 and 8)."

    It's said "lines 7 and 8", but it's actually lines 5 and 6, I  think this happened because the code that ran into a compile error doesn't have

    at the start.

Leave a Comment

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