-5

I'm making a program which reverses words to sdrow.

I understand that for it to work it needs to be written this way. I'm more interested on WHY it has to be this way.

Here is my 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 you must use quotes to initialize your string

b) Why must you start your loop at one less than the total length of your string

c) How arrayname[int] works

I'm pretty new to C# and this site, as well. I hope my questions make sense and that I've asked them in the correct and proper way.

Thank you for your time!

  • 1
    What does "doesn't work" mean? Did you read the error message? What part don't you understand? – SLaks Apr 17 '15 at 15:01
  • 1
    a) You're not using "" anywhere in the loop. b) This is a C# for loop, the first parameter is the initializer which is saying to start the loop at the end of the word. The loop will go from 5,4,3,2,1....0. The first [index] in a string starts at 0. c) word[length] gets the character from the string "word" at the position "length". It is an array accessor. – Jon Apr 17 '15 at 15:04
  • 2
    A) [Why compile error “Use of unassigned local variable”?](http://stackoverflow.com/questions/9233000/why-compile-error-use-of-unassigned-local-variable) – Alex K. Apr 17 '15 at 15:05
  • 1
    C) Is a [String Indexer](https://msdn.microsoft.com/en-us/library/vstudio/system.string(v=vs.110).aspx#Indexes) – Alex K. Apr 17 '15 at 15:08
  • You *don't have to* do anything like you've posted - `var rev = String.Join("", word.Reverse());` would work as well hiding any loops... – Alexei Levenkov Apr 17 '15 at 15:09
  • Note: asking multiple "explain me basic language feature" questions in on is double off-topic on SO and likely generate downvotes as well get your post closed as "too broad". – Alexei Levenkov Apr 17 '15 at 15:10
  • You might want to look into some tutorials before making questions. There are plenty that explain for loops, strings and variables in detail. – Daniel Langdon Apr 17 '15 at 15:12
  • @Alexei Levenkov: `var rev = (string)word.Reverse();` would work too. Shorter and possibly easier to follow? – Ulric Apr 17 '15 at 15:12
  • @Ulric `word.Reverse()` returns a `IEnumerable` and you cannot cast that to `string`. You could do `var rev = new string(word.Reverse().ToArray());`. – juharr Apr 17 '15 at 15:22
  • @juharr: Visual Studio disagrees with you. :) I rarely post code on here without testing it first. – Ulric Apr 17 '15 at 15:24
  • @Ulric Did you run it. I did and got an exception. – juharr Apr 17 '15 at 15:25
  • @juharr: I changed my code a little (to post it here) and it now fails. Odd. And I have now reverted my change and it is still broken. Very odd. – Ulric Apr 17 '15 at 15:26
  • @Metalbreath for what it is worth, I think you have asked [a perfectly reasonable first question](http://stackoverflow.com/help/on-topic). It is regrettable that some people are this unwelcoming to first time users. I also think that you will find, now the dust has settled a bit, there are some good answers that have been posted. Don't give up on trying to ask new questions. – Alex Apr 17 '15 at 15:39
  • @Metalbreath Ok, that's the spirit. Glad that gave you a better handle on things. With your new understanding, you might want to [edit] the title of your question to better match with what someone would search for if they had a problem like you had and are searching for an existing answer. – Alex Apr 18 '15 at 06:48
  • @Alex ok I see how this works. I ll change it now, Title and Questions – Metalbreath Apr 18 '15 at 07:52

6 Answers6

4

This is how I've interpreted your question.

  1. You want to know why you must use quotes to initialize your string
  2. Why must you start your loop at one less than the total length of your string
  3. 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
Cullub
  • 2,901
  • 3
  • 30
  • 47
  • That was a detailed analysis, Thank you for all your trouble. It really helped me understand all of my questions. a) Why I shouldnt leave string without " " (it will be signed as null) b)Why I should use -1 (Else a 6 letter words it will count as 0123456 = 7) c)How word[length] works. (each length index will present the required letter. and rev is empty + the word's letter As well, you were right. You re-wrote my questions in a better and more clear way :) That was exactly what I was trying to say – Metalbreath Apr 17 '15 at 22:01
2

a) you must to initialize or instantiate the variable in order to can work with it. In your case is better to use and StringBuilder, the string are inmutable objects, so each assignement means to recreate a new string.

