Write a program that calculates the mathematical expression

Solution

Oops! This is a really complex expression. Let’s take a look at an approach that even a newbie can follow.

The main idea is to break the complex expression into smaller, simpler expressions and assign each sub-result to temporary variables. In the end, you can build the original expression out of all these temporary variables! This approach is presented here.

PHP

Java

C++

C#

Visual Basic

Python

You may say, “Okay, but I wasted so many variables and as everybody knows, each variable is a portion of main memory. How can I write the original expression in one single line and waste less memory?

This job may be a piece of cake for an advanced programmer, but what about you? What about a novice programmer?

The next method will help you write even the most complex mathematical expressions without any syntax or logic errors! The rule is very simple. “After breaking the complex expression into smaller, simpler expressions and assigning each sub-result to temporary variables, start backwards and replace each variable with its assigned expression. Be careful though! When you replace a variable with an expression, you must always enclose the expression in parentheses!”

Confused? Don’t be! It’s easier in action. Let’s try to rewrite the previous program. Starting backwards, replace variables nominator and denominator with their assigned expressions. The result is

PHP

php

Java

java

C++

java

C#

java

Visual Basic

java

Python

java

Notice: Please note the extra parentheses added.

Now you must replace variables temp1, temp2, and temp3 with their assigned expressions, and the one-line expression is complete!

PHP

php2

Java

java2

C++

java2

C#

java2

Visual Basic

vb2

Python

python2

It may look scary at the end but it wasn’t that difficult, was it?

The program can now be rewritten

PHP

Java

C++

C#

Visual Basic

Python

Leave a Reply

Your email address will not be published. Required fields are marked *

This article is taken from a book of mine. If you enjoyed it, please visit my author's page inand check out all of my books!