Quantcast
Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
    1. Welcome to GTAForums!

    1. GTANet.com

    1. GTA Online

      1. The Cayo Perico Heist
      2. Find Lobbies & Players
      3. Guides & Strategies
      4. Vehicles
      5. Content Creator
      6. Help & Support
    2. Red Dead Online

      1. Frontier Pursuits
      2. Find Lobbies & Outlaws
      3. Help & Support
    3. Crews

    1. Red Dead Redemption 2

      1. PC
      2. Help & Support
    2. Red Dead Redemption

    1. Grand Theft Auto Series

      1. St. Andrews Cathedral
    2. GTA VI

    3. GTA V

      1. Guides & Strategies
      2. Help & Support
    4. GTA IV

      1. The Lost and Damned
      2. The Ballad of Gay Tony
      3. Guides & Strategies
      4. Help & Support
    5. GTA San Andreas

      1. Guides & Strategies
      2. Help & Support
    6. GTA Vice City

      1. Guides & Strategies
      2. Help & Support
    7. GTA III

      1. Guides & Strategies
      2. Help & Support
    8. Portable Games

      1. GTA Chinatown Wars
      2. GTA Vice City Stories
      3. GTA Liberty City Stories
    9. Top-Down Games

      1. GTA Advance
      2. GTA 2
      3. GTA
    1. GTA Mods

      1. GTA V
      2. GTA IV
      3. GTA III, VC & SA
      4. Tutorials
    2. Red Dead Mods

      1. Documentation
    3. Mod Showroom

      1. Scripts & Plugins
      2. Maps
      3. Total Conversions
      4. Vehicles
      5. Textures
      6. Characters
      7. Tools
      8. Other
      9. Workshop
    4. Featured Mods

      1. Design Your Own Mission
      2. OpenIV
      3. GTA: Underground
      4. GTA: Liberty City
      5. GTA: State of Liberty
    1. Rockstar Games

    2. Rockstar Collectors

    1. Off-Topic

      1. General Chat
      2. Gaming
      3. Technology
      4. Movies & TV
      5. Music
      6. Sports
      7. Vehicles
    2. Expression

      1. Graphics / Visual Arts
      2. GFX Requests & Tutorials
      3. Writers' Discussion
      4. Debates & Discussion
    1. Announcements

      1. GTANet 20th Anniversary
    2. Support

    3. Suggestions

[TUT] How to create a calculator in C++


Parik

Recommended Posts

We know about Programming Languages , but not all know all languages. So , let me tell you the basics of C++ in this tutorial wink.png?w=742 . This tutorial will tell you about the loops , variables , strings , if and else statements and blah blah blah bat.png?w=742 If you didn’t understood it , then don’t be unlove.png?w=742 , just read the summary on Mosrille

 

See the tutorial video , summary , explanation :) on http://www.mosrille.ml/tutorials/how-to-create-a-calculator-in-cpp/

 

Here is the code :) , you just have to copy it and paste it to your IDE , if you want the explanation go to http://www.mosrille.ml/tutorials/how-to-create-a-calculator-in-cpp/

 

 

 

 

 #include <iostream>using namespace std;//We'll use another methodint main(){ string repeat = "repeat";  //adds a string while (repeat == "repeat"){ cout << "Enter the first number : "; //Don't forget to put semicolon , this will print enter the first number int firstNumber; //We will have to declare an integer before doing the calculation cin >> firstNumber; //This will input the firstNumber integer. Note the use of >> instead of << cout << "Enter the sign : "; //It will ask the user to enter a sign eg. + , - , * or / string sign; //Integers don't take symbols so use string instead cin >> sign; //Takes input of sign cout << "Enter the second number : "; //Prints enter the second number int secondNumber; cin >> secondNumber; //Now how will we know what the user wants as answer , let's use an if statement if (sign == "+"){ //Notice the use of == instead of = because = assigns and == compares cout << "The answer is " << secondNumber + firstNumber; //It will print second number + first number if the sign is + } else if (sign == "-"){ //This will be executed if - is the sign cout << "The answer is " << firstNumber - secondNumber; //You know what is the answer } else if (sign == "*"){ //Multiplication Sign cout << "The answer is " << firstNumber * secondNumber; } else if (sign == "/"){ //Division //Here's how to fix that error if (secondNumber == 0){ cout << "The answer is Not Defined"; } else { cout << "the answer is " << firstNumber / secondNumber; } } cout << "Enter repeat to repeat the process : "; cin >> repeat; }}
