The ones who are crazy enough to think they can change the world are the ones who do.
- Steve Jobs

Stack - Peek

Peek() is one of a stack operation that returns the value of the top most element of the stack without deleting that element from the stack.

C program - Peek Operation in Stack

Here is the program to demonstrate Peek operation in stack.

stack-peek.c
#include <stdio.h>
#include <malloc.h>
#define MAX 10
int stack[MAX], top = -1;
void push(int stack[], int val);
int peek(int stack[]);
void display(int stack[]);
int main()
{
int val,choice;
do {
printf("\n 1. PUSH");
printf("\n 2. PEEK");
printf("\n 3. DISPLAY");
printf("\n 4. EXIT");
printf("\n Enter your option : ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("\n Enter the number to be pushed on stack : ");
scanf("%d",&val);
push(stack, val);
break;
case 2:
val = peek(stack);
if(val != -1)
printf("\n The value stored at top of stack is %d", val);
break;
case 3:
display(stack);
break;
}
} while(choice != 4);
return 0;
}
void push(int stack[], int val)
{
if(top == MAX-1)
{
printf("\n STACK OVERFLOW");
}
else {
top++;
stack[top] = val;
}
}
int peek(int stack[])
{
if(top == -1)
{
printf("\n STACK IS EMPTY");
return -1;
}
else
return (stack[top]);
}
void display(int stack[])
{
int i;
if(top == -1)
printf("\n STACK IS EMPTY");
else {
for(i = top;i >= 0;i--)
printf("\n%d",stack[i]);
}
}
1. PUSH
2. PEEK
3. DISPLAY
4. EXIT
Enter your option : 1
Enter the number to be pushed on stack : 1

1. PUSH
2. PEEK
3. DISPLAY
4. EXIT
Enter your option : 1
Enter the number to be pushed on stack : 2 

1. PUSH
2. PEEK
3. DISPLAY
4. EXIT
Enter your option : 1
Enter the number to be pushed on stack : 3

1. PUSH
2. PEEK
3. DISPLAY
4. EXIT
Enter your option : 3
3
2
1

1. PUSH
2. PEEK
3. DISPLAY
4. EXIT
Enter your option : 2
The value stored at top of stack is 3

1. PUSH
2. PEEK
3. DISPLAY
4. EXIT
Enter your option : 3
3
2
1

1. PUSH
2. PEEK
3. DISPLAY
4. EXIT
Enter your option : 4

Report Us

We may make mistakes(spelling, program bug, typing mistake and etc.), So we have this container to collect mistakes. We highly respect your findings.

Report