RPN calculator using push and pop. - c

I want to design a RPN calculator using push and pop. But I am not getting the right result for e after running the program. It seems that c and d are storing 0 after I use pop() to get the value of a and b from the stack. Any suggestions?
#include <stdio.h>
int stack[50];
int first = 0;
int main(void){
int a,b,c,d,e;
char opr[4];
printf("Enter 2 numbers \n");
scanf("%d",&a);
scanf("%d",&b);
void push(int x); // Calling the push function
int pop(); // Calling the pop function
push(a);
push(b);
printf("Enter the operator \n");
scanf("%s",&opr[4]);
switch(opr[4]){
case '+': c=pop(); d=pop(); e=c+d; break;
case '-': c=pop(); d=pop(); e=c-d; break;
case '*': c=pop(); d=pop(); e=c*d; break;
case '/': c=pop(); d=pop(); e=c/d; break;
default: printf("not a valid option");
}
push(e);
printf("%d",e);
printf("%d",stack[50]);
return 0;
}
void push(int x){
if(first==50){
printf("The stack is full");
}else{
x = stack[first];
first++;
}
}
int pop(){
int y;
if(first == 0){
printf("Stack is empty ");
}else{
first--;
y = stack[first];
return y;
}
}

Related

Implementation stack using switch case and while loop using C language

I have written the following program to implement PUSH and POP operations in the stack in such a way that the program will execute till the user choose to exit. Users can perform PUSH, POP, and display the stack in a single execution. But after the execution of the program when I choose the option (1/2/3/4) in console windows, I get executed with an infinite output. So, what modification should I done in the following program:
#include<stdio.h>
#include<stdlib.h>
int maxsize, item;
int top = -1;
int ch;
int is_stack_empty ();
int is_stack_full ();
int push (int[]);
int pop (int[]);
int display (int[]);
int main()
{
printf("Enter the size of stack: ");
scanf("%d", &maxsize);
int stack[maxsize];
printf("\n 1. PUSH");
printf("\n 2. POP");
printf("\n 3. Display");
printf("\n 4. Exit");
printf("\nEnter your choice: ");
scanf("%d", &ch);
while (1)
{
switch (ch)
{
case 1:
push (stack);
break;
case 2:
pop (stack);
break;
case 3:
display (stack);
break;
case 4:
exit(1);
break;
default:
printf("\nError! please select correct option");
}
}
return 0;
}
int display (int s[])
{
printf("\nThe created stack is :\n");
for (int i = 0; i < top; i++)
{
printf("%d\n", s[i]);
}
}
int is_stack_empty ()
{
if (top == -1)
return 1;
else
return 0;
}
int is_stack_full ()
{
if (top == maxsize-1)
return 1;
else
return 0;
}
int push (int s[])
{
if(!is_stack_full())
{
printf("\nEnter the element of STACK[%d]: ", top+1);
scanf("%d", &item);
top = top + 1;
s[top] = item;
}
else
printf("\nError: Overflow! Stack is full! Couldn't perform PUSH operation.");
}
int pop (int s[])
{
if(!is_stack_empty())
{
printf("\nPopped element is %d", s[top]);
top = top - 1;
}
else
printf("\nError: Underflow! Stack is empty! Couldn't perform POP operation.");
}
The program read the choice from users outside the while loop and hence program reads ch value once. Therefore, the switch statement checks only one ch value. The program should read ch value inside the while loop.
while (1)
{
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch (ch)
{
case 1:
push (stack);
break;
case 2:
pop (stack);
break;
case 3:
display (stack);
break;
case 4:
exit(1);
break;
default:
printf("\nError! please select correct option");
}
}

A value of type "void *" cannot be assigned to an empty type of "link". '=': cannot convert from 'void *' to 'link'