Edited by Parikshit Singh
Link to post
Share on other sites

Cool man! Have you done infix/postfix expression evaluations before? These expressions use a stack data structure to evaluate sums.

 

http://scriptasylum.com/tutorials/infix_postfix/algorithms/postfix-evaluation/

Yes , I did. They are not in this tutorial because this was for new people :)

Link to post
Share on other sites

What is the objective you are trying to achieve here? It doesn't really teach anything about principles of the language, and it's actually written in pretty poor style, which is to be avoided when introducing someone to code. The lack of indents might be due to the forum formatting, but everything else runs together as well. Most importantly, there isn't a clear objective. There are better examples to introduce someone to branching, user I/O, or program flow. A "calculator" like this works much better as a challenge than a tutorial. Either by challenging student to write a new one from scratch or, more realistically in many cases, to ask student to add missing operations.

  • Like 3
Link to post
Share on other sites

What is the objective you are trying to achieve here? It doesn't really teach anything about principles of the language, and it's actually written in pretty poor style, which is to be avoided when introducing someone to code. The lack of indents might be due to the forum formatting, but everything else runs together as well. Most importantly, there isn't a clear objective. There are better examples to introduce someone to branching, user I/O, or program flow. A "calculator" like this works much better as a challenge than a tutorial. Either by challenging student to write a new one from scratch or, more realistically in many cases, to ask student to add missing operations.

If someone wants to learn a language , he can read the comments try to use the methods in other programs. He can modify the code to see what changes and learn the basics of a language. This is how I learnt a language but Visual Basic , not C++ and also by a browser instead of Calculator.

Link to post
Share on other sites

That might explain some of the clutter. I hope you take everything that I say as constructive criticism, rather than an attempt to put you down.

 

The first thing that is worth explaining to somebody new to the language, and especially someone new to programming, is how and why the variables are declared. Unlike C++, C wouldn't even allow you to declare your variables further down the code. And in C++ it is considered a bad practice by many. The rule of thumb is that if you need a variable just in the middle of the code, it should get its own block. If a variable is useful throughout the function, it should be declared at the top of the scope. There are two reasons for all of this. First, it makes code far more readable. If you see a variable appear in a small block somewhere, you know that it's a temporary variable. For declarations of anything important, you can go to the top of the scope. In addition, this shadows how variables are created on the hardware. When you enter a block of code with some local variables defined, the stack counter gets decremented to create room for them. When you exit the block, the counter is restored.

 

This brings up a topic of scope, but there is not a whole lot to say about it based on this code. Nonetheless, I would have grouped all of the declarations at the beginning of the main() and make a comment that you are declaring variables and their types which will be accessible throughout the main function. By the way, this isn't Java. main is most definitely a function, and not a method.

 

Next is the use of control structures. It may seem to you like the while{} and the if{}else{} blocks is self explanatory, but it really isn't to a lot of people. And the code above does not really make that hierarchy particularly clear. It's bad enough that you throw in a loop without ever explaining it, but there is an entire else if chain as well. Someone who already knows how to program in another language will be able to look at that and understand all of the connections, but this isn't going to cut it for someone who's new to programming. If the goal is to make it as clear as possible what you are doing up there, I would almost suggest replacing the else if chain with a switch. To a newbie programmer, a switch will make a lot more sense.

 

As an aside, excessive use of switches and/or else if blocks is often an indicator of bad program design. Frequently, it means that you should be using an array. If you have "a few" cases, a switch/else if might be faster. But when you have 10+ options to chose from, that is a lot of unnecessary branching, and a look up table is probably a better way to deal with it. But that's way beyond what this particular example is about.

 

Back to the example, and this is a bit more controversial, but I would avoid using cin/cout in early tutorials. You just can't explain how they really work without diving into a whole mess of concepts about operator overloading. I know a lot of textbooks on C++ insist on using these from the start, but it's just not a good way to teach a language. Absolutely every instruction is deeply rooted in the way the language works. This isn't some scripting language. Unlike Basic or Java, you can go ahead and write your own implementation of cin/cout almost from scratch. But to do that, you need to understand that cin and cout are static objects of the IO stream, and that << and >> are binary operators overloaded to handle a variety of input/output types, with L-value always being an IO stream. And that brings up a bunch of questions. Namespaces, classes, methods, etc. Which is something you need to teach if you are teaching C++, but maybe, you shouldn't start with that if your students aren't C veterans.

 

