Bird
0
0
DSA Cprogramming~15 mins

Peek Top Element of Stack in DSA C - Build from Scratch

Choose your learning style9 modes available
Peek Top Element of Stack
📖 Scenario: You are building a simple program to manage a stack of books. You want to be able to see the top book on the stack without removing it.
🎯 Goal: Create a stack using an array, set up a variable to track the top, write code to peek at the top element, and print it.
📋 What You'll Learn
Create an integer array called stack with exactly these values: 10, 20, 30, 40, 50
Create an integer variable called top and set it to 4
Create an integer variable called peek and set it to the top element of the stack using stack[top]
Print the value of peek using printf
💡 Why This Matters
🌍 Real World
Stacks are used in many places like undo features in apps, browser history, and managing function calls.
💼 Career
Understanding stack operations like peek is important for software development, debugging, and working with low-level programming.
Progress0 / 4 steps
1
Create the stack array
Create an integer array called stack with these exact values: 10, 20, 30, 40, 50
DSA C
Hint

Use int stack[5] = {10, 20, 30, 40, 50}; to create the array.

2
Set the top index
Create an integer variable called top and set it to 4 to represent the top index of the stack
DSA C
Hint

Use int top = 4; to set the top index.

3
Peek the top element
Create an integer variable called peek and set it to the top element of the stack using stack[top]
DSA C
Hint

Use int peek = stack[top]; to get the top element.

4
Print the peeked element
Print the value of peek using printf with the format specifier %d
DSA C
Hint

Use printf("%d\n", peek); to print the top element.