• Advertisement

# Please check this for me. :)

This topic is 1473 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

## Recommended Posts

How would you use functions in a calculator program?
I got the jumping into c++ book and i've met functions again. This time, i kinda understand it (this is the 5th book i'm using to learn c++), last problem was vectors so i decided i needed a new book (this was after 2 failed functions learning and 1 failed array learning).
In this book, functions comes before arrays and the first time i met functions was in the cplusplus.com pdf, then in programming principles book which i just switched from and i had no idea what so ever what it did/what they were talking about, so i changed books. Now i've met it again and this book explains better.
I was writing calculator program and it doesn't seem right, it does everything right but it's like 2/3x more code than doing everything in
int main()

.

How would you use functions in a simple (+, -, /, *) calculator program?

My code is below.

Thanks.
#include <iostream>
#include <string>

double calc_add (double a, double B)/>
{
return a+b;
}

double calc_minus(double a, double B)/>
{
return a-b;
}

double calc_multiply(double a, double B)/>
{
return a*b;
}

double calc_divide(double a, double B)/>
{
return a/b;
}

void calculator ()
{

double x = 0;
double y = 0;
char unit = ' ';
std::string QUIT;

do
{

std::cout <<"CALCULATOR \n\n";

std::cout <<"Enter operation: ";
std::cin >> x >> unit >> y;

switch (unit)
{
case '+':
std::cout << calc_add(x, y);
break;

case '-':
std::cout << calc_minus(x, y);
break;

case '*':
std::cout << calc_multiply(x, y);
break;

case '/':
std::cout << calc_divide(x,y);
break;

}

std::cout << "\n\nDo you want to quit: ";
std::cin >> QUIT;

if (QUIT == "No")
{
system ("cls")
)

}

while (QUIT == "No");
}

int main()
{
calculator();

return 0;
}

No indentation (no tab key on mobile).

#### Share this post

##### Share on other sites
Advertisement

Checked.

Does not compile.

---

EDIT: I see you've updated your post, so I'll reply to that as well.

Once the compile errors and such are fixed, the application does what I expect it to.

While in this specific case it might be more tedious and more lines of code to use functions instead of just having everything inside main, I expect the example is meant to teach you several things, including:

A) How functions are declared/defined.

B) How functions are called.

C) How functions parameters work.

D) How code can be split out of 1 huge function to create several smaller & more managable ones (Refactoring).

Edited by CoreLactose

#### Share this post

##### Share on other sites

How would you use functions in a simple (+, -, /, *) calculator program?

I would not use functions, just a switch in a loop and directly using those math operators...

Checked.

Does not compile.

if (QUIT == "No")
{
system ("cls")
)

}

Edited by Alessio1989

#### Share this post

##### Share on other sites
Indentifying it for you...

#include <iostream>
#include <string>

double calc_add (double a, double B)/>
{
return a+b;
}

double calc_minus(double a, double B)/>
{
return a-b;
}

double calc_multiply(double a, double B)/>
{
return a*b;
}

double calc_divide(double a, double B)/>
{
return a/b;
}

void calculator ()
{

double x = 0;
double y = 0;
char unit = ' ';
std::string QUIT;

do
{

std::cout <<"CALCULATOR \n\n";

std::cout <<"Enter operation: ";
std::cin >> x >> unit >> y;

switch (unit)
{
case '+':
std::cout << calc_add(x, y);
break;

case '-':
std::cout << calc_minus(x, y);
break;

case '*':
std::cout << calc_multiply(x, y);
break;

case '/':
std::cout << calc_divide(x,y);
break;

}

std::cout << "\n\nDo you want to quit: ";
std::cin >> QUIT;

if (QUIT == "No")
{
system ("cls")
)

}

while (QUIT == "No");
}

int main()
{
calculator();

return 0;
}

...it becomes apparent that you forgot a closing } after the calculator() function (hence the indent level of main()). This is why indentation is good, and if mobiles don't let you indent when posting then God help us all. (But that's a different discussion.)

Typically, for a calculator program most people aren't going to use this kind of structure. It's just not very useful or flexible. For example, how would you deal with parentheses? With multiple operations?

