Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

C++ How I improved my Basic Calculator in C++

Malcolm

Administrator
Administrator
Staff Team
Code Plus
Company Plus
Hello all!

From learning C++ to Full-Stack Web Development and job prep I have been all over the place these last couple of days. I recently learned the if/else if/else statements with C++ and have used it to improve the basic calculator that I posted back March - (you can view that here).

With this update to the code, after you input firstNum & secNum you will then be asked what maths operator you'd like to use. Depending on what operator you select, it will calculate the values from firstNum and secNum and display the result.

I had to add another int labelled as int maths, this will contain the input from the user on what operator they wish to use. From there I add the following lines (Basic cout and cin, prompting the user to input their input) the result will then be stored in the int maths.
C++:
   // Asking for operator
    cout << "What operator? (1: Addition 2: Subtraction 3: Multiplication 4: Divide 5: modulo)\n";
    cin >> maths;

Now before we had a simple firstNum + secNum and that was how it displayed the answer. However, this isn't going to be too useful when you'd have to go back into the code and edit the math operator when you needed to add or subtract etc. My solution to this came shortly after I learned about if statements, so remember an if statement works when if the condition is true then do this e.g.
Code:
if (condition) {
    true then display this.
}

So what I did was if maths equals 1 then display a statement that adds the two int firstNum & secNum together.
Note: Keep in mind of this numbers 1 Addition, 2 Subtraction, 3 Multiplication, 4 Divide, 5 Modulo.

In code:
C++:
if (maths==1) {
    cout << firstNum + secNum << endl;
    return main();
}
So if(maths equal = 1) then display firstNum + secNum and return to main. I added the return to main(); (usually return 0 which will kill the program) because instead of exiting the program then restart to calculate another calculation it will now go back to the start. However we aren't done, what if you have to subtract or divide?

At the end of the if statement after the closing curly brace } I added the word else if. This says "Okay, the first if statement wasn't true, let's go to the next (If available)". The else if statement follows after the if statement. It is very similar all that's changed is that if now has else in front of it. The code is as shown below.
C++:
if (maths==1) {
    cout << firstNum + secNum << endl;
    return main();
} else if (maths==2) {
    cout << firstNum - secNum << endl;
    return main();
}
Now that solves that, however I have multiplication, divide and modulo left. So I continue to the same until I have them all added.
C++:
if (maths==1) {
    cout << firstNum + secNum << endl;
    return main();
} else if (maths==2) {
    cout << firstNum + secNum << endl;
    return main();
} else if (maths==3) {
    cout << firstNum * secNum << endl;
    return main();
} else if (maths==4) {
    cout << firstNum / secNum << endl;
    return main();
} else if (maths==5) {
    cout << firstNum % secNum << endl;
    return main();
}
However, now you can't finish an if statement with an else if (I don't so, I'll test it). But also, what if someone inputs 6 or anyother number higher? They probably wouldn't get the answer that they want. So lets finish off the if/else if statement with else. SO if none of these are true display an unknown operator message. Like this:
C++:
} else {
    cout << "Unknown Operator\n"
}

So all together we will have:
C++:
#include <iostream>
using namespace std;

int main(){
    int firstNum {0};
    int secNum {0};
    int maths {0};

    // Asking for two numbers
    cout << "Enter your first number\n";
    cin >> firstNum;
    cout << "Enter your second number\n";
    cin >> secNum;

    // Asking for operator
    cout << "What operator? (1: Addition 2: Subtraction 3: Multiplication 4: Divide 5: modulo)\n";
    cin >> maths;

    if(maths==1) {
        cout << firstNum + secNum << endl;
        return main();
    } else if (maths==2){
        cout << firstNum - secNum << endl;
        return main();
    } else if (maths==3){
        cout << firstNum * secNum << endl;
        return main();
    } else if (maths==4){
        cout << firstNum / secNum << endl;
        return main();
    } else if (maths==5){
        cout << firstNum % secNum << endl;
        return main();
    } else {
        cout << "Unknown Operator \n";
    }
    return main();
}
 
