vendredi 17 avril 2015

How strings work inside loops?

This is actually my first question so I hope I ll get it right. I ve been trying to make a "program" which reverse words to sdrow. I understand that for it to work it requires it to be this way. I'm more interest on the reason WHY it has to be this way. so here is the code



Console.WriteLine("Enter a word : ");
string word = Console.ReadLine();
string rev = "";
int length;

for (length = word.Length - 1; length >= 0; length--)
{
rev = rev + word[length];
}

Console.WriteLine("The reversed word is : {0}", rev);


My questions are:


a) Why do I HAVE to use " " on the "string rev" in order to use it inside the for loop? When I remove it, it doesnt work. I understand that it has to be there. But why?


b)How exactly does the Parameters in for loop work? More specific "length = word.Length - 1. I ve tested different stuff such as + (breaks the program) changing numbers etc. I dont understand how it works. If a word has 6 letters(123456), then length = 123456.6 - 1. From what I see here, the length = 5. (since 6 letters - 1). Then why does it display all 6 letters?


c) How does word[length] works exactly? does it force the string to turn into a string[] so it can read it as separated characters?


Im pretty new to C# and generally programming. I hope my questions does make sense and that I ve asked them in the correct and proper way.


Thank you for your time


Aucun commentaire:

Enregistrer un commentaire