How to stop a while loop in C - c

In this code, the computer asks the user what he wants to purchase between 1-7 options. And if the user presses the wrong option up to 3 times -> computer will print this message: "Do you want to leave or make a purchase? Press y(for leave) or n(for stay)". I know another way how to do this, but how can I stop the while loop and print a message?
!!!This is incorrect code(has mistakes), used for example!!!
#include <stdio.h>
int DisplayMenu();
double OrderPrice(int itemNumber);
int main
{
char process = 'y';
int mainOption;
while (process == 'y' || process == 'Y')
{
optionMain = DisplayMenu();
printf("\nYour choice was %d", optionMain);
};
return 0;
}
int DisplayMenu()
{
int option, optionCount;
printf("1 - ..., 2 - ..., 3 - ..., 4 - ..., 5 - ..., 6 - ..., 7 - ...");
scanf("%d", &option);
while (option > 7 || option < 1) {
printf("Make your chose between 1-7:");
scanf(" %d", &option);
optionCount++;
if (optionCount == 2) {
printf("Do you want to leave or make a purchase? Press y(for leave) or n(for stay)");
}
};
return option;
return 0;
}
double OrderPrice(int itemNumber)
{
double price;
switch (itemNumber) {
case 1 :
printf("\nSelection 1.");
price = 1.1;
break;
case 2 :
printf("\nSelection 2.");
price = 2.2;
break;
case 3 :
printf("\nSelection 3.");
price = 3.3;
break;
case 4 :
printf("\nSelection 4.");
price = 4.4;
break;
case 5 :
printf("\nSelection 5.");
price = 5.5;
break;
case 6 :
printf("\nSelection 6");
price = 6.6;
break;
case 7 :
printf("\nSelection 7.");
price = 7.7;
break;
// default:
// printf("Incorrect selection");
// price = 0.00;
}
return price;
}

was solved by #tadman: You need to get input at that point, test it, and if it's a stop request, break
optionCount++;
if (optionCount == 2) {
break;
}

Related

C Program are closing automatically