There is also a matter of explaining that main() is a function, what is a function, why you used an #include macro, what the using keyword does, etc. These should probably come before you start with this level of tutorial. Although, just the basics. Detailed explanation of functions etc should follow thorough explanation of how loops and conditionals work, since they are all related.

Link to post
Share on other sites

That might explain some of the clutter. I hope you take everything that I say as constructive criticism, rather than an attempt to put you down.

 

The first thing that is worth explaining to somebody new to the language, and especially someone new to programming, is how and why the variables are declared. Unlike C++, C wouldn't even allow you to declare your variables further down the code. And in C++ it is considered a bad practice by many. The rule of thumb is that if you need a variable just in the middle of the code, it should get its own block. If a variable is useful throughout the function, it should be declared at the top of the scope. There are two reasons for all of this. First, it makes code far more readable. If you see a variable appear in a small block somewhere, you know that it's a temporary variable. For declarations of anything important, you can go to the top of the scope. In addition, this shadows how variables are created on the hardware. When you enter a block of code with some local variables defined, the stack counter gets decremented to create room for them. When you exit the block, the counter is restored.

 

This brings up a topic of scope, but there is not a whole lot to say about it based on this code. Nonetheless, I would have grouped all of the declarations at the beginning of the main() and make a comment that you are declaring variables and their types which will be accessible throughout the main function. By the way, this isn't Java. main is most definitely a function, and not a method.

 

Next is the use of control structures. It may seem to you like the while{} and the if{}else{} blocks is self explanatory, but it really isn't to a lot of people. And the code above does not really make that hierarchy particularly clear. It's bad enough that you throw in a loop without ever explaining it, but there is an entire else if chain as well. Someone who already knows how to program in another language will be able to look at that and understand all of the connections, but this isn't going to cut it for someone who's new to programming. If the goal is to make it as clear as possible what you are doing up there, I would almost suggest replacing the else if chain with a switch. To a newbie programmer, a switch will make a lot more sense.

 

As an aside, excessive use of switches and/or else if blocks is often an indicator of bad program design. Frequently, it means that you should be using an array. If you have "a few" cases, a switch/else if might be faster. But when you have 10+ options to chose from, that is a lot of unnecessary branching, and a look up table is probably a better way to deal with it. But that's way beyond what this particular example is about.

 

Back to the example, and this is a bit more controversial, but I would avoid using cin/cout in early tutorials. You just can't explain how they really work without diving into a whole mess of concepts about operator overloading. I know a lot of textbooks on C++ insist on using these from the start, but it's just not a good way to teach a language. Absolutely every instruction is deeply rooted in the way the language works. This isn't some scripting language. Unlike Basic or Java, you can go ahead and write your own implementation of cin/cout almost from scratch. But to do that, you need to understand that cin and cout are static objects of the IO stream, and that << and >> are binary operators overloaded to handle a variety of input/output types, with L-value always being an IO stream. And that brings up a bunch of questions. Namespaces, classes, methods, etc. Which is something you need to teach if you are teaching C++, but maybe, you shouldn't start with that if your students aren't C veterans.

 

There is also a matter of explaining that main() is a function, what is a function, why you used an #include macro, what the using keyword does, etc. These should probably come before you start with this level of tutorial. Although, just the basics. Detailed explanation of functions etc should follow thorough explanation of how loops and conditionals work, since they are all related.

No worries :) , I will keep that in mind when I'll do the next tutorial

Link to post
Share on other sites
  • 1 month later...

You could have used a case statement ^_^

yes I could have , but I haven't

if are simple in my opinion

Edited by Parikshit Singh
Link to post
Share on other sites

yes I could have , but I haven't

if are simple in my opinion

