2.13 — 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 kind of idea, which you’d like to write a program for. 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.

In this lesson, we’ll lay out a generalized approach for converting ideas into simple functional programs.

Design step 1: Define your goal

In order to write a successful program, you first need to define what your goal is. Ideally, you should be able to state this in a sentence or two. It is often useful to express this as a user-facing outcome. For example:

  • Allow the user to organize a list of names and associated phone numbers.
  • Generate randomized dungeons that will produce interesting looking caverns.
  • Generate a list of stock recommendations.
  • Model how long it takes for a ball dropped off a tower to hit the ground.

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!

Design step 2: Define requirements

While defining your problem helps you determine what outcome you want, it’s still vague. The next step is to think about requirements.

Requirements is a fancy word for both the constraints that your solution needs to abide by (e.g. budget, timeline, space, memory, etc…), as well as the capabilities that the program must exhibit in order to meet the users’ needs. Note that your requirements should similarly be focused on the “what”, not the “how”.

For example:

  • Phone numbers should be saved, so they can be recalled later.
  • The randomized dungeon should always contain a way to get from the entrance to an exit.
  • The stock recommendations should leverage historical pricing data.
  • The user should be able to enter the height of the tower.
  • We need a testable version in 7 days.

A single problem may yield many requirements, and the solution isn’t “done” until it satisfies all of them.

Design step 3: 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:

  • 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.
  • 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: Zip it up and 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.

Design step 4: 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 clean our house. Our task hierarchy currently looks like this:

  • Clean the house

Cleaning the entire house is a pretty big task to do in one sitting, so let’s break it into subtasks:

  • Clean the house
    • Vacuum the carpets
    • Clean the bathrooms
    • Clean the kitchen

That’s more manageable, as we now have subtasks that we can focus on individually. However, we can break some of these down even further:

  • Clean the house
    • Vacuum the carpets
    • Clean the bathrooms
      • Scrub the toilet (yuck!)
      • Wash the sink
    • Clean the kitchen
      • Clear the countertops
      • Clean the countertops
      • Scrub the sink
      • Take out the trash

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 cleaning the house.

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 “go 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 cereal
      • Eat cereal
    • 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, “Clean the house” or “Go 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.

Design step 5: 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:

  • Bedroom things
  • Bathroom things
  • Breakfast things
  • Transportation things

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

At this point, we’re ready for implementation.

Implementation step 1: Outlining your main function

Now we’re ready to start implementation. The above sequences can be used to outline your main program. Don’t worry about inputs and outputs for the time being.

Or in the case of the calculator:

Note that if you’re going to use this “outline” method for constructing your programs, your functions won’t compile because the definitions don’t exist yet. Commenting out the function calls until you’re ready to implement the function definitions is one way to address this (and the way we’ll show here). Alternatively, you can stub out your functions (create placeholder functions with empty bodies) so your program will compile.

Implementation step 2: Implement each function

In this step, for each function, you’ll do three things:

  1. Define the function prototype (inputs and outputs)
  2. Write the function
  3. Test the function

If your functions are granular enough, each function should be fairly simple and straightforward. If a given function still seems overly-complex to implement, perhaps it needs to be broken down into subfunctions that can be more easily implemented (or it’s possible you did something in the wrong order, and need to revisit your sequencing of events).

Let’s do the first function from the calculator example:

First, we’ve determined that the getUserInput function takes no arguments, and will return an int value back to the caller. That gets reflected in the function prototype having a return value of int and no parameters. Next, we’ve written the body of the function, which is a straightforward 4 statements. Finally, we’ve implemented some temporary code in function main to test that function getUserInput (including its return value) is working correctly.

We can run this program many times with different input values and make sure that the program is behaving as we expect at this point. If we find something that doesn’t work, we know the problem is in the code we’ve just written. Once we’re convinced the program is working as intended up to this point, we can remove the temporary testing code, and proceed to implementation of the next function (function getMathematicalOperation).

Remember: Don’t implement your entire program in one go. Work on it in steps, testing each step along the way before proceeding.

Implementation step 3: Final testing

Once your program is “finished”, the last step is to test the whole program and ensure it works as intended. If it doesn’t work, fix it.

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 2-dimensional 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 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. It is much better to have one 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.

Don’t invest in perfecting early code. The first draft of a feature (or program) is rarely good. Furthermore, programs tend to evolve over time, as you add capabilities and find better ways to structure things. If you invest too early in polishing your code (adding lots of documentation, full compliance with best practices, making optimizations), you risk losing all of that investment when a code change is necessary. Instead, get your features minimally working and then move on. As you gain confidence in your solutions, apply successive layers of polish. Don’t aim for perfect -- non-trivial programs are never perfect, and there’s always something more that could be done to improve them. Get to good enough and move on.

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 more naturally to you. Eventually you will get to the point where you can write entire functions without any pre-planning at all.

2.x -- Chapter 2 summary and quiz
2.12 -- Header guards

337 comments to 2.13 — How to design your first programs

  • 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.

  • 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.

  • 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?)

  • 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.

  • 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).

    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.

  • 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.

  • 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.

  • 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.

  • 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.

  • 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).

  • 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.

  • Akanksha

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

  • 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.

  • Morgan

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

  • 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.

  • 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

  • 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.

  • Great advice and tips, Thank You :)

  • Daniel


    The results of a division are rarely an integer ... so I tried to change the output to a 'float'


    my math.h


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

    What am I doing wrong?

  • 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.

  • 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.

  • Joao Lopes

    Can you tell me what you think about this code.

  • 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.

  • 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.

  • 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?

  • 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.

  • 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.

  • 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().

  • 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.

  • 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.

Leave a Comment

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