baskon1
baskon1

Reputation: 330

C - Arrays. Change only specific values

I am trying to search through an array, and only check specific values (the 4th,5th and so on)- ((0+n*4) and (3+n*4). The first one found will be checked and if it has a value of 0 will it be changed to 1 and then the program should stop. If not it will try the next value and so on.. I have the following code, but it doesn't stop ..it makes all the values 1 at once.. Any suggestions?

        {
        for (i=0; i<(totalnumber); i++)
        {   for (n=0; n<((totalnumber)/4); n++)
            {   if (i==(0+(n*4)))
                {   if (array[i]==0)
                    {
                        array[i]=1;
                        break;
                    }
                }

                else if ((i==(3+(n*4))))
                {
                if (array[i]==0)
                {
                    array[i]=1;
                    break;
                }
                }
            }
        }
    }

Upvotes: 0

Views: 38

Answers (1)

Karthik Nishanth
Karthik Nishanth

Reputation: 2010

Using a single break statement only breaks out of the nearest loop. It doesnt break out of the outer i loop. So, change your code to break out of the outer loop too.

One other way is to use both counter variables i,n within the same for loop. That means, you only use break once to break out of the outer for loop.

I quote from MSDN

Within nested statements, the break statement terminates only the do, for, switch, or while statement that immediately encloses it. You can use a return or goto statement to transfer control elsewhere out of the nested structure.

This is related - Can I use break to exit multiple nested for loops?

Upvotes: 2

Related Questions