Operators in C | Arithmetic Operators

Arithmetic Operators

C defines the following arithmetic operators:

Operator Meaning
+ Addition
Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus

+ (Addition)

a+b
a=a+b
a=a+10
a=b+20

– (Subtraction (also unary minus))

a-b
a=a-b
a=a-7
a=b-5

* (Multiplication)

a*b
a=a*b
a=a*3
a=b*20

/ (Division)

a/b
a=a/b
a=a/5
a=b/20

% (Modulus Operator)

  • It returns remainder
  • It works with only int values
  • if it is used with float values an error will get generated.

When / is applied to an integer, any remainder will be truncated.
For example, 10/3 will equal 3 in integer division.

When % is applied to an integer, it gives remainder.
For example, 10%3 will equal 1.

Note:   For modulo operator, the sign of the result is always the sign of the first operand (the dividend).

-14 % 3 = -2
-14 % -3 = -2
14 % -3 = 2
14 % 3 = 2

Note:

Question: To find the remainder without using “%”.
Sol:

Modulo division is defined as:
a%b= a-(a/b)*b, where a/b is an integer division.

Question:1
C program to assume two numbers calculate and print their sum, product, difference, and average?
Sol:

#include<stdio.h>
int main()
{
    int a=10,b=20,s,p,d;
    float av;
    s=a+b;
    p=a*b;
    d=a-b;
    av=(float)(a+b)/2;
    printf("Sum = %d\n",s);
    printf("Product = %d\n",p);
    printf("difference = %d\n",d);
    printf("average = %f\n",av);

    return 0;
}

Output:

Sum = 30
Product = 200
difference = -10
average = 15.000000