Problem [Beginner] C# how does this loop code work?

sharpus 21 Reputation points
2021-03-10T15:49:41+00:00

Hey! I'm new to c# and i have some trouble with the code beneath that asks the user to input a name that later will be reversed back in the console.
I understand most of the code except for the loop part which job is to reverse the name. (I for the most part understand how loops work) But this loop looks very confusing to me so if someone could help explain that part more indepth in an easy to understand way that would be awesome!

            Console.Write("What's your name? ");


            var userName = Console.ReadLine();
            var nameArray = new char[userName.Length];


            for (var i = userName.Length; i > 0; i--)
            {
                nameArray[userName.Length - i] = userName[i - 1];


            }
            var reversed = new string(nameArray);
            Console.WriteLine("Reversed name: " + reversed);
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,239 questions
{count} votes

Accepted answer
  1. Sam of Simple Samples 5,516 Reputation points
    2021-03-10T20:42:07.627+00:00

    Notice that the for loop has i-- whereas most for loops have ++i. As a beginner let us say there is no difference between --i and i-- but in the future you will learn the difference. What is important here is that the for loop begins at the end of the string (userName.Length) and goes to the beginning (until i > 0 is not true). The i-- will cause i to be decremented, not incremented.

    0 comments No comments

0 additional answers

Sort by: Most helpful