DATA STRUCTURES PROGRAM • STACKS & EXPRESSIONS

Implement Two Stacks in One Array

Learn how to implement two stacks in one array using a clear C program.

BeginnerStackLIFOpush/pop

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
Stack 1 top = 20
Stack 2 top = 80

COMPLETE C PROGRAM

Complete C implementation

dsa-two-stacks-one-array.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int values[8];
    int first_top = -1, second_top = 8;
    values[++first_top] = 10;
    values[++first_top] = 20;
    values[--second_top] = 90;
    values[--second_top] = 80;
    printf("Stack 1 top = %d\n", values[first_top]);
    printf("Stack 2 top = %d\n", values[second_top]);
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Stack 1 top = 20
Stack 2 top = 80
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Grow one stack from the left and the other from the right until their tops meet.
  3. Display the computed result.

Grow one stack from the left and the other from the right until their tops meet.

EFFICIENCY

Time and space complexity

Time complexity

O(1) per operation

Auxiliary space

O(n)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.