1
#include <stdio.h>
#include <stdlib.h>
#define N 5
int stack[N];
int top = -1;
void push()
{
    int x;
    printf("Enter data");
    scanf("%d", &x);
    if (top == N - 1)
    {
        printf("Overflow");
    }
    else
    {
        top++;
        stack[top] = x;
    }
}

void pop()
{
    int item;
    if (top == -1)
    {
        printf("Underlfow");
    }
    else
    {
        item = stack[top];
        top--;
        printf("%d", item);
    }
}

void peek()
{
    if (top == -1)
    {
        printf("Underflow");
    }
    else
    {
        printf("%d", stack[top]);
    }
}

void display()
{
    int i;
    for (i = top; i >= 0; i--)
    {
        printf("%d\n", stack[top]);
    }
}

int main()
{
    int ch;
    do
    {
        printf("\n1.push\n2.pop\n3.peek\n4.display");
        scanf("%d", &ch);
        switch (ch)
        {
        case 1:
            push();
            break;

        case 2:
            pop();
            break;

        case 3:
            peek();
            break;

        case 4:
            display();
            break;

        case 5:
            exit(0);
            break;

        default:
            printf("invalid key pressed");
            break;
        }
    } while (ch != 0);
    return 0;
}

So it is the code which i wrote following a tutorial on youtube In push function if i excced the array size which is 5 it will still take values instead of printing overflow and when i try to display it, it will display all values same

before i was geting a error at getch(); while using void main() so i change it to int main() and used return 0; it is still not working.

  • 1
    Please explain the `display` function in great details to a [rubber duck](https://en.wikipedia.org/wiki/Rubber_duck_debugging). – Some programmer dude Jan 11 '23 at 13:39
  • Generally, it seems this is the perfect time to learn how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your programs. For example use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through the code line by line while monitoring variables and their values. – Some programmer dude Jan 11 '23 at 13:40
  • 1
    Move the code where you ask for user input to the `else` block. – 001 Jan 11 '23 at 13:43
  • 1
    in the display function, displays stack[i], not stack[top] – CGi03 Jan 11 '23 at 13:49
  • Thanks it worked!! but why it was happening? – Ashitosh bendre Jan 11 '23 at 13:50
  • 1
    Just a recommendation: C has zero-based indices and heavily operates on the 'one past the end' principle. Once getting used to you are usually better off not remembering the top position where the last element is placed at, but rather the size of the stack so that `top` would indicate the next position to place an element to. This approach fits better into the overall language concept. Many tests get a bit simpler that way, too (e.g. `if(/*top*/size == N) { /* overflow */ }`). – Aconcagua Jan 11 '23 at 13:51
  • Think about the *order* in which you do things. – Some programmer dude Jan 11 '23 at 13:51
  • 1
    As you are just playing around it's fine for now, but for the future keep in mind that utility functions like push/pop/peek should not contain any output to console as this reduces reusability – what, if someone else (or you later on) would want to translate the application or you use your list in a multi-threaded environment where the output might interfere with the one of the other thread... – Aconcagua Jan 11 '23 at 13:58
  • 1
    Similarly: The use of global variables. You limit your stack to one single instance only this way. Better: Let your stack functions receive the stack via *parameter* (though the stack itself *might* remain global then, but you could have several of, being global or not). – Aconcagua Jan 11 '23 at 13:59
  • 1
    To build on the comment by @Aconcagua, I also recommend you learn about *structures*, as then you could have a structure to collect all data needed for a stack, and it makes it easy to pass around, and create multiple stacks. – Some programmer dude Jan 11 '23 at 14:01

1 Answers1

0

So it is the code which i wrote following a tutorial on youtube In push function if i excced the array size which is 5 it will still take values instead of printing overflow and when i try to display it, it will display all values same

  1. Your logic is to always allow you to enter values. But they are not inserted in the stack (and instead "Overflow" is printed). This is because you ask for the value before checking if the stack is full. Just make the test before, and put the scan inside the else part of the if statement.
void push()
{
    int x;

    if (top == N - 1) {
        /* put \n chars at end of lines in output statements
         * like this ---vv      */
        printf("Overflow\n");
    } else {
        printf("Enter data ");
        fflush(stdout);
        scanf("%d", &x);
        top++;
        stack[top] = x;
    }
}
  1. The problem of printing always the top of the stack is basically that you print stack[top], instead of stack[i], in the display() function loop. You should use this code instead.
void display()
{
    int i;
    for (i = top; i >= 0; i--)
    {
        /* use i here --------------v */
        printf("%d: %d\n", i, stack[i]);  
    }
}
  1. This is not an error, but will save you trouble in the future. Get used to put the \n char at the end of the printing format, instead of at the beginning, if you are going to print a complete line. I understand that you want to avoid it when prompting the user, so you avoid it. But the stdio library uses buffering, so it doesn't print things when you ask it for, so it delays the printing of strings (on an interactive session) until you do printf a '\n' char (if the output device is a terminal), or before reading from stdin (also, if the input device is a terminal). This can make a mess if you print your strings without the trailing '\n'. And more, if you redirect your output, this means using a pipe (so, it is not a terminal). Then, no output is done until the buffer fills completely (meaning over 10kb of data, usually 16kb on modern unix/linux systems) You will see your program doing things while no output has been output, and you won't know why.

  2. You don't use getch() in your code, so i think you have posted a different version of the code you are talking about.

My code, after edition, leads to:

#include <stdio.h>
#include <stdlib.h>

#define N 5

int stack[N];
int top = -1;

void push()
{
    if (top == N - 1) {
        /* no overflow yet, not if we check beforehand :) */
        printf("Stack full, cannot push()\n");
    } else {
        int x;

        printf("Enter data ");
        fflush(stdout); /* to flush the output (no \n at end) */
        scanf("%d", &x);
        top++;
        stack[top] = x;
        printf("Push: %d to position %d\n", x, top);
    }
}

void pop()
{
    if (top == -1) {
        /* the appropiate message is stack empty, no underflow has
         * occured yet.  We are preventing it */
        printf("Stack empty, cannot pop()\n");
    } else {
        int item = stack[top];
        printf("Pop: %d from pos %d\n", item, top);
        top--;
    }
}

void peek()
{
    if (top == -1) {
        /* no underflow yet, we are preventing it */
        printf("Stack empty, cannot peek()\n");
    } else {
        printf("Peek: %d on pos %d\n", stack[top], top);
    }
}

void display()
{
    int i;
    printf("Stack contents:\n");
    for (i = top; i >= 0; i--) {
        printf("> %d: %d\n", i, stack[i]);
    }
}

int main()
{
    int ch = 5; /* so we exit if no valid input is made in scanf() */

    do {
        printf("1.push\n"
               "2.pop\n"
               "3.peek\n"
               "4.display\n"
               "5.exit\n");
        scanf("%d", &ch);

        switch (ch) {

        case 1:
            push();
            break;

        case 2:
            pop();
            break;

        case 3:
            peek();
            break;

        case 4:
            display();
            break;

        case 5:
            break;

        default:
            printf("Input invalid option\n");
            break;

        }
    } while (ch != 5); /* option 5 is to exit */

    return 0;
}
Luis Colorado
  • 10,974
  • 1
  • 16
  • 31