Search

1.10b — How to design your first programs

Now that you’ve learned some basics about programs, let’s look more closely at how to design a program. When you sit down to write a program, generally you have some sort of problem that you’d like to solve, or situation that you’d like to simulate. New programmers often have trouble figuring out how to convert that idea into actual code. But it turns out, you have many of the problem solving skills you need already, acquired from everyday life.

The most important thing to remember (and hardest thing to do) is to design your program before you start coding. In many regards, programming is like architecture. What would happen if you tried to build a house without following an architectural plan? Odds are, unless you were very talented, you’d end up with a house that had a lot of problems: walls that weren’t straight, a leaky roof, etc… Similarly, if you try to program before you have a good game-plan moving forward, you’ll likely find that your code has a lot of problems, and you’ll have to spend a lot of time fixing problems that could have been avoided altogether with a little thinking ahead.

A little up-front planning will save you both time and frustration in the long run.

Step 1: Define the problem

The first thing you need to figure out is what problem your program is attempting to solve. Ideally, you should be able to state this in a sentence or two. For example:

  • I want to write a phone book application to help me keep track of my friends’ phone numbers.
  • I want to write a random dungeon generator that will produce interesting looking caverns.
  • I want to write a program that will read information about stocks from the internet and predict which ones I should buy.

Although this step seems obvious, it’s also highly important. The worst thing you can do is write a program that doesn’t actually do what you (or your boss) wanted!

Step 2: Define your tools, targets, and backup plan

When you are an experienced programmer, there are many other steps that typically would take place at this point, including:

  • Understanding who your target users are and what they want.
  • Defining what target architecture and/or OS your program will run on.
  • Determining what set of tools you will be using.
  • Determining whether you will write your program alone or as part of a team.
  • Collecting requirements (a documented list of what the program needs to do).
  • Defining your testing/feedback/release strategy.
  • Determining how you will back up your code.

However, as a new programmer, the answers to these questions are typically simple: You are writing a program for your own use, alone, on your own system, using an IDE you purchased or downloaded, and your code is probably not used by anybody but you. This makes things easy.

That said, if you are going to work on anything of non-trivial complexity, you should have a plan to backup your code. It’s not enough to just zip or copy the directory to another location on your machine (though this is better than nothing). If your system crashes, you’ll lose everything. A good backup strategy involves getting a copy of the code off of your system altogether. There are lots of easy ways to do this: Email it to yourself, copy it to Dropbox or another cloud service, FTP it to another machine, copy it to another machine on your local network, or use a version control system residing on another machine or in the cloud (e.g. github). Version control systems have the added advantage of not only being able to restore your files, but also to roll them back to a previous version.

Step 3: Break hard problems down into easy problems

In real life, we often need to perform tasks that are very complex. Trying to figure out how to do these tasks can be very challenging. In such cases, we often make use of the top down method of problem solving. That is, instead of solving a single complex task, we break that task into multiple subtasks, each of which is individually easier to solve. If those subtasks are still too difficult to solve, they can be broken down further. By continuously splitting complex tasks into simpler ones, you can eventually get to a point where each individual task is manageable, if not trivial.

Let’s take a look at an example of this. Let’s say we want to write a report on carrots. Our task hierarchy currently looks like this:

  • Write report on carrots

Writing a report on carrots is a pretty big task to do in one sitting, so let’s break it into subtasks:

  • Write report on carrots
    • Do research on carrots
    • Write outline
    • Fill in outline with detailed information about carrots
    • Add table of contents

That’s more manageable, as we now have subtasks that we can focus on individually. However, in this case, “Do research on carrots” is somewhat vague, so we can break it down further:

  • Write report on carrots
    • Do research on carrots
      • Go to library and get book on carrots
      • Look for information about carrots on internet
      • Take notes on relevant sections from reference material
    • Write outline
      • Information about growing
      • Information about processing
      • Information about nutrition
    • Fill in outline with detailed information about carrots
    • Add table of contents

Now we have a hierarchy of tasks, none of them particularly hard. By completing each of these relatively manageable sub-items, we can complete the more difficult overall task of writing a report on carrots.

The other way to create a hierarchy of tasks is to do so from the bottom up. In this method, we’ll start from a list of easy tasks, and construct the hierarchy by grouping them.

As an example, many people have to go to work or school on weekdays, so let’s say we want to solve the problem of “get from bed to work”. If you were asked what tasks you did in the morning to get from bed to work, you might come up with the following list:

  • Pick out clothes
  • Get dressed
  • Eat breakfast
  • Drive to work
  • Brush your teeth
  • Get out of bed
  • Prepare breakfast
  • Get in your car
  • Take a shower

Using the bottom up method, we can organize these into a hierarchy of items by looking for ways to group items with similarities together:

  • Get from bed to work
    • Bedroom things
      • Get out of bed
      • Pick out clothes
      • Get dressed
    • Bathroom things
      • Take a shower
      • Brush your teeth
    • Breakfast things
      • Prepare breakfast
      • Eat breakfast
    • Transportation things
      • Get in your car
      • Drive to work

As it turns out, these task hierarchies are extremely useful in programming, because once you have a task hierarchy, you have essentially defined the structure of your overall program. The top level task (in this case, “Write a report on carrots” or “Get from bed to work”) becomes main() (because it is the main problem you are trying to solve). The subitems become functions in the program.

If it turns out that one of the items (functions) is too difficult to implement, simply split that item into multiple sub-items/sub-functions. Eventually you should reach a point where each function in your program is trivial to implement.

Step 4: Figure out the sequence of events

Now that your program has a structure, it’s time to determine how to link all the tasks together. The first step is to determine the sequence of events that will be performed. For example, when you get up in the morning, what order do you do the above tasks? It might look like this:

  • Get out of bed
  • Pick out clothes
  • Take a shower
  • Get dressed
  • Prepare breakfast
  • Eat breakfast
  • Brush your teeth
  • Get in your car
  • Drive to work

If we were writing a calculator, we might do things in this order:

  • Get first number from user
  • Get mathematical operation from user
  • Get second number from user
  • Calculate result
  • Print result

