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?
The modulo operator provides the whole number left after dividing the first number by the second number. This means that subtracting the remainder from the first number will make it a multiple of the second number. For example, 28 can be changed to be a multiple of 5 by taking the modulo 28 % 5.
The modulo operation (abbreviated “mod”, or “%” in many programming languages) is the remainder when dividing. For example, “5 mod 3 = 2” which means 2 is the remainder when you divide 5 by 3.
The % symbol in Python is called the Modulo Operator. It returns the remainder of dividing the left hand operand by right hand operand. It's used to get the remainder of a division problem. The modulo operator is considered an arithmetic operation, along with + , - , / , * , ** , // .
C++ provides the modulus operator, %, that yields the remainder after integer division. The modulus operator can be used only with integer operands. The expression x % y yields the remainder after x is divided by y. Thus, 7 % 4 yields 3 and 17 % 5 yields 2.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With