How can I create loop for queue? - c

This is a queue sample.This is working but when I select the choose 1 I can not select choose 2 anymore I know I need a while loop but I could not do that in the correct way.
printf_s("? ");
scanf_s("%d", &choose);
In here I need to add a loop I guess but I could not do that properly.
while (choose != 3) {
switch (choose)
{
case 1:
printf_s("Enter a character:");
scanf_s("\n%c", &chooseNo);
add(&startPtr, chooseNo);
printList(startPtr);
break;
case 2:
if (!Isempty(startPtr)) {
printf_s("Enter a character for deleting ");
scanf_s("\n%c", &chooseNo);
if (delete(&startPtr, chooseNo)) {
printf_s("%c deleted.\n", chooseNo);
printList(startPtr);
}
else
printf_s("%c could not be found.\n\n", chooseNo);
}
else
printf_s("List is empty.\n\n");
break;
default:
printf_s("Invalid choose.\n\n");
menu();
break;
printf_s("?");
scanf_s("%d", &choose);
}
}
return 0;
}

First of all, don't put all your code in. It's like 100~200 lines, from which a half is useless in order to solve your problem.
Your scanf for editing the value of choose in the loop is in the wrong place.
What happens is :
while (choose != 3) {
switch (choose) {
case 1:
//code for case 1
break; // if the user chose 1, the program end the switch statement here
case 2:
//code for case 2
break; // if the user chose 2, the program end the switch statement here
default: // For any choice but 1 or 2, this part is executed
printf_s("Invalid choose.\n\n");
menu();
break; // For the default case, the switch statement ends here
// Any code written after this point will not be reached at all
printf_s("?"); // unreachable code
scanf_s("%d", &choose); // unreachable code
}
}
So, just write :
while (choose != 3) {
switch (choose) {
/* Code of your switch statement */
}
printf_s("?");
scanf_s("%d", &choose);
}```

Related

Infinite error loop with if/else statement in a while loop

I'm trying to make a calculator with 12 operations, the 12th being exit, and I want it to produce an error message if the user tries to input a value other than 1-12.
I got it to work for numbers like 15, 500, etc. that aren't in the range, but if the user inputs the letter 'a' for example, it results in an infinite loop, while if the user enters 500 it does what I want it to, which is print the "try again" message and display the menu again.
So, I know the problem is with the if/else loop directly contained in the while loop, but I'm not sure why it doesn't return to the menu after the break; statement in the else statement containing "red" (I put red and blue so that I could tell which statement is being printed). I tried a do/while loop but had the same issue. I also tried making the default statement in the switch case be the "try again" part, and it works if the user enters a number like 500, but as soon as a letter or character like ? is entered, I get an infinite "try again" loop.
This is the code I'm having trouble with:
#define RESTRICT(option, min, max) (option > min && option < max)
while(!exit) {
printf("Choose an option:");
printf("1. Eliminate.");
printf("2. Show fraction.");
printf("3. Show all fractions.");
printf("4. Show the absolute value.");
printf("5. Simplify.");
printf("6. Add.");
printf("7. Subtract.");
printf("8. Multiply.");
printf("9. Divide.");
printf("10. Save in archive.");
printf("11. Load in archive.");
printf("12. Exit program.");
if(scanf("%i", &option) == 1){
if(RESTRICT(option,0,12)){
switch(option){
case 1:
printf("Example");
break;
case 2:
printf("Example");
break;
case 3:
printf("Example");
break;
case 4:
printf("Example");
break;
case 5:
printf("Example");
break;
case 6:
printf("Example");
break;
case 7:
printf("Example");
break;
case 8:
printf("Example");
break;
case 9:
printf("Example");
break;
case 10:
printf("Example");
break;
case 11:
printf("Example");
break;
}
} else if (option==12){
printf("\nGoodbye!\n");
exit=1;
} else {
printf("\nThat is not an option! Try again\n");
printf("\nBlue\n");
continue;
}
} else {
printf("\nThat is not an option! Try again\n");
printf("\nRed\n");
break;
}
}
'a' for example, it results in an infinite loop"
'a' is never consumed by if(scanf("%i", &option) == 1){. It is not numeric text, so gets put back into stdin for the next input function. Since scanf("%i", &option) if then call again, the results repeat.
Code needs to read and consume the 'a'. Consider fgets().
Best to avoid using scanf() at all until you understand why it it bad.
According to your code, In this code scanf("%i", &option) expects interger value from the use end. when user enter non-integer value, scanf function will not store anything in the option variable. use fgets The fgets function reads a text line or a string from the specified file or console. And then stores it to the respective string variable.
Try to update your code as follows:
char input[10];
while (!exit) {
printf("Choose an option:");
printf("1. Eliminate.");
printf("2. Show fraction.");
.
.
.
fgets(input, sizeof(input), stdin);
if (sscanf(input, "%i", &option) == 1) {
if (RESTRICT(option, 0, 12)) {
switch (option) {
case 1:
printf("Example");
break;
case 2:
printf("Example");
break;
.
.
.
}
} else if (option == 12) {
printf("\nGoodbye!\n");
exit = 1;
} else {
printf("\nThat is not an option! Try again\n");
continue;
}
} else {
printf("\nThat is not an option! Try again\n");
}
}

Little bit confused with the Switch Statements

I'm very new to C programming, and I need a help!
I have made a program of calculator with the help of Switch Statement and I want this program to be in a loop, So that it ask the menu (i.e Enter your Choice: Divide,Multiplication,Addition etc) again and again with the user.
Also I want, an End option with the Cases in Menu, which will close the program. I don't know how to code that End option which will make the Program Close.
Please Help!
#include<stdio.h>
#include<conio.h>
int main()
{
int a,b,choice;
float sum,mul,div,sub,quo;
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
printf("Enter the Second Number: ");
scanf("%d",&b);
printf("\n Enter Your Choice");
printf("\n\n1.Sum");
printf("\n2.Multiplication");
printf("\n3.Division");
printf("\n4.Subtraction");
printf("\n5.Quotient");
printf("\nYOUR CHOICE: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
sum=a+b;
printf("Sum= %f\n",sum);
break;
case 2:
mul=a*b;
printf("Multiplication= %f\n",mul);
break;
case 3:
div=a/b;
printf("Division= %lf\n",div);
break;
case 4:
sub=a-b;
printf("Subtraction= %f\n",sub);
break;
case 5:
quo=a%b;
printf("Quotient= %f\n",quo);
break;
default:
printf("\n Unavailable Choice");
}
return 0;
getch();
}
Assuming you add option number 6 to close the calculator, you can add the following case to quit the program -
case 6:
// print bye message or whatever
exit(0);
break;
You can read about the exit function and what the arguments passed to it mean. Usually a 0 indicates successful exit from the program.
You also need to include stdlib.h if you want to use exit.
I would suggest introducing a loop condition variable, eg. CarryOn, initialise it to 1, and use that in a while loop. Let the loop continue as long as the variable is 1. When the user selects "End", set the variable to 0 in the case. That will end the loop.
Let me clarify it with some example code outline:
int CarryOn = 1;
while (CarryOn == 1)
{
// ...your original code
// ...
// add to switch
case 6: // 6 will be the "End" / "Exit" option
CarryOn = 0;
break;
}
You will need to have a while loop.
while(true){
printf("\n\t\t\t\t CALCULATOR");
printf("\nEnter the First Number: ");
scanf("%d",&a);
....
//return 0; remove the return statement
getch();
}
and also add the menu item 6) Exit to your printf and handle that option as described in the one of the answers above.
case 6:
// print bye message or whatever
exit(0);
break;

Terminate program in C

Could someone help me with my code?
My program isn't terminating. After choosing a brand, it should terminate but it loops forever.
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
exit(0);
}
}
return 0;
}
I guess you are misunderstanding the default case of switch: it is executed only if number is not 0,1,2,3.
If you want to exit each time a exit(0) for each case 0 1 2 3
#include<stdio.h>
int main (void)
{
int number,count=0 ;
while (count<3)
{
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
exit(0);
break;
case 1:
printf("You have selected proace.\n");
exit(0);
break;
case 2:
printf("You have selected yonex.\n");
exit(0);
break;
case 3:
printf("You have selected reebook.\n");
exit(0);
break;
default:
printf("Please try again.\n");
}
}
return 0;
}
BTW a better code should be
#include<stdio.h>
int main (void)
{
int number;
bool canExit = false;
while (canExit == false)
{
canExit = true;
printf("Menu:\n");
printf("1.Proace\n");
printf("2.Yonex\n");
printf("3.Reebook\n");
printf("0.Exit\n");
printf("Enter your selection:");
scanf("%d",&number);
switch (number)
{
case 0:
printf("exit.\n");
break;
case 1:
printf("You have selected proace.\n");
break;
case 2:
printf("You have selected yonex.\n");
break;
case 3:
printf("You have selected reebook.\n");
break;
default:
printf("Please try again.\n");
canExit = false;
}
}
return 0;
}
Replace while (count<3) with a boolean, bool loop=true; followed by while (loop). And then inside the switch when you wish to exit, don't call the exit function but simply set loop=false;.
Your break in the switch() exits the switch() but does not exit the while().
If you enter 0, default: case won't be executed.
Is it really what you wanted ?
int number=4 ;
while (number > 3)
and you can delete count, which I can't see is being used anywhere
Actually, the following structure might be better, since you won't have to put an arbitrary number in the comparison:
int number;
do {
// the thing
} while(number > 3);
In this case, it determines whether to continue the loop AFTER the first execution rather than before it. So in a do-while it will ALWAYS execute the do ONCE before the condition can break it, even if the condition is false to begin with!
I would replace your switch with:
char* brand[] = { "proace", "yonex", "reebook" };
do{
if(number == 0)
printf("exit.\n");
else if(number <= 3)
printf("You have selected %s.\n", brand[number]);
else
printf("Please try again");
}while(number > 3);
Encapsulate it in do-while loop with condition number > 3 and it will loop until user select 0-3. In this case, exit(0) is unnecessary.
You are not updating the count variable that is why it is not exiting. For exiting the while loop the count should be greater than or equal to 3.
As long as you will be giving the input 0, 1, 2 or 3 you will never reach default which has exit() and thus the program will continue to run as we have set while conditional as (count < 3) i.e. 0 < 3 which is always true. So no chance of exiting the program by while conditional. The only chance to terminate the program is from default.
So if you give input anything other than 0, 1, 2 or 3, you will reach default which will call exit() and thus will cause the program to terminate.
Hello you can exit your program by including the header file #include in your header file section.
Then you can use the exit() command
Eg :-
#inlcude<process.h>
#include<studio.h>
into opt;
printf(" enter o ");
scant(" %d",&opt);
switch(opt)
case 0: printf(" exiting the program");
getch();
exit();

C programming do while with switch case program

I have been able to do switch case program but I want program to run again and again until a user selects to quit.
I basically wants program to run again and again using do while loop...
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
Use a do...while loop like this:
int I = 1; //Initialize to some non-zero number to prevent UB
printf("Enter 0 to quit \n");
do{
if (scanf("%d",&I) != 1) //If invalid data such as characters are inputted
{
scanf("%*[^\n]");
scanf("%*c"); //Clear the stdin
}
} while(I!=0); //Loop until `I` is not 0
This piece of code will loop until the user enters 0. You can change this code according to your needs. If you want your switch in this, copy your posted code after the scanf.
The loop will run until you enter -1 as input.
#include<stdio.h>
int main()
{
int I;
do
{
puts("Enter -1 to quit");
printf("Enter your choice: ");
scanf("%d",&I);
switch(I)
{
case 1:
printf("67\n");
break;
case 2:
printf("45\n");
break;
case -1:
puts("Bye");
break;
default:
printf("default\n");
}
}while(I != -1);
return 0;
}
this program runs untill user gives input 0 or a negative number...
#include<stdio.h>
int main()
{
int I;
do
{
scanf("%d",&I);
switch(I)
{
case 1:
printf("67");
break;
case 2:
printf("45");
break;
default:
printf("default");
}
}
while(I>0);
return 0;
}
Simple Use of Do-While Loop.
Choice is the variable in which user's choice will be stored, whether he wants to print the statement again or not.
int choice;
do{
printf("\nHello World!"); //This is the task of the program (Replace it with your task)
printf("\nDo You Want to Print it again ? 1 Yes/0 No: ");
scanf("%d",&choice);
}while(choice==1); //Loop will exit when choice gets value other than 1
// here switch will run until A is not equal to S
int N;
char A;
do{
cin>>N;
N = N%7;
cout<<endl;
cin>>A;
switch(N)
{
case 1: cout<<"Monday"<<endl; break;
case 2: cout<<"Tuesday"<<endl; break;
case 3: cout<<"Wednesday"<<endl; break;
case 4: cout<<"Thursday"<<endl; break;
case 5: cout<<"Friday"<<endl; break;
case 6: cout<<"Saturaday"<<endl; break;
case 0: cout<<"Sunday"<<endl; break;
default: cout<<"Invalid Input"; }}
while(A!='S');

While,switch, case statement

I'm using a while, switch, case statement for my menu and when it runs it keeps saying enter choice, I know while(1) creates an infinite loop but is there a way to avoid this?
while(1)
{
printf("\nEnter Choice \n");
scanf("%d",&i);
switch(i)
{
case 1:
{
printf("Enter value to add to beginning: ");
scanf("%c",&value);
begin(value);
display();
break;
}
case 2:
{
printf("Enter value to add last: ");
scanf("%c",&value);
end(value);
display();
break;
}
case 3:
{
printf("Value to enter before\n");
scanf("%c",&loc);
printf("Enter value to add before\n");
scanf("%c",&value);
before(value,loc);
display();
break;
}
case 4 :
{
display();
break;
}
}
}
Any help would be appreciated.
While(1) is ok. But you have to have some conditions to finish the loop. Like :
while(1){
.........
if(i == 0)
break;
............
}
Add a space at the beginning of every "%d" and "%c",because scanf always leaves a newline characters in buffer:
"%d"->" %d"
"%c"->" %c"
Alternative solution,
int i = !SOME_VALUE;
while(i != SOME_VALUE)
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
switch(i)
{
case SOME_VALUE: break;
.
.
.
// the rest of the switch cases
}
}
SOME_VALUE is any integer number notify to stop loop.
Alternatively, you may want to put a condition in the loop that relates to the input, e.g.
do
{
printf("\n\nEnter Choice ");
scanf("%d",&i);
// the rest of the switch is after this
} while (i != SOME_VALUE);
Note the use of the do loop, which tests the condition at the end, after a value has been read into i.
I would probably write a function that can be called in the loop:
while ((i = prompt_for("Enter choice")) != EOF)
{
switch (i)
{
case ...
}
}
And the prompt_for() function might be:
int prompt_for(const char *prompt)
{
int choice;
printf("%s: ", prompt);
if (scanf("%d", &choice) != 1)
return EOF;
// Other validation? Non-negative? Is zero allowed? Retries?
return choice;
}
You can also find relevant discussion at:
scanf() validation.
What is the reason for error while returning a structure in this C program?
Common macro to read input data and check its validity

Resources