## how to make custom loop in C?

Moderators: Darobat, RecursiveS, Dante Shamest, Bugdude, Wizard

### how to make custom loop in C?

Yes i know, my question is not very clear but let me explain what i want to do.

I want to make a loop in a program that will have specific amplitude and the counter will take all the possible values of this amplitude.
For example in a for loop we have:
Code: Select all
`for(i=0;i<N;i++){     ...//code}`

At this for loop the counter i takes the values from 0...N-1.

At my custom loop, i want to give the start point for the counter i but after that will take all the values to N-1 plus the values before tha start point.
Example: For N=6 if counter i starts from 4, it will take the values: i=4,i=5,i=6,i=0,i=1,i=2,i=3 (a complete loop for N=6).

thanks

**update: not necessery to be for loop, i am interested for the behavior of i counter.
oldboy

Posts: 22
Joined: Sat Mar 21, 2009 4:32 pm

### Re: how to make custom loop in C?

Several options:
Code: Select all
`for (int i=0; i<6; ++i) {  int shifted_i = (i+4)%6;  // do stuff with shifted_i}`

or you can save yourself the somewhat-expensive modulus operation, doing something like this:
Code: Select all
`for (int i=0, shifted_i=4; i<6; ++i, (++shifted_i==6)&&(shifted_i=0)) {  // do stuff with shifted_i}`

or, if you put your code in a function, you can use the following less-messy option.
Code: Select all
`for (int i=4; i<6; ++i)  do_something(i);for (int i=0; i<4; ++i)  do_something(i);`

Alvaro
Moderator

Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA

### Re: how to make custom loop in C?

god damn it man... What are you made off? Is there something that you don't know how to do it?

I was just ready to post a try with
Code: Select all
`i=(i+1)%N`
but i am not sure if it works.

Thanks, i will make some tries with your options in my code.
oldboy

Posts: 22
Joined: Sat Mar 21, 2009 4:32 pm

### Re: how to make custom loop in C?

oldboy wrote::o god damn it man... What are you made off? Is there something that you don't know how to do it?

Oh, there probably is something. Keep trying me.

I was just ready to post a try with
Code: Select all
`i=(i+1)%N`
but i am not sure if it works.

You can make that work, for instance like this:
Code: Select all
`int i=4;do {  // your code here  i=(i+1)%6;} while(i!=4);`

In the end, use the option that you find easiest to understand. The most important property code should have is clarity.

Alvaro
Moderator

Posts: 5185
Joined: Mon Sep 22, 2003 4:57 pm
Location: NY, USA