Using modular arithmetic (or) (%) operator in C++ we can cycle through the successive numbers with a range.
For example:
if range is 5 (or) modulo 5 then we can cycle through
0 1 2 3 4 0 (5) 1(6) 2(7) 3(8) 4(9) 0(10)............0 1 2 3 etc.
Question:
In the similar sense is there any arithmetical relation / C++ trick we can use to move increasing numbers in forward(till upper bound) and decreasing numbers in reverse direction(till lower bound or 0) with a range.
For example:
if range = 5 then
0 1 2 3 4 3 2 1 0 1 2 3 4 3 2 1 0.....................0 1 2 3 etc.
In the below program I used two approaches to iterate forward/reverse within a given range.
But I'm interested in- Is there any best way (C++ trick/Mathematical relation) of iterate through forward and reverse within a given range ?.
#include<iostream>
int main() {
int range = 5;
// 0 1 2 3 4 0 1 2 3 4 .....(Cycle through in the range 0 - 4)
int i = 0;
while(true) {
// 0 1 2 3 4 0 1 2 3 4 .....(cycle through in the range 0 - 4)
std::cout<< i;
i = (i+1)% range; // Modulo
// some break condition
}
// 0 1 2 3 4 3 2 1 0 .......... (Forward and Reverse in the range 0 - 4)
// Method 1:
int j = 0;
bool reverse = false;
while(true) {
if(reverse == false) {
if(j < range) {
std::cout << j;
j = j+1;
}
else {
reverse = true;
j = j-1;
}
}
else {
j = j-1;
std::cout << j;
if(j == 0) {
reverse = false;
j = j + 1;
}
}
// some break condition
}
// 0 1 2 3 4 3 2 1 0 .......... (Forward and Reverse in the range 0 - 4)
// Method 2:
// Using modulo (if the range is big value then this is not good approach)
int limit[8] = {0,1,2,3,4,3,2,1};
int k = 0;
while(true) {
std::cout<< limit[k];
k = (k+1)%8;
// some break condition
}
return 0;
}