I created a C Program that will take all the order of the user then generate the grandtotal of the orders.
But when I will order another food, the program is closing automatically.
I don't know if this is about my getch or the breaks in my switch method. Sometimes, it will proceed to take another error but it automatically outputs "INVALID FOOD".
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void menu();
void foods();
void main();
char food;
int quantity;
float price;
float total;
float grandtotal;
int choice;
void main()
{
clrscr();
menu();
foods();
getch();
}
void menu(){
food = ' ';
quantity = 0;
price = 0;
total = 0;
choice = 0;
printf("Please select food from the following:\n");
printf(" B = Burger, F = French Fries, P = Pizza, S = Sandwiches \n");
printf("Enter food:");
scanf("%c", &food);
}
void foods(){
switch(food)
{
case 'B':
printf("You selected Burger!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 95.50;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
menu();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
case 'F':
printf("You selected French Fries!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 47.75;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
menu();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
case 'P':
printf("You selected French Pizza!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 105.00;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
menu();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
case 'S':
printf("You selected Sandwiches\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 75.50;
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
total = price*quantity;
if(choice == 1){
main();
break;
}
else if (choice == 2){
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
break;
}
default:
printf("INVALID FOOD!");
break;
}
}
I wish someone could help or guide me. Thanks in advance.
In you code you have duplicated multiple times:
...
if(choice == 1){
menu();
break;
} ...
...
So when you choose choice = 1 then menu() get's displayed, and then the code breaks out of foods(). I think you meant to do the foods section again:
...
if(choice == 1){
menu();
foods();
break;
} ...
...
Yet another problem in your code is the %c scanf modifier. It will not eat up leading whitespaces, so it will read a newline (inputted on the last scanf). Use a leading space " %c" to tell scanf to read up leading whitespaces and ignore the leading newline, in scanf(" %c", &food);
Indent your code.
Don't duplicate statements. The whole scanf(... &choice); if (choice == 1) ... else if (choice == 2) could be placed outside the while switch not beeing duplicated 4 times.
Nesting functions using recursive calls can make your stack run out. Better just use a while loop.
Try not to use global variables. They are misleading and lead to maintainable code.
A slightly modified version of you code with a bit of indententation, added a do ... while loop and removed global variables and code duplication, may look like this:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
char menu(void);
float foods(char food);
void main()
{
clrscr();
float grandtotal = 0;
int choice = 0;
do {
// print menu and choose the food
char food = menu();
// choose food quantity and get it's price
float total = foods(food);
// print the total price
grandtotal = grandtotal + total;
printf("\n Total Price is: %0.2f", grandtotal);
// do you want to continue?
printf("\n Do you want to order more? [1] Yes [2] No:");
if (scanf("%d", &choice) != 1) {
perror("scanf error");
abort();
}
// continue until choice is equal to 1
} while (choice != 1);
}
char menu(void)
{
char food;
printf("Please select food from the following:\n");
printf(" B = Burger, F = French Fries, P = Pizza, S = Sandwiches \n");
printf("Enter food:");
if (scanf(" %c", &food) != 1) {
perror("scanf error");
abort();
}
return food;
}
float foods(char food){
float price = 0;
switch (food) {
case 'B':
printf("You selected Burger!\n");
price = 95.50;
break;
case 'F':
printf("You selected French Fries!\n");
price = 47.75;
break;
case 'P':
printf("You selected French Pizza!\n");
price = 105.00;
break;
case 'S':
printf("You selected Sandwiches\n");
price = 75.50;
break;
default:
fprintf(stderr, "INVALID FOOD!\n");
abort();
}
printf("Enter quantity:");
int quantity;
if (scanf("%d", &quantity) != 1) {
perror("scanf error");
abort();
}
return (float)price * (float)quantity;
}
When you call menu after user input is [1] yes. with menu() function show menu and after menu you should show call food() function.
HERE WHAT YOU WANT
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
void menu();
void foods();
void main();
char food;
int quantity;
float price;
float total;
float grandtotal;
int choice;
void main()
{
clrscr();
do {
menu();
foods();
printf("\n Do you want to order more? [1] Yes [2] No:");
scanf("%d", &choice);
getchar(); // <== remove newline
grandtotal = grandtotal + total;
} while (choice == 1);
printf("\n Total Price is: %0.2f", grandtotal);
getch();
}
void menu() {
food = ' ';
quantity = 0;
price = 0;
total = 0;
choice = 0;
printf("Please select food from the following:\n");
printf(" B = Burger, F = French Fries, P = Pizza, S = Sandwiches \n");
printf("Enter food:");
scanf("%c", &food);
}
void foods() {
switch (food)
{
case 'B':
printf("You selected Burger!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 95.50;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
//getchar(); // <== remove newline
total = price*quantity;
break;
//if (choice == 1) {
// menu();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
case 'F':
printf("You selected French Fries!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 47.75;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
total = price*quantity;
break;
//if (choice == 1) {
// menu();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
case 'P':
printf("You selected French Pizza!\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 105.00;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
total = price*quantity;
break;
//if (choice == 1) {
// menu();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
case 'S':
printf("You selected Sandwiches\n");
printf("Enter quantity:");
scanf("%d", &quantity);
price = 75.50;
//printf("\n Do you want to order more? [1] Yes [2] No:");
//scanf("%d", &choice);
total = price*quantity;
break;
//if (choice == 1) {
// main();
// break;
//}
//else if (choice == 2) {
// grandtotal = grandtotal + total;
// printf("\n Total Price is: %0.2f", grandtotal);
// break;
//}
default:
printf("INVALID FOOD!");
break;
}
}

Switch case menu isn't being executed and reads only the default case

I'm fairly new to the C language. Here my question is that the switch case in the function getDiscount(int ch, float total) only reads the default case and execute the code. I can't identify any errors as it runs correctly, but is generating a wrong answer. Here's my complete code. Does my scanf statements take their ASCII values and execute? I just have no idea.
#include<stdio.h>
float getTotalPrice(char type, int qty);
float getDiscount(char mode, float total);
void getGift(float total);
int main(void)
{
int quantity;
float total;
char garment, method;
printf("\nAvailable Garment Types:\n");
printf("Garment Type\tPrice\\u\n");
printf("T-Shirt - 't'\tRs. 1500.00\n");
printf("Frock - 'f'\tRs.3500.00\n");
printf("Skirts - 's'\tRs.2000.00\n");
printf("\nEnter Your Choice: ");
scanf("%c", &garment);
printf("Enter the quantity: ");
scanf("%d", &quantity);
printf("\nAvailable payment methods are:\n");
printf("Cash - 'c'\nCredit Card - 'd'\nOther - 'o'\n");
printf("\nEnter Your Payment Method: ");
scanf("%c", &method);
total = getTotalPrice(garment,quantity);
total = getDiscount(method,total);
getGift(total);
return 0;
}
float getTotalPrice(char type, int qty)
{
float total=0;
switch(type)
{
case 't':
case 'T':
total = 1500*qty;
break;
case 'f':
case 'F':
total = 3500*qty;
break;
case 's':
case 'S':
total = 2000*qty;
break;
default:
printf("\nError: Enter a valid choice\n");
break;
}
return total;
}
float getDiscount(char mode, float total)
{
switch(mode)
{
case 'c':
case 'C':
total = (total - (total*15/100));
break;
case 'd':
case 'D':
total = (total - (total*10/100));
break;
case 'o':
case 'O':
total = (total - (total*5/100));
break;
default:
printf("\nError: Enter a valid payment method\n");
break;
}
return total;
}
void getGift(float total)
{
float gift;
if(total >= 10000)
{
gift = 3000;
}
else if((total >= 5000)&&(total <= 9999))
{
gift = 2000;
}
else if((total < 4999)&&(total > 1))
{
gift = 1000;
}
else
{
printf("\nError: Invalid inputs\n");
}
printf("\nTotal Price = Rs. %.f\n", total);
printf("\nYour gift voucher value = Rs. %.f\n", gift);
}
add whitespace in your scanf here scanf("%c", &method); so it will become scanf(" %c", &method);
why is this happeneing? you always enter the getdiscount function with the enter of the previous scanf() and that's ruining your input, the whitespace before the %c will ignore that enter and thus let you choose the correct char - c, d,d or o

Switch statement executes case 2 even after break

When case 1, the program executes the code intended but then when it asks you if you want to calculate volume again if you pick yes it just executes case 2. I'm not sure what's wrong. How can I get it to only execute case 1 unless the you pick 2 in the menu?
#include <stdio.h>
#include <stdlib.h>
int main()
{
float menu1, opt1, opt2, opt3, opt4, t;
int td;
printf("Enter: ");
scanf("%d",&td);
switch(td) {
case 1:
printf("Enter a, b, c, and h of the triangular prism in meters\n\n");
printf("a ");
scanf("%f", &opt1);
printf("b ");
scanf("%f", &opt2);
printf("c ");
scanf("%f", &opt3);
printf("h ");
scanf("%f", &opt4);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}
case 2:
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
scanf("%f", &opt1);
printf("h ");
scanf("%f", &opt2);
printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if (menu1 == 2) {
t = 0;
break;
}
if (menu1 < 1 || menu1 > 2) {
printf("\n\nUser choice must be between 1 and 2!\n\n");
printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
scanf("%f", &menu1);
if(menu1 == 2) {
t = 0;
break;
}
}
}
}
Your break statements [for case 1:] are only inside if blocks. If neither if is true, you get the fall through.
Here is your original:
case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
// BUG: there should be a break here
case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...
Here is the fixed code:
case 1:
// ...
if (menu1 < 1 || (menu1 > 2) {
// ...
if (menu1 == 2) {
t = 0;
break;
}
}
break; // FIX: this is your _missing_ break statement
case 2:
// ...
printf("Enter a and h of the triangular pyramid\n\n");
printf("a ");
// ...

Having troubles with nested while loops

The goal is to assign the average to different players based on their uniform number. The problem is that it keeps skipping the second printf and the characters from the switch statement aren't working. I'm sure it's a pretty simple error on my part, but I just can't seem to find it.
int main(){
float ab;
float hits;
int un;
char pa;
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
while( un!= -1)
{
printf("Please enter either an H for a hit or an O for a out, enter E to stop. \n");
scanf("%c%*c", &pa);
while(pa != 'E')
{
switch (pa)
{
case 'h':
case 'H':
ab += 1;
hits +=1;
break;
case 'o':
case 'O':
ab+=1;
break;
default:
printf("Error: Please insert an O or H \n");
break;
}
float average = (ab/hits);
printf("Player %d's score is equal to: %d \n", un, average);
printf("Please enter the player number, or -1 to exit. \n");
scanf("%d%*c \n", &un);
}
}
return 0;
}
Your loop nesting wasn't quite correct, your scanf calls would hang, you needed to preinitialize ab and hits, and your final printf had an incorrect format.
Here's the corrected code [please pardon the gratuitous style cleanup]:
#include <stdio.h>
int
main()
{
float ab;
float hits;
int un;
char pa;
while (1) {
printf("Please enter the player number, or -1 to exit.\n");
#if 0
scanf("%d%*c \n", &un);
#else
scanf(" %d", &un);
#endif
if (un == -1)
break;
ab = 0;
hits = 0;
printf("Please enter either an H for a hit or an O for a out, enter E to stop.\n");
while (1) {
#if 0
scanf("%c%*c", &pa);
#else
scanf(" %c", &pa);
#endif
if ((pa == 'E') || (pa == 'e'))
break;
switch (pa) {
case 'h':
case 'H':
ab += 1;
hits += 1;
break;
case 'o':
case 'O':
ab += 1;
break;
default:
printf("Error: Please insert an O or H\n");
break;
}
}
float average = (ab / hits);
#if 0
printf("Player %d's score is equal to: %d\n", un, average);
#else
printf("Player %d's score is equal to: %g\n", un, average);
#endif
}
return 0;
}

Remove an element from a vector in C

How can I remove an element from a vector in C without changing my print_vector function?
1) Here's the code that I made for removing an element on a position given from the keybord:
void remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if(nr>a)
{
printf("The remove is impossible!\n");
}
else
{
for(c=nr;c<=a;c++)
{
chelt[c]=chelt[c+1];
}
}
}
2)This is the print function
void print_costs(int a)
{
int i;
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nCost %d\n\n",i);
printf("Day: %s\n", chelt[i].day);
printf("Sum: %d\n", chelt[i].sum);
printf("Type: %s\n", chelt[i].type);
}
}
}
3) Here's the add_new_cost() function
int add_new_cost()
{
int a,i;
printf("Nr of costs = ");
scanf("%d", &a);
if(a>0 && a<=n)
{
for(i=1;i<=a;i++)
{
printf("\nType the attributes for cost %d",i);
printf("\nDay = ");
scanf("%s",chelt[i].day);
printf("Sum = ");
scanf("%d", &chelt[i].sum);
printf("Type = ");
scanf("%s",chelt[i].type);
}
}
return a;
}
4) This is the main function
int main()
{
setbuf(stdout,NULL);
int b,choice;
do
{
printf("\nMenu\n\n");
printf("1 - Add a cost\n");
printf("2 - Print a cost\n");
printf("3 - Update a cost\n");
printf("4 - Delete a cost\n");
printf("5 - Exit\n\n");
printf("Command = ");
scanf("%d",&choice);
switch (choice)
{
case 1: b=add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: remove_a_cost(b);
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}
} while (choice != 0);
return 0;
}
Example:
If I have 4 elements on the vector:
1)Type the attributes for cost
Day = luni
Sum = 2
Type = dsasa
Type the attributes for cost 2
Day = marti
Sum = 23
Type = adsds
Type the attributes for cost 3
Day = miercuri
Sum = 23
Type = asd
Type the attributes for cost 4
Day = joi
Sum = 232
Type = asdas
and I try to delete, let's say the 3rd element, this is what I receive when I print:
Cost 1
Day: luni
Sum: 20
Type: maradf
Cost 2
Day: marti
Sum: 23
Type: afas
Cost 3
Day: joi
Sum: 45
Type: sdfadsf
Cost 4
Day:
Sum: 0
Type:
The element(COST 4) appears when it should've been deleted. Is there a solution for deleting the element WITHOUT changing the print function?
After updating of question, everything is clear, do these modifications:
int remove_a_cost(int a)
{
int nr, c;
printf("Give the number of cost for remove: ");
scanf("%d", &nr);
if (nr > a)
{
printf("The remove is impossible!\n");
}
else
{
for (c = nr; c <= a; c++)
{
chelt[c] = chelt[c + 1];
}
a--; // decrease a
}
return a; // return new size
}
And
switch (choice)
{
case 1: b = add_new_cost();
break;
case 2: print_costs(b);
break;
case 3: update_cost(b);
break;
case 4: b = remove_a_cost(b); // <- store returned value in b
break;
case 0: printf("Goodbye\n");
break;
default: printf("Wrong Choice. Enter again\n");
break;
}
Your code is a bit messy. You should try to give meaningful names to your variables.
But, for what I understand, the print_costs function receives the value of the last 'cost' that it should print.
Perhaps you're passing it the wrong value after you remove a 'cost'.

Resources