Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Inside loop only do something every forth time

1. ## Inside loop only do something every forth time

Hi

I have an array and want to insert "--" in between every 4th number - how do i do this?

Thanks

Code:
```var arr = {1,2,3,4,5,6,7,8,9};

var n = "";

for (var i=1 ; i<= arr.length ; i ++){

n += arr[i].toString();

if( if the forth loop ){

n += "--"; //only add this every 4 loops

}

}

• Code:
```var arr = [ 1,2,3,4,5,6,7,8,9 ];
var n = "";
for (var i = 0; i < arr.length; i++) {
n += arr[i];
if(((i + 1) % 4) == 0) {
n += "--"; //only add this every 4 loops
}
}

• ## Users who have thanked Krupski for this post:

code-in-time (05-31-2012)

• thanks

what does the % mean?

• % means remainder or modulo

1%4 = 1
2%4 = 2
3%4 = 4
4%4 = 0
5%4 = 1
6%4 = 2
7%4 = 3
8%4 = 0
9%4 = 1

and so on -so if you increment the nember on the left by one every time the result will be zero when that number is exactly divisible by 4 - ie every fourth time.

• ## Users who have thanked felgall for this post:

code-in-time (06-12-2012)

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•