Copy the Stack to an Array in C#

CsharpServer Side ProgrammingProgramming

<p>To copy the stack to an array, the code is as follows &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/pl0uzSOy" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">using System; using System.Collections.Generic; public class Demo { &nbsp; &nbsp;public static void Main(){ &nbsp; &nbsp; &nbsp; Stack&lt;int&gt; stack = new Stack&lt;int&gt;(); &nbsp; &nbsp; &nbsp; stack.Push(10); &nbsp; &nbsp; &nbsp; stack.Push(20); &nbsp; &nbsp; &nbsp; stack.Push(30); &nbsp; &nbsp; &nbsp; stack.Push(40); &nbsp; &nbsp; &nbsp; stack.Push(50); &nbsp; &nbsp; &nbsp; stack.Push(60); &nbsp; &nbsp; &nbsp; stack.Push(70); &nbsp; &nbsp; &nbsp; stack.Push(80); &nbsp; &nbsp; &nbsp; stack.Push(90); &nbsp; &nbsp; &nbsp; stack.Push(100); &nbsp; &nbsp; &nbsp; Console.WriteLine(&quot;Displaying the stack...&quot;); &nbsp; &nbsp; &nbsp; foreach(int val in stack){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(val); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; int[] intArr = new int[stack.Count]; &nbsp; &nbsp; &nbsp; stack.CopyTo(intArr, 0); &nbsp; &nbsp; &nbsp; Console.WriteLine(&quot;Displaying the array...&quot;); &nbsp; &nbsp; &nbsp; foreach(int val in intArr){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(val); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">Displaying the stack... 100 90 80 70 60 50 40 30 20 10 Displaying the array... 100 90 80 70 60 50 40 30 20 10</pre><h2>Example</h2><p>Let us now see another example &minus;</p><p><a class="demo" href="http://tpcg.io/JV3TLZyg" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate" style="">using System; using System.Collections.Generic; public class Demo { &nbsp; &nbsp;public static void Main(){ &nbsp; &nbsp; &nbsp; Stack&lt;int&gt; stack = new Stack&lt;int&gt;(); &nbsp; &nbsp; &nbsp; stack.Push(10); &nbsp; &nbsp; &nbsp; stack.Push(20); &nbsp; &nbsp; &nbsp; stack.Push(30); &nbsp; &nbsp; &nbsp; stack.Push(40); &nbsp; &nbsp; &nbsp; stack.Push(50); &nbsp; &nbsp; &nbsp; Console.WriteLine(&quot;Displaying the stack...&quot;); &nbsp; &nbsp; &nbsp; foreach(int val in stack){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(val); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; int[] intArr = new int[10]; &nbsp; &nbsp; &nbsp; stack.CopyTo(intArr, 2); &nbsp; &nbsp; &nbsp; Console.WriteLine(&quot;Displaying the array...&quot;); &nbsp; &nbsp; &nbsp; foreach(int val in intArr){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Console.WriteLine(val); &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} }</pre><h2>Output</h2><p>This will produce the following output &minus;</p><pre class="result notranslate">Displaying the stack... 50 40 30 20 10 Displaying the array... 0 0 50 40 30 20 10 0 0 0</pre>
raja
Updated on 10-Dec-2019 10:35:19

Advertisements