I have received the following two errors as well as an additional one "'return': cannot convert from 'link *' to 'link'" for these lines of code. The other two errors are listed in the subject of the question. I am not sure how to fix the problem. Any suggestions are helpful.
I am trying to code the card game War, and this is what I have so far. I am testing the code at each interval and have ran into problems at the code lines listed below
link NEWnode(Card card, link next) {
link x;
x = malloc(sizeof *x); //allocate memory
if (x == NULL) {
printf("Out of memory. \n");
exit(EXIT_FAILURE);
}
x->next = next;
x->card = card;
return x;
}
The entire code is as follows:
#include <stdio.h>
#define DECKSIZE 52
typedef int Card;
int rank(Card c) {
return c % 13;
}
// allow for multi-deck war
int suit(Card c) {
return (c % 52) / 13;
}
// representing the cards
void showcard(Card c) {
switch (rank(c)) {
case 0: printf("Deuce of "); break;
case 1: printf("Three of "); break;
case 2: printf("Four of "); break;
case 3: printf("Five of "); break;
case 4: printf("Six of "); break;
case 5: printf("Seven of "); break;
case 6: printf("Eight of "); break;
case 7: printf("Nine of "); break;
case 8: printf("Ten of "); break;
case 9: printf("Jack of "); break;
case 10: printf("Queen of "); break;
case 11: printf("King of "); break;
case 12: printf("Ace of "); break;
}
switch (suit(c)) {
case 0: printf("Clubs\n"); break;
case 1: printf("Diamonds\n"); break;
case 2: printf("Hearts\n"); break;
case 3: printf("Spades\n"); break;
}
}
// testing the code
// representing the deck and hands (with linked lists because need direct access to top and bottom cards, draw cards from top, won cards go to bottom)
typedef struct node* link;
struct node {
Card card;
link next;
};
link Atop, Abot;
link Btop, Bbot;
// showing a hand
void showpile(link pile) {
link x;
for (x = pile; x != NULL; x = x->next)
showcard(x->card);
}
int countpile(link pile) {
link x;
int cnt = 0;
for (x = pile; x != NULL; x = x->next)
cnt++;
return cnt;
}
// Creating the 52 card Deck
#include <stdlib.h> //for malloc()
link NEWnode(Card card, link next) {
link x;
x = malloc(sizeof *x); //allocate memory
if (x == NULL) {
printf("Out of memory. \n");
exit(EXIT_FAILURE);
}
x->next = next;
x->card = card;
return x;
}
link makepile(int N) {
link x = NULL;
Card c;
for (c = N - 1; c >= 0; c--)
x = NEWnode(c, x);
return x;
}
// testing the code
int main(void) {
link deck;
deck = makepile(DECKSIZE);
showpile(deck);
return 0;
}
This happens because you make use of a C++ compiler instead of a C compiler. In C++ a cast is necessary on that line:
x = (link) malloc(sizeof *x)
...while in C that cast is not needed -- the cast happens implicitly -- and it is actually considered best practice to not add such a cast in C.
On the other hand, in C++ you would better avoid malloc in favor of new. But since your code is intended to be C and not C++, make sure you choose the C compiler.

Values are getting stored in different stack even though different variables are used in the code for each stack