In order to deal with the full range of possibilities of a calculator, you need to have a bit more complex paradigm. At the simplest, you'll probably want to implement a simple stack-based lexer and parser. This will convert the input expression to a stream of tokens (lexical analysis) then construct a syntax tree on the stack that can then be evaluated to generate the result. This will allow you to deal with any level of parenthetical nesting and any kind of complex expression, as long as it is well-formed. (And you can test for syntax errors during parsing to catch the malformed expressions).

Typically too, all of this (lexing, parsing, evaluation) will be encapsulated into their own modules, whether by C style functions, by C++ class, whatever. They will be quite separate from all of the input and output facilities you provide, rather than all tied up together. A sample structure might be (pseudocode)

while (running)
Obtain input string
Pass input string to lexer to obtain a token stream
Pass the token stream to parser to obtain a syntax tree (stack)
Pass the stack to the evaluator to obtain the result
Display the result
Wanna quit? yes/no

You can see how in the simple pseudocode there are clearly delineated sections? Each of those sections can be implemented as a separate module. Lexer/parsing/evaluation stuff is an excellent example of black-box design, where each component or module accepts some input and returns some output, no side-effects, no persistent state or any complexity. Just simple input/output. Makes it very easy to separate into discrete tasks.

#### Share this post

##### Share on other sites
The code (the one in my pc compiles). I posted via phone so there is no way to indent or check errors.

What kind of program will use functions, i need something to practice on.
Thanks.

#### Share this post

##### Share on other sites

I was writing calculator program and it doesn't seem right, it does everything right but it's like 2/3x more code than doing everything in main()

In this case, the program's overall complexity is probably just at the point where there is little to be gained by moving the math to independent functions. Imagine that your next task is implementing a scientific calculator, which might have ten times the number of operations - main() would become very long, difficult to read and debug.

There are other benefits too. Without trying to go into too much detail, as this is probably a bit beyond where you are now, but there are advanced techniques available where the code in main() could be reduced considerably by moving from a giant switch statement to having an array of key, function pointer pairs - main becomes a little loop to find the appropriate entry in the array and call whatever function is relevant.

This is the nature of textbooks, due to space constraints it is difficult to include complex examples that might merit using more advanced techniques, not to mention the daunting task of introducing complex examples in a way that adds to understanding rather than creates confusion.

#### Share this post

##### Share on other sites

The code (the one in my pc compiles). I posted via phone so there is no way to indent or check errors.

What kind of program will use functions, i need something to practice on.
Thanks.

Literally an infinite amount of programs will use functions.

For testing purposed, I know several books have functions for e.g.:

- Compute the circumference of a circle, given radius as input.

- Compute the area of a circle, given radius as input.

- Compute the radius of a circle, given the area or circumference as input.

- Compute the volume of a sphere, given the radius as input.

- Store the users name (input) and print (output) a box of asterisks (*) large enough to fit the name + some padding.

- Print a ASCII triangle with the height determined by the user's input.

- Figure out the distance between 2 points, given 2 or 3 coordinates per point (2 for 2D distance, 3 for 3D distance).

- Write a function that takes a non-zero integer as input which computes the factorial of that input. Don't worry if it doesn't work for huge numbers where the result would exceed what a float/int can store. Stuff like that is more advanced.

- Create a function to output a sting using alternate UPPERCASE and lowercase.

#### Share this post

##### Share on other sites

The goal of functions is to break up larger groups of logic into smaller, self contained groups of logic.  In your case, you are breaking up mathematical operations.  While it is true that this produces more code, it *usually* makes programs easier to maintain.  Since I have seen you post a lot about game engines, I will use an example relating to a game engine.  You don't write a game engine entirely in the entry point -- to do so would be stupid, long, and it I can almost guarantee the code would not be maintainable (or is some cases usable).  On top of that, there are some special use cases were you would need functions.  Take for example a "collision check" function which returns a Boolean value -- "true" if there is collision, "false" if there is no collision.  Because of the functions nature, it could be called 1000+ times per-frame.  If you don't use functions, you would have to type the same code over and over again, versus calling a self contained function that takes two objects and returns a Boolean value.

