# how to loop through an array and jump back to beginning

• 02-21-2011, 03:01 AM
drhinri
how to loop through an array and jump back to beginning
I'm trying to write a program and part of it is stumping me. I have an array of seven integers. The default value of each is 0. Some have other values though. Here's my issue. When the element is 0, i want to replace the value with x. For example, if array[1] = 0, then x would go into array[1]. So, if array[1] != 0, then i want to put "x" into the next xth element, if that next element is 0. So if x was 3, array[1]!=0 so then it checks array[3]. array[3] =0, so x goes into array[3]. heres my question. it checks array[3], and it !=0, so i go to the next xth element, which is array[6] in this case. array[6]!=0. now i want to go to the next xth element, but there are no elements, so i want to loop back around to the beginning, starting at array[0]. so the next comparison it would make would be at array[2]. how do i write a loop like this? in order to find the zero, it checks every xth element through the array, looping around until it finds a zero. there is guaranteed to be a zero somewhere.
thanks a bunch.
• 02-21-2011, 03:08 AM
Junky
Code:

```while not finished {     if array element is 0 {         change array element         update x         if x is greater than length {             reset back to zero (or what ever)         }     }     determine if finished }```
• 02-21-2011, 03:59 AM
drhinri
worked like a charm. thanks a bunch
• 02-21-2011, 04:45 AM
liyuyu_852000
you can try this code
Code:

```      for(int i=0;i<array.length;i++){             if(array[i]==0){                 //....update code             }       }```
• 02-21-2011, 04:52 AM
Junky
You could but it wouldn't do what the OP wants.