Need to loop switch statement until 1 or 2 is entered - c

I need to loop the switch statement until 1 or 2 is entered as an input. Any help would be nice or sample code. I tried to use a while loop and it kept crashing. I tried a do while as well and it turned into an infinite loop so I must be doing something wrong.
int main (void)
{
int choice; // choice to run program from start menu or quit
while (1)
{
// Menu for entering resistor and capacitor values
printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
printf("Please enter two resistor values in between ");
printf("1 kOhms and 100 kOhms and a capacitor value\n\n");
//Start of menu
printf("Menu\n\n");
printf("1. Continue\n");
printf("2. Exit\n");
scanf("%d", &choice); // User inputs value
switch (choice)
{
case 1:
resistor(); // Program resistor is run if 1 is input
break;
case 2:
printf("Goodbye."); // Program ends if 2 is input
break; // break is used to exit while loop
default:
printf("Sorry I do not understand\n\n");
fflush(stdin); /* clears input buffer to allow user to input a new value if anything other
than 1 or 2 is input into scanf */
}
break;
}
return 0;
}

The problem is that you have a "break" right at the end of your "while", so it's only executed once.
It has been a long time since I did program in C, but if I remember correctly you should avoid using "fflush()" since it has an undefined behavior. Instead, you can change your "scanf()" to be something like:
scanf(" %d", &choice); // User inputs value
That way, you have the same supposed effect of the "fflush()" at the same time of having a cleaner code.

You can use this code
for(;;) {
// Menu for entering resistor and capacitor values
// Start of menu
// User inputs value
if(choice == 1) { ... break; }
else if(choice == 2) { ... return 0; } // If you use the break,the for loop will be stopped or You can use return 0; to return the whole function
else { ... break; }
}
or, also you can use this code
for(;;) {
switch(choice ) {
case 1: ... break;
case 2: ... return 0; // If you use the break, only switch statement is stopped. You can use return 0; to return the whole function
default: ... break;
}
}
Edit :
#include <stdio.h>
int main (void)
{
int choice; // choice to run program from start menu or quit
// Menu for entering resistor and capacitor values
printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
printf("Please enter two resistor values in between ");
printf("1 kOhms and 100 kOhms and a capacitor value\n\n");
while (1)
{
//Start of menu
printf("Menu\n");
printf("1. Continue\n");
printf("2. Exit\n");
scanf("%d", &choice); // User inputs value
switch (choice)
{
case 1: // Program resistor is run if 1 is input
break;
case 2: printf("Goodbye."); // Program ends if 2 is input
return 0; // return 0; is used to exit while loop
default: printf("Sorry I do not understand\nStart Again !\n");
// fflush(stdin); /* clears input buffer to allow user to input a new value if anything other than 1 or 2 is input into scanf */
break;
}
printf("\n");
}
return 0;
}

Related

C Program crashing when character is entered into menu option

