37

Let's say that I need to format the output of an array to display a fixed number of elements per line. How do I go about doing that using modulus operation?

Using C++, the code below works for displaying 6 elements per line but I have no idea how and why it works?

for ( count = 0 ; count < size ; count++)
{
    cout << somearray[count];
    if( count % 6 == 5) cout << endl;
}

What if I want to display 5 elements per line? How do i find the exact expression needed?

ronalchn
  • 12,225
  • 10
  • 51
  • 61
Tex Qas
  • 371
  • 1
  • 3
  • 4
  • 3
    Please note that the name of the operation is **modulo operation**. The term **modulus** is the role given to `b` in `a % b`. https://en.wikipedia.org/wiki/Modulo_operation – parml Sep 02 '19 at 08:20

5 Answers5

43

in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:

5 % 2 = 1
13 % 5 = 3

With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).

To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).

KCH
  • 2,794
  • 2
  • 23
  • 22
7

Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2

for same thing C++ has modulus operator ('%')

Basic code for explanation

#include <iostream>
using namespace std;


int main()
{
    int num = 11;
    cout << "remainder is " << (num % 3) << endl;

    return 0;
}

Which will display

remainder is 2

Atri Dave
  • 152
  • 2
  • 9
3

It gives you the remainder of a division.

int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c
Gung Foo
  • 13,392
  • 5
  • 31
  • 39
3

This JSFiddle project could help you to understand how modulus work: http://jsfiddle.net/elazar170/7hhnagrj

The modulus function works something like this:

     function modulus(x,y){
       var m = Math.floor(x / y);
       var r = m * y;
       return x - r;
     }
SkySibe
  • 153
  • 1
  • 7
2

You can think of the modulus operator as giving you a remainder. count % 6 divides 6 out of count as many times as it can and gives you a remainder from 0 to 5 (These are all the possible remainders because you already divided out 6 as many times as you can). The elements of the array are all printed in the for loop, but every time the remainder is 5 (every 6th element), it outputs a newline character. This gives you 6 elements per line. For 5 elements per line, use

if (count % 5 == 4)

Andy Harris
  • 928
  • 5
  • 10