Nice program, but if I may, I see 3 little things you could improve ;).
1. Adding "return main();" in each "if/else if/else" statement is not required. Once one of the "if/else if/else" statements equals true, the instructions inside the statement are executed and then the whole if structure is stepped over (The execution of the program starts back after it). The return statement at the line 37 is therefore, no matter what, always executed (Unless the program returns before it is reached).
2. It is better to use a loop (loop while here) than calling the main function again. By calling the main function like that, the stack keeps growing, because the function main never returns (It must wait for the function it called in its return statement to return before being able to return). Performance-wise it is not good and the program may crash if the stack grows too big. (Basically, a function call takes memory space as long as it has not returned, and there is a limit to the amount of memory function calls may use).
3. In that case, it would be better to use a switch-case structure than a if/else if/else structure. A switch-case structure may often be optimized such as the program "jumps" to the appropriate section of code rather than test all the possibilities.
Here is an (almost) equivalent program with the changes stated above:

C++:
#include <iostream>
using namespace std;

int main(){
    int firstNum {0};
    int secNum {0};
    int maths {0};

    // Infinite loop
    while(true)
    {
        // Asking for two numbers
        cout << "Enter your first number\n";
        cin >> firstNum;
        cout << "Enter your second number\n";
        cin >> secNum;

        // Asking for operator
        cout << "What operator? (1: Addition 2: Subtraction 3: Multiplication 4: Divide 5: modulo)\n";
        cin >> maths;

        switch(maths)
        {
        case 1:
            cout << firstNum + secNum << endl;
            break; // Leave the 'switch' structure.
        case 2:
            cout << firstNum - secNum << endl;
            break;
        case 3:
            cout << firstNum * secNum << endl;
            break;
        case 4:
            cout << firstNum / secNum << endl;
            break;
        case 5:
            cout << firstNum % secNum << endl;
            break;
        default: // Invalid operator (Any other number).
            cout << "Unknown Operator \n";
        }

        // Asks if the user wants to leave the program.
        cout << "Leaving the calculator? (Y to leave) ";
        char answer;
        cin >> answer;
        cout << endl;

        // If the user entered 'y' or 'Y', we leave the loop.
        if(answer == 'y' || answer == 'Y')
            break; // Leave the loop.
    }

    return 0;
}
 
1. Adding "return main();" in each "if/else if/else" statement is not required. Once one of the "if/else if/else" statements equals true, the instructions inside the statement are executed and then the whole if structure is stepped over (The execution of the program starts back after it). The return statement at the line 37 is therefore, no matter what, always executed (Unless the program returns before it is reached).
Oh okay! I tried this out, I think I did it because I assumed that once it executed it would exit the program. But thanks for pointing this! :)
2. It is better to use a loop (loop while here) than calling the main function again. By calling the main function like that, the stack keeps growing, because the function main never returns (It must wait for the function it called in its return statement to return before being able to return). Performance-wise it is not good and the program may crash if the stack grows too big. (Basically, a function call takes memory space as long as it has not returned, and there is a limit to the amount of memory function calls may use).
Would you be able to touch on what you are referring to as "stack"? I'm just a tiny bit confused with that!
3. In that case, it would be better to use a switch-case structure than a if/else if/else structure. A switch-case structure may often be optimized such as the program "jumps" to the appropriate section of code rather than test all the possibilities.
Here is an (almost) equivalent program with the changes stated above:
Basically, the tutorial that I wrote was actually based on what I learned at the time while following a YouTube Tutorial. Shortly after creating this tutorial I learned about switches. After learning about switches I went to the code and rebuilt it using switches. They are so much easier to work with! Your points are amazing and much appreciated thank you so much! :)
 
Thanks for looking into my reply!
The stack is, simply put, a memory space used by the processor to temporarely store information. In the case of the call of a function, it is used (from other things) to store the address where the function had been called (So the processor can return to it when the execution of the function is finished).
If you do not mind some reading, I wrote a page covering that, here.
 
Last edited:
Thanks for looking into my reply!
The stack is, simply put, a memory space used by the processor to temporarely store information. In the case of the call of a function, it is used (from other things) to store the address where the function had been called (So the processor can return to it when the execution of the function is finished).
If you do not mind some reading, I wrote a page covering that, here.
That's super interesting! I knew that our systems stored specific information but didn't know much about it nor knew what a stack was. Thank you for sharing @LTomy!
 

Buy us a coffee!

Back
Top Bottom