Friday, July 29, 2016

C Basics - Arithmetic Operators in C

The following table shows all the arithmetic operators supported by the C language. Assume variable x holds 21, y holds 10 and variable z holds 0 then.

Operator Name Syntax Description Example
Direct assignment x = y Assigns values from right side operands to left side operand z = x;
z = 21
Addition x + y Adds two operands. z = x + y;
z = 31
Subtraction x - y Subtracts second operand from the first. z = x – y;
z = 11
Multiplication x * y Multiplies both operands. z = x * y;
z = 210
Division x / y Divides numerator by de-numerator. z = x / y;
z = 2
Modulo x % y Modulus Operator and remainder of after an integer division. z = x % y;
z = 1
IncrementPrefix ++x Increment operator increases the integer value by one. z = ++x;
z = 22
Postfix x++ z = x++;
z = 21
Decrement Prefix --x Decrement operator decreases the integer value by one. z = --x;
z = 20
Postfix x-- z = x--;
z = 21
Unary plus +x Integer promotion. Operates on single operand z = +x;
z = 21
Unary minus -x Additive inverse. Operates on single operand z = -x;
z = -21


#include <stdio.h>

int main() 
{
 int x = 21;
 int y = 10;
 int z = 0;
    
 printf("Arithmetic operators demo\n");
 printf("Value of x is %d\n", x );
 printf("Value of y is %d\n", y );
 printf("Value of z is %d\n", z ); 
   
  z = x;
 printf("Direct Assignment (z = x): %d\n", z );
 
 z = x + y;
 printf("Addition (z = x + y): %d\n", z );
 
 z = x - y;
 printf("Subtraction (z = x - y): %d\n", z );
 
 z = x * y;
 printf("Multiplication (z = x * y): %d\n", z );
 
 z = x / y;
 printf("Division (z = x / y): %d\n", z );
 
 z = x % y;
 printf("Modulo  (z = x mod y): %d\n", z );
 
 z = ++x;
 printf("PreIncrement (z = ++x): %d\n", z );
 
 x = 21;
 z = x++;
 printf("PostIncrement (z = x++): %d\n", z );
 
 x = 21;
 z = --x;
 printf("PreDecrement (z = --x): %d\n", z );
 
 x = 21;
 z = x--;
 printf("PostDecrement (z = x--): %d\n", z );
 
 x = 21;
 z = +x;
 printf("Unary plus (z = +x): %d\n", z );

 z = -x;
 printf("Unary minus (z = -x): %d\n", z );   

    return 0;
}

The output of the above program would be:

Arithmetic operators demo
Value of x is 21
Value of y is 10
Value of z is 0
Direct Assignment (z = x): 21
Addition (z = x + y): 31
Subtraction (z = x - y): 11
Multiplication (z = x * y): 210
Division (z = x / y): 2
Modulo  (z = x mod y): 1
PreIncrement (z = ++x): 22
PostIncrement (z = x++): 21
PreDecrement (z = --x): 20
PostDecrement (z = x--): 21
Unary plus (z = +x): 21
Unary minus (z = -x): -21



Related topics:
Overview of Operators in C   |   Relational Operators in C   |   Logical Operators in C   |   Bitwise Operators in C   |   Compound Assignment Operators in C   |   Conditional Operators in C   |   Miscellaneous Operators in C   |   Operator Precedence and Associativity in C

List of topics: C Programming

No comments:

Post a Comment