I'm writing my first C program and there's not a single way I can figure out how I can reduce the size of my if statements, for some reason I think that its a little too long. I have tried reducing the lines of code, playing with it but when I change something some messages when I test it don't appear such as Purchase was successful or it failed. I know that this is a little of a beginner question. Could you help me out and if possible give any tips on what to use and research to make it more concise?
if (input == 'A') {
calculation = budget - apple;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", apple);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
} else if (input == 'O') {
calculation = budget - orange;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", orange);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
} else if (input == 'P') {
calculation = budget - pear;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", pear);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
} else {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
};
Create a temporary variable (e.g. fruits), and use input to determine what it should be set to, using an otherwise impossible value for "invalid item", like:
if (input == 'A') {
fruits = apple;
} else if (input == 'O')
fruits = orange;
} else if (input == 'P') {
fruits = pear;
} else {
fruits = -1; // Invalid item
}
Once that's done the rest can become:
if(fruits != -1) {
calculation = budget - fruit;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", input);
printf("Price: \x9C%.2f\n", fruits);
printf("Remaining budget: \x9C%.2f\n\n", calculation);
printf("Thanks for shopping with us!");
} else {
fruits = -1; // Low budget or invalid item!
}
}
if(fruits == -1) {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
Expanding upon the concepts of the posted solution, one might consider that "insufficient funds" and "item does not exist" to require different messages. It is also possible to determine based on the chosen fruit, if the user has the funds needed, or if the user indeed has insufficient funds to purchase ANY fruit at all.
To allow for additional fruit items, we can use arrays:
#include <stdio.h>
#define MAXLINE 80
#define WALLET 10.00
typedef struct {
int id;
double cost;
} Product;
int main() {
char buffer[MAXLINE];
double balance = WALLET;
Product pricelist[] = {
{0, 0.00}, {1, 1.45}, {2, 1.16}, {3, 1.23}
};
char* fruit[] = {"", "Apple", "Orange", "Pear"};
size_t itemcount = (sizeof(pricelist)/sizeof(Product));
double low_price = pricelist[1].cost;
while (1) {
int choice = 0;
printf("Price List:\n");
for (size_t i = 1; i < itemcount; ++i) {
double c = pricelist[i].cost;
printf("%d: %s\t\%.2f\n", i, fruit[i], c);
low_price = c < low_price ? c : low_price;
}
printf("Your balance is: %.2f. Enter Selction: ", balance);
if (fgets(buffer, MAXLINE, stdin) != NULL) {
sscanf(buffer, "%d", &choice);
}
if (choice > 0 && choice < itemcount) {
Product p = pricelist[choice];
if (balance - p.cost >= 0.00) {
balance -= p.cost;
printf("\nPurchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %s\n", fruit[choice]);
printf("Price: \x9C%.2f\n", p.cost);
printf("Remaining budget: \x9C%.2f\n\n", balance);
}
else {
printf("\nPurchase FAILED!\n");
printf("Insufficient funds, sorry.\n\n");
}
}
else {
printf("Choice not recognized, please try again\n\n", choice);
}
if (balance <= low_price ) {
printf("You can make no further purchases\n");
break;
}
}
printf("Thanks for shopping with us!\n");
}
Related
I am getting this error as shown in the image pls tell me how to fix it.
the error is in line 115 of the code
#include<stdio.h>
#include<string.h>
#define MAX 100
#define product_limit 50
typedef struct {
int p_id;
char p_name[product_limit + 1];
int p_quantity;
int unit_price;
char type_product[50];
} product;
int main()
{
int ok = 1, menu;
do
{
menu = display_menu();
if(menu < 1 || menu > 7)
{
printf("Invaid option.\n");
}
else
{
switch(menu)
{
case 1:
add_product();
break;
case 2:
change_product();
break;
case 3:
display_all_products();
break;
}
}
}
while(ok);
printf("Exiting Program.\n");
return 0;
}
int display_menu()
{
int menu;
printf("Choose option from below.\n");
printf("1. Add new product.\n");
printf("2. Update product.\n");
printf("3. Display products.\n");
printf(". Exit.\n");
scanf("%d", &menu);
return menu;
}
product products[MAX];
int c_p = 0;
int product_exists(int id)
{
int x;
for(x=0;x<c_p;x++)
{
if(products[x].p_id == id)
{
return x;
}
}
return -1;
}
int add_product()
{
int price,id,quantity,type;
char name[product_limit + 1];
printf("Product ID: ");
scanf("%d", &id);
if(product_exists(id) != -1)
{
printf("ID: %d already exists.\n", id);
return;
}
printf("Enter Product Name: ");
scanf("%s", name);
printf("Enter Quantity: ");
scanf("%d", &quantity);
printf("Enter Price: ");
scanf("%d", &price);
printf("Enter Product Type:");
scanf("%s",type);
products[c_p].p_id = id;
strcpy(products[c_p].p_name, name);
products[c_p].p_quantity = quantity;
products[c_p].unit_price = price;
c_p++;
printf("Product added Successfully\n");
}
int change_product()
{
int id, exists,name;
char z[2];
printf("Product ID: ");
scanf("%d", &id);
exists = change_product(id);
if(exists == -1) {
printf("ID: %d not exists.\n", id);
printf("Type Y to try once more or N back to menu: ");
scanf("%s", z);
if(strcmp(z, "Y") == 0)
{
change_product();
}
} else {
printf("Product found successfully\n");
printf("Product Name: %s\n", products[exists].p_name);
printf("Type new name: ");
scanf("%d", name);
products[exists].p_name += name;
printf("Successfully updated.\n");
}
}
int display_products()
{
int x;
if(c_p == 0)
{
printf("No products were added\n");
return;
}
printf("Products\n\n");
for(x = 0; x < c_p; x++)
{
printf("Product ID: %d\n", products[x].p_id);
printf("Product Name: %s\n", products[x].p_name);
printf("Quantity: %d\n", products[x].p_quantity);
printf("Product price: %d\n", products[x].unit_price);
printf("Product type:%s\n",products[x].p_name);
printf("\n");
}
}
You're trying to add an integer to a string. This is not allowed in C:
products[exists].p_name += name;
Looking at the change_product method it seems like maybe you want to update the name field or concatenate it. I think you should do these things:
Read all compiler warnings and consider addressing them, They are addressing valid concerns like not declaring your functions first, not returning any int value in add_product, display_product etc which is supposed to return int. Provide a function body for display_all_products (Did you mean display_products()?)
Use a string variable for updating name char newName[product_limit + 1] and use library functions from C string library to either concatenate(strcat) or copy(strcpy) newName taken as user input to products[exists].p_name:
char newName[product_limit + 1];
// ...
} else {
printf("Type new name: ");
fgets(newName, product_limit + 1, stdin);
strcpy(products[exists].p_name, newName);
}
}
You can't add integer to string.
You have used string functions like strcpy() and should do the same for this.
You have also made other errors :
declaring int for string(char array)
wrong return data type
calling wrong funtion
I have fixed those errors, do side by side comparison.
#include<stdio.h>
#include<stdlib.h>//here
#include<string.h>
#define MAX 100
#define product_limit 50
//here
void add_product(void);
void change_product(void);
int display_menu(void);
void display_products(void);
int product_exists(int);
typedef struct {
int p_id;
char p_name[product_limit + 1];
int p_quantity;
int unit_price;
char type_product[50];
} product;
int main()
{
int ok = 1, menu;
do
{
menu = display_menu();
if(menu < 1 || menu > 4)
{
printf("Invaid option.\n");
}
else
{
switch(menu)
{
case 1:
add_product();
break;
case 2:
change_product();
break;
case 3:
display_products();//here
break;
case 4:
exit(0);//here
}
}
}
while(ok);
printf("Exiting Program.\n");
return 0;
}
int display_menu()
{
int menu;
printf("Choose option from below.\n");
printf("1. Add new product.\n");
printf("2. Update product.\n");
printf("3. Display products.\n");
printf("4. Exit.\n");
scanf("%d", &menu);
return menu;
}
product products[MAX];
int c_p = 0;
int product_exists(int id)
{
int x;
for(x=0;x<c_p;x++)
{
if(products[x].p_id == id)
{
return x;
}
}
return -1;
}
void add_product() // here
{
int price,id,quantity;
char type[product_limit + 1];
char name[product_limit + 1];//here
printf("Product ID: ");
scanf("%d", &id);
if(product_exists(id) != -1)
{
printf("ID: %d already exists.\n", id);
return;
}
printf("Enter Product Name: ");
scanf("%s", name);
printf("Enter Quantity: ");
scanf("%d", &quantity);
printf("Enter Price: ");
scanf("%d", &price);
printf("Enter Product Type:");
scanf("%s",type);
products[c_p].p_id = id;
strcpy(products[c_p].p_name, name);
products[c_p].p_quantity = quantity;
products[c_p].unit_price = price;
strcpy(products[c_p].type_product,type);//here
c_p++;
printf("Product added Successfully\n");
}
void change_product() //here
{
int id, exists;
char z[2];
char name[product_limit + 1];//here
printf("Product ID: ");
scanf("%d", &id);
exists = product_exists(id);//here
if(exists == -1)
{
printf("ID: %d not exists.\n", id);
printf("Type Y to try once more or N back to menu: ");
scanf("%s", z);
if(strcmp(z, "Y") == 0)
{
change_product();
}
}
else
{
printf("Product found successfully\n");
printf("Product Name: %s\n", products[exists].p_name);
printf("Type new name: ");
scanf("%s", &name);//here
strcpy(products[exists].p_name, name);//here
printf("Successfully updated.\n");
}
}
void display_products() //here
{
int x;
if(c_p == 0)
{
printf("No products were added\n");
return;
}
printf("Products\n\n");
for(x = 0; x < c_p; x++)
{
printf("Product ID: %d\n", products[x].p_id);
printf("Product Name: %s\n", products[x].p_name);
printf("Quantity: %d\n", products[x].p_quantity);
printf("Product price: %d\n", products[x].unit_price);
printf("Product type:%s\n",products[x].type_product);//here
printf("\n");
}
}
Every time I try and run only the first loop runs. It ask how many items were sold and then just stops running. I'm not really sure what I did wrong. If anyone has any tips that would be great(story if there's some formatting issues, SO wouldn't let me post the question without them).
Everything else looks fine but if any other improvements could be made please let me know.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int digit(char term[])
{
int i = 0;
int val = 0;
while (term[i] != '\0')
{
val = val * 10 + term[i] - '0';
i++;
}
return val;
}
void error()
{
printf("Error: Sales figures must be numbers.\n");
printf("Please try again.\n");
}
bool isnumber(char term[])
{
int i = 0;
while (term[i])
{
if( isdigit(term[i]) == 0)
{
return false;
i++;
}
}
return true;
}
int main()
{
int sales[3][2], costs[3] = {3, 4, 1}, weekends[2] = {0, 0};
int i, j, val;
char term[100];
while (1)
{
printf("Number of Bagel sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[0][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Saturday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[1][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Saturday: ");
scanf("%s", term);
if (isnumber(term) == false)
{
error;
}
else
{
sales[2][0] = digit(term);
break;
}
}
while (1)
{
printf("Number of Bagel sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[0][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Flatbread sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[1][1] = digit(term);
break;
}
}
while (1)
{
printf("Number of Muffin sales on Sunday: ");
scanf("%s", term);
if( isnumber(term) == false)
{
error;
}
else
{
sales[2][1] = digit(term);
break;
}
}
for (i = 0; i < 2, i++;)
{
for (j = 0; j < 3, j++;)
{
weekends[i] += costs[j] * sales[i][j];
}
}
printf("\n");
for (i = 0; i < 3, i++;)
{
printf("%d", costs[i]);
}
printf(".");
for (i = 0; i < 3, i++;)
{
for (j = 0; j < 2, j++;)
{
printf("%d", sales[i][j]);
}
if (i == 0)
{
printf(" = ");
printf("%d %d", weekends[0], weekends[1]);
}
printf("\n ");
}
printf("\nTotal sales on Saturday: $%d", weekends[0]);
printf("\nTotal sales on Sunday: $%d", weekends[1]);
printf("\nTotal sales over the weekend: $%d", weekends[0] + weekends[1]);
return 0;
}
You have an infinite loop in isnumber(). It will return false if the first character is not a digit. But if the first character is a digit, it never increments i, so it keeps testing the first character repeatedly.
i++ should not be in the if statement.
bool isnumber(char term[])
{
int i = 0;
while (term[i])
{
if(!isdigit(term[i]))
{
return false;
}
i++;
}
return true;
}
And as others have pointed out, you need to put () after error to call it.
As for your programming stopping; you use isdigit on line 30 without declaring it.
Along that, you use error everywhere without invoking it. Use error() to invoke the function and print the error-information.
Just a small formatting tip as well: instead of if (something == false) use if (!something)
Your use of error; is incorrect. You should write error(); instead.
I'm having difficulty writing a loop that will ask a user if he/she wants to continue the purchase of the products. It's part of my coursework at school. I have written all the required functions but Im struggling to get the loop to work.
Basically, what I want the loop to do is ask a user if he/she wants to continue the purchase and the answer should be either Y or N. Which will then take the remaining budget, implement it back to the program and run it again with that budget in mind, then deduct the value of the product chosen.
I have been trying to write that loop for more than 2 hours now and I'm running out of ideas.
That's the code I'm working with:
#include <stdio.h>
int getItemPrice(char itemPrefix, int applePrice, int orangePrice, int pearPrice);
displayMenu(int applePrice, int orangePrice, int pearPrice);
withinBudget(int budget, char purchase, int applePrice, int orangePrice, int pearPrice);
purchaseItem(int budget, char purchase, int applePrice, int orangePrice, int pearPrice);
int main()
{
int orangePrice, applePrice, pearPrice, budget;
char purchase;
printf("*****************\n");
printf("Item prefixes\n");
printf("A: Apple\n");
printf("O: Orange\n");
printf("P: Pear\n");
printf("*****************\n\n");
printf("***************\n");
printf("*** MyStore ***\n");
printf("***************\n\n");
printf("**** SHOPKEEPER PANEL ****\n");
printf("Welcome to the store. Please enter the prices for the following products: \n");
printf("Please enter the price for the Orange: \x9C");
scanf_s("%d", &orangePrice);
printf("Please enter the price for the Apple: \x9C");
scanf_s("%d", &applePrice);
printf("Please enter the price for the Pear: \x9C");
scanf_s("%d", &pearPrice);
printf("\n\n");
displayMenu(applePrice, orangePrice, pearPrice);
printf("**** Customer menu ****\n");
printf("Please enter your budget: \x9C");
scanf_s("%d", &budget);
printf("Please enter the item you would like to purchase using the item Prefix: ");
scanf_s(" %c", &purchase, 1);
printf("\n\n");
displayMenu(applePrice, orangePrice, pearPrice);
withinBudget(budget, purchase, applePrice, orangePrice, pearPrice);
purchaseItem(budget, purchase, applePrice, orangePrice, pearPrice);
return 0;
};
int getItemPrice(char itemPrefix, int applePrice, int orangePrice, int pearPrice)
{
if (itemPrefix == 'A') {
return applePrice;
}
else if (itemPrefix == 'O') {
return orangePrice;
}
else if (itemPrefix == 'P') {
return pearPrice;
}
else {
return -1;
}
return getItemPrice;
}
displayMenu(int applePrice, int orangePrice, int pearPrice)
{
printf("**** Shop Menu ****\n");
printf("Item:\t\tPrice\n");
printf("A:\t\t\x9C%d\n", applePrice);
printf("O:\t\t\x9C%d\n", orangePrice);
printf("P:\t\t\x9C%d\n", pearPrice);
printf("\n\n");
return 0;
}
withinBudget(int budget, char purchase, int applePrice, int orangePrice, int pearPrice)
{
int getItemPrice(itemPrefix, applePrice, orangePrice, pearPrice);
if (purchase == 'A') {
return applePrice;
}
else if (purchase == 'O') {
return orangePrice;
}
else if (purchase == 'P') {
return pearPrice;
}
else {
return -1;
}
}
purchaseItem(int budget, char purchase, int applePrice, int orangePrice, int pearPrice)
{
int items ;
int calculation;
if (purchase == 'A') {
items = applePrice;
}
else if (purchase == 'O') {
items = orangePrice;
}
else if (purchase == 'P') {
items = pearPrice;
}
else {
items = -1;
}
if (items != -1) {
calculation = budget - items;
if (calculation >= 0) {
printf("Purchase was a success!\n");
printf("Purchase details\n");
printf("----------------------\n");
printf("Item: %c\n", purchase);
printf("Price: \x9C%d\n", items);
printf("Remaining budget: \x9C%d\n\n", calculation);
printf("Thanks for shopping with us!");
}
else {
items = -1;
}
}
if (items == -1) {
printf("Purchase FAILED!\n");
printf("Low budget or invalid item!\n\n");
printf("Thanks for shopping with us!");
}
;
I have already tried writing the while loop in the body of the program as well as inside of the purchase item function. I'm completely clueless at this point and don't really know what can I do to make it work. Or what I'm not doing that would help me this program to work as I want it to.
Any help would be appreciated. As well as any tips on what can I do to improve it.
You can implement a loop logic like this:
int main(void){
... // Your definitons
bool proceed = true;
while(proceed){
... // All your code here
bool isValid = false; // Check the answer character's validity
while(!isValid){
printf("Would you like to purchase anything else? [Y / N]");
char answer = getchar();
putchar('\n'); // Add a line feed
if (answer == 'Y' || answer == 'y'){
proceed = true;
isValid = true;
}
else if (answer == 'N' || answer == 'n'){
proceed = false;
isValid = true;
}
else{
// Entered an unexpected character, force the user to enter a valid character
printf("Please enter a valid answer\n");
isValid = false;
}
}
}
return 0;
}
More precisely.. How do I add a "go back to main menu" function as all other softwares and games have?
void showMenu()
{
puts( "1. Create school\n"
"2. Add room\n"
"3.Add student to room\n"
"4.Find student\n"
"5. Show students in room\n"
"\n" "6. Exit");
}
int main()
{
clrscr();
studentList *foundStudent;
int input;
showMenu();
while( scanf("%d", &input) )
{
if(input == 6)
{
periods("Exiting");
break;
}
if(input == 1)
{
school *school;
school = createSchool();
}
if(input == 2)
{
int room, roomNr;
printf("Enter room Nr. and Class:");
scanf("%d %d", &room, &roomNr);
}
}
return 0;
}
Anything I attempted didn't work and just created more redundancy, never expected how goto can be so confusing.
Although switch makes more sense, I don't believe it fixes my problem.
Here is a working example.
The solution for this problem was simply making a "menu within a menu" kind of, I did use some gotos but as far as commandline menu goes, this may be all.
#define clrscr() printf("\e[1;1H\e[2J")
void periods(char* message)
{
const int trigger = 500; // ms
const int numDots = 3;
while (1)
{
// Return and clear with spaces, then return and print prompt.
printf("\r%*s\r%s", sizeof(message) - 1 + numDots, "", message);
fflush(stdout);
// Print numDots number of dots, one every trigger milliseconds.
for (int i = 0; i < numDots; i++)
{
usleep(trigger * 1000);
fputc('.', stdout);
fflush(stdout);
}
break;
}
}
void showmenu()
{
clrscr();
puts("1. New Game\n"
"2. Load Game\n"
"3. Credits\n\n"
"4. Exit\n" );
}
int checkString(char *str)
{
int status = 0;
int ln = strlen(str);
for(int i = 0; i < ln; i++)
{
if(isdigit( str[i] ) )
status = 1;
break;
}
return status;
}
int main(){
char choice;
clrscr();
int status, isNum = -101;
char *name, *buffer, YN;
showmenu();
while(1)
{
scanf(" %c", &choice);
if( isdigit(choice) )
{
break;
}
else
{
fflush(stdin);
printf("Please only enter numbers!\n");
sleep(1);
showmenu();
}
}
do{
switch(choice)
{
case '1':
{
createG:;
clrscr();
printf("Enter name or press 0 to return\n");
scanf("%s", buffer);
status = checkString(buffer);
if(status == 1)
{
clrscr();
break;
}
clrscr();
name = (char*)malloc(strlen(buffer)+1);
strcpy(name, buffer);
printf("New game created, welocome %s!\n");
for(int i = 0; i < 5; i++)
{
sleep(1);
printf("%d\n", i);
}
break;
}
case '2':
{
int what;
caseL:;
clrscr();
printf("No saves!\n Create new game? [Y/N] \n to return press 0\n");
scanf(" %c", &YN);
if(YN == 'N') what = 0;
if(YN == '0') what = -1;
if(YN == 'Y') what = 1;
switch(YN)
{
case 'N':
{
goto caseL;
}
case '0':
{
break;
}
case 'Y':
{
choice = 1;
goto createG;
break;
}
}
break;
}
case '3':
{
periods("Hello World");
break;
}
case '4':
{
clrscr();
periods("Goodbye");
clrscr();
exit(1);
}
default:
{
printf("Wrong input\n Try again");
sleep(1);
break;
}
}
}while(choice != -2);
return 0;
}
This may still need a lot of error checking and handling for "unexpected" inputs but it answers the problem.
I have multiple errors with this project. The first and most important one would have to be one I answer a question in a case. Rather than it going back to choosing a case, it instead goes towards the difficulty. This won't let me exit the program and to get the average questions correct.
Another error is the end average questions correct. My program crashes whenever I try to just skip questions and go to the end. All it would do is divide 0/0 unless that's not possible. I'm supposed to use a switch function which is something I've seen has a problem with loops. Sadly, I can't find a way to fix it on my end, or every answer has just gone right over my head.
#include <stdio.h>
int main()
{
int option = 0;
int answer = 0;
int remainder = 0;
int ttlProblems = 0;
int correctAnswers = 0;
double averageCorrect = 0;
char difficulty;
printf("Math Practice Program Menu");
printf("\n\n1. Addition\n");
printf("2. Subtraction \n");
printf("3. Multiplication \n");
printf("4. Division \n");
printf("5. Exit\n\n");
printf("Select an option: ");
scanf_s("%d", &option);
while (option != 5)
{
switch (option)
{
case 1:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("3 + 1 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 4)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 + 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 53)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 + 119 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 253)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty set\n");
}
break;
case 2:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("3 - 1 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 2)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 - 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 15)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 - 119 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 15)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty s\n");
}
break;
case 3:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("3 * 1 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 3)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 * 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 646)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 * 119 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
if (answer == 15946)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty set\n");
}
break;
case 4:
printf("Select difficulty level...\ne for easy\nm for medium\nh for hard\n");
scanf_s(" %c", &difficulty, 1);
if (difficulty == 'e')
{
printf("9 / 2 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
printf("Enter any remainder: ");
scanf_s("%d", &remainder, 1);
if (answer == 4 && remainder == 1)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'm')
{
printf("34 / 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
printf("Enter any remainder: ");
scanf_s("%d", &remainder, 1);
if (answer == 1 && remainder == 15)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else if (difficulty == 'h')
{
printf("134 / 19 = ? Enter answer: ");
scanf_s("%d", &answer, 1);
printf("Enter any remainder: ");
scanf_s("%d", &remainder, 1);
if (answer == 7 && remainder == 1)
{
++ttlProblems;
++correctAnswers;
printf("Correct!\n");
}
else
{
++ttlProblems;
printf("Sorry, Incorrect\n");
}
}
else
{
printf("Invalid difficulty set\n");
break;
}
break;
case 5:
break;
default:
printf("Not a valid option.\n");
}
}
averageCorrect = ttlProblems / correctAnswers;
printf("You attempted %d problems and got %d correct\nFor a percentage of %.2f correct.", ttlProblems, correctAnswers, averageCorrect);
}
Currently, your code asks the user to enter the option type before the while loop, so it will only ask once and use that value for the option every loop iteration. Moving your option input scanf_s("%d", &option); into the beginning of the while loop should solve your first problem.
In regards to dividing by zero, this will cause the program to crash because it is not possble. You might want to check whether correctAnswers is zero or not before performing the division.