Hi this program keeps crashing when I enter a character into the menu. I have figured out it is because scanf is looking for an integer and cannot find one so it goes into an infinite loop. I have yet to find how to correct this anywhere online and am looking for some much needed help. I cant seem to create a function to do input validation and that is where I need help as our professor does not seem to help us with these. Thank you.
#include <stdio.h>
void resistor (void);
float calc_freq(float ra, float rb, float c) // function to calculate Frequency
{
return 1.44/((ra+(2*rb))*c);
}
float calc_duty_cycle(float ra, float rb, float c) // function to calculate duty cycle
{
return (rb)/(ra+(2*ra));
}
int main (void)
{
int choice; // choice to run program from start menu or quit
while (1)
{
// Menu for entering resistor and capacitor values
printf("Welcome to the 555 Timer Frequency and Duty Cycle Calculator\n");
printf("Please enter two resistor values in between ");
printf("1 kOhms and 100 kOhms and a capacitor value\n\n");
printf("Menu\n\n");
printf("1. Continue\n");
printf("2. Exit\n");
scanf("%d", choice);
switch (choice)
{
case 1: resistor();
break;
case 2 : printf("Goodbye.");
break;
default: printf("Sorry I do not understand\n\n");
main();
}
break;
}
return 0;
}
void resistor (void)
{
float ra, rb, c; // Float variables for two resistor values and capacitor
while(1) // While loop to gather resistor A value
{
printf("Enter a value for Resistor Ra (kOhms): "); // First Resistor Value
scanf("%f", &ra);
if(ra < 1 || ra > 100) // Will repeat loop until value between 1 and 100 is entered
printf("Invalid selection, choose again.\n");
else
break; // breaks loop when valid data is entered
}
while(1)
{
printf("Enter a value for Resistor Rb (kOhms): "); // Second Resistor Value
scanf("%f", &rb);
if(rb < 1 || rb > 100) // Will repeat loop until value between 1 and 100 is entered
printf("Invalid selection, choose again.\n");
else
break; // breaks loop when valid data is entered
}
while(1)
{
printf("\nCapacitor (uF) : "); // Capacitor Value
scanf("%f", &c);
if(c <= 0)
printf("Invalid selection, choose again.\n");
else
{
float freq = calc_freq(ra, rb, c); // call function to calculate frequency
float duty_cycle = calc_duty_cycle(ra, rb, c); // cal function to calculate duty cycle
printf("\nFrequency is: %.2f kHz\n", freq); // print frequency
printf("Duty cycle is: %.2f percent\n", duty_cycle*100); // print duty cycle
break; // break while loop
}
}
}

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;

Logic Error in C Program on xcode

I have written this code for a grocery store.. This code makes perfect sense to me. However, I keep getting a logic error. Every time the user enters a bill and then presses -1 to exit, he is taken back to the main menu. When user presses choice 2 to EXIT program, the program is NOT exiting and he taken back to case 1 for some reason. Could you please help me? Thank you!
#include <stdio.h>
int main(void){
double prices[7];
prices[0]=2.55;
prices[1]=12.07;
prices[2]=2.00;
prices[3]=0.55;
prices[4]=5.35;
prices[5]=8.65;
prices[6]=2.55;
int choice;
int productCode;
int quantity;
char stop[3];
int compare;
double price;
double totalPrice=0;
do{
printf("\n1. Create new bill");
printf("\n2. EXIT");
printf("\n\nEnter choice: ");
choice=scanf("%d", &choice);
switch(choice){
case 1:{
do{
printf("\nEnter product code: ");
scanf("%d",&productCode);
printf("\nEnter quantity of product: ");
scanf("%d",&quantity);
price=prices[productCode]*quantity;
totalPrice=totalPrice+price;
printf("\nTo stop entering products enter -1.. to continue press any other character ");
scanf("%s", &stop);
compare=strcmp(stop, "-1");
}while(compare!=0);
break;
}
case 2: break;
default: printf("\nInvalid choice");
}
}while(choice!=2);
getchar();
return 0;
}
Instead of
choice=scanf("%d", &choice);
Do
scanf("%d", &choice);
scanf return value is:
On success, the function returns the number of items of the argument
list successfully filled. This count can match the expected number of
items or be less (even zero) due to a matching failure, a reading
error, or the reach of the end-of-file.
If a reading error happens or the end-of-file is reached while
reading, the proper indicator is set (feof or ferror). And, if either
happens before any data could be successfully read, EOF is returned.
If an encoding error happens interpreting wide characters, the
function sets errno to EILSEQ.
http://www.cplusplus.com/reference/cstdio/scanf/
for (;;){
printf("\n1. Create new bill");
printf("\n2. EXIT");
printf("\n\nEnter choice: ");
scanf("%d", &choice);
if(choice == 2 ){
break;
} else if(choice == 1){
do{
printf("\nEnter product code: ");
scanf("%d",&productCode);
printf("\nEnter quantity of product: ");
scanf("%d",&quantity);
price=prices[productCode]*quantity;
totalPrice=totalPrice+price;
printf("\nTo stop entering products enter -1.. to continue press any other character ");
scanf("%s", &stop);
compare=strcmp(stop, "-1");
}while(compare!=0);
} else {
printf("\nInvalid choice");
}
}

Returning values from a function using a switch statement to call the fnctions

