0

For each problem

char[] charArray = zig.ToCharArray(); //puts each character in zigs in an array
Array.Reverse(charArray); // Reverses the array 

foreach (char zigArray in charArray) 
{
    Console.Write(zigArray);
}
Console.ReadLine();

This block works how i want it to but i don't understand why i need a for each statement here. I am confused why i shouldn't just do console.write after i have reversed the string.

(I am following a tutorial)

maccettura
  • 10,514
  • 3
  • 28
  • 35
  • 5
    Try doing it your way and see what happens. The beauty of programming is that if you have a different idea- you can try it out and see if it works. – chevybow Apr 23 '18 at 18:40
  • 1
    _We_ wont know why you need a foreach statement either. It depends on what the tutorial is trying to teach you. A `foreach` loop is pretty essential in C#, its for iterating over something (usually a collection of some sort). You should try your `Console.Write(charArray)` and see what happens, then ponder the differences between a `char[]` and a `string` – maccettura Apr 23 '18 at 18:42
  • 1
    Please be aware that `Array.Reverse(string.ToCharArray())` [does not reverse strings](https://stackoverflow.com/questions/15029238/). – Dour High Arch Apr 23 '18 at 18:45
  • 1
    Fire your tutorial. – P.Brian.Mackey Apr 23 '18 at 18:59

1 Answers1

1

The simple answer is: try it!

I did. The answer: there is none. The end result on the screen is the same, however, a minor detail, the reversed string is now a character array which makes it a little harder to see what happens right away.

Calling Console.Write on an array of chars outputs the text as expected and reproduces the exact samen result as foreach does (and not System.Array or something like that you might see when printing an object).

Why did they use foreach then? Probably to learn you how iterating over a collection works. I guess it is just a bad example, move on.

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325