Ads

Arithmetic Operators

ARITHMETIC OPERATORS:


- They are binary operators, because they operate on two operands.
- These are the basic operators like addition, subtraction, multiplication, division and their symbols are same as the mathematical operators ‘+’ for addition, ‘-‘ for subtraction, ‘*’ for multiplication, ‘/’ for division but we have an operator called  modulus or percentile denoted by ‘%’ which gives out the remainder after dividing operands. And the basic syntax is

Syntax:

<first operand> <operator> <second operand>;

or you can also go for multiple operators like

<operand1> <operator> <operand2> <operator> <operand3> <operator>…..;
- Angled brackets are used for demonstration purpose only and should not be used in your c program.

Ex:

a+b /*performs addition */
a*b /*performs multiplication*/
a-b /*performs subtraction*/
a/b /*performs division returns quotient*/
a%b /*gives remainder as output*/

Ex:
if a=5,b=6
then
a+b /*adds the value in a and b and returns the results*/
a*b /* multiplies and returns the result
a-b
if a=3,b=5 then,
a/b=0 
a%b =3

- While performing division or modulus division the denominator must not be a zero.
- 3/5 is zero? why?

Explanation: Mathematically 3/5 is 0.6 but we are storing the 0.6 in integer variable so .6 is truncated and thus 0 is the result. This topic is called type casting and explained in separate chapter.

- While modulo operation if numerator is less than denominator the value returned is numerator itself.

Note: % operator cannot be used on float values like
5.0 % 8.38, it is not valid.
5%7 since 5<7 output is 5


Arithmetic example program:

/*Write a program to print result of addition, subtraction, multiplication, division and modulo division of two values. */


#include<stdio.h>
int main()
{
 int a=10, b=3;
 printf ("\nThe value of a=%d and b=%d",a,b);
 printf("\n a+b=%d",a+b);
 printf("\n a-b= %d",a-b);
 printf("\n a*b=%d",a*b);
 printf("\n a/b=%d",a/b);
 printf("\n a%%b=%d",a%b); /* %% inserts a % symbol*/

  return 0;
}

Output:
The value of a=10 and b=3
a+b=13
a-b= 7
a*b=30
a/b=3
a%b=1
- We can also take the values of a and b from runtime using scanf() function as demonstrated in below example.

Program:


/*Write a program to take a and b values from runtime and perform addition, multiplication, etc. */


#include<stdio.h>
int main()
{
 int a,b;
 printf("\nEnter the value of a: ");
 scanf("%d",&a);
 printf("\nEnter the value of b: ");
 scanf("%d",&b);
 printf("\nThe value of a=%d and b=%d",a,b);
 printf("\n a+b=%d",a+b);
 printf("\n a-b= %d",a-b);
 printf("\n a*b=%d",a*b);
 printf("\n a/b=%d",a/b);
 printf("\n a%%b=%d",a%b); /* %% inserts a % symbol*/

 return 0;
}

Output:
Enter the value of a: 3
Enter the value of b: 10
The value of a=3 and b=10
a+b=13
a-b= -7
a*b=30
a/b=0
a%b=3

No comments:

Post a Comment