Implementation stack using switch case and while loop using C language - c

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");
}
}

Related

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.

When I call a function I get: Process returned -1073741819

I am writing a program to print a fee invoice of a student. When I call my function getPrefix() my program essentially crashes and says Process returned -1073741819; the program compiles and everything.
The problem is occuring in my deleteCourse() function. I call the function getPrefix() to print out the name associated with the specific crn and the program crashes.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LOAD 12
#define creditHour 120.25
// prototype functions above main
void printMenu();
void addCourse(int [], int crnValid[]);
void courseList ();
int deleteCourse (int [], int crnValid[]);
char* getPrefix (int);
void printInvoice (int [], int);
int main()
{ // start main
int studentId ;
int option = 1;
int crn[MAX_LOAD] = {0}; // used to keep track of courses being taken
int crnValid[MAX_LOAD] = {4587,4599,8997,9696,7895,9658,4287,9599,8927,7696,7890,9008} ; // used to check if crns are valid
printf("Welcome! Enter the student's ID number:\n");
scanf("%d", &studentId);
while (option != 0){
printMenu();
scanf("%d", &option);
switch(option){
case 1:
addCourse (crn, crnValid);
break;
case 2:
deleteCourse (crn, crnValid);
break;
case 3:
printInvoice (crn, studentId) ;
break;
case 0:
break;
default:
printf("Please enter a valid option: \n");
} ;
}
return 0;
} // end main
// define functions below main
// ------------------------------------------------------------------------------------
void printMenu(){
printf("\n---------------------------------\n") ;
printf("Choose from the following options:\n");
printf("1- Add a course for the student\n");
printf("2- Drop a course for the student\n");
printf("3- Print the fee invoice\n");
printf("0- Exit program\n");
printf("---------------------------------\n") ;
printf("Enter your selection: ");
}
// --------------------------------------------------------------------------------------
void addCourse(int crn[], int crnValid[]){
char choice ;
printf("Would you like to print the list of courses? (y/n)");
scanf(" %c", &choice) ;
if (choice == 'y'){
courseList();
}
int i; // loop incrementer
int success = 0;
int valid;
for (i = 1; i < MAX_LOAD; i++){
if (crn[i] == 0){
printf("Enter the course number to add: ");
scanf("%d", &crn[i]);
success = 1; // success = 1 when course has not been taken
break ;
}
}
if (success == 0){
printf("Course can't be added, you have attained the max number of courses!\n");
}
else {
printf("Course added, you have added course %d\n", crn[i]) ;
}
}
// --------------------------------------------------------------------------------------
void courseList ()
{
printf("CRN\tCOURSE\t\tCREDIT HOURS\n");
printf("4587\tMAT 236\t\t4\n");
printf("4599\tCOP 220\t\t3\n");
printf("8997\tGOL 124\t\t1\n");
printf("9696\tCOP 100\t\t3\n");
printf("7895\tMNT 125\t\t2\n");
printf("9658\tOPT 120\t\t3\n");
printf("4287\tMAT 836\t\t4\n");
printf("9599\tCOP 220\t\t3\n");
printf("8927\tGOM 124\t\t3\n");
printf("7696\tCOT 100\t\t4\n");
printf("7890\tMOT 125\t\t3\n");
printf("9008\tOPT 520\t\t5\n");
}
// -------------------------------------------------------------------------------------
int deleteCourse(int crn[], int crnValid[])
{
int i;
int success = 0;
int crnToDelete;
printf("Enter the course number to delete: ");
scanf("%d", &crnToDelete);
char prefix[20] ;
for (i=1; i < MAX_LOAD; i++){
if ( crn[i] == crnToDelete )
{
crn[i] = 0; // deletes course from array crn
success = 1;
break;
}
}
if (success == 0){
printf("The student isn't taking %d/%s", crnToDelete, getPrefix(crnToDelete)) ;
}
else {
printf("Course deleted!\n");
}
return crnToDelete ;
}
//--------------------------------------------------------------------------------------
char* getPrefix (int crnToDelete){
switch(crnToDelete){
case 4587:
return "MAT 236";
case 4599:
return "COP 220";
case 8997:
return "GOL 124";
case 9696:
return "COP 100";
case 4580:
return "MAT 230";
case 4581:
return "MAT 231";
case 4582:
return "MAT 232";
case 4583:
return "MAT 233";
case 3587:
return "MAT 256";
case 4519:
return "COP 420";
case 6997:
return "GOL 127";
case 9494:
return "COP 101";
}
}
// --------------------------------------------------------------------------------------
void printInvoice (int crn [], int studentId)
{
printf("\n\tVALENCIA COMMUNITY COLLEGE\n");
printf("\tORLANDO FL 10101\n");
printf("\t----------------------------\n");
printf("\n\tFee Invoice Prepared for Student V%d\n", studentId);
printf("\n\t1 Credit Hour = $ 120.25\n");
printf("\n\tCRN\tCR_PREFIX\tCR_HOURS");
int i;
for (i=1; i < MAX_LOAD; i++)
{
if (crn[i] != 0){ // if a course is in spot i, print course
printf("\n\t%d\n", crn[i]) ;
}
}
printf("\n\t\tHealth and Id fees:\t $ 35.00");
printf("\n\t-----------------------------------------");
printf("\n\t\tTotal Payments:") ;
}

