Hi i have a problem with my stack data structure program. It seems that when i define the size of my array/the imaginary size of array just to call it through a loop the size i defined or specified by the user is being depleted or somewhat edited when i enter a data or push.
For ex. i entered 5 for the size and choose push and then add 2. It is working properly. But if i choose to push data again, it is now passing to the size variable. I do not know understand what is happening...
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
#define p printf
#define s scanf
int top;
int ar[1];
int size;
main()
{
void push();
int opt, num;
char cont[] = { 'y' };
clrscr();
p("Stacking Program");
p("\n\nData Size: ");
s("%d", &size);
p("\n");
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
p("Stacking Program");
p("\n\nData Size: %d\n\n", size);
p("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
s("%d", &opt);
p("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top > size)
{
p("You can't push more data");
}
else
{
p("Enter data for Data[%d]: ", top);
s("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
p("Your choice is not in the list.");
break;
}
p("\n\nDo you want continue\(Y\/N\)?");
s("%s", &cont[0]);
}
}
pop()
{
int a;
if(top < 0)
{
p("Stack empty.");
return 0;
}
else
{
a = ar[top];
p("\(Data[%d] = %d\) removed.", top, a);
top--;
}
}
void push(int b)
{
top++;
ar[top] = b;
}
pick()
{
if(top < 0)
{
p("Nothing to display.");
return 0;
}
else
{
p("\(Data[%d] = %d\) is the last data.", top, ar[top]);
}
}
view()
{
int i;
if(top < 0)
{
p("Nothing to display.");
return 0;
}
else
{
for(i = 1; i < (top + 1); i++)
{
p("Data[%d] = %d\n", i, ar[i]);
}
}
}
You need to define the size of the array at runtime, using the size entered by the user.
instead of:
int top;
int ar[1];
int size;
...
int top = -1;
int *ar = NULL;
int size = 0;
and then after getting size from the user:
if ( size > 0 )
{
ar = malloc(size * sizeof(int));
if ( ar == NULL )
{
printf("ERROR: malloc() failed\n");
exit(2);
}
}
else
{
printf("ERROR: size should be positive integer\n");
exit(1);
}
....
p("\n\nDo you want continue(Y/N)?");
s("%s", &cont[0]);
}
free(ar);
} // end of main
I think the for loop in view() should be:
for(i = 0 ; i <= top ; i++)
also
case 2:
if ( top == ( size - 1 ))
If you don't want to dynamically size the array, another approach is to allocate an array with MAXSIZE elements, where MAXSIZE is "big enough". Also, some other comments:
You declared at the top of your program a character array of size 1:
char cont[] = { 'y' };
But in your scanf line later you try to use this:
s("%s", &cont[0]);
This will overflow your buffer even if the user types just one character, because %s assumes that the buffer has at least two bytes available, one for the character and one for the '\0'. Possible fix:
char cont[] = { 'y', '\0' };
// ...
s("%1s", cont);
Note that cont is the same and more common way of saying &cont[0].
Another problem is with things that might be caught by the compiler if warnings are turned on: all functions should be prototyped before they are mentioned, functions without explicit return type should be declared with type int, and you should not let a function drop off without returning a value even though you declared it to explicitly or implicitly. Also, '(' and ')' do not need to be escaped in string literals.
Here is a modified version with changes noted. I have redefined clrscr() because I don't have conio.h on this system:
#include <stdio.h>
#include <ctype.h>
// #include <conio.h>
#define clrscr() printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#define p printf
#define s scanf
#define MAXSIZE 500
// prototypes [Changed]
int pop();
void push(int b);
int pick();
int view();
int top;
int ar[MAXSIZE];
int size;
int main()
{
int opt, num;
char cont[] = { 'y', '\0' }; // [Changed]
clrscr();
p("Stacking Program\n\n");
// keep asking until we get a valid size [Changed]
for (;;)
{
p("Data Size: ");
s("%d", &size);
if (size > 0 && size < MAXSIZE)
break;
printf("Not a valid size!\n");
}
p("\n");
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
p("Stacking Program");
p("\n\nData Size: %d\n\n", size);
p("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
s("%d", &opt);
p("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top > size)
{
p("You can't push more data");
}
else
{
p("Enter data for Data[%d]: ", top);
s("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
p("Your choice is not in the list.");
break;
}
p("\n\nDo you want continue(Y/N)?");
s("%1s", cont); // [Changed]
}
return 0;
}
int pop()
{
int a;
if(top == 0) // [Changed]
{
p("Stack empty.");
return 0;
}
else
{
top--; // [Changed]
a = ar[top];
p("(Data[%d] = %d) removed.", top, a);
return a; // [Changed]
}
}
void push(int b)
{
ar[top] = b;
top++; // [Changed]
}
int pick()
{
if(top == 0) // [Changed]
{
p("Nothing to display.");
return 0;
}
else
{
p("(Data[%d] = %d) is the last data.", top, ar[top-1]); // [Changed]
return -1; // [Changed]
}
}
int view()
{
int i;
if(top < 0)
{
p("Nothing to display.");
return 0;
}
else
{
for(i = 0; i < top; i++) // [Changed]
{
p("Data[%d] = %d\n", i, ar[i]);
}
return -1; // [Changed]
}
}
Related
I m trying to implement stack using array and performing basic operations on it. All my operations are performing well. But the issue is when i again try to do the same operation, it seems like they are begin performed on the same old stack and not the updated one after the performing the operations.
for e.g when i push an element in the stack and then try to display the stack , it doesn't display's the pushed element. The same happens with pop() as well every time it shows the same element begin popped out.
Here's my C code for stack:
#include <stdio.h>
#define MAXSIZE 15
int stack[MAXSIZE];
int top = -1;
void push(int x)
{
if (top == MAXSIZE - 1)
{
printf("Overflow Condition");
}
else
{
top++;
stack[top] = x;
}
}
void pop()
{
int item;
if (top == -1)
{
printf("Underflow Condition\n");
}
else
{
item = stack[top];
top--;
printf("The popped element is: %d", item);
}
}
void peek()
{
if (top == -1)
{
printf("Underflow Condition\n");
}
else
{
printf("%d", stack[top]);
}
}
void displayStack()
{
int i;
for (i = top; i >= 0; i--)
{
printf("%d ", stack[top]);
top--;
}
}
int main()
{
// Push the starting element:
push(2);
push(3);
push(4);
push(5);
push(6);
int ch, a;
printf("Enter Choice: \n 1: push\n 2: pop\n 3: peek\n 4: display \n\n");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter the element you want to push to stack: ");
scanf("%d", &a);
push(a);
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
displayStack();
break;
default:
printf("Invalid Choice...");
}
}
Any idea what's the matter??
Try to replace your displayStack() function with this:
void displayStack()
{
int i;
for (i = top; i >= 0; i--)
{
printf("%d ", stack[i]);
}
}
You should not modify a data structure inside an output function. Everything else seems fine.
The purpose of this code is to implement the queue, input I is to store a value, G is to retrieve a value, and E is to end the storage and retrieval work.
My problem is that I don't know why the output "[I]存入數值[G]取出數值[E]結束:" will output more than one after the first time.
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
int main()
{
int rear = -1;
int front = -1;
int queue[MAX] = {0};
char ch;
int val;
while (rear < MAX - 1 && ch != 'E')
{
printf("[I]存入數值[G]取出數值[E]結束:");
scanf("%c", &ch);
switch (ch)
{
case 'I':
printf("請輸入數值:");
scanf("%d", &val);
rear++;
queue[rear] = val;
break;
case 'G':
if (rear > front)
{
front++;
printf("取出的值:%d\n", queue[front]);
queue[front] = 0;
}
else
{
printf("佇列已空!\n");
exit(0);
}
break;
default:
printf("\n");
break;
}
}
if (rear == MAX - 1)
printf("佇列已滿!\n");
printf("目前佇列中的資料:");
if (front >= rear)
{
printf("沒有\n");
printf("佇列已空!\n");
}
else
{
while (rear > front)
{
front++;
printf("%d ", queue[front]);
}
printf("\n");
}
return 0;
}
//Stack Study by yoonseul at 210719
#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
#define _CRT_SECURE_NO_WARNINGS
typedef struct {
int item[SIZE];
int top;
} Stack;
void InitStack(Stack* pstack)
{
pstack->top = -1;
}
bool IsFull(Stack* pstack)
{
return pstack->top == SIZE - 1;
}
bool IsEmpty(Stack* pstack)
{
return pstack->top == -1
}
int Peek(Stack* pstack)
{
if (IsEmpty(pstack)) {
return -1;
}
return pstack->item[pstack->top];
}
void Push(Stack* pstack, int disk)
{
if (IsFull(pstack)) {
exit(1);
}
pstack->item[++(pstack->top)] = disk;
}
void Pop(Stack* pstack) {
if (IsEmpty(pstack)) {
exit(1);
}
--(pstack->top);
}
int exchange(int x);
int main()
{
int num;
int rod[3][SIZE];
char from='0', to;
int move;
scanf("%d", &num);
InitStack(&rod[0]);
InitStack(&rod[1]);
InitStack(&rod[2]);
for (int i = 0; i < num+1; i++) {
Push(&rod[0], i+1);
Push(&rod[1], 0);
Push(&rod[2], 0);
}
while (from != 'q') {
printf("%3c %3c %3c\n", 'A', 'B', 'C');
for (int i = 0;i<num; i++) {
printf("%3d %3d %3d\n", rod[0][i], rod[1][i], rod[2][i]);
}
scanf("%c %c", &from, &to);
if (from == 'q')
return 0;
int peekF, peekT;
int numF = exchange(from);
int numT = exchange(to);
peekF = Peek(&rod[numF]);
peekT = Peek(&rod[numT]);
if (peekF > peekT && peekT != -1) {
printf("Invalid Move");
}
else {
Pop(&rod[numF]);
Push(&rod[numT],peekF);
}
}
}
int exchange(int x)
{
switch (x) {
case 'A':
return 0;
case 'B':
return 1;
case 'C':
return 2;
}
}
Here is my full code for Hanoi Problem.
The objective is to make a problem that can move this between the rod, and print 'invalid move' if the move is invalid. Also, user can input the number of the disks.
When I debug, there are two errors occur.
One is beneath ' A B C' the last number disk is printed three times. My objective is to print ' 1 0 0'
(ex. if maximum disk is 3,' 3 3 3' is printed.)
edited I solved the first one.
for (int i = 0; i < num + 1; i++) {
Push(&rod[0], i+1);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[1], 0);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[2], 0);
}
I changed disk putting part like like using for statement three times. but I don't know the reason why this happens.
Edited
The hanoi Tower is printed twice, after 2nd scan. I want to know the reason why this happens. It seems like memory problem. I want to know why. I'm new to coding.
PLZ help me. I'm crying.
I implemented an RPN Calculator in C. Now I want to output the current iteration meaning
Iteration 1: Contents: [5, 5]
Iteration 2: Contents: [25]
I am not quite sure how i am going to print them. I tried Printing them in the main function, but the output was coming
Iteration 1: Contents: 5
Iteration 2: Contents: 5
10
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = 0;
void makeEmpty()
{
top = 0;
}
bool isEmpty()
{
return top == 0;
}
bool isFull()
{
return top == MAX_SIZE;
}
void push(int value)
{
stack[top++] = value;
}
int pop()
{
if(isEmpty())
{
printf("Not enough operands in expression\n");
exit(EXIT_FAILURE);
}
return stack[--top];
}
//adds 2 integers
int add(int a, int b)
{
return a + b;
}
//subtracts 2 integers
int sub(int a, int b)
{
return a - b;
}
//multiplies 2 integers
int mul(int a, int b)
{
return a * b;
}
//divides 2 integers
int divide(int a, int b)
{
return a / b;
}
int main(void)
{
char ch;
while(1)
{
//Emptying the stack before the user enters another expression
makeEmpty();
printf("Enter an RPN expression: ");
//Reads expression from user
scanf("%c", &ch);
//parse all characters until a newline is reached
while(1)
{
if(ch == '\n')
break;
//if character is an integer
if(ch >= 48 && ch <= 57)
{
if(!isFull())
{
//convert char to int and push integer onto stack
printf("Iteration %d: Contents: %d \n", (top+1), (ch-48));
push(ch - 48);
}
else
{
//stack ran out of space, print error and exit program
printf("Expression is too complex\n");
exit(EXIT_FAILURE);
}
}
switch(ch)
{
case '+':
push(add(pop(), pop()));
break;
case '-':
push(sub(pop(), pop()));
break;
case '*':
push(mul(pop(), pop()));
break;
case '/':
push(divide(pop(), pop()));
break;
case '=':
printf("%d\n", pop());
break;
}
//get next character
scanf("%c", &ch);
}
}
return 0;
}
You can easily workaround it in your program without creating temporary stacks:
void print_stack(void)
{
printf("[");
for(int index = top -1; index >= 0; index--)
{
printf("%d%s", stack[index], index ? ", " : "");
}
printf("]\n");
}
Hello everyone i got some issues here with the following code actually the code compiles successfully but when i called the display function it outputs one's instead of the actual content of the stack. can anyone explains to me what wrong with the display function.
thank you
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
int menu();
void push();
void pop();
void peep();
void display();
void main() {
char ch;
int item;
do{
switch(menu()) {
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peep();
break;
case 4:
display();
default:
printf("Invalid choice try again\n");
break;
}
printf("Do you want to continue ? (Y/N): ");
printf("top value is %d", top);
fflush(stdin);
scanf("%c", &ch);
}while(ch == 'Y' || ch == 'y');
}
int menu() {
int choice;
printf("Welcome to stack program \n\n");
printf("\n #1. push");
printf("\n #2. pop");
printf("\n #3. peep");
printf("\n #4. display");
printf("\nchoice: ");
scanf("%d", &choice);
return choice;
}
void push() {
int item;
printf("Enter element to add to stack: ");
item = scanf("%d", &item);
if(top == MAXSIZE - 1) {
printf("stack overflow can't add any more item\n");
exit(0);
} else {
top++;
stack[top] = item;
}
}
void pop() {
if(top == -1) {
printf("stack underflow deletion not possible\n");
exit(0);
} else {
printf("Element %d is deleted from the stack\n", stack[top]);
top--;
}
}
void peep() {
int i;
int element;
printf("Enter the location that you want to peep");
fflush(stdin);
scanf("%d", &i);
if(top - i + 1 < 0) {
printf("Location not valid");
exit(0);
} else {
element = stack[top - i + 1];
printf("The location %d contains the element %d \n", i, element);
}
}
void display() {
if(top != -1){
int j;
printf("Elements in the stack\n");
for(j = top; j >= 0; j--) {
printf("%d\n", stack[j]);
}
} else {
printf("Stack is empty\n");
}
}
Specific issues: missing break statement on case 4:; inconsistent use of fflush(stdin) when fpurge(stdin) seems to make more sense; using success exit code on failure and printing fatal errors to stdout instead of stderr; not clear what location in peep() represents relative to stack, should be documented;
I didn't like your basic design (all stack operations have void return value and no arguments) so I redid it such that the stack operations are functional and the I/O to get values into or out of them is handled external to the routines in the switch statement in main:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
int menu();
void push(int item);
int pop();
int peep(int location);
void display();
int main() {
char ch = 'Y';
int temporary;
while (ch == 'Y' || ch == 'y') {
switch(menu()) {
case 1:
printf("Enter element to add to stack: ");
(void) scanf("%d", &temporary);
(void) fpurge(stdin);
push(temporary);
break;
case 2:
temporary = pop();
printf("Element %d is deleted from the stack\n", temporary);
break;
case 3:
printf("Enter the location that you want to peep: ");
(void) scanf("%d", &temporary);
(void) fpurge(stdin);
printf("The location %d ", temporary);
temporary = peep(temporary);
printf("contains the element %d\n", temporary);
break;
case 4:
display();
break;
default:
printf("Invalid choice try again\n");
break;
}
printf("Value of 'top' is %d\n", top);
printf("Do you want to continue? (Y/N): ");
(void) scanf("%c", &ch);
(void) fpurge(stdin);
}
return EXIT_SUCCESS;
}
int menu() {
int choice;
printf("Welcome to stack program\n");
printf("\n #1. push");
printf("\n #2. pop");
printf("\n #3. peep");
printf("\n #4. display");
printf("\nchoice: ");
(void) scanf("%d", &choice);
(void) fpurge(stdin);
return choice;
}
void push(int item) {
if (top + 1 == MAXSIZE) {
fprintf(stderr, "stack overflow can't add any more item\n");
exit(EXIT_FAILURE);
}
stack[++top] = item;
}
int pop() {
if (top == -1) {
fprintf(stderr, "stack underflow deletion not possible\n");
exit(EXIT_FAILURE);
}
return stack[top--];
}
int peep(int location) {
if (top - location + 1 < 0) {
fprintf(stderr, "Location not valid");
exit(EXIT_FAILURE);
}
int element = stack[top - location + 1];
return element;
}
void display() {
if (top != -1) {
printf("Elements in the stack\n");
for (int j = top; j > -1; j--) {
printf("%d\n", stack[j]);
}
} else {
printf("Stack is empty\n");
}
}
Lots more error checking can, and should be done, this is not finished code.