1

Could anyone tell me why the nested for loop in the code below doesn't execute? I.e. The "Hello World" is not printed. The first loop is being executed.

 for (int i = 0; i < data.Length; i++)
        {// Loop through array


            **for (int j = data.Length - 1; j < i; j--)**
            {
                // Loop backwards through array
                **Console.WriteLine("Hello World");**
                double subTotal = 0;   //Keeps track of current subsequence's value
                subTotal += data[j];
                if (bbestTotal < subTotal)
                {
                    bbestTotal = subTotal;
                }
            }

        }
7
  • 2
    What is the value of data.Length? Commented Mar 7, 2013 at 18:34
  • 1
    try j > i as condition for 2nd loop Commented Mar 7, 2013 at 18:34
  • What does data look like? Commented Mar 7, 2013 at 18:34
  • You want for (int j = data.Length - 1; j > i; j--) Currently, j will always be bigger than or equal to i, so the terminating condition will fail immediately. Commented Mar 7, 2013 at 18:35
  • Cheers guys brain was fried lol. Answer below solved it. Cheers. Commented Mar 7, 2013 at 18:36

3 Answers 3

3

The loop is not executing because the loop condition

j < i

is false right at the beginning of the loop.

Since your loop advances j down, you should change the condition to

for (int j = data.Length - 1 ; j >= i ; j--)
Sign up to request clarification or add additional context in comments.

Comments

2

The inner loop variable j is initialized with top value and it is greater then i so use j > i instead of j < i in loop condition part.

Change

for (int j = data.Length - 1; j < i; j--)

to

for (int j = data.Length - 1; j > i; j--)

Comments

0

The root cause of the problem is that the condition j < i for the 2nd for loop is always false for all values of i. So it never goes inside the body of the 2nd for loop. This should fix the problem:

for (int j = data.Length - 1; j > i; j--)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.