Question about an exercise C# Basics course

For the second exercise of the Array and Lists bit. I didn’t understand the entire code after looking at the solution.

The exercise:
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.

This being the solution:
public void Exercise2()
{
Console.Write("What’s your name? ");
var name = Console.ReadLine();

        var array = new char[name.Length];
        for (var i = name.Length; i > 0; i--)
            **array[name.Length - i] = name[i - 1];**

        var reversed = new string(array);
        Console.WriteLine("Reversed name: " + reversed);

I understand most of the code, aside from the bit marked. Can anyone explain what this does exactly?

Hi
Basically it is just copying separate letters from name in the reversed order into your array.

Example for the word testing

var array = new char[name.Length];

is equivalent to

var array = new char[7];

So you’re basically creating an array of char with 7 elements

for (var i = name.Length; i > 0; i--)
   array[name.Length - i] = name[i - 1];

7 times exclusively, you scan the name from its end backwards

and store the result in the array

image

This is important to understand the expressions that were used to :

  • stay within correct zero based indexes in both array and name.

  • Have them progress in opposite order.

Other ways you could have done that :

  • Using the hat operator (^) array[^i] = name[i - 1]; More @MSDN → System.Index
  • Using available static methods from Array type.
    static void ReverseName()
    {
        var name = "testing";

        var array = name.ToCharArray();
        Array.Reverse(array);
        var reversed = new string(array);
        Console.WriteLine("Reversed name: " + reversed);
    }
  • Using LINQ (certainly one of the big pleasures you’ll be introduced to later)
    static void ReverseName()
    {
        var name = "testing";

        var reversed = new string(name.Reverse().ToArray());
        Console.WriteLine("Reversed name: " + reversed);
    }

Hope this helps.

Cheers

1 Like

This was helpful thank you for your time and explanation! :blush:

1 Like