When I choose push in my menu, then I enter some number value, then the program works fine, but when I enter some letter value, then program never stops, where is my mistake?
I'm beginner in c, so maybe someone can help solve this problem.
I have this code:
#include <stdio.h>
#include <curses.h>
int a[15], top = -1;
void push (int value)
{
if (top == 14)
{
printf("Stack is full");
}
else{
top = top + 1;
a[top] = value;
}
}
void pop()
{
if (top == -1)
{
printf("Stack is empty");
}
else
{
top = top - 1;
}
}
void display()
{
int i;
if (top == -1)
{
printf("\n Nothing to display");
}
else
{
printf("\nArray is:\n");
for (i=0; i<=top; i++)
{
printf("%d\n", a[i]);
}
}
}
int main()
{
int choice, value;
do{
printf("\n1.Push :");
printf("\n2.POP :");
printf("\n3.Display :");
printf("\n4.Exit :");
printf("\nEnter your Choice:");
scanf("%d", &choice);
if(choice == 1)
{
printf("\nEnter Value to be inserted: ");
scanf("%d", &value);
push(value);
}
if(choice == 2)
{
pop();
}
if (choice == 3)
{
display();
}
}
while (choice !=4);
getch();
return 0;
}
You need to change two things for your code to work.First change the following variables to character
char a[15];
char value;
plus you also need to pass a charater to the function not an integer.
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 code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 500
#define M 100
/*Version 1*/
void replace_word(char *word);
void add_new_word_dictionary(void);
void do_nothing(void);
void return_basic(void);
void check_word(void);
void compute_words(void);
void compute_characters(void);
void compute_ch_sp(void);
void compute_num_dif_words(void);
void create_istogram(void);
void save_file(void);
int get_choice(void);
void return_word(void);
void insert_text(int numwords, char matrix[N][M], int posit);
int main() {
int j;
int choice = 0;
char matrix[N][M];
char word[40] = { "t" };
while (1) {
choice = get_choice();
if (choice == 0) {
insert_text(M, matrix, 1);
}
if (choice == 1) {
add_new_word_dictionary();
}
if (choice == 2) {
do_nothing();
}
if (choice == 3) {
save_file();
}
if (choice == 4) {
compute_words();
}
if (choice == 5) {
break;
}
for (j = 0; j < M; j++) {
printf("%s", matrix[N][M]);
}
}
printf("\n End of Program \n");
return 0;
}
void replace_word(char *word) {
return;
}
void add_new_word_dictionary(void) {
char word[50] = { "s" };
printf("\nPlease enter the word\n");
scanf("\n%s", word);
printf("Your word is %s", word);
return;
}
void do_nothing(void) {
printf("\n do_nothing \n");
return;
}
void return_basic(void) {
printf("\n return basic \n");
return;
}
void check_word(void) {
printf("\n check word \n");
return;
}
void compute_words(void) {
printf("\n compute_words \n");
return;
}
void compute_characters(void) {
printf("\n compute characters \n");
}
void compute_ch_sp(void) {
printf("\n compute_ch_sp \n");
return;
}
void compute_num_dif_words(void) {
printf("\n compute_num_same_words \n");
return;
}
void create_istogram(void) {
printf("\n create istogram \n");
return;
}
void save_file(void) {
printf("\n save_file \n");
return;
}
int get_choice(void) {
int choice = 0;
printf("\n Select a choice from the below \n");
printf("\n Select 0 to add text \n");
printf("\n Select 1 to add new words in the dictionary \n");
printf("\n Select 2 to enter enter correction mode \n");
printf("\n Select 3 to save the text \n");
printf("\n Select 4 to see the statistics about your text \n");
printf("\n Select 5 to exit the program\n");
scanf("\n%d", &choice);
return choice;
}
void insert_text(int numwords, char matrix[N][M], int posit) {
int i;
int j;
char word2[40] = { "" };
while (strcmp(word2, "*T*E*L*O*S*")) {
printf("\n Add the word \n");
scanf("\n%s", word2);
if (posit + 1 > numwords) {
printf("\n Out of Bounds \n ");
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
if (!i)
break;
}
strcpy(matrix[posit], word2);
j++;
}
for (i = 0; i < j; i++) {
printf("%s", matrix[i]);
printf("\n j is %d\n", j);
}
return;
}
The problem: I have a function called insert_text. This function adds a string in the 1st position of an array (at least that is what I think it does) and it is called if choice is 0 and executes itself until the string *Ī¤ELOS* is given. When in insert_text I print matrix I get a bunch of *(null)*s... I can count how many words matrix has (by declaring a variable j and incrementing by 1 inside the while loop, but that does not seem to work either. How can I fix this?
The printing code is incorrect: matrix is an array of N arrays of M characters, where you store null terminated C strings. As coded, you pass a single character just beyond the end of the array to printf for %s, which expects a string. The loop should be:
for (j = 0; j < N; j++) {
printf("%s ", matrix[j]);
}
Note that char matrix[N][M]; is uninitialized, so its contents will seem random. Initialize matrix as char matrix[N][M] = { "" };
Also note that in add_new_word_dictionary(), the scanf() conversion should be scanf("%49s", word); to prevent a potential buffer overflow if the user enters a very long word.
Same in insert_text, the code should be scanf("%39s", word2) ans you should test the return value to check for input errors.
Finally, arrays are indexed from 0 in C, so insert_text should be given a position of 0 and the number of words should be N, not M.
Both the test and the insertion loop have problems too.
Here is a modified version:
// call from main as insert_text(N, matrix, 0);
//
void insert_text(int numwords, char matrix[N][M], int posit) {
char word2[40];
int i, j = 0;
for (;;) {
printf("\n Add the word \n");
if (scanf("%39s", word2) != 1) {
break; // end of file or input error
}
if (!strcmp(word2, "TELOS")) {
break; // magic word
}
if (posit >= numwords) {
printf("\n Out of Bounds \n");
break;
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
}
strcpy(matrix[posit], word2);
j++;
}
for (i = 0; i < j; i++) {
printf("%s ", matrix[i]);
}
printf("\n j is %d\n", j);
}
Here is a modified version of the whole program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 500
#define M 100
/*Version 1*/
void replace_word(char *word);
void add_new_word_dictionary(void);
void do_nothing(void);
void return_basic(void);
void check_word(void);
void compute_words(void);
void compute_characters(void);
void compute_ch_sp(void);
void compute_num_dif_words(void);
void create_istogram(void);
void save_file(void);
int get_choice(void);
void return_word(void);
void insert_text(int numwords, char matrix[N][M], int posit);
int main() {
int j, done = 0;
char matrix[N][M] = { "" };
while (!done) {
switch (get_choice()) {
case 0:
insert_text(N, matrix, 0);
break;
case 1:
add_new_word_dictionary();
break;
case 2:
do_nothing();
break;
case 3:
save_file();
break;
case 4:
compute_words();
break;
default:
done = 1;
break;
}
for (j = 0; j < N; j++) {
if (matrix[j][0])
printf("%s ", matrix[j]);
}
printf("\n");
}
printf("\n End of Program \n");
return 0;
}
void add_new_word_dictionary(void) {
char word[50];
printf("\nPlease enter the word\n");
if (scanf("%49s", word) == 1)
printf("Your word is %s\n", word);
}
void replace_word(char *word) { printf("\n replace word \n"); }
void do_nothing(void) { printf("\n do_nothing \n"); }
void return_basic(void) { printf("\n return basic \n"); }
void check_word(void) { printf("\n check word \n"); }
void compute_words(void) { printf("\n compute_words \n"); }
void compute_characters(void) { printf("\n compute characters \n"); }
void compute_ch_sp(void) { printf("\n compute_ch_sp \n"); }
void compute_num_dif_words(void) { printf("\n compute_num_same_words \n"); }
void create_istogram(void) { printf("\n create istogram \n"); }
void save_file(void) { printf("\n save_file \n"); }
int get_choice(void) {
int choice = -1;
printf("\nSelect a choice from the below \n");
printf("Select 0 to add text \n");
printf("Select 1 to add new words in the dictionary \n");
printf("Select 2 to enter enter correction mode \n");
printf("Select 3 to save the text \n");
printf("Select 4 to see the statistics about your text \n");
printf("Select 5 to exit the program\n");
scanf("%d", &choice);
return choice;
}
// call from main as insert_text(N, matrix, 0);
//
void insert_text(int numwords, char matrix[N][M], int posit) {
char word2[40];
int i;
for (;;) {
printf("\n Add the word \n");
if (scanf("%39s", word2) != 1) {
break; // end of file or input error
}
if (!strcmp(word2, "TELOS")) {
break; // magic word
}
if (posit >= numwords) {
printf("\n Out of Bounds \n");
break;
}
for (i = numwords - 2; i >= posit; i--) {
strcpy(matrix[i + 1], matrix[i]);
}
strcpy(matrix[posit], word2);
posit++;
}
for (i = 0; i < posit; i++) {
printf("%s ", matrix[i]);
}
printf("\n posit is %d\n", posit);
}
So I am learning how stack works in C, and I wrote out a little menu that allows the user to push and pop integers to and from the stack. I used the global array implementation of stack.
#include <stdio.h>
#define MAX 5
int top = -1;
int myStack[MAX];
int push(int item){
if(top >= MAX - 1){
printf("stack overflow");
return -999;
}
else{
top++;
myStack[top] = item;
}
return 1;
}
int pop(){
if(top == -1){
printf("no integer to pop from stack.");
return -999;
}
int popped = myStack[top];
top--;
return popped;
}
void displayStack(int myStack[], int top){
for(int i = 0; i < top; i ++){
printf("%d ", myStack[i]);
}
}
int main(){
printf("Menu Options:\n");
printf("1 - Push\n");
printf("2 - Pop\n\n");
int data, choice;
while(1){
printf("Enter choice: ");
scanf("%d", &choice);
if(choice == 1){
printf("Enter data to push: ");
scanf("%d", &data);
push(data);
displayStack(myStack, top);
printf("\n\n");
}
if(choice == 2){
pop();
displayStack(myStack, top);
printf("\n\n");
}
if(choice == 3){
break;
}
}
return 0;
}
My problem is, when I run the code for the first time and insert 1 to push an integer to the stack, everytime, the first call to push, my display doesn't return anything. Only the second time will it display an item from the stack on the screen.
I think this has something to do with the indexes in my display function, but I'm pretty sure I have them correct? After I call push, the top of the stack for the first time goes from -1 to 0, and my displayStack function is starting at index 0.
Any help would be appreciated, thank you!
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.
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]
}
}