My question is i have been asked to write a menu driven program that will ask the user to 1. enter a 4 digit code 2. Encrypt the code and verify against a set 4 digit code. 3. Exit the program. The program should loop back to the start menu after the user is done with their selected option apart from when they choose to exit. i.e the user will enter their code and return to the menu before encrypting and verifying the code entered against a set 4 digit code.
My code below does not loop back to the menu nor does it run correctly when i choose option 1 it asks me to enter the 4 digit code twice. I have tried tiredlessy to fix this but to no avail. Any help you can give me would be great.
#include <stdio.h>
#include <stdlib.h>
#define CODE 4
//prototypes
int enter_code (int* code_arr);
int encrypt_code (int* pass_code, int* user_code);
int main(void)
{
//declare variables
int password[CODE] = {0};
int passOK[CODE] = {4,5,2,3};
int option;
int exit1;
int code;
//do while loop
do
{
//print the menu on screen
printf("\t \t \t \t Pearse Security \n \n");
printf("\t \t \t1 - Enter the access code\n");
printf("\t \t \t2 - Enter the encrypt code and verify\n");
printf("\t \t \t3 - Exit the program \n");
//scan for user input
scanf("%d",& option);
switch(option)
{
case 1:
{
code =enter_code(password);
break;
}
case 2:
{
if (encrypt_code(passOK, password))
printf("You unlocked the vault\n");
break;
}
case 3:
{
// prompt user to a key to exit
printf("\n You choose to exit the program.\n Press a key to exit\n ");
getchar();
exit(0);
break;
}
default:
{
printf("You must enter a number between 1-5\n");
}
} // end switch()
if (!enter_code(password))
{
printf ("Bad password entry\n");
}
else
{
if (encrypt_code(passOK, password))
{
printf("You unlocked the vault\n");
}
else
printf("You don't know the passcode\n");
}
return 0;
}//end do
while(exit1!=4 & exit1 <5);
}//end main()
//enter code function()
int enter_code (int* code_arr)
{
//declare variables for enter_code()
int i;
//prompt user to enter the 4 digit code
printf("Enter your 4 digit code\n");
for(i=0;i<CODE;i++)
{
if (scanf("%d", &code_arr[i]) != 1)
{
return 0;
}//end if()
}//end for()
return 1;
}//end enter_code()
//encrypt code and verify function
int encrypt_code (int* pass_code, int* user_code)
{
//variables for encrypt_code()
int i;
for(i=0;i<CODE;i++)
{
if (pass_code[i] != user_code[i])
{
return 0;
}//end if()
}//end for()
return 1;
}//end encrypt_code()
The output of this program is
Enter 4 digits
4
5
2
3
Enter 4 digits
4
5
2
3
You have unlocked the vault
And the program ends
Why does it ask me to enter the code twice and why does it not loop back to the menu.
I received two compiler warnings about this line
while(exit1!=4 & exit1 <5);
Firstly it should be
while(exit1!=4 && exit1 <5);
It is also undefined behaviour since exit1 has never been assigned a value.
I suggest you replace the line with
while(1);
since case 3: contains an exit().
Next, you say that enter_code() is being called twice. The reason is because it is being called twice: once within case 1: and again outside the switch() code block.
Here is the amended main() in which I deleted the surplus stuff below the switch() block and added a failure message to case 2:
int main(void)
{
int password[CODE] = {0};
int passOK[CODE] = {4,5,2,3};
int option;
int code;
do
{
printf("\t \t \t \t Pearse Security \n \n");
printf("\t \t \t1 - Enter the access code\n");
printf("\t \t \t2 - Enter the encrypt code and verify\n");
printf("\t \t \t3 - Exit the program \n");
scanf("%d",& option);
switch(option)
{
case 1: {
code =enter_code(password);
break;
}
case 2: {
if (encrypt_code(passOK, password))
printf("You unlocked the vault\n");
else
printf("You don't know the passcode\n");
break;
}
case 3:{
// prompt user to a key to exit
printf("\n You choose to exit the program.\n Press a key to exit\n ");
getchar();
exit(0);
break;
}
default: {
printf("You must enter a number between 1-5\n");
}
}
} while(1);
return 0;
}

Resources