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

344 comments to 2.13 — How to design your first programs

  • Nicolas

    Hello Alex.
    First of all thank you for the great tutorial, as a person with no previous programming knowledge its really helpful so far.
    I made a program that calculates your test score on a scale of 1-10 based on how many points you got on your test (lets say you got 76 out of 120 points on your test and you want to know what score that translates into).  

    When I run the program it prints "What score did you get?" first instead of "What is the maximum score of your test?" I thought it might be because int scoreValue() calls the maximumScore function, so I made scoreValue() a forward declaration and put the function below main() but it still reads "What score did you get?" first. How do I fix this?

    • Alex

      Execution starts at the top of main(). The first thing main() does is call yourScore(), which asks the user "What score did you get?". The second line of main() calls scoreValue(), which calls maximumScore(), which prints "What is the maximum score of your test".

      If you want to change the order of those outputs, flip the first two lines in main().

      • Nicolas

        Thank you for the quick answer!

      • Nicolas

        Another thing I'd like to ask you is, is there any simple way to have my function display non-integer numbers(for example 8.5)? Or do you explain that later on in the tutorial?

        • Alex

          I talk about that in chapter 2, when we discuss floating point numbers.

        • himanshu

          hey you can see my code above

        • himanshu

          #include <iostream>
          using namespace std;
          int getUserInput()
              cout << "Please enter an integer: ";
              float value;
              cin >> value;
              return value;
          int opp()
              cout << "enter operator  1= +,2= -, 3= /, 4= * ";
              int op;
              cin>> op;
              return op;

            float expression( float x,int op, float y)
              return x+y;

              return x-y;

              return x/y;

              return x*y;

              return 8;

          void output( float result)
              cout<< "the result is: "<<result;

          int main()
              int value1=getUserInput();
               int op=opp();
              int value2=getUserInput();

              float result= expression(value1,op,value2);


              return 0;

  • Abbas

    hey Alex.

    when i wanted to write code i made a mistake i used "=" instead of "==" in if (op == 2):  

    compiler worked fine and program was running and i didn't notice that but the result wasn't right until i find the problem, my question is if we make a mistake like this in bigger programs with 100 or 1000 lines of codes how we can find the problem ? compiler said nothing and worked fine. should we check the code line by line ?

    • Alex

      Problems like these can be very hard to find. One approach is to start from a point where you know your values are still good (e.g. right after the user enters input) and then step through your program in the debugger (or set a breakpoint farther downstream) until you notice they're no longer correct. The problem must occur between the last known good and first known bad point. Working this way, you can quickly rule out entire portions of code as the culprit (e.g. if the values are still good at the midpoint of your program, you know the problem must be in the second half of the program, not the first half).

      It takes a bit of practice and experience to get good at it, which is why so many people suck at debugging.

  • MJ

    Hi, could you take a look at my code please? It asks somebody what their level of Dutch is on a scale from 1 -5  and then prints it out on a scale from 1-100. It seems to work but I would be happy with any feedback. Thanks!

  • Dennis

    Consider putting 'Collecting requirements (a documented list of what the program needs to do).' just after
    'Understanding who your target users are and what they want.'
    since it can have an effect on the subsequent activities and usually involves the stakeholders (target users).

  • sam

    oh wow! i made a calculator program that works exactly like that, back in lesson 1.4/1.5 .
    Since then it was my main program, each time i learned a new thing i made some changes to it ( and each time i get unsolvable errors and had to make a new project i recreated the same program! I'm looking at you "Error: C1083"!! ) and now I'm setting here with 5 calculators, 4 aren't working and 1 that does, until now...

    but hey, i did something good/functional out of my head!
    i cant wait to learn how to get text inputs from the user!

    thanks again for the great lessons!

  • Felipe

    That code works fine but is there a way I could've made it better, apart from using switch statements, thanks.

    • Alex

      Instead of having getMathematicalOperation return an integer, it could just return the symbol of the operation. That way you wouldn't need additional code to convert the integer to the operation symbol as part of printResult(). Other than that, and using switch, I can't think of anything else.

  • Skyler

    Would a flash cruiser work for a backup location?

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

  • 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 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 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 say that and
    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 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 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 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
    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.

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

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

  • Clark

    Amazing job so far, thank you so much Alex

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

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

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

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

  • Ahmed Gurie

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

  • Satwant

    Above example using header file :XD~


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

  • 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

    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

        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.

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

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

  • Tristan Gybels

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

    • Alex

      Two things look wrong:

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

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

Leave a Comment

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