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.
Problem [Beginner] C# how does this loop code work?
sharpus
21
Reputation points
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);
Accepted answer
-
Sam of Simple Samples 5,546 Reputation points
2021-03-10T20:42:07.627+00:00