1

What I am trying to do is loop through an integer array

int[] integerarray = { 1, 2, 3, 4 };
for (??????)
{
    // What do I do here?
}

Until I get to 3. I'm not sure how though.

5
  • 2
    by 3 you mean the third position, or the value 3 ? Commented Feb 1, 2014 at 6:44
  • what do you want to do ? What is your goal ? Commented Feb 1, 2014 at 10:00
  • @simsim the value 3 which is the third position. Commented Feb 1, 2014 at 16:44
  • I still couldn't figure out which of which, your comment is confusing. The answer by @Sudhakar Tillapudi will serve you Well, in the if statement condition, put either a check on the position or the value, if the condition is satisfied, the break keyward will stop the loop, or use continue keyward instead to skip the current cycle and continue the loop Commented Feb 1, 2014 at 17:13
  • ya, as what you said the answer can server the request, but the problem is with the break statement, when the condition is true he is skiping the code then how it works? and if the condition is not satisfied then it executes the code. Commented Feb 3, 2014 at 10:12

5 Answers 5

4

we can achieve this by using simple for each loop

foreach(int i in integerarray)
{
  if(i==3)
  {
   // do your stuf here;
    break;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yow most welcome and always get solutions from the site,
2
    int[] integerarray = { 1, 2, 3, 4 };
    for (int i=0;i<integerarray.Length;i++)
    {
        if(integerarray[i]==3)
            break;
        //Do something here 

    }

Comments

0

One way to do a loop of a fixed number is a while loop.

int counter = 0;
while(counter < 3)
{
    tmp = integerArray[counter];
    ????
    counter++;
}

Comments

0

You can use linq TakeWhile method to get the elements from a sequence as long as a specified condition is true.

Here you want that return element untill we found 3 in the sequence so you can write this statement like this

var result = integerarray.TakeWhile(x => !x.Equals(3)).ToList();

result will contains the items which comes before 3

in your case result will have 1,2

Comments

-2

Use LINQ.

int[] integerarray = { 1, 2, 3, 4 };
for (var number = integerarray.TakeWhile(x => x != 3))
{
    // Do something
}

2 Comments

Not my downvote. but this is wrong. What if array contains { 4, 2, 3, 1 }; ?
Point taken. I based in OP actual information. Corrected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.