Learn C - C Arithmetic Operators






C supports the four basic arithmetic operations such as addition, subtraction, multiplication, and division.

An arithmetic statement is of the following form:

variable_name = arithmetic_expression;

The arithmetic expression on the right of the = operator specifies a calculation using values stored in variables or explicit numbers that are combined using arithmetic operators such as addition (+), subtraction (-), multiplication (*), and division (/).

total_count = birds + tigers + pigs + others;

The following table lists the Basic Arithmetic Operators.

OperatorAction
+Addition
-Subtraction
*Multiplication
/Division
%Modulus

The values that an operator is applied to are called operands. An operator that requires two operands, such as %, is called a binary operator.

An operator that applies to a single value is called a unary operator. Thus - is a binary operator in the expression a - b and a unary operator in the expression -data.


    #include <stdio.h> 
      //from  www. ja  v  a2  s  .  c  om
    int main(void) 
    { 
      int cakes = 5; 
      int CALORIES = 125;                     // Calories per cookie 
      int total_eaten = 0;              
      
      int eaten = 2;                       
      cakes = cakes - eaten;               
      total_eaten = total_eaten + eaten; 
      printf("I have eaten %d cakes.  There are %d cakes left", eaten, cakes); 
      
      eaten = 3;                            // New value for cakes eaten 
      cakes = cakes - eaten;                
      total_eaten = total_eaten + eaten; 
      printf("\nI have eaten %d more.  Now there are %d cakes left\n", eaten, cakes); 
      printf("\nTotal energy consumed is %d calories.\n", total_eaten * CALORIES); 
      return 0; 
    } 

The code above generates the following result.





Example

The following is the code illustration for basic arithmetic:


  #include <stdio.h> 
/*from w  w w .  j a  va2  s. com*/
  int main() { 
     int a,b,c; 
     a = 10; 
     b = 6; 

     c = a + b; 
     printf("%d + %d = %d\n",a,b,c); 

     c = a - b; 
     printf("%d - %d = %d\n",a,b,c); 

     c = a * b; 
     printf("%d * %d = %d\n",a,b,c); 

     float d = a / b; 
     printf("%d / %d = % .2f\n",a,b,d); 

     float e =(float)a / b; 
     printf("%d / %d = % .2f\n",a,b,e); 

     return 0; 
  } 

The code above generates the following result.





Division and the Modulus Operator

Suppose you have 45 cakes and a group of seven children.

You'll divide the cakes equally among the children and work out how many each child has.

Then you'll work out how many cakes are left over.


#include <stdio.h> 
  /*  www.ja  va 2 s  . c  om*/
int main(void) { 
  int cakes = 45;                         
  int children = 7;                       
  int cakes_per_child = 0;                
  int cakes_left_over = 0;                
  
  // Calculate how many cakes each child gets when they are divided up 
  cakes_per_child = cakes/children;     
  printf("%d children and %d cakes\n", children, cakes); 
  printf("each child has %d cakes.\n", cakes_per_child); 
  
  cakes_left_over = cakes%children; 
  printf("%d cakes left over.\n", cakes_left_over); 
  return 0; 
} 

The code above generates the following result.

op= Form of Assignment

C is a very concise language and it provides you with abbreviated ways of specifying some operations.

Consider the following statement:

number = number + 10;

This sort of assignment has a shorthand version:

number += 10;

The += operator after the variable name is one example of a family of op= operators.

This statement has exactly the same effect as the previous one, and it saves a bit of typing.

The op in op= can be any of these arithmetic operators:

+  -  *  /  %

If you suppose number has the value 10, you can write the following statements:

number *= 3;               // number will be set to number*3 which is 30 
number /= 3;               // number will be set to number/3 which is 3 
number %= 3;               // number will be set to number%3 which is 1 

The op in op= can also be a few other operators that you haven't encountered yet:

<<  >>  &  ^  |

The op= set of operators always works the same way.

The general form of statements using op=:

lhs op= rhs;

where rhs represents any expression on the right-hand side of the op= operator.

The effect is the same as the following statement form:

lhs = lhs op (rhs);

First, consider this statement:

variable *= 12;

This is the same as:

variable = variable * 12;

You now have two different ways of incrementing an integer variable by 1.

Both of the following statements increment count by 1:

count = count + 1; 
count += 1; 

Because the op in op= applies to the result of evaluating the rhs expression, the statement:

a /= b + 1;

is the same as

a = a/(b + 1);

divisions we have known


  #include <stdio.h> 
  int main(void) 
  { /*from  w  w  w.  j  av  a 2s  .  com*/
       printf("integer division:  5/4   is %d \n", 5/4); 
       printf("integer division:  6/3   is %d \n", 6/3); 
       printf("integer division:  7/4   is %d \n", 7/4); 
       printf("floating division: 7./4. is %1.2f \n", 7./4.); 
       printf("mixed division:    7./4  is %1.2f \n", 7./4); 
   
       return 0; 
  }    

The code above generates the following result.

Example 2

The following code shows how to write a simple calculator that can add, subtract, multiply, divide, and find the remainder when one number is divided by another.


#include <stdio.h>
/*from www  .j a  va 2s .c o  m*/
int main(void) {
  double number1 = 0.0;           //* First operand value a decimal number  *//
  double number2 = 0.0;           //* Second operand value a decimal number *//
  char operation = 0;             //* Operation - must be +, -, *, /, or %  *//

  printf("\nEnter the calculation(eg. 1+2)\n");
  scanf("%lf %c %lf", &number1, &operation, &number2);

  switch(operation)
  {
    case '+':                     // No checks necessary for add
      printf("= %lf\n", number1 + number2);
      break;

    case '-':                     // No checks necessary for subtract
      printf("= %lf\n", number1 - number2);
      break;

    case '*':                    // No checks necessary for multiply
      printf("= %lf\n", number1 * number2);
      break;

    case '/':
      if(number2 == 0)           // Check second operand for zero
        printf("\n\n\aDivision by zero error!\n");
      else
        printf("= %lf\n", number1 / number2);
      break;

    case '%':                    // Check second operand for zero
      if((long)number2 == 0)
         printf("\n\n\aDivision by zero error!\n");
      else
        printf("= %ld\n", (long)number1 % (long)number2);
      break;

    default:                     // Operation is invalid if we get to here
      printf("\n\n\aIllegal operation!\n");
      break;
  }

  return 0;
}

The code above generates the following result.