Reputation: 6522
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;
}
}
}
Upvotes: 1
Views: 315
Reputation: 836
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--)
Upvotes: 0
Reputation: 727047
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--)
Upvotes: 3
Reputation: 148180
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--)
Upvotes: 2