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

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.

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;
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.