Navigation



1.10a — 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 every day 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: leaky roofs, walls that weren’t straight, etc… Similarly, if you try to program before you have a good gameplan 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 design.

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 friend’s phone numbers.
  • I want to write a random dungeon generator that will produce interesting looking caverns.
  • I want to write a program that will take information about stocks and attempt to 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 targets

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

  • Understanding who your target user is
  • 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 should do)

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. This makes things easy, so we won’t spend any time on this step.

Step 3: Make a heirarchy of tasks

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 details about carrots

That’s a more managable, 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:

  • Write report on carrots
    • Do research on carrots
      • Go to library and get book on carrots
      • Look for information about carrots on internet
    • Write outline
      • Information about growing
      • Information about processing
      • Information about nutrition
    • Fill in outline with details about carrots

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
    • 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 item 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 subitems, and have that function call multiple subfunctions that implement those new tasks. 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:

int main()
{
    GetOutOfBed();
    PickOutClothes();
    TakeAShower();
    GetDressed();
    PrepareBreakfast();
    EatBreakfast();
    BrushTeeth();
    GetInCar();
    DriveToWork();
}

Or in the case of the calculator:

int main()
{
    // Get first number from user
    GetUserInput();

    // Get mathematical operation from user
    GetMathematicalOperation();

    // Get second number from user
    GetUserInput();

    // Calculate result
    CalculateResult();

    // Print result
    PrintResult();
}

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

int GetUserInput()

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:

int CalculateResult(int nInput1, char chOperator, int nInput2);

Step 6: Write the task details

In this step, for each task, you will write it’s 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:

char GetMathematicalOperation()
{
    cout << "Please enter an operator (+,-,*,or /): ";

    char chOperation;
    cin >> chOperation;

    // What if the user enters an invalid character?
    // We'll ignore this possibility for now
    return chOperation;
}

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 temporary store the result so it can be passed between functions. For example:

// nResult is a temporary value used to transfer the output of CalculateResult()
// into an input of PrintResult()
int nResult = CalculateResult(nInput1, chOperator, nInput2);
PrintResult(nResult);

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

PrintResult( CalculateResult(nInput1, chOperator, nInput2) );

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

Note: To fully complete this example, you’ll need to utilize if statements, which we won’t cover for a while, but you’re welcome to take a sneak-peak at now.

A fully completed version of the above calculator sample follows (hidden in case you want to take a stab at it yourself first):

Show Solution

Words of advice when writing programs

Keep your program 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 representation of the world 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 world, 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 — Comprehensive quiz
Index
1.10 — A first look at the preprocessor

