Question

What does the following code fragment print? Explain the result? int [] a = new int[10];...

What does the following code fragment print? Explain the result?

int [] a = new int[10];

for (int i = 0; i < 10; i++)

   a[i] = 9 - i;

for (int i = 0; i < 10; i++)

   a[i] = a[a[i]];

for (int i = 0; i < 10; i++)

   System.out.println(a[i]);

0 0
Add a comment Improve this question Transcribed image text
Answer #1

0
1
2
3
4
4
3
2
1
0

int [] a = new int[10];     // initializes an array of 10 integers
for (int i = 0; i < 10; i++)    // loop through each element in array
    a[i] = 9 - i;       // set 9-i for all elements
// array a after first for loop is
// 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
for (int i = 0; i < 10; i++)    // loop through each element again
    a[i] = a[a[i]]; // set a[i] to a[a[i]]
// a[0] => a[a[0]] = a[9] = 0
// a[1] => a[a[1]] = a[8] = 1
// a[2] => a[a[2]] = a[7] = 2
// a[3] => a[a[3]] = a[6] = 3
// a[4] => a[a[4]] = a[5] = 4
// a[5] => a[a[5]] = a[4] = 4
// a[6] => a[a[6]] = a[3] = 3
// a[7] => a[a[7]] = a[2] = 2
// a[8] => a[a[8]] = a[1] = 1
// a[9] => a[a[9]] = a[0] = 0
for (int i = 0; i < 10; i++)
    System.out.println(a[i]);
// finally, printed array is 0 1 2 3 4 4 3 2 1 0
Add a comment
Know the answer?
Add Answer to:
What does the following code fragment print? Explain the result? int [] a = new int[10];...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT