In this situation, I take out the for loop at the end of the main function and the printf statement in it and call it as a display function, but I don't know how to write the code.I want an example code.
#include<stdio.h>
#define SIZE5
int stack [SIZE];
intsp;
void push (int value);
int pop(void);
int main (void)
{
sp = 0;
int resp, data;
while(1){
printf("1:push2:pop0:end:");
scanf("%d", & resp);
if(!resp)break;
switch(resp){
case1: printf("push:"); scanf("%d", & data);
push(data);
break;
case2:pop();
break;
}
printf("sp=%d\n",sp);
}
printf("\n");
for(inti=0;i<sp;i++){
printf("stack[%d]=%d\n", i, stack[i]);
}
return 0;
}
void push (int value)
{
if(sp>=SIZE){
printf("The stack is full\n");
} else {
stack [sp++] = value;
}
}
int pop(void)
{
if(sp<=0){
printf("The stack was empty\n");
return 0;
} else {
return stack [--sp];
}
}
The code example shows how to think about @metropolis' introduction.
void
stack[]
sp
i
void
: Required variables stack[]
and sp
are defined globally & other push()
/pop()
functions do not specify themint[]
(stack[]) and int
(sp) as parameters → Allow parameters to specify what to process for scalability and versatility
display()
function → printf("\n");
before the for
loop of the display()
function so that it always appears from the beginning of the linedisplay()
function specializes in displaying stack contents, leaving the initial display start position adjustment to the caller→display()
function only in the for
loopmain()
The self-made functions you call in the function are pre-prototyped, such as void push(int value);
and int pop(void);
display()
function to match the above and move the stack content display processdisplay()
function into the original stack content display actionstack[]
sp
i
void
: Required variables stack[]
and sp
are defined globally & other push()
/pop()
functions do not specify themint[]
(stack[]) and int
(sp) as parameters → Allow parameters to specify what to process for scalability and versatility
display()
function → printf("\n");
before the for
loop of the display()
function so that it always appears from the beginning of the linedisplay()
function specializes in displaying stack contents, leaving the initial display start position adjustment to the caller→display()
function only in the for
loop
© 2024 OneMinuteCode. All rights reserved.