tanman
tanman

Reputation: 175

How do I execute the if statement 3 times?

I have a program which will keep on listing numbers. i.e. 1,3,5,3,2,5,7,,8,3,10,14, etc. How would I edit this for loop/if statement to check every 3 numbers? Is this correct?

for(int i = 0; i<theMessage.length;i+3){ 
    if(...)
    return ...;
}

Upvotes: 1

Views: 293

Answers (2)

Lrrr
Lrrr

Reputation: 4805

You need to update the value of i after every iteration so you have to use i+=3 instead of i+3 as i+=3 is a shorthand for i=i+3

This would iterate through your numbers, every three number:

for(int i = 0; i<theMessage.length;i+=3){ 
    if(...)
    return ...;
}

and if you want to start from 1 you could start your loop from 1 instead of zero:

for(int i = 1; i<theMessage.length;i+=3){ 
    if(...)
    return ...;
}

This would iterate through your numbers, every three number:

for(int i = 0; i<theMessage.length;i+=3){ 
    if(...)
    return ...;
}

Edit(to answer comment I wanted the loop to check every number in sets of three):

you could have a if statement like this:

if(theMessage[i] have condition)
    if(i+1<theMessage.length && theMessage[i+1] have condition)
        if(i+2<theMessage.length && theMessage[i+2] have condition)
            return what you want;

Upvotes: 1

Stephen C
Stephen C

Reputation: 719229

What is the difference between i+3 and i+=3?

The first one says "take the value of i and add 3 to it

The second one says "take the value of i and add 3 to it, AND assign the result to i".

If you don't assign the result back to i, the value of i doesn't change ... and you repeat your loop over and over again with i set to zero,

Upvotes: 2

Related Questions