Practical Modulo Examples
Real-World Modulo Applications
1. Even/Odd Number Detection
bool isEven(int number) {
return number % 2 == 0;
}
bool isOdd(int number) {
return number % 2 != 0;
}
2. Cyclic Array Indexing
graph LR
A[Input Index] --> B[Modulo Operation]
B --> C[Circular Array Access]
class CircularBuffer {
private:
std::vector<int> buffer;
int size;
public:
int getCircularIndex(int index) {
return index % size;
}
}
Time and Clock Calculations
3. 12-Hour Clock Conversion
int convertTo12HourFormat(int hour) {
return hour % 12 == 0 ? 12 : hour % 12;
}
Random Number Generation
4. Generating Random Numbers in Range
int generateRandomInRange(int min, int max) {
return min + (rand() % (max - min + 1));
}
Data Distribution
5. Hash Table Distribution
Operation |
Description |
Hash Index |
index = key % tableSize |
Load Balancing |
Distribute data evenly |
Cryptography and Security
6. Simple Hash Function
unsigned int simpleHash(std::string input) {
unsigned int hash = 0;
for (char c : input) {
hash = (hash * 31 + c) % UINT_MAX;
}
return hash;
}
Game Development
7. Sprite Animation Cycling
class SpriteAnimator {
private:
int totalFrames;
int currentFrame;
public:
int getNextFrame() {
return ++currentFrame % totalFrames;
}
}
8. Bitwise Modulo for Power of 2
// Faster modulo when divisor is power of 2
int fastModulo(int value, int divisor) {
return value & (divisor - 1);
}
Advanced Pattern Matching
9. Periodic Pattern Detection
bool hasRepeatingPattern(std::vector<int>& sequence, int patternLength) {
for (int i = 0; i < sequence.size(); ++i) {
if (sequence[i] != sequence[i % patternLength]) {
return false;
}
}
return true;
}
Unlock the power of modulo operations with LabEx, where coding becomes an art of precision!