This list essentially defines what will go into your main() function:

Or in the case of the calculator:

Note that if you’re going to use this “outline” method for constructing your programs, it’s a good idea to comment each of these out until you actually write them, and then work on them one at a time, testing each as you go. That way the compiler won’t complain about them not being defined.

Step 5: Figure out the data inputs and outputs for each task

Once you have a hierarchy and a sequence of events, the next thing to do is figure out what input data each task needs to operate, and what data it produces as a result (if any). If you already have the input data from a previous step, that input data will become a parameter. If you are calculating output for use by some other function, that output will generally become a return value.

When we are done, we should have prototypes for each function. In case you’ve forgotten, a function prototype is a declaration of a function that includes the function’s name, parameters, and return type, but does not implement the function.

Let’s do a couple examples. getUserInput() is pretty straightforward. We’re going to get a number from the user and return it back to the caller. Thus, the function prototype would look like this:

In the calculator example, the calculateResult() function will need to take 3 pieces of input: Two numbers and a mathematical operator. We should already have all three of these by the time we get to the point where this function is called, so these three pieces of data will be function parameters. The calculateResult() function will calculate the result value, but it does not display the result itself. Consequently, we need to return that result as a return value so that other functions can use it.

Given that, we could write the function prototype like this:

Step 6: Write the task details

In this step, for each task, you will write its actual implementation. If you have broken the tasks down into small enough pieces, each task should be fairly simple and straightforward. If a given task still seems overly-complex, perhaps it needs to be broken down into subtasks that can be more easily implemented.

For example:

Step 7: Connect the data inputs and outputs

Finally, the last step is to connect up the inputs and outputs of each task in whatever way is appropriate. For example, you might send the output of calculateResult() into an input of printResult(), so it can print the calculated answer. This will often involve the use of intermediary variables to temporarily store the result so it can be passed between functions. For example:

This tends to be much more readable than the alternative condensed version that doesn’t use a temporary variable:

This is often the hardest step for new programmers to get the hang of.

A fully completed version of the above calculator sample follows. Note that it uses a few more concepts we haven’t covered yet:

  • if statements let you execute a line of code if a given condition is true
  • the == operator lets you compare two items to see if they are equivalent

You are not expected to understand these at this time (we’ll cover these in more detail later). Focus more on the overall flow of the program, and how data moves between the functions.

Words of advice when writing programs

Keep your programs simple to start. Often new programmers have a grand vision for all the things they want their program to do. “I want to write a role-playing game with graphics and sound and random monsters and dungeons, with a town you can visit to sell the items that you find in the dungeon” If you try to write something too complex to start, you will become overwhelmed and discouraged at your lack of progress. Instead, make your first goal as simple as possible, something that is definitely within your reach. For example, “I want to be able to display a 2d field on the screen”.

Add features over time. Once you have your simple program working and working well, then you can add features to it. For example, once you can display your 2d field, add a character who can walk around. Once you can walk around, add walls that can impede your progress. Once you have walls, build a simple town out of them. Once you have a town, add merchants. By adding each feature incrementally your program will get progressively more complex without overwhelming you in the process.

Focus on one area at a time. Don’t try to code everything at once, and don’t divide your attention across multiple tasks. Focus on one task at a time, and see it through to completion as much as is possible. It is much better to have one fully working task and five that haven’t been started yet than six partially-working tasks. If you split your attention, you are more likely to make mistakes and forget important details.

Test each piece of code as you go. New programmers will often write the entire program in one pass. Then when they compile it for the first time, the compiler reports hundreds of errors. This can not only be intimidating, if your code doesn’t work, it may be hard to figure out why. Instead, write a piece of code, and then compile and test it immediately. If it doesn’t work, you’ll know exactly where the problem is, and it will be easy to fix. Once you are sure that the code works, move to the next piece and repeat. It may take longer to finish writing your code, but when you are done the whole thing should work, and you won’t have to spend twice as long trying to figure out why it doesn’t.

Most new programmers will shortcut many of these steps and suggestions (because it seems like a lot of work and/or it’s not as much fun as writing the code). However, for any non-trivial project, following these steps will definitely save you a lot of time in the long run. A little planning up front saves a lot of debugging at the end.

The good news is that once you become comfortable with all of these concepts, they will start coming naturally to you without even thinking about it. Eventually you will get to the point where you can write entire functions without any pre-planning at all.

1.11 -- Debugging your program (stepping and breakpoints)
Index
1.10a -- Header guards

