Peek Operation in Stack Using Array
Peek Operation in Stack Using Array
pushing an element into a stack needs you to first check if the stack is
not full, and then insert the element at the incremented value of the top.
And similarly, popping from a stack, needs you to first check if it is not
empty, and then you just decrease the value of the top by 1.
Peek operation requires the user to give a position to peek at as well.
Here, position refers to the distance of the current index from the top
element +1.
The index, mathematically, is (top -position+1).
So, before we return the element at the asked position, we’ll check if the
position asked is valid for the current stack. Index 0, 1 and 2 are valid for
the stack illustrated above, but index 4 or 5 or any other negative index
is invalid.
Note: peek(1) returns 12 here.
1. Create an integer function peek, and pass the reference to the stack,
and the position to peek in, as its parameters.
2. Inside the function, create an integer variable arrayInd which will store
the index of the array to be returned. This is just (top-position +1).
3. Before we return anything, we’ll check if the arrayInd is a valid index. If
it’s less than 0, it is invalid and we report an error. Otherwise,we just
return the element at the index, (top-position+1).
return -1;
else{
return sp->arr[arrayInd];
#include<stdlib.h>
struct stack{
int size ;
int top;
int * arr;
};
if(ptr->top == -1){
return 1;
else{
return 0;
return 1;
else{
return 0;
if(isFull(ptr)){
else{
ptr->top++;
ptr->arr[ptr->top] = val;
}
int pop(struct stack* ptr){
if(isEmpty(ptr)){
return -1;
else{
ptr->top--;
return val;
return -1;
else{
return sp->arr[arrayInd];
int main(){
sp->size = 10;
sp->top = -1;
push(sp, 23);
push(sp, 99);
push(sp, 75);
push(sp, 3);
push(sp, 64);
push(sp, 57);
push(sp, 46);
push(sp, 89);
return 0;
Bold lines are added in last program. Rest of the code is same.
Output:
Stack has been created successfully