Simple C++ calculator explained

in #programming8 years ago (edited)

I just wanted to give an example of a simple and easy C++ program you can write. This program takes two integers and adds them, subtracts them, multiplies them, divides them, finds the remainder of them after division, or computes powers of them. Feel free to use this program however you want.

#include<iostream>
using namespace std;

int cal(int a, int b, char c)
{
    switch(c)
    {
        case '+':
            return a + b;
        case '-':
            return a - b;
        case '*':
            return a * b;
        case '/':
            return a / b;
        case '%':
            return a % b;
        case '^':
            int temp = a;
            for(int x = 1; x < b; x++)
                a *= temp;
            return a;
    }
}

int main()
{
    cout << "Welcome to Calculator!\n"
         << "Enter one operation at a time.\n"
         << "Supported operators: + - * / ^ %\n"
         << "Format: integer operator integer\n\n";

    int a, b;
    char c;

    while(1)
    {
        cout << ">";
        cin >> a >> c >> b;
        if(!(c == '+' || c == '-' || c == '*' || c == '/' || c == '%' || c == '^') )
        {
            cout << "Invalid operator.\n";
            continue;
        }
        cout << "= " << cal(a,b,c) << endl;
        end:;
        cout << "Continue? y for yes, any other key for no: ";
        cin >> c;
        if(c != 'y')
            break;
    }
    cout << "Goodbye!\n";
    return 0;
}

main()

  • prints welcome statement
  • int a <-- stores first number
  • int b <-- stores second number
  • char c <-- stores operator
  • while(1) <-- this will loop forever (until the program hits a break statement)
    • prints the prompt
    • scans for a, b, and c
    • if the operator was not one of the 6 supported, print "Invalid operator" and end the current loop iteration
    • print "= " and call the cal() function to compute the answer
    • ask if the user wants to continue
    • if the user doesn't input 'y' exit the while loop
  • print "Goodbye!"

cal()

  • this function calculates the answer
  • variables a, b, and c serve the same purpose
  • each case of the switch statement is self-explanatory except the last one
  • case: '^'
    • temp <-- to hold the value of a
    • multiply a by temp b times
    • return the answer

And finally, here is some sample output:

[cmw4026@omega test]$ ./a.out
Welcome to Calculator!
Enter one operation at a time.
Supported operators: + - * / ^ %
Format: integer operator integer

>5 + 5
= 10
Continue? y for yes, any other key for no: y
>5 - 10
= -5
Continue? y for yes, any other key for no: y
>6 * 12
= 72
Continue? y for yes, any other key for no: y
>18 / 3
= 6
Continue? y for yes, any other key for no: y
>10 % 3
= 1
Continue? y for yes, any other key for no: y
>2 ^ 4
= 16
Continue? y for yes, any other key for no: n
Goodbye!
[cmw4026@omega test]$
Sort:  

Great tutorial, we need more tutorials on languages like C and C++. String manipulation will definitely be a big one, introducing pointers, the null character and dynamic memory allocation / deallocation (sp?).

One question: Did you choose to implement the logic for powers to avoid getting into adding another header file to keep things simple (math.h, pow(...) function)?

First, are you asking for those tutorials? Because I will gladly write them! It just sounds like you know how to do all of that already! String manipulation is super easy in C++. It is a bit more confusing in C (but not too bad!). I'm just not sure what you mean about the null character. The character is '\0'.

Normally I include as many headers as I need. Sometimes I just decide to write little of my own code. That was about three lines of code though, so it wasn't time consuming to come up with at all!

Yeah, I was thinking more along the lines of C tutorials rather than C++ like the one above, my bad. Sometimes, depending on how one copies array's of characters (or reverses them) in C they forget copying the null character if its a copy function or forget that they have to write their code in such a way that avoids reversing it along with the "string" itself in a reverse function.

I would enjoy those tutorials, but that's just me. I like building blocks, starting from the ground up (okay, we might not need asm tutorials, although I'd love to dig into that as well). Basically, knowing how to do it in C and then being thankful for what we have in C++. ;)

Its not really a request per se, just a comment that I would find them interesting, especially for those who might be reading that are new to programming.

Cool, I was just curious about writing out the power logic. Would love to see a follow up post on the 2^n functions to introduce the concept of bit shifting optimizations.

Not sure if anyone else would be interested in those though.

Bit shift would be a cool idea for the next one! I'll be sure to go back to these comments before I start posting again.

In my opinion, it is easier to learn programming in a language like C++, then move C once you get the hang of it. C is a bit more confusing when you are a beginner.

Let me know EXACTLY what tutorials you really want. No one has made suggestions yet, so you are on the top of the list! Would you rather see more C or C++? I have about 14 tutorials in C++. Here is a link to the last one (there are links to the rest of them in there):
My C++ Tutorials
These aren't about everything in C++. Just some things I thought were useful for beginners. It starts off with a lot of language neutral tutorials. When you click on the link, the topics will all be listed.

I would love to see C first, then C++. I'm thinking about it like a textbook, going systematically from one step to the next, which it looks like you are doing. Awesome stuff!

What would be really cool, just my opinion, would be posts that do something in C and then showing how to do it (easier or not) in C++, to show both and illustrate the difference for a particular task. Seems like that might be a bit of work though.

No, these are great ideas, keep them coming!

Love the tutorials. Getting into more complex data structures and algorithms, it would be great to emphasize the time complexities and space complexities of operations performed on those data structures, like with the binary search tutorial.

I can get into Big Oh. And there is a great website comparing all of the search algorithms! I just have to find it!

Awesome! So, obviously, you know what you are doing. In the case of the binary search tutorial, the first thing you pointed out was that it has to be sorted to work.

But there's obviously a cost involved with that, so adding, inserting, sorting, removing, etc... into the data structure being used, whether its represented in memory as an array, linked list, doubly-linked list, hash table where each entry points to an array (or linked list) when you get to creating dictionaries... trees, binary trees, balanced binary trees and graphs... oh the list could go on. You definitely have a lot of material to pick from!

So, getting into why you would use this data structure over that data structure for a particular implementation, maybe this data structure is fast at adding but slow at sorting, but the solution doesn't require a sorted list/array of items... etc... I think that too would be really cool and interesting to talk about.

https://www.toptal.com/developers/sorting-algorithms

It is on sorting, not searching, sorry! Still very cool to watch. Check it out!

Coin Marketplace

STEEM 0.28
TRX 0.11
JST 0.031
BTC 69123.03
ETH 3739.29
USDT 1.00
SBD 3.69