Consider the following code: String word [] = {"algorithm", "boolean", "char", "double"}; for ( int i =0; i < word.length/2; i++) { word[i] = word[word.length - 1 - i]; } What is stored in word after running this code? algorithm algorithm algorithm algo

Respuesta :

Answer:

{"double", "char", "char", "double"} will be stored in word.

Explanation:

Given the word is an array of four strings,  {"algorithm", "boolean", "char", "double"}. Hence, the length of the word array is 4.

The for-loop will only run for two iterations due to i < word.length/2, with i = 0 (first loop) and i = 1 (second loop).

In the first loop,  

  • word[word.length - 1 - i]  =  word[4 - 1 - 0]  = word[3]  = "double"
  • Hence, the string "double" will be assigned to word[0] and overwrite "algorithm"

In the second loop,

  • word[word.length - 1 - i]  =  word[4 - 1 - 1]  = word[2]  = "char"
  • Hence, the string "char" will be assigned to word[1] and overwrite "boolean"

At last, the word array will hold {"double", "char", "char", "double"}

Answer:

At the end of this code word array will hold {"double","char","char","double"}

Explanation:

  • The string word is an array of four strings {"algorithm","boolean","char","double"}.
  • This means that the length of this array is 4.
  • The for runs for half the length of array i.e. 2.

First Loop: (i = 0)

  • For i = 0 word[0] = word[word.length - 1 - 0]
  • Now here we will have word[0] = word [3] which is "double"

Second Loop (i = 1)

  • For i = 1 word[1] = word[word.length - 1 - 1]
  • Now here we will have word[1] = word [2] which is "char"

Rest of the array will remain the same hence the output will be:

word[] = {"double","char","char","double"}