Arithmetic operators and precedence in C# vs Python

Arithmetic operators in C# and Python

In the previous lesson we used the * operator to calculate the product of two integers. Let us now discuss briefly about the arithmetic operators available in C# and Python.

Symbol

*

/

+

Operation

Multiplication

Division

Addition

Subtraction

Operator precedence

Lets take an example to understand the order in which operations are performed C# and Python. Suppose we have 10 dollars at the start of an year and we earn 2.5 dollars each day till the end of the year. The following program calculates the number of dollars we will have at the end of the year.

C# code

Python code

It is important to memorize the order in which a programming language performs operations. In the above example, the value of  final is 922.5. This value is obtained by first multiplying 365 with 2.5 and adding 10 to the product. Irrespective of the order in which these operations are written, multiplication takes precedence over addition operation. If we wanted to add first, we must enclose the addition operation inside parenthesis.



In this case, addition will be performed first since parenthesis take precedence over multiplication. The variable final will have a value of 4562.5. The precedence of basic operators is shown in the following table. Topmost symbol has the highest precedence.

Operator Precedence

()

/ *

+ –

Parenthesis

Multiplication and Division

Addition and Subtraction

 

< Variable declaration and initialization               Getting string input >

What we learnt

  1. Arithmetic operators available in C# and Python.
  2. The order in which operations are performed by a programming language must be kept in mind.

You may also like: