Click 'Run' to go.
It's this simple: Arithmetic inside of parentheses is calculated first. If there are parentheses inside of parentheses, then the arithmetic within the inner parentheses is calculated first, and then the calculation proceeds into the outer parentheses.
Any arithmetic calculated within parentheses proceeds with the normal order for precedence.
So this expression:
(2 + 3) * 4
Evaluates to 20 because:
Note that in this example addition was done before multiplication. Normally, multiplication preceeds addition according to the rules of precedence, but the parentheses changed that. So, it is often said that parentheses are used to change or govern the order of precedence.
Be sure to note the parentheses as they appear in the print command in this demo. Try different combinations of numbers and arithmetic operators. Imagine the answer, and then run the program to see if you are correctly understanding how parentheses and precedence work.
Many programers will use parentheses to show their calculations more clearly. For example, the equation for a straight line can be expressed in mathematics notation as:
In a computer language this could look like:
Since multiplication has precedence over addition, m times x will be calculated first, and then b will be added, which is just what we want. However, this code might be expressed with parentheses as:
Although the parentheses are not needed, many feel they aid understanding by clearly showing the m times x to be a separate term as it is presented in the math notation.
Here's the current flowchart for this demo:
This could appear like so in an imaginary computer language:
print((2 + 3) * 4);
Suggested next article:
The following article is related to this demo: