C++ Calculator

3 Likes

Very well done!! :grinning:

If you would like suggestions for improvements:


I would use a switch instead of the if and else gates`, simply bacause it the code a little simpler when you are only testing one value.

You could use a while loop to lt the code keep running so someone can make another calculation without having to hit run again.

Then you could add a fifth option to terminate the program.

1 Like

It would be great if you could give an example :slight_smile:

W3Schools has a good C++ switch statement article: @8-bit-gaming is suggesting that you replace your if branches with a switch statement, since you’re effectively checking only one value (a):

switch(a) {
  case 1:
    // code block
    break;
  case 2:
    // code block
    break;
  default:
    // code block
}
1 Like

@825orion @8-bit-gaming
You could use a while loop to lt the code keep running so someone can make another calculation without having to hit run again.

How would this block look like.

I’d actually use a do-while for this…

do{
    //All of your code goes here... then add the condition to continue
    int cont;
    std::cout << "Enter 0 to exit or 1 to continue: ";
    std::cin >> cont;
}while(cont==1);
2 Likes

A while loop will test for a condition and run the code inside of it until that condition becomes false:

#include <iostream>

int main() {
  int number = 0;  
  
  while (number < 10) {
    number += 1;
  } 
}
2 Likes

So the code [Calculator] will run upto 10 times

1 Like

Exactly!
Each time it loops it adds to number until number reaches 10.


Obviously I am coming at this from a different perspective than @825orion.

I was thinking to make an infinite loop in your code:

while (true) {
  //do stuff here
}

and then making a fifth option that would run return 0;
Therefor ending the program.

2 Likes

I am getting the point but can you show me a program based on what you are saying :smile:

Try running this program, it contains both a while loop and a switch.

#include<iostream>
int
main ()
{
    while (true) {
        int number;
        std::cout << "Type (1) to loop again or (0) to exit:\n";
        std::cin >> number;
        
        switch (number) {
            case 0: 
            std::cout << "Good bye\n";
            return 0;
            
            case 1:
            std::cout << "Here we go again\n";
            break;
            
            default:
            std::cout << "That was not a valid entry!\n";
        }
    }
}

1 Like

Thank You :grinning:

1 Like