b) The arrays in C# are zero index based so their indexes go from zero to length -1.

c) An string is an characters array.

Any case maybe you must to try the StringBuilder, it is pretty easy to use

I hope this helps

dobleUber
  • 566
  • 6
  • 22
  • You don't need the `ToString`. The `rev = rev + word[length];` is turned into `rev = string.Concat(rev, word[length]);` and that will call the `ToString` on each parameter passed in. See this [quesiton](http://stackoverflow.com/questions/10341188/string-concatenation-using-operator) and [`string.Concat(object, object)`](https://msdn.microsoft.com/en-us/library/kbseaaft(v=vs.110).aspx) – juharr Apr 17 '15 at 15:16
  • 2
    @melaspelas: `word[length].ToString()` is not necessary. You can concatenate chars onto strings without converting them. – Ulric Apr 17 '15 at 15:17
  • Thank you, I usually don't do that... I use always the StringBuilder :-) – dobleUber Apr 17 '15 at 15:34
1

a) you need to initialize a variable if you want to use it in an assignment rev = rev + word[length];

b) you are using a for loop which means that you define a start number length = word.Length - 1, a stop criteria length >= 0 and a variable change length--

So lenght basically descends from 5 to 0 (makes 6 loops). The reason is that Arrays like 'string' a char[] are zerobased indexed.. means that first element is 0 last is array.Length - 1

c) So a string is basically a chain of char's.. with the []-Operator you can access a single index. The Return Type of words[index] is in this case a character.

I hope it helped

LuckyLikey
  • 3,504
  • 1
  • 31
  • 54
1

a) You need to first instantiate the string rev before you can assign it values in the loop. You could also say "string rev = String.Empty". You are trying to add word to rev and if you don't tell it first that rev is an empty string it doesn't know what it is adding word to.

b) The characters of the string have indexes to show which position they appear in the string. These indexes start at 0. So you're first character will have an index of 0. If the length of your string is 6 then the last character's index will be 5. So length - 1 will give you the value of the last character's index which is 5. A c# for loop uses the following parameters

for (int i = 0; i < 10; i++)
    {
        Console.WriteLine(i);
    }

where "int i = 0;" is the starting index; "i < 10" tells the loop when to stop looping; and "i++" tells it to increment i (the index) after each loop. So in your code you are saying start at the last character of my string; perform this loop while there are still characters in the string; and decrease the index of the string after each loop so the next loop will look at the previous character in the string.

c) word[length] then in this scenario is saying add the character that has the position with index "length" to the rev string. This will basically reverse the word.

0

As usual you can do it in linq and avoid the (explicit) loops

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Enter a word : ");
            string word = Console.ReadLine();

            Console.WriteLine("The reversed word is : {0}", new string (word.Reverse().ToArray()));
            Console.ReadLine();
        }
    }
}
Ewan
  • 1,261
  • 1
  • 14
  • 25
  • That is an interesting way of making reverse word. I havent reach Linq yet but it seems its something useful to have a look at. – Metalbreath Apr 17 '15 at 21:50
-1
var reversedWords = string.Join(" ",
      str.Split(' ')
         .Select(x => new String(x.Reverse().ToArray())));

Take a look here :

Easy way to reverse each word in a sentence

Community
  • 1
  • 1
Julien698
  • 676
  • 3
  • 10
  • 27
  • This doesn't really answer the question. Although he started with a false assumption (that that was the only way it could be done), his *questions* were quite different. – Cullub Apr 18 '15 at 16:50