Home » C#.Net

Stack.Push() method with example in C#

C# Stack.Push() method: Here, we are going to learn about the Push() method of Stack class in C#.
Submitted by IncludeHelp, on March 25, 2019

C# Stack.Push() method

Stack.Push() method is used to insert an object at the top of the stack.

Syntax:

    void Stack.Push(object obj);

Parameters: It accepts an object to be inserted at the top of the stack.

Return value: void – it returns nothing.

Example:

    declare and initialize a stack:
    Stack stk = new Stack();

    insertting elements:
    stk.Push(100);
    stk.Push(200);
    stk.Push(300);
    stk.Push(400);
    stk.Push(500);
    
    Output:
    500 400 300 200 100

C# example to insert an object to the stack using Stack.Push() method

using System;
using System.Text;
using System.Collections;

namespace Test
{
    class Program
    {
        //function to print stack elements
        static void printStack(Stack s)
        {
            foreach (Object obj in s)
            {
                Console.Write(obj + " ");
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {            
            //declare and initialize a stack
            Stack stk = new Stack();

            //insertting elements
            stk.Push(100);
            stk.Push(200);
            stk.Push(300);
            stk.Push(400);
            stk.Push(500);

            //printing stack elements
            Console.WriteLine("Stack elements are...");
            printStack(stk);


            //hit ENTER to exit
            Console.ReadLine();
        }
    }
}

Output

Stack elements are...
500 400 300 200 100

Reference: Stack.Push(Object) Method






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.