This is how I've interpreted your question.
- You want to know why you must use quotes to initialize your string
- Why must you start your loop at one less than the total length of your string
- How
arrayname[int]
works
I think that the best way to explain this to you is to go through your code, and explain what it does.
Console.WriteLine("Enter a word : ");
The first line of code prints Enter a word :
into the console.
string word = Console.ReadLine();
This line "reads" the input from the console, and puts it into a string called word
.
string rev = "";
This initiates a string called rev
, setting it's value to ""
, or an empty string. The other way to initiate the string would be this:
string rev;
That would initiate a string called rev
to the value of null
. This does not work for your program because rev = rev + word[length];
sets rev
to itself + word[length]
. It throws an error if it is null.
The next line of your code is:
int length;
That sets an int (which in real life we call an integer, basically a number) to the value of null
. That is okay, because it gets set later on without referencing itself.
The next line is a for
loop:
for (length = word.Length - 1; length >= 0; length--)
This loop sets an internal variable called length
to the current value of word.Length -1
. The second item tells how long to run the loop. While the value of length
is more than, or equal to 0, the loop will continue to run. The third item generally sets the rate of increase or decrease of your variable. In this case, it is length--
that decreases length
by one each time the loop runs.
The next relevant line of code is his:
rev = rev + word[length];
This, as I said before sets rev
as itself +
the string word
at the index of length
, whatever number that is at the time.
At the first run through the for loop, rev
is set to itself (an empty string), plus the word
at the index of length - 1. If the word entered was come
(for example), the index 0 would be c
, the index 1 would be o
, 2 would be m
, and 3 = e
.
The word length is 4, so that minus one is 3 (yay - back to Kindergarten), which is the last letter in the word.
The second time through the loop, length
will be 2, so rev
will be itself (e) plus index 2, which is m
. This repeats until length hits -1, at which point the loop does not run, and you go on to the next line of code.
...Which is:
Console.WriteLine("The reversed word is : {0}", rev);
This prints a line to the console, saying The reversed word is : <insert value of rev here>
The {0}
is an internal var set by the stuff after the comma, which in this case would be rev
.
The final output of the program, if you inserted come, would look something like this:
>Enter a word :
>come
>
>The reversed word is : emoc