Reputation: 45
I made an array int spriteAnimationRight[3] = {0, 136, 272};
and I want these numbers to repeat like following:
0
136
272
0
136
272
..
..
How can we do it?
Upvotes: 0
Views: 154
Reputation: 459
#include <iostream>
using namespace std;
int main()
{
int index=0;
int spriteAnimationRight[3] = {0, 136, 272};
while(1)
{
if(index==3)
{/*when index=3, resset it to first index*/
index=0;
}
cout<<spriteAnimationRight[index]<<endl;
index++;
}
}
And if you want to see output clearly then you need to create some delay in each output, for that purpose you can make a function delay like this.
#include <iostream>
using namespace std;
void delay()//to see output clearly you can make a sleep function
{
/*this fucntion uses empty for loops to create delay*/
for(int i=0;i<7000;i++)
{
for(int j=0;j<7000;j++)
{
}
}
}
int main()
{
int index=0;
int spriteAnimationRight[3] = {0, 136, 272};
while(1)
{
if(index==3)
{/*when index=3, resset it to first index*/
index=0;
}
cout<<spriteAnimationRight[index]<<endl;
index++;
delay();//for creating delay
}
}
Upvotes: 0
Reputation: 95958
You can use the modulo operator:
int i = 0;
while(1) {
if(i == 3) i = 0; //preventing overflow
cout<<spriteAnimationRight[i % 3];
i++;
}
Why this works?
The modulo operator finds the remainder of division of one number by another1.
0 % 3 → 0
1 % 3 → 1
2 % 3 → 2
0 % 3 → 0
1 % 3 → 1
2 % 3 → 2
..
..
1 http://en.wikipedia.org/wiki/Modulo_operation
Upvotes: 1
Reputation: 2140
int i=0;
while(1)
{
DoSomething(spriteAnimationRight[i]);
i++;
if(i >= 3) i = 0;
}
Upvotes: 1
Reputation: 5597
Use modulo:
int spriteAnimationRight[3] = {0, 136, 272};
for (auto i = 0; ; i++) {
printf("%d\n", spriteAnimationRight[i%3]);
}
Upvotes: 3
Reputation: 783
You can do the following
while(1)
{
cout<<spriteAnimationRight[0];
cout<<spriteAnimationRight[1];
cout<<spriteAnimationRight[2];
}
Upvotes: 5