Addressing the code snippets you have posted and the fact that they do not compile.

First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."  The way you are declaring functions is C-style syntax, but you are including C++ standard headers and using C++ data types (std::string).  While not an issue, it is a pet peeve of mine.  Second, after each function declaration you have "/>."  I am not sure if that is something your phone added, or if you coded that, but "/>" is not valid C or C++ syntax.  Third, C++ is CASE SENSITIVE.  In the parameter list of the functions you declare "B" as uppercase, but when you use it in the method, you use "b."  Finally, while not a problem, it annoys me a little.  The way you handle input is off.  You print out instructions once, and then have the user input three numbers, two of which have no instructions as to what they are.  If I didn't know this was a calculator, I would be staring at the screen, scratching my head.

Happy coding,

~ Byte.

EDIT: One more thing -- "Quit" generally referrers to the program exiting.  "system( "cls" )" clears the screen.

Edited by ByteTroll

#### Share this post

##### Share on other sites

The goal of functions is to break up larger groups of logic into smaller, self contained groups of logic.  In your case, you are breaking up mathematical operations.  While it is true that this produces more code, it *usually* makes programs easier to maintain.  Since I have seen you post a lot about game engines, I will use an example relating to a game engine.  You don't write a game engine entirely in the entry point -- to do so would be stupid, long, and it I can almost guarantee the code would not be maintainable (or is some cases usable).  On top of that, there are some special use cases were you would need functions.  Take for example a "collision check" function which returns a Boolean value -- "true" if there is collision, "false" if there is no collision.  Because of the functions nature, it could be called 1000+ times per-frame.  If you don't use functions, you would have to type the same code over and over again, versus calling a self contained function that takes two objects and returns a Boolean value.

Addressing the code snippets you have posted and the fact that they do not compile.

First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."  The way you are declaring functions is C-style syntax, but you are including C++ standard headers and using C++ data types (std::string).  While not an issue, it is a pet peeve of mine.  Second, after each function declaration you have "/>."  I am not sure if that is something your phone added, or if you coded that, but "/>" is not valid C or C++ syntax.  Third, C++ is CASE SENSITIVE.  In the parameter list of the functions you declare "B" as uppercase, but when you use it in the method, you use "b."  Finally, while not a problem, it annoys me a little.  The way you handle input is off.  You print out instructions once, and then have the user input three numbers, two of which have no instructions as to what they are.  If I didn't know this was a calculator, I would be staring at the screen, scratching my head.

Happy coding,
~ Byte.

EDIT: One more thing -- "Quit" generally referrers to the program exiting.  "system( "cls" )" clears the screen.

Um, what do you mean by i declare functions c style. I haven't learnt c so could you compare my code with a pure c++ code.
I know c++ is case sensitive, the phone thinks it's a smiley and changes it from b to B and adds /> everytime i edit the post.
What's wrong with my input?

#### Share this post

##### Share on other sites

If you leanr C++ you learn C too because c++ inherits from c as language. He mean with c style exactly what he wrote:

First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."  The way you are declaring functions is C-style syntax, but you are including C++ standard headers and using C++ data types (std::string).  While not an issue, it is a pet peeve of mine

#### Share this post

##### Share on other sites

He mean with c style exactly what he wrote:

First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."  The way you are declaring functions is C-style syntax, but you are including C++ standard headers and using C++ data types (std::string).  While not an issue, it is a pet peeve of mine

I know what he meant. What i'm asking is what part is c style since i don't know what c style code looks like.

#### Share this post

##### Share on other sites

I'm curious about that too. How would those functions look if they weren't in 'c-style'?

#### Share this post

##### Share on other sites

C-style functions are stand alone functions, C++-style functons are wrapped up and stored in an object.

Header.h

//This is C-Style header
void MakeAnimalSound();

//This is C++ style header
class Animal {
public:
void MakeSound();
}


Source.c

//This is a C-style implementation
void MakeAnimalSound() {
//Do stuff here

}


