Dustin Fain
Dustin Fain

Reputation: 120

Circular iteration in C++

I am looking for a simple way to iterate through a set of integers in C++. For example, if I had an integer variable 'x' and wanted to use the increment statement 'x++' continuously over 4 integer values, the desired output would be something like '0 1 2 3 0 1 2...'.

I know that a circularly linked list is a solution, but it just seems like overkill to me, I really need something short and sweet. I suspect that enumerated types may be able to do something like this, but my research has not turned up anything.

Upvotes: 1

Views: 2136

Answers (3)

Infinite Recursion
Infinite Recursion

Reputation: 6557

Try this:

for (int i = 0; i < n; i = i+4) {
   for (int j = 0; j < i; j++) {
      // print here
   }
}

Upvotes: 0

Matt
Matt

Reputation: 20796

for( int x=0 ; ; x = (x+1) % 4 ) {
  // body of loop
}

Upvotes: 5

Abhishek Bansal
Abhishek Bansal

Reputation: 12705

while (1) {
  for ( int x = 0; x < 4; x++ ) {
   //... 
  }
}

Upvotes: -1

Related Questions