C - Use Basic Arithmetic Operators and variables

Basic Arithmetic Operators

Operator Action
+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.

- is a binary operator in the expression a - b and a unary operator in the expression -data.

The following code demonstrates subtraction and multiplication:

Demo

// Calculations with bugs
#include <stdio.h>

int main(void)
{
      int bugs = 5;
      int bug_cost = 125;          // cost per bug
      int total = 0;               // Total bugs fixed

      int fixed = 2;               // Number to be fixed
      bugs = bugs - fixed;         // Subtract number fixed from bugs
      total = total + fixed;//w ww .  j av a  2  s .  c  om
      printf("\nI have fixed %d bugs.  There are %d bugs left", fixed, bugs);

      fixed = 3;                    // New value for bugs fixed
      bugs = bugs - fixed;          // Subtract number fixed from bugs
      total = total + fixed;
      printf("\nI have fixed %d more.  Now there are %d bugs left\n", fixed, bugs);
      printf("\nTotal energy consumed is %d cost.\n", total*bug_cost);
      return 0;
}

Result

You first declare and initialize three variables of type int:

int bugs = 5;
int bug_cost = 125;                // cost per bug
int total = 0;                      // Total bugs fixed

You'll use the total variable to accumulate the total number of bugs fixed as the program progresses, so you initialize it to 0.

next you declare and initialize a variable that holds the number of bugs to be fixed:

int fixed = 2;                            // Number to be fixed

You use the subtraction operator to subtract fixed from the value of bugs:

bugs = bugs - fixed;                // Subtract number fixed from bugs

the result of the subtraction is stored back in the variable bugs, so the value of bugs will now be 3.

Because you've fixed some bugs, you increment the count of the total that you've fixed by the value of fixed:

total = total + fixed;

You add the current value of fixed, which is 2, to the current value of total, which is 0. the result is stored back in the variable total.

printf() statement displays the number of bugs that have been fixed and that are left:

printf("\nI have fixed %d bugs.  There are %d bugs left",fixed, bugs);

Related Topic