Arithmetic Operators in C

by | Aug 15, 2021 | C

Home » C » Arithmetic Operators in C

Arithmetic Operators in C

Arithmetic operators in C take numerical values (literals or variables) as their operands and give a single numeric value as a result.

Arithmetic operators in C are:

Operator Description
+Adds operands
Subtracts second operand from the first
*Multiplies both operands
/Divides numerator by denominator
%Modulus operator returns the remainder after an integer division.

Examples

#include<stdio.h>
int main()
{
int a,b;
a=10;
b=20;
printf("Sum=%d\n",a+b);
int product;
product=a*b;
printf("product=%d",product);
printf("\nremainder=%d",b%a);
}

Output

Arithmetic Operators in C

Hopefully, the above code and its output are clear.

 

Now, let’s discuss the ‘/’ operator.

Scenario:

If we declare two variables as integers and perform division operations on them, the result will be an integer.

9/2=4 (not 4.5)

To get a float value as a resultant, either the numerator or the denominator, or both of them must be the float values.

9.0/2=4.5

9/2.0=4.5

9.0/2.0=4.5

9/2=4

Program:

#include<stdio.h>
int main()
{
float a;
int b;
a=9.5;
b=2;
printf("%f ",a/b);
}

Output:

Arithmetic Operators in C Output

‘a’ is of type float, and ‘b’ is of type int. We get the float type result value. Remember to use ‘%f’ format specifiers in such cases.

Practice each case on your own to get a better understanding.

Hierarchy of Operations

How should we evaluate an expression with more than one operator in an expression like ‘x*5+y/z-q*s’? In mathematics, BODMAS is used to decide which operator will be evaluated first. However, this rule is not applicable in the programming language.

There is a precedence order in C language that decides which operator to be evaluated first in the problems containing more than one operator.

  1. Expressions written inside brackets ‘( )’ are evaluated first.
  2. *, /, %, all three operators have the highest priority and have associativity left to right if two or all three operators come in one expression.
  3. +, , comes at the 2nd number in the priority list and has associativity left to right.
  4. =, equality comes last in the priority list having associativity right to left.

Example:

X=16*4/2+9/3

Solving, ‘16*4’ first from left to right: 64/2+9/3

Now solving both ‘64/2’ and ‘9/3’: 32+3

Operating addition in last: 35

Now, making 35 equals X since it has the least priority:

X=35.

Practice Question

Question: int a= 10/45*23%45/(45%4*21), what would be the value of ‘a’?

Solution: 10/45*23%45/(45%4*21)

10/45*23%45/21

0*23%45/21

0

a= 0

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author