There are conditions under witch a switch will get better optimized than an else if chain. It can also be a little cleaner under right organization. But I'm of the opinion that if you're facing a situation where you have a whole bunch of cases, it's much better to start using function pointers. Consider a situation where you have a dozen of possible states, like messages from a server that you want to decode, and each one requires a good deal of code to process. If you use a switch or an else if chain, you are going to have a big mess that's hard to follow. If you have an array of function pointers, you have a neat little table of functions to follow, a couple of lines of code that actually selects the correct entry and calls it, and then each operation has its own function scope, making it easier to debug. The drawback is that it can make your branching slightly worse, so you don't want to do this in a middle of some performance-critical code. As I've indicated above, if you're doing performance-critical section, switch is probably your best bet.
Link to post
Share on other sites

I wrote few explanations in the Summary , I will add it here soon.

Link to post
Share on other sites
  • 2 weeks later...

This inspired me to try my own calculator in C. It's not done yet, but I got it to work a little bit, and need some help refining it.

// Postfix calculator// Adds, subtracts, multiplies, divides, and does modular arithmetic#include <stdio.h>int main(int argc, char *argv[]){  int num1, num2, ans;    if(argc != 4){				//quits at invalid arguement #    puts("Usage: calc int int operation.");    return 0;    }    else{				    num1 = *argv[1] - '0';			//converts char input to integers    num2 = *argv[2] - '0';      switch(*argv[3]){				//calc operations            case '+':        ans = num1 + num2;        printf("%d\n", ans);        break;            case '-':        ans = num1 - num2;        printf("%d\n", ans);        break;              case 'x':        ans = num1 * num2;        printf("%d\n", ans);        break;              case '/':        ans = num1 / num2;        printf("%d\n", ans);        break;              case '%':        ans = num1 % num2;        printf("%d\n", ans);         break;            default:        puts("Bad operator. Use +, -, x, /, or %");    }    }  return 0;}

(Here, if you want line numbers.)

 

Things it does:

- Calculates single digit numbers

 

Things it can't do that I'd like help with:

- Calculate any integer, I guess I'd like to know how to use strings instead of characters in argv, or is there a better solution?

- Not floating point numbers, I know how to implement that already.

- Use '*' instead of 'x' for multiplication. When '*' is used it returns an error as if I didn't provide enough arguements. Maybe that's a unix problem?

- I don't understand how the conversion at line 15 and 16 works. I got that from stack overflow as a trick for converting char data to integers, but they didn't explain how it works. Are they just deleting a null terminator?

 

 

(Sorry if this is off-topic by the way, I just didn't want to create a whole 'nother topic for such a similar program.)

Edited by m.toreno
Link to post
Share on other sites

1) There are a few function in the standard C library that can do this. You can use strtol or atoi, I recommend the first one since you can check if the given number is a valid integer. These function also have float variants, so I'm curious how you know how to handle floating values and not integers.

 

2) On windows I don't seem to have any problems with the * sign. As far as I'm aware bash uses the * symbol as "anything" so maybe you should try putting quotation marks around it.

 

3) A computer calculates with numbers not characters, so any character is a number basically. All characters are in sequential order so "0" might mean 48 to the computer and "3" 51. So if you subtract "0" from "3" you get 51 - 48 = 3. That is how characters are converted to numbers in your code.

Link to post
Share on other sites

Alright, strtol() worked! http://codepad.org/84SAVcJ9

>so I'm curious how you know how to handle floating values and not integers.
I was kinda talking out of my butt. :blush: I figured converting integers to floating point numbers would be easy if I was just able to get converting characters to integers down right, I think I've done it before.

>On windows I don't seem to have any problems with the * sign. As far as I'm aware bash uses the * symbol as "anything" so maybe you should try putting quotation marks around it.
That was the problem, should've tested it myself to be sure. I was hoping there'd be a way to get the program to ignore bash syntax, but that doesn't seem like a good thing to use on second thought.

Thanks for the help. :)

Edited by m.toreno
Link to post
Share on other sites

Gah. Just take input from a string.

 

 

char str1[] = "42";char str2[] = "3.14";float x;int n;sscanf(str1, "%d", &n); //n is now 42.sscanf(str2, "%f", &x); //x is now 3.14.
Takes all the same parameters as printf does, so you don't have to worry about forgetting them, can read multiple values, including strings, from the same source string, and it's part of stdio.
Link to post
Share on other sites
  • 1 month later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • 1 User Currently Viewing
    0 members, 0 Anonymous, 1 Guest

×
×
  • Create New...

Important Information

By using GTAForums.com, you agree to our Terms of Use and Privacy Policy.