question

sharpus-4191 avatar image
0 Votes"
sharpus-4191 asked ·

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

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);
dotnet-csharp
· 1
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@sharpus-4191
I strongly recommend that you take a look at this document to learn how to use breakpoints to debug your program.
Add breakpoints, run the program, and then use the F11 key to execute step by step. This will allow you to easily observe the real-time changes of each variable.
In terms of personal experience, after I learned to use it, the logic problems that were difficult to understand in the past became very clear.

0 Votes 0 ·

1 Answer

SimpleSamples avatar image
0 Votes"
SimpleSamples answered ·

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.

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.