user3259141
user3259141

Reputation: 25

Optimising while loops in C?

Is there a better way to write the following while loops in C

while (x > 0 && x <= 16)
    // do this
while (x > 16 && x <= 32)
    // do that 
while (x > 32 && x <= 48)
    //do this
while (x > 48 && x <= 64)
    //do that 
while ( x > 64 && x <= 80)
    //do this

.... and so on

I have to go up to a ridiculous high number and I was wondering if there is any better way to do this? I am new to coding so any suggestions would help.

Upvotes: 1

Views: 206

Answers (4)

Utkan Gezer
Utkan Gezer

Reputation: 3069

Hope this helps:

for ( int k = 0; k <= yourRidiculousHighLowerBound; k += 16 ) {
    while ( x > k && x <= k + 16 ) {
        if ( k % 2 ) {
            // do that
        }
        else {
            // do this
        }
    }
}

Sorry if you didn't mean this and thats are the same... Then I'd need more information.

edit: Well, after looking at the other answers, this appears to be the only answer that does exactly what has been asked; others differ in the exact behaviour. Apparently the question wasn't reflecting what OP was asking for, oh well =/

Upvotes: 1

Claudiu
Claudiu

Reputation: 229281

As per your comment, you're doing one of two actions depending on which range x falls into as a multiple of 16. Note that:

x   | (x-1)/16 | ((x-1)/16)%2
----+----------+--------------
1   |    0     |       0
15  |    0     |       0
16  |    0     |       0
17  |    1     |       1
31  |    1     |       1
32  |    1     |       1
33  |    2     |       0
50  |    3     |       1
68  |    4     |       0
... |   ...    |      ...

So you can use ((x-1)/16)%2 to determine which action to do:

while (x < ridiculous_high_number) {
    if (((x-1)/16) % 2 == 0) {
       //do this
    }
    else {
       //do that
    }
}

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490018

Perhaps it's just my own little oddity, but for cases like this, I find it perfectly reasonable to use an array of pointers to functions, and use the relevant bit to index into that array:

void turn_off() { /* ... */ }
void turn_on() { /* ... */ }

typedef void (*func)();

func f[] = {turn_off, turn_on};

for (int x=1; x<whatever; x++)
    f[((x-1) >> 4) & 1]();

Upvotes: 1

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

Here is a proposal:

for (;;)
{
    if ((x - 1) % 32 < 16)
        do this
    else
        do that
}

Upvotes: 2

Related Questions