160 comments to 1.10b — How to design your first programs

  • Milten

    Very well done!
    Btw: Thank you very much for your great tutorial!

  • Freacky

    I think you exchanged the arrows with next/previous steps.
    I think this is a very good and “noob friendly” tutorial too, good job ;).

    [ Thanks for the note about the arrows. Fixed! -Alex ]

  • William Manson

    I tried to make a program that does simple operations, but it doesn’t seem to work.

    The piece in particular:

    The compiler (code::blocks) gives the error, “error: expected ‘;’ before “chOperation”” and “error: expected ‘;’ before “nInput2″”

    I’m trying to make the function return an operation, e.g. 3 + 5 or 4 / 14 or 14 % 8, is this not how I would accomplish this?

    • Deyan

      The “return” function can only return one value at a time. Thus the compiler is expecting to see a ; after nInput1.

      If you really must return more than one value, you may want to try using global variables.

      Good Luck.

    • Alex

      chOperation is a character, not an operator, and there’s no way to directly convert one to the other.

      You’ll have to use “if” statements to convert each value of chOperator into the respective operator (if chOperator is the ‘+’ character, then do the plus operation)

  • tartan

    Thank you very much for this tutorial. Seems to be the best online cpp tutorial so far, and I find this part and your comments on coding style of as great importance as explanation of commands, functions etc.

  • Lawrence G

    Fantastic guide, I have been trying to write this carrot report for months; your simple breakdown made it possible.

    • Merv

      Haha me too! Not just those pesky carrot reports, getting dressed and ready for work was a real challenge for me, but now I have this amazing tutorial at hand.

  • User1

    I recently decided to teach myself C++ because I would like to get into game programming and well I am glad I found this wonderful tutorial. I understand it will take time and am willing to do give time, but I’m curious if I will be able to make a 2D World (as stated in this article) soon seeing as I am on Chapter 2 at the moment and am a bit confused how to put graphics to program.

    • kurt

      Putting graphics into a program usually uses separate libraries that incorporate c++ to teach the graphics to react/act to one another.
      It is a lot to understand if you want to make games with c++, I am taking a Game Design + Development course and c++ is more used for larger scale games that require a team to implement it.

      If you want to create indie games (games created by you, yourself) you may want to start coding with another program like Flash AS3 (ActionScript) or java.

      This is a really good tutorial on c++ though from all the online / book instructions I have come across (which is a lot) and c++ is really important to know on any coding scale. I would recommend googling graphics programming and see what comes up. Check out DirectX or SDL which are c++ graphic related libraries and there are probably more, those are the only two I know about and somewhat know how to use. DirectX is a very LARGE library though and can be kind of overwhelming. OpenGL is another graphics related one, but I am not sure if it uses windows programming (which is still c++ the libraries are just different)

      Correct me if I am wrong anybody, open to any critiscm.

      Thanks for the great tutorial!

  • armian

    Thank you a lot for this magical tutorial!!!

    I have a question:”How can I compile my program if I haven’t finished it yet?”
    When i compile to see if i have any error till here,my Bloodshed Dev-C++ “says” that i have too many mistakes!

    Thanks a lot again!

    • Alex

      Ideally, you should never end up in this situation -- if you write one piece at a time, and test it, you should never have a ton of code that won’t compile, or more than a few errors.

      But if you do end up in this case, one thing that can be helpful is to comment out as much code as necessary until your program compiles. Then you can start uncommenting things (in an order that makes sense) and fixing errors along the way.

  • Johnny

    Amazingly simple -- awesome work -- thanks!! You definitely used KISS (keep it simple stupid) LOL Again, thanks!!

  • Eric

    I must say, I absolutely love your tutorials!
    It’s extremely easy to understand, and is fun too!

    I’ve been doing programming for several years now.
    So far, I know the following: HTML, CSS, JS, PHP, VB.Net & GML.

    I wanted to expand my coding knowledge, and begin writing PC games in C++.
    Sadly, I wasn’t able to find any good, full tutorials.

    That is.. Until I found yours!

    Your tutorials are the best on the web, and I thank you for that!

    Thanks,

    Eric

  • Phil

    Hey!
    I have read through all the stuff before it now, and i think this is an ideal moment to say thanks for these amazing guides! I just wrote my first program all myself, (basic but it makes me look clever to my friends ;)), it basiclly just adds to numbers together, find multiples, although i did manage to use a IF thingy, (i looked at the later chapter). So YEAH! Just shows how well you have wrote your guides 🙂

    Thanks sooo much
    I’m gonna be reading all of this no matter what so watch out for more of my posts.

    ~Phil

  • Leo

    Usually in tutorials they talk about the language, and not about this kind of stuff. This is awesome!

  • jlovejoy

    This is my second time reading through this chapter and one particular issue that caught my eye is that in section 0.1, you say “We will also avoid the twin evils…and the unexplained new concept, where a new concept that is integral to the example is introduced without any mention of what it is or how it works…”

    However, in section 1.10a, you use the command “char” without having ever introduced it, or its function anywhere in the tutorial. I was able to eventually pick up on what it did, but still very confusing for first time programmers.

    • Alex

      Guilty as charged.

      I find myself in a tough position here. In order to really make the point of this lesson stick, it’s necessary to use a non-trivial example. But I couldn’t think of a non-trivial example that didn’t use at least one concept I haven’t introduced yet.

      I’ve updated the example to remove the use of “char”, but the user of “if” and operator== still remain. I’ve added a little bit of additional description around these to hopefully make it easier for readers to understand what they are doing.

  • Lakshya

    very nice tutorial

  • Maksism

    Finally got it

    • Cleverlegs

      Very nice, but remember that you don’t need two different functions to get numbers. i.e
      GetNumber1() and GetNumber2() can be replaced with GetNumber(). Since they’re doing the exact same thing

  • Need some help with the calculator code. I wrote it and compiled it. It worked, with small numbers and adding/subtracting. I used it in my other program but when I got someone to test it they used big numbers. It works but gives wrong answer. And if it’s a really big number then it just shows the 3 outputs at the same time, asking for operator, new number and result, in the same row and gives result as 0.
    This is what happens:
    Please enter a number: 586565730854226435643
    Please enter an operator (+,-,*,/): Please enter a number: Your result is: 0
    I can’t work out where I went wrong.

    • artxworks

      “int” has limits … try using “double”

      int = signed: -2147483648 to 2147483647
      unsigned: 0 to 4294967295

      double = +/- 1.7e +/- 308 (~15 digits)

  • Ollie999

    Great tutorials thanks and some good advice in this section.

    I would just like to point out that it’s not only new programmers who make the mistake of not bothering with any pre-planning before they start coding. I’ve worked in software development for many years and quite a high proportion of the experienced developers I work with repeatedly make this mistake on every project and then wonder why they spend most of their working life debugging their code. I would urge anyone new to programming to heed the advice here and put some time into planning out programs in some detail before you start coding. This will avoid a lot of debugging and I can confirm from experience that debugging badly written code is probably the most mind-numbingly tedious activity I’ve ever come across.

  • artxworks

    So in this example I can actually ask the user to give me 3 numbers by using only 1 “int getNumber()” function …. then call it whenever I want a new user input by changing the variable ….

    int user1 = getNumber();
    int user2 = getNumber();
    int user3 = getNumber();

    etc …

    then just tweak the corresponding equations in the calculate and result functions ….. that’s nice ….. wow I just started yesterday and I’m getting really hooked on C++ …. well, your way of explaining things is really easy to understand …. thanks Alex.

  • DDrum

    I think the arrows to the links to next or previous chapter are switched. I displays an arrow to the left for the next chapter and an arrow to the right for the previous chapter.

    Great tutorial by the way.

  • Hi,

    everything is great. But at the very end the redirection arrows are wrong =P

    Not that it's so important but… it's harmless to fix it.

    Regards,
    Matthew

  • Jay

    Hey, I just wanted to say thanks for this awesome tutorial, I hope that once you reach a point where you are satisfied. That you publish this work in book. I've read many books on C++, but none have had this level of clarity to them. You're doing great work.

  • Twisted Code

    "
    That’s a more manageable, as we now have three tasks that we can focus on individually. However, in this case, “Do research on carrots is somewhat vague”, so we can break it down further:
    "
    i don’t think this is formatted properly…

  • Sandro

    Help plez. It sais that in main, that CalculateResult is no matching operator.

    Using c++ xCode

    • Alex

      On line 26, you have:

      Note that this function takes no parameters.

      On line 57, you have:

      Note that you’re trying to pass 3 parameters to this function.

      Consequently, there’s a mismatch between the function definition and the function call.

      Your function call to CalculateResult() is correct. Your definition of CalculateResult() needs some work. 🙂

  • Scott Matejka

    Hi Alex,

    I’m really having trouble with the user friendliness of the IDEs.  I’m currently trying to use visual studio.  And I get a Fatal Error C1083 for #include "stdafx.h".

    I’m opening a new empty project in C++.

    Do I need to download that directory from somewhere?
    What am I doing wrong?

  • Alex

    Error C1083 means the file can’t be found.

    I suspect your main.cpp has a line that looks like this:

    But stdafx.h hasn’t been included as part of your project.

    Two suggestions:
    1) Make sure your project is a Win32 console application instead of an empty project
    2) You can create stdafx.h if it doesn’t exist and add it to your project. The file can be empty, so long as it exists.

    • Scott Matejka

      I think visual studio is too advanced. The functions and even tabs are quite intimidating.

      As a win32 console application it loads a wall of text that is Greek to me so far.  I can’t get a grip on where to insert anything and its possible interactions with the stuff they already have up.

      Is there an IDE for newbies/idiots?

      • Tito

        I am using Eclipse IDE and find it simple enough.

      • David

        I use Code::Blocks and yeah, its very easy to use.

      • Alex

        Personally I found Visual Studio easier to use than Eclipse or Code::Blocks. It does have a lot of complexity, but you’ll learn to ignore most of it, as it’s not relevant. Visual Studio has a fantastic integrated debugger as well.

        Since you’re finding Visual Studio complicated, you could try Code::Blocks or Eclipse, but I suspect you won’t find them too much different.

    • obwan02

      on my visual studio it uses

      #include "stdafx.h"

      intead of <stdafx.h> maybe that might make a difference

  • David

    Okay so I made a programm that is suposed to convert usd to euros or euros to usd. But I cant get it to work. Despiting my input, it always converts dollars to euros. What did go wrong?

    #include <iostream>
    #include <string>
    using namespace std;
    int getEur()
    {
    int x;
    cout << "Enter ammount of euros to convert";
    cin >> x;
    return x; // x is the euros ( if wanted ) the user typed in.
    }

    int getUsd()
    {
    int y;
    cout << "Enter ammount of dollars to convert";
    cin >> y;
    return y; // y is the dollars ( if wanted ) the user typed in.
    }

    int convertEU()
    {
    int a = getEur(); // attempt to get euros
    return (a * 1.08735); //conversion to dollars
    }

    int convertUE()
    {
    int b = getUsd(); // attempt to get dollars
    return (b * 0.91966); // conversion to euros
    }

    int choose()
    {
    cout << "Type the currency your value uses. (usd / eur)";
    string input;
    cin >> input; // read the users’ currrent currency.
    int x = 1;
    int y = 2;
    if (input == "usd") { // return x if it are dollars
    return x;
    }
    else if (input == "eur") // return y if it are euros
    return y;
    }

    int main()
    {
    int a = choose();
    if (a = 1) { // convert usd to euros if chooses’ returning was 1
        cout << "The entered value equals: " << convertUE() << "euros" << endl;
    }
    else if (a = 2) { // convert euros to usd if chooses’ returning was 2
    cout << "The entered value equals: " << convertEU() << "usd" << endl;
    }
    }
    I didnt know who to ask or where to put it and I hope you can help me lol.

  • Jeremy

    OK so I found another typo in "Step 2" - there’s a period missing after the bulleted sentence:

  • Joeri Vanden Abeele

    Hello. Can you explain this pleace?  How does the program links the nInput1 and the nInput2 to the nX and nY? You tell him to return nX nOperator and nY, to the main.

    • Alex

      When CalculateResult() is called, the value of nInput1 is copied into parameter nX, the value of nOperator is copied into parameter nOperator, and the value of nInput2 is copied into parameter nY.

      The function code determines which value is returned to the caller. This return value is then assigned to variable nResult.

  • crelm

    Hi. I was just wondering if there was any way to create an error message for the calculator, as from what I can understand it will only return -1 if you input a number greater than 4.

    • Alex

      In this program, not really. The problem here is that -1 could be an error value or a legitimate value, and there’s no way to tell the difference.

      There are many ways to fix this problem. One of the easiest would be to write a validateOperator() function that returns true if operator is valid and false otherwise. Then you could do something like this:

  • Todd

    Another quick grammatical fix (user ‘Twisted Code’ alluded to this):

    "That’s a more manageable….However, in this case, ‘Do research on carrots is somewhat vague’…"

    should be

    "That’s more manageable….However, in this case, ‘Do research on carrots’ is somewhat vague…"

    (remove ‘a’ before ‘more’ and end quotes after ‘carrots’ not ‘vague’)

    Thanks for hearing feedback!

  • Todd

    Sorry for being a pain in the butt, but here’s another grammatical error:

    "This will often involve the use of intermediary variables to temporary store the result"

    should be

    "This will often involve the use of intermediary variables to temporarily store the result"

    (change ‘temporary’ to ‘temporarily’)

    In the future, I’ll be sure to consolidate my responses into one comment.

  • cpplx

    in main() 2 variables are named input1 and input2.
    in calculateResult() they are named x and y.
    is it me that do not understand or you made an oversight?

    if (op == 1)
    are the () a part of the c++ syntax? ive used python before and seems odd to me
    also I wonder what if = is used instead of ==, but I might test that myself someday. probably it will result in an error since the operators do different things.

    • Alex

      It’s okay for function parameters to have different names than the variables being passed in. In the example above, x will be assigned the value from input1, and y will be assigned the value from input2.

      With if statements, the parenthesis are part of the syntax.

      If you use = instead of ==, you’ll do an assignment instead of a comparison.

  • Youssef abdelrahman

    Hello, when i compile the program it gives me  "fatal error LNK1120: 1 unresolved externals" and "error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup" . Can anyone please tell me how to solve this error ?

    • Alex

      It sounds like you don’t have a function named “main” in your program. If you have a function named _tmain or anything like that, replace it with int main().

  • Rand

    I was wondering if there was any way to make this any more efficient? Or smaller?

    • Alex

      Yes, anywhere you have redundancy, there’s probably a way to get rid of it. I’d move:

      Before the if/else statements.

  • BobZ

    Hi, Alex:

    I am stuck; this time on your "Step 6: Write the task details"

    In your example, it seems to me that we are returning -1 regardless.  How are we limiting that to only when the user enters an invalid character?
    +++++++++++++++++++++++++++++++++++++++++++++++++++
    My idea for a program is to make a countdown timer.  I could really use it!  Probably too difficult just now with my present (lack of) skill set.

    Thanks again for your help.

  • Justice

    Hey Alex, Visual Studio is giving me a Link2019 error about unresolved external errors, but if I change void printResult() to int printResult() it compiles with no errors.

    Is this a bad way to do it, or is this fine?

    • Alex

      printResult() doesn’t return anything, so it should have a return type of void. Do you have printResult() declared more than once in your program?

  • Ashley

    Hey Alex,

    I had the same getUserInput(), getMathematicalOperation(), and calculateResult() functions as you, but in the main function, instead of assigning each variable the result from each function and then calling the calculateResult() function using those variables as arguments, I did this:

    cout << calculateResult(getUserInput(), getMathematicalOperation(),getUserInput()) << endl;

    but this messed up the answers for subtraction and division. It flipped the answer so instead of 100-20=80, it gave me -80 and instead of 32/16=2, it gave me 0. Then I tried what you did and that worked fine. I don’t understand why calling the functions as arguments doesn’t work. I thought the values returned from the functions would serve as arguments for the calculateResult() function which would copy over into the calculateResult() function’s parameters in order.

    • Alex

      It sounds like you’re presuming the function arguments will be evaluated from left to right, but it turns out that C++ doesn’t specify whether function argument should be evaluated left to right or right to left. Yours appear to be going right to left.

      Consequently, the first number the user enters is becoming the third parameter, not the first. And the second number is becoming the first parameter, not the third. So instead of 100 - 20, you’re getting 20 - 100. And instead of 32 / 16, you’re getting 16 / 32 (which is 0.5, which gets truncated to 0 because we’re dealing with integers here).

      In short, calling getUserInput() twice in sequence before calling calculateResult() guarantees a particular ordering. Using getUserInput() as arguments does not.

      I applaud your creativity and understanding of inputs and outputs. You just happened to run into one of C++’s quirks.

  • Matthew

    So I have the code pretty much how you have it above, yet when I enter integers and operators, it always does addition no matter my choice.  I’ve tried writing via Vim and compiling via command line using g++ and via Code::Blocks (I know it uses the same compiler…), and it happens in VS15 Community.

    My code is:

    • Matthew

      Cleaned my code a bit, same problem:

    • Matthew

      Oddly enough, this works fine:

    • Alex

      You have a wayward semicolon after your first if statement. This is the equivalent of writing:

      Which always returns x + y.

  • Joao Lopes

    Can you tell me what you think about this code.

  • Joao Lopes

    Did some research about repeating functions etc and got this made I think its good imo.
    Can tell me what you think about it sry for spamming I got very interested in c++ programming, and I dont carry on until I try almost everything that comes to my mind. xD

    • Alex

      Did you test what happens with this program if you enter a number greater than 5?

      For what it’s worth, recursion (having a function call itself) usually isn’t the best way to do a loop. C++ has loop structures (covered in chapter 5) for this. We haven’t covered them yet, so glad to see you exploring.

  • Joseph

    Hey I believe I screwed something up in codeblocks and this is rather trivial. But when I start a new project no files come up…the part of the screen where code is written has nothing in it and when I create a new file I am asked to name it and there is a file named main already there. So I decided to start from the beginning, created a new project, and opened main directly from there. I copy and pasted code to check and when built and ran I get the hello world program.
    I also get that I have main() defined more than once in multifile projects….any suggestions?

    • Alex

      You can only have one main() function per project. That means if you want to change programs, you either need to overwrite your current main(), or you need to create a new project.

  • Daniel

    Hi,

    The results of a division are rarely an integer … so I tried to change the output to a ‘float’

    calculateResults.cpp

    my math.h

    main.cpp

    The (constant) variable ‘testDecimal’ outputs as a float but calculation results doesn’t.

    What am I doing wrong?

  • Great advice and tips, Thank You 🙂

  • Alex (Sp)

    So I decided to add a do while loop to your getMathematicalOperation function to check for the correct value. I noticed that I forgot to add the return statement at the end of the function, yet everything works? I don’t understand.

    Using this function in the program with the return statement commented out the program still compiles and executes correctly. How are my other functions able to use the "op" that is defined in main?

    • Devashish

      “Executes Correctly?” It will compile because it’s okay if a non-void function omits return statement, but if the caller works with the data returned by the function, it will always produce unexpected results. When I run your program, it gives -1 as result.

      • Alex (Sp)

        Yeah it’s weird I don’t get it. I just compiled and ran it again and it always works correctly for me even with that return commented out. Every time.

        Full program:

        Doesn’t make any sense that I always get the correct calculation.

        • Alex

          A function with a non-void return value that does not have a return statement is invalid syntax, and should not even compile. The fact that your compiler is not flagging this as an error is worrying. What compiler are you using?

          With Visual Studio, I get this error upon compilation:

          error C4716: 'getMathematicalOperation': must return a value
          

          (Note: some compilers do allow you to omit a return type for main -- this isn’t officially allowed by C++ but some compilers do it anyway. This does not extend to other non-main functions).

          It’s unclear to me whether your compiler is ignoring the comment in this case, or whether it’s just working coincidentally due to the way the compiler is setting up function call.

  • Amin

    In the name of God
    Hi, Very thanks of You and your time and kindness .
    and thanks for sharing your information, Studies, Lessons, Experiences and all of other things .
    God Bless You,
    Hope to God

  • Anthony

    Hey I started this last night, I have to say, it’s been great so far.  I’m writing this now because instead of following what you put on there, I decided to use multiple pages for the calculator.  I ended up running into an issue I never figured out how to fix, and that was having a void on a separate page for the printResult.  I found a solution, but it really didn’t appease what I was trying to do.

    Fix : move the void function onto main.cpp and delete printResult.cpp

    So I’m asking for future projects, is it possible to have a void on a separate page?  Is it bad practice?

    For reference : I made one page per function, honestly to try and create errors that I could try to troubleshoot rather then follow the code given to me.  It was a random thought because I’m a hands on learner and I figured troubleshooting issues would help me significantly in the long run because I could grasp what errors occur at what stages.

  • Morgan

    Nevermind I spent last night fixing it and making it shine.

  • Alex

    I’m not sure about the text. Sounds like ghosts. 🙂

    As for your use of comments, I think they’re still too vague. What does “// First Number” mean? Is it asking the user? Reading it from disk? “Get first number from user” would be more insightful. The error message case is clearly an error message, so it doesn’t need a comment.

    Also, for what it’s worth, you generally won’t want main() to call main(). In this case, if you first input is -54321 and then your second input is valid, I think your program will not operate as expected in terms of printing the result.

  • Akanksha

    thank you..after a long time found such a useful tutorial

  • Pierre

    I feel that there is something to be said about version control. Emailing source code around isn’t bet practice, keeping it in version control is much better. No need to dive too deep in the explanations (there are tons of very good tutorials about git for instance) but mentioning that it is much more preferable to emailing files around or copying directories would make sense IMHO.

    Thanks for the details about top down and bottom up, it’s throughly explained.

  • Chuck

    This might be very confusing, but would it result in more optimized code?

    • Alex

      Possibly, depending on whether your compiler optimizes it well or not. But you should generally be writing your programs for understandability, not for performance. You can always optimize later, if you need to (most of the time, you won’t).

  • Karl

    can you please tell why we used void here…can’t we simply print the value using cout in main?

    • Alex

      The function returns void because it does not pass a value back to the caller. It just does a job (prints the string) and returns.

      We could have printed the value in main, but using a function is often better because it’s easier to debug, modify, and call multiple times.

  • Nyap

    Designing your program and organising the code into multiple files seems pretty boring to me

    • Alex

      It is, which is why many people skip it. This can lead to poorly structured code, and a lot of rework down the line.

      The good news is that you eventually get good at it, so it becomes second nature.

  • Liam

    Please help, VS2015C is telling me that the identifier “result” is undefined when I try and use it in main.

    • Alex

      Variable result does not exist in the scope of function main. The parameter result that you’ve defined in function printResult() only exists within function printResult() -- main can not access it directly.

      In function main, result should probably be calcResult.

  • Cameron

    Hi Alex, first up this is a fantastic tutorial, really like the way you explain the reasoning behind doing things. I’ve put together code for this calculator and my multiplication/division tasks give me addition/subtraction respectively. Tried stepping ahead and having a crack at debugging it and couldn’t figure it out. Can you tell me where I’ve gone wrong? (Note - originally it was in separate files with a header file, but it compiled fine that way and when I copied it all into one file I had the same problem. Thanks in advance.

    I can’t figure out how to tag my code sorry, not a great sign I guess.

  • Weird question that requires setup:

    It’s interesting to note that if you collapse the main() into one line the program will still run despite using the same function call twice without storing the variables.

    It will however ask you for the inputs from right to left (the function call in the y argument slot of calculateResult(x,op,y) is called 1st, then op then x).

    Question:
    How/where does it implicitly store the values for these function calls if I haven’t explicitly assigned a memory location for them via a definition statement ( int variable = function(); )?

    Minor question:
    How do I make pasted code look all pretty with the line numbers and formatting i see in other posts?

    • Never mind that is probably a compiler specific question (Visual Studio 2015).

      Also the minor question got answered when the edit clock ran out and the code displayed correctly.

      Sorry to bother, Thanks for reading anyway.

    • Alex

      The order in which function parameters are evaluated is undefined. It could be left to right, or right to left.

      If you use the return value from one function directly as an argument for another function, the compiler will create a anonymous (unnamed) variable for you to facilitate the handoff.

      It looks like you figured out the code formatting already.

  • Brent

    When I use the example calculator program in the tutorial, when I enter the second number it prints the answer and closes really fast.
    This only happens when I use the .exe file, when I ctrl+F5 in Microsoft Visual Basic 2015 it prints ‘Press Enter to continue . . .’.
    What is going wrong and where does it get the ‘Press enter to continue . . .’?

    • Alex

      The IDE is pausing your console application at the end, so you can see any output before the console window closes. I show a method to do your own pausing in lesson 0.7.

  • strong

    in this program :
    main.cpp :

    readInt.cpp :

    readInt.h :

    and the rest of files like this , why I get an error :
    ||=== Build: Debug in practice 3 (compiler: GNU GCC Compiler) ===|
    /home/strong/Documents/C++/practice 3/readInt.cpp||In function ‘int readInt()’:|
    /home/strong/Documents/C++/practice 3/readInt.cpp|3|error: ‘cout’ was not declared in this scope|
    /home/strong/Documents/C++/practice 3/readInt.cpp|5|error: ‘cin’ was not declared in this scope|
    ||=== Build failed: 2 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

    • A1R

      You should

      within any files using commands from the iostream library.

      Also make sure you add

      to the top of readInt.cpp since you’re just using cout.
      (I believe this can be done outside of the function?)

  • A1R

    Say i wanted to print an error message when the user inserted an invalid number for operator 5 or 6 etc..
    How would i go about it?

    I don’t want to return a number because that one time a number is the same as the return value it’ll say the syntax is invalid.

    • Alex

      This is a slightly more advanced topic, as the techniques used to do this kind of thing involve additional knowledge that the tutorial hasn’t covered yet (so this topic is covered in future tutorials). But to enumerate some possibilities:
      * Have your function return a bool indicating success, and return the calculated value as a reference parameter.
      * Assert out if the user passes in an invalid operation
      * Throw an exception if the user passes in an invalid operation

      Don’t worry if the above doesn’t make sense yet -- we’ll cover all these things in time.

  • gurparkash

    My code is this. And the problem is that it first asks me "Enter another integer" and the asks me "enter an integer." What’s the problem here?

    • Alex

      C++ does not define the order in which function arguments are processed -- it could be left to right or right to left. In your case, it looks like it’s right to left, so value2() is getting evaluated before value1().

      • gurparkash

        Is there any way to correct this, other than to of course interchange their places? And is my program fine? Please tell me what improvements can be made.

  • Alex

    You shouldn’t interchange their places, because other machines may use a different order of evaluation than yours.

    The right way to fix this is to explicitly define the order in which these are called:

    This way, the ordering is explicit and unambiguous.

  • Andrew

    "That’s more manageable, as we now have subtasks that we can focus on individually. However, in this case, “Do research on carrots is somewhat vague”, so we can break it down further:"

    The fragment is from Step 3 and contains a typo. Should be:

    "That’s more manageable, as we now have subtasks that we can focus on individually. However, in this case, “Do research on carrots” is somewhat vague, so we can break it down further:"

    P.S. Thanks for the tutorial! So far so great.

  • Tristan Gybels

    Does someone know why this code doesn’t wanna work?

    • Alex

      Two things look wrong:

  • Tristan Gybels

    Read The comment on line 9

    Can someone help me how to do that? without adding a second GetValue?

    • Alex

      The easiest way right now is to create a getFirstValue() function and a getSecondValue() function, and change how they prompt the user.

      The other option is to pass in a boolean parameter indicating whether this is the first or second call, and use if statements to determine what to print based on the value that parameter has. But we haven’t covered booleans or if statements at this point in the tutorial.

  • Priyanga

    Thanks a lot! This is very helpful and a rich tutorial and has helped me a lot. And it will for a lot of people!

  • Josh

    Hello, I exactly copied the code you made here. I’m using visual studio 2015 version 14 update 3.

    Thank you for the informative tutorial. But I’m missing something. It doesn’t want to show the result on my screen.

    I noticed I don’t have stdafx.h and when I #include it, it always gives an error. So I included an empty file instead.

    I want to print the result, I want to se it in the screen but it won’t show. I can encode the numbers fine, but after the 2nd number, it just disappears. I tried to use Maksism’s code above and it prints until it gives me the result, but mine doesn’t. Please help.

    My code is:

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

    using namespace std;

    int getUserInput() //ask input from user
    {
        cout << "Please enter an integer ";
        int input;
        cin >> input;
        return input;
    }

    int getMathematicalOperation() //equate integer to operator
    {
        cout << "Please select 1= +, 2= -, 3= *, 4= / ";

        int op;
        cin >> op;
        return op;
    }

    int calculateResult(int x, int op, int y)
    {
        if (op == 1);  // if user chose #1
        return x + y;

        if (op == 2);  // if user chose #2
        return x - y;

        if (op == 3);  // if user chose #3
        return x * y;

        if (op == 4);  // if user chose #4
        return x / y;

        return -1;  // default "error" value in case user passed in an invalid op
    }

    void printResult(int result)
    {
        cout << "Your result is " << calculateResult << endl;
    }
    int main()
    {
        // Get first number from user
        int x = getUserInput();

        // Get mathematical operation from user
        int op = getMathematicalOperation();

        // Get second number from user
        int y = getUserInput();

        // Calculate result
        int result = calculateResult(x, op, y);
        cout << "The result is " << result << endl;

        // Print result
        printResult(result);

        return 0;
    }

    • Alex

      It sounds like your IDE is closing the console window at the end of the program, so you can’t see the output. I show a solution to this in lesson 0.7.

  • Matthieu B.

    You forgot "Get dressed" in the organized list in step 3, which is terribly unimportant for the understanding of the rest of this tutorial.

  • Josh

    Ok, so I copied maksim’s end code from the cin.clear to cin.get. I can see the result now but my result looks like a color code instead of an integer. a 1+1 equation gives me 0093146A. Why does it do this? Please help…

    I’m using visual studio version 14 update 3. stdafx.h is not available and I included a blank header as suggested. but even if I delete #include stdafx.h it still compiles and runs but with the same equation.

    • Alex

      Because printResult() is printing calculateResult instead of result. calculateResult is a function, not a variable, so it’s printing the address in memory that function calculateResult lives at.

    • Lyle

      You have errant statement terminators ";" at the end of each of your "if (…)" statements in your calculateResult function.
      They should look like this:

  • Satwant

    Above example using header file :XD~

    //howToWriteaProgramEg.cpp

  • Ahmed Gurie

    I have no enough words to thank you Alex, you are great

  • Obi Wan

    I simply just made it all into one function in my 2nd .cpp file. Is there any drawbacks from doing it this way? Also, I’m struggling with understanding the usage of header files and using prototypes and etc! But great tutorial nonetheless, I’m just slow! Lol. Anyway here is the code I function I made on my 2nd cpp.

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

    int add(int x, int y)
    {
        return x + y;
    }

    int getUserInput()
    {
        std::cout << "Input a number here" << std::endl;
        int a = 0;
        std::cin >> a;
        std::cout << "Next number is" << std::endl;
        int b = 0;
        std::cin >> b;
        std::cout << "Last, pick an operator. 1 = +, 2 = -, 3 = *, 4 = /" << std::endl;
        int c = 0;
        std::cin >> c;
            if(c == 1)
                {
                std::cout << a + b << std::endl;
                return a + b;
                }
             if(c == 2)
                {
                std::cout << a - b << std::endl;
                return a - b;
                }
             if(c == 3)
                {
                std::cout << a * b << std::endl;
                return a * b;
                }
            if (c == 4)
                {
                std::cout << a / b << std::endl;
                return a / b;
                }
    }

    • Alex

      The main drawbacks are:
      * Your function is longer and more complicated than it needs to be.
      * Your function doesn’t have any reusable parts (if you wanted the user to enter a number for some other reason, you’d have to duplicate code or refactor your original function).
      * You’re not practicing good function composition, which is helpful later when we get into more complicated examples.

      None of these are critical issues, more like warnings. 🙂

  • Arjun Srivastav

    Hello. Thank you for these tutorials. You mentioned for beginners to write a small portion and debug, continuously until the end. When I compile and then edit my program, my IDE Code::Blocks does not allow it to be compiled. Why is that so?

    • Alex

      I have no idea. You can compile your program once, but then when you modify the program, you can’t compile it again? Is it giving you any error messages?

  • Arjun Srivastav

    Hi Alex. I am trying to write a compound interest calculator. The problem is : it is not compiling. what may be the problem. Here is the code:

    • Alex

      Your compiler should be telling you exactly what’s wrong.

      But in short:
      1) Your main function is missing a parameter list
      2) You’re using << endl with cin, which doesn't work.

  • Rahul

    Hey Alex,
    1.Why program execution start from ‘main()’ function only?
    2. How Operating System come to know that to start program execution from ‘main()’ function ?
    3. Can we change name of ‘main()’ function?

    • Alex

      1) Because the C++ specification says so.
      2) When the linker builds your executable, it does so in a way that causes the contents of main() to be the starting point for execution.
      3) No.

  • Clark

    Amazing job so far, thank you so much Alex

  • Ayush Sharma

    whats the full name of the language on which the code would run???
    i mean,c++(gcc4.3.2) or c++(gcc4.9.2)??

    • Alex

      I don’t understand the question. gcc4.3.2 and gcc4.9.2 are just different versions of the GCC compiler that is used to compile your code into an executable that can be run. Newer is generally better, as newer compilers have bug fixes and support newer features introduced in C++11/14.

      • Ayush Sharma

        Thanks for the reply.
        i recently started coding on codechef and when i tried to submit my code
        i saw that there were a lot of options for c++. I was confused on which to choose. I thought they were different versions of c++ and had different syntax.
        this was the best place i could seek help…..
        Great work.
        THANKS.

  • Leander

    One might think that these things come naturally to mind when designing a program as a novice, but if you don’t break down a task properly it just seems impossible to do or to overwhelming, like you’re staring at a brick wall. Good read thanks.

  • My dear c++ Teacher,
    Please let me comment that in "Step 1: Define the problem" sentence: "I want to write a phone book application to help me keep track of my friend’s phone numbers." you mean "friends’s".
    Also in next sentence by “dungeon” you mean “zork”. I found at http://www.dictionary.com/browse/zork
    Also that I write programs just for learn c++!
    With regards and friendship.

    • Alex

      “friends’s” isn’t correct grammar -- it should be “friends'” (possessive of a plural that ends in s means apostrophe goes after the s). I’ve updated the article.
      I do mean dungeon (in the general sense) -- Zork is a specific game, which is not what I am referring to.

  • My dear c++ Teacher,
    Please let me say that
    https://www.codechef.com/ide and
    http://coliru.stacked-crooked.com/
    output:
    Please enter an integer: Please enter which operator you want (1 = +, 2 = -, 3 = *, 4 = /): Please enter an integer: Your result is: -1
    It seems they do not execute "cin".
    However http://cpp.sh/ executes program fine.
    Also let me a question:
    How can I change op values from numbers (1, 2, 3, 4) to symbols +, -, *, /. I changed op’s type from “int” to “char” and http://cpp.sh/ outputs:
    Please enter an integer: 9
    Please enter which operator you want (1 = +, 2 = -, 3 = *, 4 = /): 3
    Please enter an integer: 2
    Your result is: -1
    Instead of “Your result is: 18”. Number -1 is just the return value.
    I think numbers are characters too.
    With regards and friendship
    Georges Theodosiou

    • Alex

      In chapter 2, I talk about “char” in more detail and how to use it. You’ll need to understand the char data type, char literals (e.g. ‘+’), and ASCII values to proceed.

  • My dear c++ Teacher,
    Please let me say that I changed, for simplification, in line 51: "input1" to "x", in line 57: "input2" to "y", and in line 60 did the same. Program runs fine.
    What is the reason for you use "input1" and "input2"?
    With regards and friendship.

  • My dear c++ Teacher,
    Please let me be meticulous saying that at Step 5, last paragraph, last sentence, you state:
    "Consequently, we need to return that result as a return value so that other functions can use it."
    As long I understand you use this return value in one function only, namely printResult(result).
    Do you mean "another function"?
    With regards and friendship.

    • Alex

      No, I’m not thinking in terms of a single function call here, I’m thinking in terms of the fact that the function could be called multiple times, by different callers.

      Also, although a given return value is passed back to the caller, that caller may pass that value back to it’s caller, or as an argument to a different function. In this way, a single return value can be passed along to functions other than the immediate caller.

  • My dear c++ Teacher,
    Please comment following calculator program:

    With regards and friendship.

    • Alex

      A few minor nitpicks:
      1) It’s weird to split up the operator selection prompt and the operators over two lines.
      2) You should define your variables as close to their first use as possible. For example, result should be defined just before your first if statement.

      Other than that, it looks fine.

  • My dear c++ Teacher,
    Please let me express my gratitude for you commented my program, and ask you: Is it now okay?

    With regards and friendship.

    • Alex

      Yes, though I’d probably additionally space out the top, like this:

      Functionally, it’s the same, but it’s just a little easier to read.

Leave a Comment

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