# Modulo example

Im looking for a situation wehere you need the modulo operator

1/18/2017 3:18:02 PM

Eyup Sogukcesme6 Answers

New AnswerSo i used it in a lot of places already. Basic example is to shift an array. So i'll illustrate it: You have an array with 3 values and you want to shit it 1 place to the left and save as second array So you creating basic loop and fo each element you are getting shifted one: arr[i] = arr[(i + 1) % len(arr)] Now for 0th element we are getting element # (0 + 1) % 3 # 3 is array length(example) so index will be 1 % 3 = 1 But for last element: arr[2] = arr[(2 + 1) % 3] Index will be 3 % 3 = 0, it will close the cycle

Think division, but you are looking for the remainder fraction. You want the result to be exactly equal giving you 0, and not have excess - after the period. int a = 13, b = 2; if (a % b == 0) { cout << "Great"; }else{ cout << "Not great"; } This will output "Not great" because 13 % 2 = 5. If a was 12, the output would be "Great" as they are shared equally with no remainder fraction || piece.

May b odd even example. If a number divided by 2 is equal to 0 then number is even else odd.

Best examples are to find a number whether it is even or odd, whether a number is prime or not.

As many people are used to packages and modules while writing a code we are not coming across using modulo operations as such... One obvious thing I can say is it is used in date module for sure...