Jan 14, 2012

Arithmetic Expression

Basic arithmetic expression such as addition, subtraction, multiplication and division can be written in C by using following signs:
  • plus (+)
  • minus (-)
  • asterisk (*)
  • slash (/)

For example,

#include<stdio.h>

int main()
{
   int n1, n2, n3;
   n1 = 4;
   n2 = 2;
   n3 = n1 + n2;
   printf("n3 is %d\n", n3);

   n3 = n1 - n2;
   printf("n3 is %d\n", n3);

   n3 = n1 * n2;
   printf("n3 is %d\n", n3);

   n3 = n1 / n2;
   printf("n3 is %d\n", n3);

   return 0;
}

2 and 4 are assigned to n1 and n2. n3 is assigned with the result of adding n1 with n2. The next arithmetic is subtracting n2 from n1 and the result is stored in n3. Statement

n3 = n1 * n2;

introduces multiplication operator and storing the result in n3. The last arithmetic statement reads,

n3 = n1 / n2;

n1 is divided with n2 and the result (quotient) is stored in n3. Remainder of a division operation can be obtained by using modulus operator which is denoted by percent (%) sign. For example,

   ...
   n1 = 5;
   n2 = 2;

   n3 = n1 % n2;
   printf("n3 is %d\n", n3);
   ...

The value of n3 is 1.