C - Use Division And Modulus Operator

Introduction

Suppose you have a program of 45 bugs and a group of seven developers.

You'll divide the bugs equally among the developers and work out how many each developer has.

You'll work out how many bugs are left over.

Demo

#include <stdio.h>

int main(void)
{
  int bugs = 45;                   // Number of bugs in the code
  int developers = 7;              // Number of developers
  int bugs_per_developer = 0;      // Number of bugs per developer
  int bugs_left_over = 0;          // Number of bugs left over

  // Calculate how many bugs each developer gets when they are divided up
  bugs_per_developer = bugs/developers;     // Number of bugs per developer
  printf("You have %d developers and %d bugs\n", developers, bugs);
  printf("Give each developer %d bugs.\n", bugs_per_developer);

  // Calculate how many bugs are left over
  bugs_left_over = bugs%developers;//  www. j  a  v  a2s .c o  m
  printf("There are %d bugs left over.\n", bugs_left_over);
  return 0;
}

Result

Program step by step

Four integer variables, bugs, developers, bugs_per_developer, and bugs_left_over, are declared and initialized with the following statements:

int bugs = 45;               // Number of bugs in the jar
int developers = 7;          // Number of developers
int bugs_per_developer = 0;  // Number of bugs per developer
int bugs_left_over = 0;      // Number of bugs left over

The number of bugs is divided by the number of developers by using the division operator / to produce the number of bugs given to each developer:

bugs_per_developer = bugs/developers;     // Number of bugs per developer

The next two statements output what is happening, including the value stored in bugs_per_developer:

printf("You have %d developers and %d bugs\n", developers, bugs);
printf("Give each developer %d bugs.\n", bugs_per_developer);

The division operator always produces an integer result when the operands are integers.

The result of dividing 45 by 7 is 6, with a remainder of 3.

You calculate the remainder in the next statement by using the modulus operator:

bugs_left_over = bugs%developers;

Finally, you output the remainder in the last statement:

printf("There are %d bugs left over.\n", bugs_left_over);

Related Topic