Max Daniel
Max Daniel

Reputation: 45

How can we make infinite loop with repeating numbers?

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

Answers (5)

Taimour
Taimour

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

Maroun
Maroun

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

Torben Schramme
Torben Schramme

Reputation: 2140

int i=0;
while(1)
{
    DoSomething(spriteAnimationRight[i]);
    i++;
    if(i >= 3) i = 0;
}

Upvotes: 1

David Xu
David Xu

Reputation: 5597

Use modulo:

int spriteAnimationRight[3] = {0, 136, 272};
for (auto i = 0; ; i++) {
    printf("%d\n", spriteAnimationRight[i%3]);
}

Upvotes: 3

Akshay
Akshay

Reputation: 783

You can do the following

while(1)
{
   cout<<spriteAnimationRight[0];
   cout<<spriteAnimationRight[1];
   cout<<spriteAnimationRight[2];
}

Upvotes: 5

Related Questions