Home » C#.Net

Stack.Peek() method with example in C#

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

C# Stack.Peek() method

Stack.Peek() method is used to get the object at the top from a stack. In Stack.Pop() method we have discussed that it returns the object from the top and removes the object, but Stack.Peek() method returns an object at the top without removing it from the stack.

Syntax:

    Object Stack.Peek();

Parameters: None

Return value: Object – it returns the top most object of the stack.

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);

    printig stack's top object/element:
    stk.Peek();
    
    Output:
    500

C# example to get an object at the top from the stack using Stack.Peek() 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);

            //printig stack's top object/element
            Console.WriteLine("object at the top is : " + stk.Peek());

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

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

Output

object at the top is : 500
Stack elements are...
500 400 300 200 100

Reference: Stack.Peek 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.