77 comments to 1.10a — How to design your first programs

    • RobP

      I could use a little help, if anyone is willing/able:

      #include “stdafx.h” // Precompiled header
      #include // Needed for cout, cin, endl
      #include // Needed for sqrt
      #include // Needed for setpecision

      using namespace std; // Standard namespace

      int main()
      {
      // Declare variables. User will set values
      double x, y, hyp, sinRad, sinDeg, cosRad, cosDeg, tanRad, tanDeg, secRad,
      secDeg, cscRad, cscDeg, cotRad, cotDeg;
      const double PI(3.141592653);
      int precision, ch1, ch2, ch3, ch4;

      // User sets the level of precision here
      cout << "Please enter how many digits your answer will display." <> precision;

      // Now the user enters the x and y values of their triangle
      cout << "Please enter the horizontal and vertical length" << endl;
      cout << "as x and y, respectively, separated by a space." <> x >> y;

      // Calculate and print hypotenuse to screen. Definition of hypotenuse is included.
      hyp = sqrt((x*x)+(y*y));
      cout << setprecision(precision) << hyp << " is the hypotenuse. "
      "It is the root of the sum of " << x*x << " + " << y*y << endl << endl;

      // Calculate and print sin, first in Radians, then in degrees
      sinRad = y/hyp;
      cout << sinRad << " is the sine of the triangle (in radians). It is "
      << y << '/' << hyp << endl;
      cout << "Which is the y value divided by the hypotenuse." << endl;
      sinDeg = sinRad*(180.0/PI);
      cout << sinRad << " Radians is " << sinDeg << " degrees." << endl << endl;

      // Calculate and print cos first in Radians, then in degrees
      cosRad = x/hyp;
      cout << cosRad << " is the cosine of the triangle (in radians). It is "
      << x << '/' << hyp << endl;
      cout << "Which is the x value divided by the hypotenuse." << endl;
      cosDeg = (cosRad*180)/PI;
      cout << cosRad << " Radians is " << cosDeg << " degrees." << endl << endl;

      return 0
      }

      …and so on. The basic idea is that the user inputs a horizontal (x) and vertical (y) length, and gets delicious trig function goodness out. The program outputs the correct hypotenuse, and sin/cos/tan in radians, but it doesn't output the correct sin/cos in degrees. When x = y = some double, the angles should be 45 degrees, but I get something along the lines of 40.5 to whatever level of precision specified. Anyone have any idea why this is happening and what I can do to fix it?

      Thanks!

      • Seally

        Looking at the date I’m pretty sure you’ve figured it out by now, but just in case:

        Your error in this case is a reasoning error. sin(x) = opposite/hypotenuse, with x being the angle. Your error started with your assumption that opposite/hypotenuse equals the angle. As stated, angle != sin(angle). In order to find the angle you should use the inverse function, found in ‘cmath’ for C++ and ‘math.h’ for C. The inverse function is asin(double x), where x = sin(x), called mathematically as arc sine. Arc cosine is acos(double x). You can convert things from there.

        Note that arc sine and arc cosine is not definitively an inverse function to sine and cosine if you know what inverse functions are, but that doesn’t matter all that much here.

  • [...] 1.10a — 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:

    int CalculateResult(int nInput1, char chOperation, int nInput2)
    {
        return nInput1 chOperation nInput2;
    }

    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.

  • The Mirror universe episode is on now. ,

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

  • Josh

    Should we be able to make a calculator-like program by this listen? Just curious.

  • Lawrence G

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

  • rami

    hi i have a problem with my code

    #include <cstdlib>
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
           int GetNumber();
    
           char GetOperation();
    
           int GetNumber2();
    
           int CalResult();
    
           int PrintResult();
           return 0;
    }
    
    int GetNumber()
    {
        int x;
        cin >> x;
        return x;
    }
    
    char GetOperation()
    {
         char chOperation;
         cin >> chOperation;
         return chOperation;
    }
    
    int GetNumber2()
    {
        int y;
        cin >> y;
        return y;
    }
    
    int CalResult(int x, char chOperation, int y);
    
    int PrintResult( CalResult(int x char chOperation int y) );
    
    PrintResult(Presult);
    

    here is the following erros
    44 C:\Users\nabeel\main.cpp expected primary-expression before “int”
    46 C:\Users\nabeel\main.cpp expected constructor, destructor, or type conversion before ‘(‘ token
    46 C:\Users\nabeel\main.cpp expected `,’ or `;’ before ‘(‘ token
    C:\Users\nabeel\Makefile.win [Build Error] [main.o] Error 1

  • replax

    you missed the function prototypes at the beginngin and you need to put the last functions inside of int main(). it’s best for you to read on, your problems will be addressed very soon in alex’s superb tutorials!

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

  • Nick

    Hello, I am fairly new to programming and have been finding these tutorials very helpful. Could someone please help me find out what is wrong with my code. Everything compiles fine, but when I run the program the result is for example if I wanted to calculate 1+2 the answer would print 2. The second number always gets printed and not the calculated value.

    #include "stdafx.h"
    #include <iostream>
    
    int GetUserInput();
    char GetMathematicalOperation();
    int CalculateResult(int nInput1, char chOperator, int nInput2);
    void PrintResult(int x);
    using namespace std;
    
    int main()
    {
        // Get first number from user
        int nInput1 = GetUserInput();
    
        // Get mathematical operation from user
        char chOperator = GetMathematicalOperation();
    
        // Get second number from user
        int nInput2 = GetUserInput();
    
        // Calculate result and store into variable nResult
        int nResult = CalculateResult(nInput1, chOperator, nInput2);
    
        // Print result
        PrintResult(nResult);
    
        return 0;
    }
    
    int GetUserInput()
    {
    	int input;
    	cin >> input;
    	return input;
    }
    
    char GetMathematicalOperation()
    {
    	char chOperation;
    	cin >> chOperation;
    	return chOperation;
    }
    
    void PrintResult(int x)
    {
    	cout << x << endl;
    }
    
    int CalculateResult(int nInput1, char chOperator, int nInput2)
    {
    	int x = (nInput1, chOperator, nInput2);
    	return x;
    }
    
  • Gio

    I did not understand one thing in this lesson, but you may have not been mentioning it or be mentioning it later: How do you get keyboard input? So, like, the person can enter their name, press enter, and then the program will print it? If you will explain this later, I am sorry for being impatient.

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

  • Eric

    This began as an attempt to somewhat duplicate the calculator program in the example, one that would read the value, expression, and second value all at the same time. I failed for so long I decided to just try and make a program that would identify what KIND of expression you entered, not even evaluate it. Just for it to say: “You entered an addition equation. ” … and so on for other types of equations. The problem is that no matter what type of equation I enter, whether it is 5 + 5, 5 – 5, 5 * 5, or 5 / 5 I always get a response telling me that I entered a subtraction equation. Any ideas, anyone?

    #include <iostream>
    using namespace std;
    
    long int remainder;
    long int x;
    long int y;
    long int z;
    bool expression; 
    
    int main()
    {
        cout << "Enter an expression to be evaluated: " << endl;
        cin >> expression;
    
        if(expression == true + true) /* i.e. if any integer other than zero is
        entered, followed by a plus sign, then another integer other than zero */
        {
        cout << "You entered an addition equation. " << endl;
        }
    
        if(expression == true/true) /* i.e. if any integer other than zero is
        entered, followed by a division sign, then another integer other than zero */
        {
        cout << "You entered a division equation. " << endl;
        }
    
        if(expression == true-true) // like above, but with subtraction
        {
        cout << "You entered a subtraction equation. " << endl;
        }
    
        if(expression == true*true) // and again like above, with multiplication
        {
        cout << "You entered a multiplication equation. " << endl;
        }    
    
        cin.clear();
        cin.ignore(255, '\n');
        cin.get();
        // ^^ is for Dev C++ so the program stays open until I prompt it to exit
        return 0;                  
    
    }
    
  • skywolf96

    Is this code good or should I write it a deferent way.

    #include
    int a;
    int b;
    int c;
    int d;
    int main ()
    { using namespace std;
    
    cout << "Enter your first Number" <> a;
    
    cout << "Enter your second number" <> b;
    
    cout << "Enter your third number" <> c;
    
    cout << "Enter your fourth number" <> d;
    
    cout << "your numbers added up and Multiplyed by 2 is " << a+b+c+d*2 << endl;
    
    }
    
    
    		
  • skywolf96

    It did not paste right the first time but is this a good way to write the program it takes 4 numbers adds them up and multiples them.

    #include <iostream>
    int a;
    int b;
    int c;
    int d;
    int main ()
    { using namespace std;
    
    cout << "Enter your first Number" << endl;
    
    cin >> a;
    
    cout << "Enter your second number" << endl; 
    
    cin >> b;
    
    cout << "Enter your third number" << endl;
    
    cin >> c;
    
    cout << "Enter your fourth number" << endl;
    
    cin >> d;
    
    cout << "your numbers added up and Multiplyed by 2 is " << a+b+c+d*2 << endl;
    
    }
    
  • 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

  • B2S

    It might be because of my Google Chrome, but you say this:

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

    int GetUserInput()

    but shouldnt’that be:

    int GetUserInput();

    I think you forgot the semicolon for the function prototype ;)

  • Bekim

    Regarding the calculator, I tried according to your example and it was a bit confusing(I’m a noob as you can guess) and i was having a bit hard time understanding what goes, where it goes…, but then I tried a different approach. I typed on separate file what I want to do as you suggested so I can keep track of what i’m doing, what is expected and what I want to achieve. After the typing, things were MUCH MUCH simpler, so, this is my short code I made:

    
    #include <iostream>
    using namespace std;
    
    int main ()
        {
            cout << "Please type any 2 numbers to be calculated and one of the following operators:  '+', '-', '*', '/'.  " << endl;
            int a, b;
            char cOperator;
            cin >> a;
            cin >> b;
            cin >> cOperator;
    
                        if (cOperator == '+')
                           cout << a + b << endl;
    
                        if (cOperator == '-')
                            cout << a - b << endl;
    
                        if (cOperator == '*')
                            cout << a * b << endl;
    
                        if (cOperator == '/')
                            cout << a / b << endl;
    
            cout << "You succeeded. Wohooo...!!!! " << endl;
    
                        cin.get();
                        cin.get();
                        return 0;
          }
    

    Your tutorials compared to the others i tried are the best, and they are so For-Noob-Ppl, such as me. Keep it up and please don’t stop :) .

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

  • after all those digging around with this chapter…i found out another way of writing the calculator….it is much better because u dont need to enter it one by one
    but u can enter the whole calculation at once and then the result is up…

    #include “stdafx.h”
    #include “iostream”

    int Calculate(int aa, char Operator, int bb)
    {
    if (Operator==’+')
    return aa + bb;
    if (Operator==’-')
    return aa – bb;
    if (Operator==’*')
    return aa * bb;
    if (Operator==’/')
    return aa / bb;
    }

    int main()
    {
    using namespace std;
    cout << "Enter your calculation: " <> aa;

    char Operator;
    cin >> Operator;

    int bb;
    cin >> bb;

    cout << "The result is: " << Calculate(aa, Operator, bb) << endl;
    return 0;
    }

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

  • JLaughters

    Thank you for these tutorials. I have bought text books to try and teach myself…didn’t work out so well. It seems in most cases the textbooks are 90% BS and 10% the stuff i need to know. These tutorials seem to be 100% of what i need to know. Again, thanks.

    I am attempting to write the calculator program but, am having an issue. Through my troubleshooting it seems that when each function returns the value to main the value it returns is 0 (or ” ” in the char’s case). I am wondering if I am not using cin correctly or what? I have looked at a few different sections including the comments sections and not been able to find the answer, so i apologize if it has already been covered. cin >> a should store the users input as variable a correct? Here is my code.

    
    // Calc.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <iostream>
    
    int Input1(int a)
    {
    	using namespace std;
    	cout << "Enter First Didgit";
    	cin >> a;
    	return a;
    }
    
    char InputO(char Operator)
    {
    	using namespace std;
    	cout << "Enter the desired operation";
    	cin >> Operator;
    	return Operator;
    }
    
    int Input2(int b)
    {
    	using namespace std;
    	cout << "Enter Second Didgit";
    	cin >> b;
    	return b;
    }
    
    int Calculate(int a, char Operator, int b, int c)
    {
    
    	return c = a, Operator, b;
    }
    
    int Output(int c)
    {
    	using namespace std;
    	cout << c;
    	return c;
    }
    
    int main()
    {
    	using namespace std;
    	int a = 0;
    	int b = 0;
    	int c = 0;
    	char Operator = a ;
    	Input1(a);
    	InputO(Operator);
    	Input2(b);
    	Calculate(a, Operator, b, c);
    	Output(c) ;
    	return 0;
    }
    
  • Lakshya

    very nice tutorial

  • drock921

    I keep getting an error on code blocks saying
    |error: stdafx.h: No such file or directory|
    ||=== Build finished: 1 errors, 0 warnings ===|
    what am I doing wrong?

  • drock921

    I keep getting an error on code blocks saying
    |error: stdafx.h: No such file or directory|
    ||=== Build finished: 1 errors, 0 warnings ===|
    what am I doing wrong?
    Please help

  • Tehchaos

    I’m having an issue with my calculator program, and I can’t figure out what the error means. The code won’t compile and gives me an error saying “No conversion from ‘const char *’ to ‘int’ and ‘int differs in indirection from’. Here’s the code:


    // calcTest.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    using namespace std;

    int getUserInput()
    {
    cout << "Please enter an integer: ";
    int nValue1;
    cin >> nValue1;

    return nValue1;
    }

    char getOperator()
    {
    cout << "Please enter an operator: ";
    char chOperator;
    cin >> chOperator;

    return chOperator;
    }

    int doCalc(int nVal1, char chOp, int nVal2)
    {
    if(chOp == "+")
    return nVal1 + nVal2;
    if(chOp=="-")
    return nVal1 - nVal2;
    if(chOp=="*")
    return nVal1 * nVal2;
    if(chOp=="/")
    return nVal1 / nVal2;

    return 0;
    }

    int main()
    {
    int Val1 = getUserInput();
    char chOperate = getOperator();
    int Val2 = getUserInput();

    cout << "The result of the calculation is: " << doCalc(Val1, chOperate, Val2) << endl;

    return 0;
    }

    • Chris

      I copied your code into Code::Blocks and the only thing wrong with it was that you used “” instead of ”.

      Your code:

      if(chOp == "+")
      return nVal1 + nVal2;
      if(chOp=="-")
      return nVal1 - nVal2;
      if(chOp=="*")
      return nVal1 * nVal2;
      if(chOp=="/")
      return nVal1 / nVal2;

      The correct code:

      if(chOp=='+')
      return nVal1 + nVal2;
      if(chOp=='-')
      return nVal1 - nVal2;
      if(chOp=='*')
      return nVal1 * nVal2;
      if(chOp=='/')
      return nVal1 / nVal2;

      or if you wanna save lines and maybe make it a bit prettier:

      if(chOp=='+') return nVal1 + nVal2;
      if(chOp=='-') return nVal1 - nVal2;
      if(chOp=='*') return nVal1 * nVal2;
      if(chOp=='/') return nVal1 / nVal2;

      I advise using Code::Blocks. Every time i made a mistake it was clear enough to tell me whats wrong.

      Good luck codding :)

  • Chris

    Thank you Mr. Alex for these tutorials. This are the first tutorials that actually explain everything. I have a few questions tho.

    1. Why arent the forums working? It says the page doesnt exist.

    2. After writing the calculator I’m trying to modify it so that after it displays the result, I want it to use that result as the first integer, and then ask the user for an operator and the second integer, but no luck. The result is always “4199440″ :P
    Guess its not time for that yet lol.
    Can anyone at least satisfy my curiosity on that matter?

    Heres the code:


    #include

    using namespace std;

    int GetUserInput()
    {
    int nValue;
    cout <> nValue;
    return nValue;
    }

    int CalculaterResult(int nInput1, int chOperator, int nInput2);

    int GetOperation()
    {
    char chOperation;
    cout <> chOperation;
    return chOperation;
    }

    int CalculateResult(int nX, char chOperation, int nY)
    {
    if (chOperation=='+') return nX + nY;
    if (chOperation=='-') return nX - nY;
    if (chOperation=='*') return nX * nY;
    if (chOperation=='/') return nX / nY;
    }

    void PrintResult(int nResult)
    {
    cout << "The result is: " << nResult << endl;
    }

    void PrintResult2(int nResult2)
    {
    cout << "The result is: " << nResult2 << endl;
    }

    void Continue()
    {
    int nResult;
    int nInput1 = nResult;
    char chOperator = GetOperation();
    int nInput2 = GetUserInput();
    int nResult2 = CalculateResult(nInput1, chOperator, nInput2);
    PrintResult2(nResult2);
    Continue();
    }

    int main()
    {
    int nInput1 = GetUserInput();
    char chOperator = GetOperation();
    int nInput2 = GetUserInput();
    int nResult = CalculateResult(nInput1, chOperator, nInput2);
    PrintResult(nResult);
    Continue();
    }

  • Kostas81

    Hello to eveyone!

    I am a beginner in programming, and as any beginner, I encounter some problems!

    More specific, I think that I have not exactly understand how functions interact with each other, returning values and passing parameters.

    Why do I say so? At the example of the calculator presented in this section, I understand for example that when Alex writes this line:

    int nInput1 = GetUserInput();

    he assigns the result of the function GetUserInput() to the integer variable nInput1.

    I also understand that inside the GetUserInput() function he uses a different variable nValue, because this is a local variable. This has been explained perfect in a previous section.

    What i do NOT understand is the function:

    int CalculateResult(int nX, char chOperation, int nY)

    The parameters int nX and int nY are supposed to be defined in another function and passed to this function. But there is no function where this variables are defined!

    I am sure I have don’t understand something critical, but I can’t figure out what …

    I hope it is not a silly question, but anyway: “The one who asks is stupid for a second. The one who never asks is stupid for ever.”

    So, pls, can anyone help me with this?

    Thanks in advance.

  • Maksism
    #include "stdafx.h"
    #include <iostream>
    
    using namespace std;
    
    int GetNumber1()
    {
    	cout << "Please type in number ";
    	int nX;
    	cin >> nX;
    	return nX;
    	}
    
    char GetMathOperation()
    {
    	cout << "Please enter + - * /";
    	char cOp;
    	cin >> cOp;
    	return cOp;
    }
    
    int GetNumber2()
    {
    	cout << "Please type in number ";
    	int nY;
    	cin >> nY;
    	return nY;
    }
    
    int CalResults(int nX, char cOp, int nY)
    {
    	if (cOp=='+')
    		return nX + nY;
    	if (cOp=='-')
    		return nX - nY;
    	if (cOp=='*')
    		return nX * nY;
    	if (cOp=='/')
    		return nX / nY;
    
    	return 0;
    }
    
    void PrintResults(int nResult)
    {
    	cout << "The answer is " << nResult << endl;
    }
    int main()
    {
    	int nX = GetNumber1();
    	char cOp = GetMathOperation();
    	int nY = GetNumber2();
    	int nResult = CalResults(nX, cOp, nY);
    	PrintResults(nResult);
    	cin.clear();
    	cin.ignore(255, '\n');
    	cin.get();
    }

    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

  • Hex

    int Calculate(int, char, int)
    {
    if (Operation = ‘+’)
    return Number1+Number2;

    if (Operation = ‘-’)
    return Number1-Number2;

    if (Operation = ‘*’)
    return Number1*Number2;

    if (Operation = ‘/’)
    return Number1/Number2;

    return (0);
    }
    my code wont do any thing but add. What have i done wrong.

  • Ascendancy

    Haha, I ended up with an answer almost identical to Alex’s. I used a header file for the first question; who cares if I didn’t read every question thoroughly, I used the best method for the job.

  • Andrew_Hicks

    What is the reason for adding

    #include

    i deleted it for the calculator that you made and it still worked, i was wondering if it was just added to be sure or if i’m missing something?

  • Cleverlegs

    Just to try and validate user input, I did something like this

    
    char GetOperation(){
    	cout << "Enter an operator(+,-,*,/)";
    	char op;
    	cin >> op;
    	if(op != '+' || op != '-' || op != '*' || op != '/'){
    		cout << "Please enter an operator" << endl;
    		GetOperation();
    	}
    	return op;
    }
    
    

    But no matter what the input, it still calls GetOperation() everytime. Why is that?

    • Cleverlegs

      Wait, I just worked out why. If I put in say, a + as the input, the other tests will result true, meaning it will always call GetOperation() again.
      I replaced the if with
      if(op != '+' && op != '-' && op != '*' && op != '/')
      However, it seems to return the first value I put in. So, if I tried to have the letter ‘a’ as an operator, it tells me its not valid, then asks for another, so I put in +. It’s still returning a.

      • Cleverlegs

        Fixed it
        Man I love this language

        
        char GetOperation(){
        	cout << "Enter an operator(+,-,*,/)";
        	char op;
        	cin >> op;
        	if(op != '+' && op != '-' && op != '*' && op != '/'){
        		cout << "Please enter an operator" << endl;
        		op = GetOperation();
        	}
        	return op;
        }
        
        
  • 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.

  • B_E_N_M

    Why does there have to be two ‘=’ signs after chOperation on the calculator.

    if (chOperation==’+')
    return nX + nY;
    if (chOperation==’-')
    return nX – nY;
    if (chOperation==’*')
    return nX * nY;
    if (chOperation==’/')
    return nX / nY;

    i tried it with just one ‘=’ sign, but when I ran it, no matter what operator I put in it just kept doing addition.

    Please enter an integer: 5
    elease enter an operator (+,-,*,or /): -
    Please enter an integer: 2
    Your result is: 7

    Why do you need two ‘=’ signs?
    if it helps, i’m using netbeans IDE 7.1.2 on mac.

    • marcsasson

      If you read some coments your question have been answered…
      Here is a copy paste answer (answer from zingmars):
      You need to use two equality signs (“=”) when comparing something.
      A single sign is an assignment.

  • marcsasson

    Im new and i need some help.
    Wats wrong in this calculator?
    Thanks in advance.

    #include “stdafx.h”
    #include
    using namespace std;

    int ReadNumber()
    {
    cout <> a;
    return a;
    }

    char sign()
    {
    cout <> b;
    return b;
    }

    int result(char z, int x, int y)
    {
    if (z == ‘+’)
    return (x+y);
    if (z == ‘-’)
    return (x-y);
    if (z == ‘*’)
    return (x*y);
    if (z == ‘/’)
    return (x/y);

    return 0;
    }

    int main()
    {
    int x = ReadNumber();
    char z = sign();
    int y = ReadNumber();
    cout << "The answer is " << result << endl;
    return 0;
    }

    • Frelion

      I don’t know about using cout , i would just use “cin >> a” (but declare int a; on the line previous, do that same with char for the operand. Also, for the if statements you need to use the single apostrophe, not the punctuation mark shifted from the tilde. ` vs ‘. Finally, your last line of code that says result needs parameters inside the parentheses. That should do it.

You must be logged in to post a comment.