Source.cpp

//This is a C++ style implementation
void Animal::MakeSound() {
//Do stuff here
}

Edited by ByteTroll

#### Share this post

##### Share on other sites

-- First, you mention "C++."  What you are programming in there is the beginner "hybrid mix."

So, put everything in a class "just because?" I see people who liberally create c++11 inline templated headers as full fledged implementations. It's not how I program, and I don't judge them either. They certainly know what they're doing, but it's an uncomfortable read for me. I came from many years of programming C. If anything, it has taught me to be practical about my programming. I programmed faster when I didn't use classes, but I also produced more code. I soon after programmed mostly pure C++. Now, I just do whatever I need to do, simply out of acknowledging I should really only produce the code I absolutely need (right now). Whatever floats your boat, right?

I don't think the guy who posted the questions is currently learning classes, though.

It's easier to learn functions by seeing the simplest examples where they are useful, and many here have already provided some.

#### Share this post

##### Share on other sites

One basic rule of thumb: "prefer non-friend non-member functions". Meaning: if there isn't a good reason for a function to be part of a class (like needing to access private members), it has no business being a member-function.

Unless one wants to argue that most of the C++ standard library is bad code, it's not just perfectly fine but even recommended not to stuff everything into objects "just because". Namespaces on the other hand are almost always a good idea for projects that are either complex and/or use multiple libraries.

Here are two examples of "C style functions":

//Explicitly declaring "no parameters" (in C: empty list = any number of parameters)

int function(void) { return 42; }

//Skipping return and/or parameters type (C defaults to int, C++ won't compile)

function(x) { return 2*x; }

#### Share this post

##### Share on other sites
I haven't learned classes.
What's the difference between my code and pure c++ code? I thought mine was c++. I didn't copy/paste it from anywhere, i wrote it after reading about it in the jumping into c++ book.
Could you write that code using only c++ so that i know what you guys are refering to.

#### Share this post

##### Share on other sites
Think of functions in a programming language same as you would in mathematics. That's where the name comes from, after all.

A parabola is defined algebraically as y=x*x. It could be defined as a function P:R->R (the function named 'P' that converts one Real number into another Real number) denoted P(x) = x*x.

Then anytime you need a parabola you don't have to type out the whole expression (though quite short in this case, it wouldn't be for something like an associated Legendre function) but instead you can just drop in P(whatever) and get the result. This is a form of parameterization. You want to encode some behavior that you can change with different inputs. You don't want to write code for a single specific parabola but rather for all parabolas (any X parameter).

In math, you usually write functions for complicated pieces of math because you don't want to repeat yourself while writing out a complex equation. This is similar for programs: you write functions where you have complicated pieces of logic that you don't want to cut-n-paste all over while writing your program.

In your example, std::cin>> and std::cout<< are actually function calls (using a funky form of operator overloading in C++, a more advanced topic). Writing something like std::cout<<"text" is basically equivalent to writing print("text"). That's a use of a function (which itself calls through many, many other functions). You're very thankful that's a function because you really, really don't want to have to write all the code get text on your screen.

As you explore C++, you may also come across "methods" (formally called "member functions" in C++) and operator loading (which are just a fancy syntax for functions that look like built-in operators like << or + or whatnot). Conceptually, they're all the exact same thing: they are differing syntaxes for convenience purposes.

#### Share this post

##### Share on other sites

I haven't learned classes.
What's the difference between my code and pure c++ code? I thought mine was c++. I didn't copy/paste it from anywhere, i wrote it after reading about it in the jumping into c++ book.
Could you write that code using only c++ so that i know what you guys are refering to.

Yeah just ignore the c/c++ comparison stuff.

#### Share this post

##### Share on other sites
Ok. I'm going to write a switching menu program (i.e. switch from calculator to games and vice versa).
I think that would use functions better because i won't have to use if statements when the user inputs switch to game and the re-type the game code.

#### Share this post

##### Share on other sites

• Advertisement
• Advertisement
• ### Popular Tags

• Advertisement
• ### Popular Now

• 11
• 20
• 10
• 11
• 12
• Advertisement