Home » C# programs » C# Data structure programs

C# program to copy stack elements to array

In this C# program, we will learn how to copy stack elements to array? Here we use CopyTo method of Stack class.
Submitted by IncludeHelp, on November 23, 2017

Stack.CopyTo method

This is a method of 'Stack' class, it copies stack elements to array.

Syntax:

void Stack.CopyTo(Array arr, int index);

Parameter(s):

arr : array in which we copy stack elements.
item : starting at the specified array index.

Program to copy stack elements to an array in C#

using System;
using System.Collections;

namespace ConsoleApplication1
{
    
    class Program
    {
        static void Main()
        {
            int[] arr = new int[5];
            Stack S = new Stack(5);

            S.Push(10);
            S.Push(20);
            S.Push(30);
            S.Push(40);

            S.CopyTo(arr, 1);

            Console.WriteLine("Items are:");
            for (int i = 0; i < arr.Length; i++)
            {
                Console.WriteLine("\tItem[" + (i + 1) + "]: "+arr[i]);
            }
        }
    }
}

Output

Items are:
        Item[1]:  0
        Item[2]: 40
        Item[3]: 30
        Item[4]: 20
        Item[5]: 10

Note: In above program, to use 'Stack' class, we need to include System.Collection namespace.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.