0

I took a UIL test this weekend, and I don't understand this problem:
What is output by //2 in the code to the right? The answer is 540,280, but I'd like to know why.

    int ct1 = 0;
    int ct2 = 1;
    for(int i=0; i<1040;i++){
        for(int j=i; j<0; j--){
            ct1++;
        }
        ct2++;
    }

System.out.println(ct2);
System.out.println(ct1); //2
2
Contributors
2
Replies
9
Views
3 Years
Discussion Span
Last Post by nullptr
0

It's a summation problem, right? J is assigned to i, each outer loop iteration; the first outer loop, j is 0. So, the inner loop does't run. The second, i is 1, so the inner loop executes once. The third time through i is 2, so twice, and so on. So 1 + 2 + 3 + ... + 1040, but I get 541,320.

0

The inner loop should be for (int j=i; j>0; j--)
Your logic is correct, though the sum will only apply for 1 + 2 + ... + 1039 = 540,280
ct1 could be written as:

    int ct1 = 0;
    for (int i = 0; i < 1040; ++i)
        ct1 += i;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.