RPN calculator using push and pop.

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;
}
}

Prevent array from accepting duplicate values

I have a stack where I want to push distinct elements. I wrote the following code. But it always checks only first element. If I enter a duplicate value first value, it doesn't accept that, but if I enter a duplicate value of 2nd or 3rd value it accepts it.
For example if I enter 20 and again enter 20 it will not accept the second,
but if I enter 20, 22, 22 it accepts the duplicate. How can I prevent this?
#include <stdio.h>
#define MAXSIZE 5
struct stack
{
int stk[MAXSIZE];
int top;
};
typedef struct stack STACK;
STACK s;
void push(void);
int pop(void);
void display(void);
void main ()
{
int choice;
int option = 1;
s.top = -1;
printf ("STACK OPERATION\n");
while (option)
{
printf ("------------------------------------------\n");
printf (" 1 --> Bus Status \n");
printf (" 2 --> Enter Bus \n");
printf (" 3 --> Exit Bus \n");
printf (" 4 --> EXIT \n");
printf ("------------------------------------------\n");
printf ("Enter your choice\n");
scanf ("%d", &choice);
switch (choice)
{
case 1:
display();
break;
case 2:
push();
break;
case 3:
pop();
break;
case 4:
return;
}
fflush (stdin);
printf ("Do you want to continue(Type 0 or 1)?\n");
scanf ("%d", &option);
}
}
/* Function to add an element to the stack */
void push ()
{
int num,i,j,status=0;
if (s.top == (MAXSIZE - 1))
{
printf ("Terminal is Full\n");
return;
}
else
{
printf ("Enter the Bus Number\n");
scanf ("%d", &num);
if(num<1 || num>30) {
printf("This bus Does not Exist.\n");
}
for(i=0;i<5;i++){
if(s.stk[i]==num){
printf("Bus Already in the Terminal\n");
break;
}
else {
s.top = s.top + 1;
s.stk[s.top] = num;
status=1;
break;
}
}
if(status==1)
printf("Bus %d Successfully Entered\n", num);
}
return;
}
You're bus insert loop is looping through and adds a bus the first time it finds s.stk[i] != num. You need to check to see if the bus is in the station ie search the whole stack before inserting a new bus.
for(i=0;i<5;i++) {
if(s.stk[i]==num){
printf("Bus Already in the Terminal\n");
break;
}
else {
s.top = s.top + 1;
s.stk[s.top] = num;
status=1;
break;
}
}

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