Terminate program in C - 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();

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

Problem when going back to main menu - C programming

When this program is executed and case 1 is chosen, a submenu will be displayed. In this submenu there is an option to go back to the main menu, now this isn't displaying properly when chosen as it seems to be displaying the main menu twice as well as the default. This is the code:
#include <stdio.h>
#include "functions.h" //calls the functions.h file
int switch1();
int switch2();
int main() {
//Declaring variable
char command;
do {
do {
printf(SPLIT);
printf("\nEnter choice to operate one of the following functions.\n");
printf("1 - Operate using integer representation\n");
printf("2 - Operate using textual representation\n");
printf("0 - Quit\n");
printf("Choice:");
scanf("%c", &command);
switch (command) {
case '1':
switch1(); //Executes function switch1
break;
case '2':
switch2(); //Executes function switch2
break;
case '0':
printf(SPLIT);
printf("\nQuitting.");
printf(SPLIT);
return 0; //Program stops
default: //Switch statement reaches default if no other cases are reached
printf("\nIncorrect input, please re-try.\nEnter choice\n");
break;
}
} while(command != '0');
} while (command < '0' || command > '2');
return 0;
}
int switch1() {
//Declaring variables
char command;
int *array, *iZeroed = NULL;
printf(SPLIT);
printf("\nInteger representation will be used!\n");
array = generate(); //Executes function generate and sets the return to be array
do {
do {
printf("\nChoose an option:\n");
printf("1) Shuffle the array\n");
printf("2) Sort the array\n");
printf("3) Zero an element from the array\n");
printf("4) Display previous zeroed out element\n");
printf("0) Go back to main menu\n");
printf("Choice:");
scanf(" %c", &command);
switch (command) {
case '1':
array = shuffle(array); //Executes function shuffle and sets the return to be the new array
break;
case '2':
array = sort(array); //Executes function shuffle and sets the return to be the new array
break;
case '3':
iZeroed = shoot(array); //Executes function shoot and sets the return to be the element changed to 0
break;
case '4':
target(iZeroed); //Executes function target
break;
case '0':
return 0;
default: //Switch statement reaches default if no other cases are reached
printf(SPLIT);
printf("\nIncorrect input. Please re-enter an option\n");
break;
}
} while (command != '0');
} while (command < '0' || command > '1');
return 0;
}
This is the output I am getting when I choose to go back to main menu:
====================================================================
Choose an option:
1) Shuffle the array
2) Sort the array
3) Zero an element from the array
4) Display previous zeroed out element
0) Go back to main menu
Choice:0
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:
Incorrect input, please re-try.
Enter choice
====================================================================
Enter choice to operate one of the following functions.
1 - Operate using integer representation
2 - Operate using textual representation
0 - Quit
Choice:
Place a space character int the format string for scanf() before the input specifier %c, and it means scanf() should drop whitespace characters there.
You are already doing so in your switch1() function, so you should also do so in your main() function.
printf("Choice:");
scanf("%c", &command);
Make it " %c"

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;

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