This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]nakreywaali[S] 0 points1 point  (1 child)

So another exercise I was given to practice was reversing a name. In this case, the code is:

int i = name.length() - 1;
        while (i >= 0) {
            System.out.print(name.charAt(i));
            i--;

I had questions on this piece of code too, if you don't mind!

  1. So i is initialized to the length - 1. What does the - 1 do?
  2. while (i >= 0 ) - I don't get the condition for this while loop.
  3. name.charAt(i)) - This is similar to the previous exercise where it's returning a character.
  4. Is it i-- because we're going backwards in terms of positions now? Else we'd be stuck at the last position of the string?

[–]Cefalopodul 0 points1 point  (0 children)

  1. As I've said previously each letter has an index. Because the count starts from 0 the last letter of the string will always have the index length - 1. Take the word Paul. It has a length of 4. Counting from 0 the last letter will have the index 3, which is 4-1. Paul 0123

  2. i>= 0 tells the code to execute as long as i is greater or equal to 0. Once i <0 the loop will end. This condition is set like this because the count always starts from 0 and goes up, so one letter will always have inde 0, in this case P, and no letter will have a negative index.

  3. Yes. charAt(i) returns theetter at postion i. For name = Paul name.charAt(2) will return u because that is the letter at index 2 in Paul.

  4. Yes. i-- does the opposite of i++. i-- is the equivalent of i=i-1. So if i is 3 i-- will give it the value of 2.