Prevent array from accepting duplicate values - c

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

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

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.

I cant seem to understand how to restrict my scanf to only numbers of float

#include <stdio.h>
#include <string.h>
#define mL 5
#define NL 20
#define UL 6
struct LIST
{
char n[NL];
float am;
char u[UL];
};
struct array
{
struct LIST array;
};
void addCityInformation(struct array *add, int *items);
void printCities(struct array *all, int items);
int main(void)
{
struct array shopping[mL];
int choice, nrOfItemsAdded = 0;
do
{
printf("\nWhat du you want to do?");
printf("\n1 - add grocery");
printf("\n2 - print shopping list");
printf("\n3 - exit");
printf("\nYour choice: ");
scanf("%d", &choice);
while(getchar() != '\n');
switch (choice)
{
case 1:
addCityInformation(&shopping[nrOfItemsAdded], &nrOfItemsAdded);
break;
case 2:
printCities(shopping, nrOfItemsAdded);
break;
case 3:
printf("Exiting program\n\n");
break;
default:
printf("Invalid input\n\n");
break;
}
}
while(choice != 3);
return 0;
}
int clean_stdin()
{
while (getchar()!='\n');
}
void addCityInformation(struct array *add, int *items)
{
if(*items == mL)
printf("No more space in the list\n");
else
{
printf("Enter name: ");
fgets(add->array.n, NL, stdin);
add->array.n[strlen(add->array.n)-1] = '\0';
do {
printf("Enter amount: ");
}while (scanf("%f", &add->array.am )); //loop untill other than float
getchar();
printf("Enter unit: ");
fgets((add->array.u), UL, stdin);
add->array.u[strlen(add->array.u)-1] = '\0';
(*items)++;
}
}
void printCities(struct array *all, int items)
{
printf("\n\n%-20s %-15s %-9s | %-6s\n", "Name", "amount", "unit");
printf("--------------------------------------------------------\n");
for(int i = 0; i < items; i++)
printf("%-20s %-15.1f %-9.4s \n", all[i].array.n, all[i].array.am, all[i].array.u);
}
This is my loop beside that i am only showing a part of the code. It now just continues to give enter amount and letting me register it in the struct. I want to restrict the user to only entering positive numbers and no character at all. And if he types a character it should rerun the loop even if it is 123Av123 it should run the loop and only register the correct number
Edit: now showing the whole code//loop untill other than float is what i want help with
int check=scanf("%f", &add->array.am )
if(check!=1||add->array.am<0){
printf("Incorrect input");
return 1;
}
I think that will do it.
Edit: you wanted it to rerun after so use continue; instead of return;

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

interactive menu with switch statement

Hi I'm trying to make an interactive menu with switch statement in C.
Though I'm unsure of how to trigger a function that has certain arguments.
I'm a total beginner and I'm stumped how to do this.
The function in the switch statement needs the arguments though I would like the function to ask for the numbers. I'm doing this as an assignment and cannot provide the actual code so I made this mock up. Thank you for your help.
Here is an example of code I might use.
#include <stdio.h>
void printMenu()
{
int choice;
do
{
printf("Main Menu:\n");
printf("1) do this\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
function(); /* though this needs the arguments */
break;
}
} while (choice != 7);
int main(void)
{
printMenu();
return 0;
}
void function(int number1, float number2)
{
/*calculation*/
printf("enter your numbers");
/* Not sure how to read the numbers in here */
printf("%d + %d = %d", number1, number2, number1 + number2);
return;
}
If you want the switch to be as minimal as possible then just call another function which takes in input and then calls the function...
case 1:
read_input_and_function()
break;
...
void read_input_and_function(void)
{
printf("Enter your numbers: ");
/* scanf number1, number2 */
function(number1, number2);
}
The function in the switch statement needs the arguments though I
would like the function to ask for the numbers.
How about asking the arguments first , and then calling the function. This way the two arguments can be declared once and be used in other functions of the same switch , but be defined according to the chosen case.
void function1(int, float);
void printMenu()
{
int choice = 0 , num1 = 0;
float num2 = 0;
do
{
printf("Main Menu:\n");
printf("1) do this\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter number 1\n");
scanf("%d",&num1);
printf("\nEnter number 2\n");
scanf("%f",&num2);
function1(num1,num2);
break;
}
} while (choice != 7);
}
#include <stdio.h>
#include <stdlib.h>
#define Pi 3.14159216
/*
*small program of how to create a menu
*/
main ()
{
float degree,radians;
int input;
/*degrees to radians */
float degreesToRadians (float deg)
{
return ((Pi * deg) / 180.0);
}
/*radians to degrees*/
float radiansToDegrees (float rad)
{
return rad * (180 / Pi);
}
void menu ()
{
printf ("\n");
printf ("1. degrees\n");
printf ("2. radians\n");
printf ("3. quit\n");
do
switch (input) {
case 1:
printf ("\n");
printf ("\n");
printf (" Enter value of degrees: ");
scanf ("%f", &degree);
printf ("RADIANS = %f \n\n", degreesToRadians (degree));
menu ();
break;
case 2:
printf ("\n");
printf ("\n");
printf (" Enter value of radians: ");
scanf ("%f", &radians);
printf ("DEGREES = %f \n\n", radiansToDegrees (radians));
menu ();
break;
case 3:
printf (" quiting app \n");
exit (0);
break;
default:
printf ("wrong option\n");
break;
}
while (input != 3);
getchar ();
}
}
menu ();
}

Resources