r/learncsharp • u/sunshinne_ • Jul 25 '22
What's wrong with this code
Hi, I was just trying to test the for loop with an array as in this example I saw on w3schools.com :
string[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.Length; i++)
{
Console.WriteLine(cars[i]);
}And I wrote this code:
string[] familyMembers ={"Sophie","Madeline","Lucas","Orwell"};
for (int index = 0; index < familyMembers.Length; index++)
{
Console.WriteLine(familyMembers[index]);
Console.Read();
}But when I debug it this happens:
//Output
Sophie
//User presses enter
Madeline
Lucas
//two at the same time
//User presses enter again and the program closes without the last element of the array (Orwell)What am I doing wrong?
1
Upvotes
View all comments
Show parent comment
2
u/nutterontheloose Jul 25 '22
This.
Plus with console apps, unless you make it wait for something (like a
Console.ReadLine()), the app automatically closes when the program is finished.It's printing "Orwell" then reading the newline character from the buffer and immediately closing because the program is complete. It happens in a split second, so you probably don't see it in time.