Question about an exercise

Hi guys, I’ve been struggling hard trying to solve some of the exercises but this one particularly got my attention.

The exercise is the second one of Array and Lists section.

Looking at the solution I found something interesting I didn’t understand why did Mosh use:

// var array = new char[…]

When he was trying to get a name from the input.

The for loop as well was a bit weird he wanted to have

// name[I -1].

I didn’t understand that.

The exercise is:

2- Write a program and ask the user to enter their name. Use an array to reverse the name and then store the result in a new string. Display the reversed name on the console.

I got the concept but I didn’t quite catch the reason of those things and I didn’t find at his lessons.
I’d appreciate any help!

Thanks!

Hi, the array is needed to get the reversed name.
But to do that you need to start from the end of the name, hence the i=name.lenght, and stop at the first char of the name.
In an array, the first char is i=0. So let’s say your name.lenght is 6,your “i” will go from 0 to <6 wich is 5.
But if you want it in reverse, you will need to go from the last char i=6 to the first one i=1.
So the first char of your array will be 0 (name.lenght - i (6 in the first loop)) and need to be the last char of the original name (the 5th so) hence the [i-1]
Hope i was clear enough :slight_smile:

Wow. Crystal clear.

Thank you so much for spending your time on this. Thanks a lot for your help! :muscle:t2:

You’re welcome :slight_smile:
Hope i’ll be able to take the intermediary course and further once they decide to stop declining my card and take my damn money :grimacing:

1 Like