I wanted to create 4 stacks, 1 for each subject. Then in each stack store number of days left for each assignment to be submitted. This is the code I have written. The code works with the exception of 1 flaw:
When values are stored in one stack they also show up in the other stacks with value 0 and same number of elements for example :
I store values 5,20,7 in the stack of ds exit that stack and go to the stack of dsgt and store 9,11 and then on printing the values in stack of dsgt the code prints out as " 0 0 0 9 11" here 0 0 0 are the 3 elements of the 1st stack. Now on exiting the stack of dsgt and going back to stack of ds and printing its value the output is "5 7 20 0 0 " , 0 0 here are the elements of the stack of dsgt which I dont want to print with ds and rest of the stacks.
#include <stdio.h>
#include <conio.h>
#define MAXSIZE 20
int st1[MAXSIZE];
int st2[MAXSIZE];
int st3[MAXSIZE];
int st4[MAXSIZE];
int top = -1;
void push(int st[], int item);
int pop(int st[]);
int peek(int st[]);
void display(int st[]);
void sort(int st[]);
int main() {
int subj;
printf("\nEnter the number associated with the Subject assignment that has to be tracked\n");
int choice = 0, item1;
do {
printf("\n 1. Data Structures");
printf("\n 2. DSGT ");
printf("\n 3. CG ");
printf("\n 4. Math");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
ds();
break;
case 2:
dsgt();
break;
case 3:
cg();
break;
case 4:
math();
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
return 0;
}
int dsgt() {
int choice, item2;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item2);
push(st2, item2);
sort(st2);
break;
case 2:
item2 = pop(st2);
printf("\n Removed Assignment is: \n %d", item2);
break;
case 3:
item2 = peek(st2);
printf("\n The Latest Assignment to be Submitted is:%d", item2);
break;
case 4:
display(st2);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
int ds() {
int choice, item1;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item1);
push(st1, item1);
sort(st1);
break;
case 2:
item1 = pop(st1);
printf("\n Removed Assignment is: \n %d", item1);
break;
case 3:
item1 = peek(st1);
printf("\n The Latest Assignment to be Submitted is:%d", item1);
break;
case 4:
display(st1);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
int cg() {
int choice, item3;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item3);
push(st3, item3);
sort(st3);
break;
case 2:
item3 = pop(st3);
printf("\n Removed Assignment is: \n %d", item3);
break;
case 3:
item3 = peek(st3);
printf("\n The Latest Assignment to be Submitted is:%d", item3);
break;
case 4:
display(st3);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
int math() {
int choice, item4;
do {
printf("Stack Operation \n");
printf("\n 1. Add A New Assignment");
printf("\n 2. Remove the latest Completed Assignment ");
printf("\n 3. View the latest Pending Assignment ");
printf("\n 4. View All the pending Assignments");
printf("\n 5. Exit Code");
printf("\n Enter Your Choice");
scanf("%d", & choice);
switch (choice) {
case 1:
printf("\n Enter the Number of Days Left for the Assignment to be Submitted");
scanf("\n %d", & item4);
push(st4, item4);
sort(st4);
break;
case 2:
item4 = pop(st4);
printf("\n Removed Assignment is: \n %d", item4);
break;
case 3:
item4 = peek(st4);
printf("\n The Latest Assignment to be Submitted is:%d", item4);
break;
case 4:
display(st4);
break;
case 5:
printf("Exited");
break;
default:
printf("\n Wrong Input");
}
} while (choice != 5);
}
void push(int st[], int item) {
if (top == MAXSIZE - 1) {
printf("\n You Have a lot of Assignments Due, GET WORKING!!!");
} else {
top = top + 1;
st[top] = item;
}
}
int pop(int st[]) {
int item;
if (top == -1) {
printf("Great Work No Assignment Are Pending");
return 0;
} else {
item = st[top];
top = top - 1;
}
return item;
}
int peek(int st[]) {
int item;
if (top == -1) {
printf("Great Work No Assignment Are Pending");
return 0;
} else {
item = st[top];
return item;
}
}
void display(int st[]) {
if (top == -1) {
printf("Great Work No Assignment Are Pending");
} else {
for (int i = top; i >= 0; i--) {
printf("\n%d\n", st[i]);
}
}
}
void sort(int st[]) {
int tmp, i, j;
for (int i = top; i >= 0; i--) {
for (j = i + 1; j <= top; j++) {
if (st[i] < st[j]) {
tmp = st[j];
st[j] = st[i];
st[i] = tmp;
}
}
}
}
I would recommend that you use a structure for your stacks that contains the array and the top value e.g.
typedef struct{
int stack[MAXSIZE];
int top;
}stack_t;
Then you can declare your stacks and initialize them:
stack_t st1 = {{0}, -1};
stack_t st2 = {{0}, -1};
stack_t st3 = {{0}, -1};
stack_t st4 = {{0}, -1};
or place them in an array
stack_t stacks[4]={
{{0}, -1},
{{0}, -1},
{{0}, -1},
{{0}, -1}, };
You need to declare your functions as follows and update their implementation accordingly:
void push(stack_t* st, int item);
int pop(stack_t* st);
int peek(stack_t st);
void display(stack_t st);
void sort(stack_t* st);
void dsgt(void);
void cg(void);
void math(void);
void ds(void);
The push, pop, sort functions then all use pointers to stack_t e.g.
int pop(stack_t* st) {
int item =0;
if (st->top == -1) {
printf("Great Work No Assignment Are Pending");
} else {
item = st->stack[st->top];
st->top = st->top - 1;
}
return item;
}
display and peek function are okay with stack_t parameter as they don't change it.
If you place all of your stack structures in an array, you then can use a global variable as an index into your stack_t array and reduce the duplication of your choice code.

Reverse Polish Notation Troubleshooting in C

The question being asked is to evaluate RPN expressions and have the = be the terminating character of the sequence so that the program runs the RPN and calculates the expression it is given. So what I'm having some trouble with is understanding how I should convert my characters to integers as the instructions specifically say use scanf("%c", &ch) which pulls the input in as characters and not ints. How would I convert my characters to ints so I can push them to the array and do the operations on them accordingly?
//
// input: 1 2 3 * + =
// output: 7
//
#include <stdio.h>
#include <stdlib.h>
int collection[100];
int top;
void push(double v){
if (top>99)
{
printf ("Stack Overflow\n");
exit(0);
}
collection[++top]=v;
}
double pop(){
double v;
if(top < 0)
{
printf("stack underflow\n");
exit(0);
}
v=collection[--top];
return v;
}
int main(void){
char ch;
double a,b,c,sum;
int i;
top=-1;
printf("Enter an RPN expression: ");
while(ch!='='){
scanf("%c", &ch);
i=0;
c=1;
push(ch);
if(collection[i]=='+'){
a=pop();
b=pop();
c=b+a;
push(c);
}
else if(collection[i]=='-'){
a=pop();
b=pop();
c=b-a;
push(c);
}
else if(collection[i]=='*'){
a=pop();
b=pop();
c=b*a;
push(c);
}
else if(collection[i]=='/'){
a=pop();
b=pop();
c=b/a;
push(c);
}
else{
while(collection[i]!=0){
i++;
}
i=i-1;
sum=0;
while(i>=0){
sum=sum+((collection[i]-48)*c);
c=c*10;
i--;
}
push(sum);
}
}
printf("%lf\n",c);
}
If satisfied with unsigned int digits:
char ch;
scanf( "%c", &ch );
ch -= '0';
Then you can compose the number from digits by multiplying by 10 and adding the next digit.
Use double atof(const char *nptr);
The atof() function converts the initial portion of the string pointed
to by nptr to double. Although your programming structure in giving commands to the calculator is bad. Use separate functions for each task in algorithm to avoid complications
Here is (some of) my RPN calculator:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "cal.h"
#define MAXOP 100
int main(){
int type;
double op2,op3;
char s[MAXOP];
while((type = getop(s)) != EOF){
switch(type){
case NUMBER:
push(atof(s));
break;
case 'x':
op2 = pop();
op3 = pop();
push(op2);
push(op3);
break;
case 'o':
clear();
break;
case 's':
push(sin(pop()));
break;
case '+':
push(pop() + pop());
break;
case '*':
push(pop() * pop());
break;
case '-':
op2 = pop();
push(pop() - op2);
break;
case '/':
op2 = pop();
push(pop() / op2);
break;
case '%':
op2 = pop();
push((int)pop() % (int)op2);
break;
case '\n':
printf("\t%.4g\n",showtop());
break;
default:
printf("What was that?\n");
break;
}
}
return 0;
}

C: Stack implementation

following code for stack implementation, produces runtime-errors, although it does compile .. Can anyone help me identify find the error?
#include<stdio.h>
#define size 5
// declared a structure for stack which has an int array and top as it's members..
struct stack{
int a[size],top;
}s;
// following method pushes element 'item' in stack when called after checking if stack-overflows or not?
void push(int item){
if(s.top >= size-1)
printf("\nStack overflow..\n");
else
s.a[++s.top] = item;
}
following method pops one element when called..
int pop(){
if(s.top == -1){
printf("\n..Stack underflow..\n");
return 0;
}
return s.a[s.top];
}
// displays elements in the stack till a[top]
void display(){
int i;
for(i = s.top; i>=0; i--){
printf("\n%d", &s.a[i]);
}
}
// main() method..
int main(){
s.top = -1;
int item, choice;
char ans;
printf(" ..Stack Implementation..\n");
printf("-----------------------------");
do{
printf("\nMain Menu");
printf("\n-------------");
printf("\n 1. Push\n 2. Pop\n 3. Display\n 4. Exit\n");
printf("\n Enter your choice: ");
scanf("%d", choice);
switch(choice){
case 1:
printf("\nEnter item to be pushed: ");
scanf("%d", &item);
push(item);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
return 0;
}
printf("\n Want to continue? :");
scanf("%c", &ans);
}while(ans == 'Y' || ans == 'y');
return 0;
}
There is a small typo [I think so, as your other occurrences are correct]. Change
scanf("%d", choice);
to
scanf("%d", &choice);
Also, there is a small problem in scanf("%c", &ans);. It will suffer from the previously-pressed enter. Use
scanf(" %c", &ans); //mind the space before %
Other Issues: [Added after the edit]
printf("\n%d", &s.a[i]); -- get rid of the &, don't need that in printf()
return s.a[s.top]; should be return s.a[s.top--];

Resources