Arithmetic Operators

      Some of the basic mathematical operators that we use in our high school algebra are included in Arithmetic operators, including a few more useful ones that you don't generally come across in mathematics. These are illustrated in the code example below.

#include <stdio.h>

int main() {

   int  a = 5;
   int  b = 10; 
   
   printf("A + B = %d\n", a+b); 
   /*Addition operator - Adds two operands */
 
   printf("A - B = %d\n", a-b); 
   /*Substraction operator - Substracts second operand from the first */
 
   printf("A * B = %d\n", a*b); 
   /*Multiplication operator - Multiplies two operands and produces product */
 
   printf("B / A = %d\n", b/a); 
   /*Division operator - First operand (dividend) is divided by the second (divisor) and pr  oduces their quotient */
 
   printf("B %% A = %d\n", b%a); 
   /*Modulus operator - Produces remainder when performing b/a. '%%' is used to display '%'   */
 
   printf("++A = %d\n", ++a); 
   /*Increment operator - Increments value by 1 */
 
   printf("--B = %d\n", --b); 
   /*Decrement operator - Decrements value by 1 */
 
   return 0;

}
Output:








+, -, *, /, % are Binary operators, operating on two operands. ++ and -- are Unary operators, meaning, they operate on single operand. When ++ & -- are applied before the variable/expression, they are called pre increment and pre decrement operators respectively. In the contrary, if they are applied after a variable, then they are called post increment/decrement operators.
Post increment/decrement operators increments/decrements the value of the variable after the variable is evaluated, while Pre increment/decrement operators causes change in value of the variable before the variable is evaluated.

For example :


#include <stdio.h>

int main() {

   int  a = 5;
   int  b = 10; 
   
   printf("(A++) + (++A) + (--B) = %d", ((a++) + (++a) + (--b)));
 
   return 0;

}

The output produced is:
(A++) + (++A) + (--B) = 21
    Let us examine how the expression ((a++) + (++a) + (--b))  produced 21

  • a++ gives 5, a=6 (post increment), b=10
  • ++a gives 7, a=7 (pre increment), b=10
  • --b gives 9, a=7, b=9 (pre decrement)
Therefore, 5 + 7 + 9 = 21

This ends the discussion of Arithmetic Operators.
Previous
Next Post »