Numbers in C#


For numbers in C#, use the int type. It represents an integer, which is positive or negative whole number.

Let us see how to add two integers in C# using mathematical operator + −

using System;
using System.Linq;

class Program {
   static void Main() {
      int x = 20;
      int y = 30;
      int sum = 0;

      sum = x + y;
      Console.WriteLine(sum);
   }
}

Now let us learn about the order in which these mathematical operators i.e. operator precedence.

Operator precedence determines the grouping of terms in an expression. This affects evaluation of an expression. Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator.

For example x = 9 + 2 * 5; here, x is assigned 19, not 55 because operator * has higher precedence than +, so the first evaluation takes place for 2*5 and then 9 is added to it.

The following is an example showing the order of operators −

Example

using System;
namespace Demo {
   class Program {
      static void Main(string[] args) {

         int a = 200;
         int b = 100;
         int c = 150;
         int d = 50;
         int res;

         res = (a + b) * c / d;
         Console.WriteLine("Value of (a + b) * c / d is : {0}", res);

         res = ((a + b) * c) / d;
         Console.WriteLine("Value of ((a + b) * c) / d is : {0}", res);

         res = (a + b) * (c / d);
         Console.WriteLine("Value of (a + b) * (c / d) : {0}",res);

         res = a + (b * c) / d;
         Console.WriteLine("Value of a + (b * c) / d : {0}",res);

         Console.ReadLine();
      }
   }
}

Updated on: 21-Jun-2020

107 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements