C programming do while with switch case program - c

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');

Related

How can I create loop for queue?

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

Why is there an infinite loop when I do not enter a number?

When I enter the letter 'q' as grade, it runs infinitely.
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int grade;
bool flag = true;
while (flag) {
puts("-----------------------------"); // comment
printf("What's your grade out of 10? ");
scanf(" %d", &grade);
switch (grade) {
case 10:
case 9:
case 8:
case 7:
case 6:
printf("Pass\n");
break;
case 5:
printf("Fail\n");
break;
case 4:
printf("Fail\n");
break;
case 3:
printf("Fail\n");
break;
case 2:
printf("Fail\n");
break;
case 1:
printf("Fail\n");
break;
case 0:
printf("Fail\n");
break;
default:
printf("Illegal Grade\n");
flag = false;
break;
}
}
return 0;
}
scanf(" %d",&grade);
It scans int in string. "q" is not int. When you enter "q", value of the variable grade left unchanged. You must check returned value of scanf to validate number of filled placeholders.
if (scanf(" %d",&grade) != 1) {
printf("Illegal Grade\n");
exit(1); // or break
}
Other parts are ok.
scanf(" %d", &grade); fails when you type something that cannot be parsed as into an integer. grade is not modified, so it is uninitialized if the conversion error happens immediately and the behavior is undefined, otherwise you get the same value and behavior as the previous time.
The offending input stays in the input stream, so the same thing happens when the code executes again in the while loop, hence the infinite loop.
You want to test if the conversion was successful and discard the input if not:
#include <stdio.h>
#include <stdbool.h>
int main(void) {
int res, c, grade;
bool flag = true;
while (flag) {
puts("-----------------------------"); // comment
printf("What's your grade out of 10? ");
res = scanf("%d", &grade);
if (res == EOF)
break;
if (res == 0) {
printf("Invalid input\n");
/* discard the offending line of input */
while ((c = getchar()) != EOF && c != '\n')
continue;
/* try again */
continue;
}
switch (grade) {
case 10:
case 9:
case 8:
case 7:
case 6:
printf("Pass\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Fail\n");
break;
default:
printf("Illegal Grade\n");
flag = false;
break;
}
}
return 0;
}

Why will my program not flag characters?

I'm making this program using switch statements that will assign letter grades based on if the user enters numbers 0 - 10. If the user enters a number that is not 0-10, the program outputs an error message and has the user re-enter. However, if the user enters a character the program will loop at the default case. I want it to output the error message from the default case once, and have them re-enter if they enter a character. I'm not sure as to why it loops the default case when a character is entered though.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
}
}
return 0;
}
Try something like:
#include <stdio.h>
int main()
{
int grade;
int r=0;
while(r != 1)
{
scanf("%i", &grade);
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
r=1
break;
case 8:
printf("Your grade is a B\n");
r=1
break;
case 7:
printf("Your grade is a C\n");
r=1
break;
case 6:
printf("Your grade is a D\n");
r=1
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
r=1
break;
default:
printf("Invalid score, please re-enter\n");
break;
}
}
return 0;
}
This will clear the input buffer on an invalid input and allow a retry.
#include <stdio.h>
int main()
{
int grade;
int r;
while((r = scanf("%i", &grade)) != EOF)
{
if ( r != 1) {//r == 1 is successful input of integer
grade = -1;//reset grade on invalid input
}
switch(grade)
{
case 10:
case 9:
printf("Your grade is an A\n");
break;
case 8:
printf("Your grade is a B\n");
break;
case 7:
printf("Your grade is a C\n");
break;
case 6:
printf("Your grade is a D\n");
break;
case 5:
case 4:
case 3:
case 2:
case 1:
case 0:
printf("Your grade is an F\n");
break;
default:
printf("Invalid score, please re-enter\n");
while ( getchar() != '\n');//clear input buffer
}
}
return 0;
}
The reason your code always loops is because there is no way to exit out of your while other than to kill the program. Remember that break only breaks out of the inner-most switch or loop.
The cleanest way to break out of multiple levels is to use a flag. One way to do what you want is like this:
bool valid_grade = false;
while(!valid_grade && (r = scanf("%i", &grade)) != EOF)
{
valid_grade = true;
switch(grade)
{
case 10:
// unchanged from your code
default:
valid_grade = false;
printf("Invalid score, please re-enter\n");
}
}

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();

Removing contents of variable in C

I want to delete the contents of an int variable when it gets to an else statement.
The program requests a number between 1 and 5 using scanf and the number is stored in the int variable and if the number isn't between 1 and 5 then the user is directed to an else statement and I have used a goto statement to take it back to the start and I was wondering how I removed the contents of the variable during the else statement so I don't create a continuos loop.
With getchar it's fpurge(stdin). I'm running Mac OS X.
BELOW IS THE CODE:
#include <stdio.h>
int main (int argc, const char * argv[])
{
int code;
start:
puts("Please type your error code.");
puts("Range 1-5: ");
scanf("%d", &code);
switch(code)
{
case 1:
printf("INFORMATION\n");
case 2:
printf("INFORMATION\n");
case 3:
printf("INFORMATION\n");
case 4:
printf("INFORMATION\n");
case 5:
printf("INFORMATION\n");
default:
printf("INFORMATION\n");
goto start;
}
}
Just set the int value to something else, eg:
theValue = 0;
You are probably looking for a do...while loop
Edit Don't forget your break statements!!
do
{
puts("Please type your error code.");
puts("Range 1-5: ");
scanf("%d", &code);
switch(code)
{
case 1:
printf("INFORMATION\n");
break;
case 2:
printf("INFORMATION\n");
break;
case 3:
printf("INFORMATION\n");
break;
case 4:
printf("INFORMATION\n");
break;
case 5:
printf("INFORMATION\n");
break;
default:
printf("INVALID CODE\n");break;
}
} while(code<1 || code> 5);

Resources