WHY AM I GETTING THE BUG IN THE CODE? [SOLVED] | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 17

WHY AM I GETTING THE BUG IN THE CODE? [SOLVED]

I am almost done with my C# lessons on sololearn and I decided to practise with some of the newly acquired ideas on stack collection. Why am I encountering the bug in the code? https://code.sololearn.com/cxlvndP3Bgou/?ref=app

29th Sep 2020, 12:39 PM
๐Ÿ‘‘ Tchybooxuur!
๐Ÿ‘‘ Tchybooxuur! - avatar
7 Answers
+ 11
The error occurs because on line 48, in the foreach loop, you are modifying the stack while iterating on it. Just replace `foreach (string i in friends)` with `for (int i=0; i < friends.Count; i++)` And it will work fine https://code.sololearn.com/c2VFDrrrKNMq/?ref=app
29th Sep 2020, 12:49 PM
XXX
XXX - avatar
+ 10
The mistake in the lines below, you should change tp another loop, because you modify your collection friends you cannot use foreach for it. foreach (string i in friends) Console.WriteLine("Pop: " + friends.Pop());
29th Sep 2020, 12:53 PM
Vladimir (temporary inactive)
Vladimir (temporary inactive) - avatar
+ 9
It worked! Thanks XXX, Vladimir & elvisreal ๐Ÿ‘๐Ÿผ
29th Sep 2020, 12:59 PM
๐Ÿ‘‘ Tchybooxuur!
๐Ÿ‘‘ Tchybooxuur! - avatar
+ 7
Not expert at cs, but it has to do with your try block https://code.sololearn.com/crdjMZbGInuS/?ref=app
29th Sep 2020, 12:48 PM
elvisreal
elvisreal - avatar
+ 7
As said, Modifiying collection in Foreach causing error. Also for normal for loop use copy of friends.count as maxI= friends.count ; and use i<maxI. Because friends.count also modifed, you miss some elements poping.. Here Iterator works fine for modifying collections...
29th Sep 2020, 1:06 PM
Jayakrishna ๐Ÿ‡ฎ๐Ÿ‡ณ
+ 6
Jayakrishna๐Ÿ‡ฎ๐Ÿ‡ณ Oh that's true. Thanks ๐Ÿ‘๐Ÿผ. I'll add that too.
29th Sep 2020, 1:09 PM
๐Ÿ‘‘ Tchybooxuur!
๐Ÿ‘‘ Tchybooxuur! - avatar
+ 1
In html, When i use / for ending code it displays the same results as without / why?plz answer me also
1st Oct 2020, 9:18 AM
shubham Bhati