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;
}
}
Related
First of all, I am a total beginner to both C (and any programming) and Stack Overflow, so sorry if something like this has been asked before.
So I've been having trouble with my math operations code in the loop part. When I type in N or Y, the program acts as if I typed in a different option and says I have to type in Y or N.
Here's the code. Sorry if it's a jumbled mess, this is all I know so far.
#include <stdio.h>
int main() {
while (1) {
int choice1, choice2, num1, num2;
printf("\n [1] Addition\n [2] Subtraction\n [3] Multiplication\n [4] Division\n");
printf("\n Pick a choice: ");
scanf("%d", &choice1);
printf("\n Give a number: ");
scanf("%d", &num1);
printf("\n Give another number: ");
scanf("%d", &num2);
switch (choice1) {
case 1:
printf("Sum is %d", num1+num2);
break;
case 2:
printf("Difference is %d", num1-num2);
break;
case 3:
printf("Product is %d", num1*num2);
break;
case 4:
printf("Quotient is %d", num1/num2);
break;
default:
printf("Please select a valid operation");
}
printf("\n Try another operation [y/n]: ");
scanf("%d", &choice2);
if (choice2 == 'y' || choice2 == 'Y') {
printf("Retrying...");
break; }
else if (choice2 == 'n' || choice2 == 'N') {
printf("Exiting...");
break; }
else {
printf("Pick y or n only");
break;
}
}
return 0;
}
the issue here is that in the if statement you are using break which breaks the flow, instead you should be using continue
major changes: (I've added comment line to make the changes more obvious for you)
int check = 1; //added a check variable
while (check) { //used check variable for while loop
printf("\n Try another operation [y/n]: ");
scanf("%c", &choice2); //changed %d to %c as the input is a char
if (choice2 == 'y' || choice2 == 'Y') {
printf("Retrying...");
continue; } //changed break with continue
else if (choice2 == 'n' || choice2 == 'N') {
printf("Exiting...");
check= 0; } //updated check so next iteration fails and terminates the loop
else {
printf("Error wrong input");
check= 0; //there cannot be a 2nd try using if else statement
}
there will be few more changes which I'll mark in the code below
#include <stdio.h>
int main() {
int check = 1; //added a check variable
while (check) { //used check variable for while loop
int choice1, choice2, num1, num2;
printf("\n [1] Addition\n [2] Subtraction\n [3] Multiplication\n [4] Division\n");
printf("\n Pick a choice: ");
scanf("%d", &choice1);
printf("\n Give a number: ");
scanf("%d", &num1);
printf("\n Give another number: ");
scanf("%d", &num2);
switch (choice1) {
case 1:
printf("Sum is %d", num1+num2);
break;
case 2:
printf("Difference is %d", num1-num2);
break;
case 3:
printf("Product is %d", num1*num2);
break;
case 4:
printf("Quotient is %d", num1/num2);
break;
default:
printf("Please select a valid operation");
}
printf("\n Try another operation [y/n]: ");
scanf("%c", &choice2); //changed %d to %c as the input is a char
if (choice2 == 'y' || choice2 == 'Y') {
printf("Retrying...");
continue; } //changed break with continue
else if (choice2 == 'n' || choice2 == 'N') {
printf("Exiting...");
check= 0; } //updated check so next iteration fails and terminates the loop
else {
printf("Error wrong input");
check= 0; //there cannot be a 2nd try using if else statement
}
}
return 0;
}
for more detail, you can read the docs
I think you will have to do some major changes as shown below
#include <stdio.h>
int main() {
while (1) {
int choice1, num1, num2;
char choice2;
printf("\n [1] Addition\n [2] Subtraction\n [3] Multiplication\n [4] Division\n");
printf("\n Pick a choice: ");
scanf("%d", &choice1);
printf("\n Give a number: ");
scanf("%d", &num1);
printf("\n Give another number: ");
scanf("%d", &num2);
switch (choice1) {
case 1:
printf("Sum is %d", num1+num2);
break;
case 2:
printf("Difference is %d", num1-num2);
break;
case 3:
printf("Product is %d", num1*num2);
break;
case 4:
printf("Quotient is %d", num1/num2);
break;
default:
printf("Please select a valid operation");
}
printf("\n Try another operation [y/n]: ");
scanf("%s", choice2);
if (choice2 == 'y' || choice2 == 'Y')
{
scanf("%d", &choice1);
}
else;
{
printf("Exiting...");
}
}
return 0;
}
Problem: Scholarship Endowment Fund Part 2 (fund2.c)
How do I return back to main menu and add a counter for the total number of donations and investment made, here's what i got?
Then, your program should allow the user the following options:
Make a donation
Make an investment
Print balance of fund
Quit
#include <stdio.h>
#include <stdlib.h>
//main functions
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!\n");
printf("What is the initial balance of the fund\n");
scanf("%d", &fund);
int ans;
printf("What would you like to do?\n");
printf("\t1- Make a Donation\n");
printf("\t2- Make an investment\n");
printf("\t3- Print balance of fund\n");
printf("\t4- Quit\n");
scanf("%d", &ans);
if (ans == 1) {
printf("How much would you like to donate?\n");
scanf("%d", &donation);
}
if (ans == 2) {
printf("How much would you like to invest?\n");
scanf("%d", &investment);
return main();
}
if (ans == 3) {
total = donation + fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amount\n");
return main();
}
else {
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
}
}
if (ans == 4) {
printf("Type 4 to quit\n");
}
else {
printf("Not a valid option.\n");
}
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?\n");
scanf("%d", &donation);
return main();
case 2:
printf("How much would you like to invest\n");
scanf("%d", &investment);
return main();
case 3:
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
return main();
case 4:
break;
}
return 0;
}
You should put in a loop the part that you want to be repeated, using a varaible to decide when to stop.
here is an example, also in the switch costruct you should usa a default option, maybe to warn the user that the option they inserted is not valid.
int main() {
// variables
int donation, investment, fund, total, tdonations, tinvestments;
// prompt user
printf("Welcome!\n");
printf("What is the initial balance of the fund\n");
scanf("%d", &fund);
//loop until the user decide so
int exit = 0;
while(exit == 0){
int ans;
printf("What would you like to do?\n");
printf("\t1- Make a Donation\n");
printf("\t2- Make an investment\n");
printf("\t3- Print balance of fund\n");
printf("\t4- Quit\n");
scanf("%d", &ans);
//switch
switch (ans) {
case 1:
printf("How much would you like to donate?\n");
scanf("%d", &donation);
break;
case 2:
printf("How much would you like to invest\n");
scanf("%d", &investment);
break;
case 3:
total = donation + fund - investment;
if (total < fund) {
printf("You cannot make an investment of that amount\n");
}
else {
printf("The current balance is %d\n", total);
printf(" There have been %d donations and %d investments.\n", tdonations, tinvestments);
}
break;
case 4:
exit = 1;
break;
default:
printf("Incorrect option\n");
break;
}
}
return 0;
}
In this code at checkout function g_tot calculation brings garbage value. I think its because I'm calculating two variables from another two functions, but I don't know how to fix it. There's another error in restaurant function in if condition if I enter value more than 8 it'll bring garbage value to tot. But the most important one is
#include<stdio.h>
#include<conio.h>
// Global variables
int room,answr,days=0;
char name[20],choose;
int i=0,tot=0,p_tot=0,g_tot=0,z=0;
int p_price[2][5]={4000,10000,20000};
void screenheader()
{
printf("\n ::::::::::::::::::::::::::::::::::::::");
printf("\n :: ::");
printf("\n :: ############################ ::");
printf("\n :: # # ::");
printf("\n :: # WELCOME # ::");
printf("\n :: # TO # ::");
printf("\n :: # SURF HOTEL # ::");
printf("\n :: # # ::");
printf("\n :: ############################ ::");
printf("\n :: ::");
printf("\n ::::::::::::::::::::::::::::::::::::::");
}
void check_in()
{
int contact_No[20],NIC[10];
char first_name[10],last_name[10],Country[10];
system("cls");
screenheader();
printf("\n1. Packages");
printf("\n2. Room Allocation");
printf("\n3. Back\n\n");
scanf(" %d",&answr);
switch(answr)
{
case 1:{
system("cls");
printf("\n\n\nPer 2 Persons");
printf("\n\t\tPackage Name >>>> Couple");
printf("\n\t\tRs.4000/= per day");
printf("\n\t\tBed >>>> 1");
printf("\n\t\t *Tv Available");
printf("\n\n\n\n\t\t\nPer 4 Persons\n\t\tPackage Name >>>>
Family");
printf("\n\t\tRs.10,000/= per day");
printf("\n\t\tBed >>>> 2");
printf("\n\t\t*Tv Available \n\t\t*A/C \n\t\t*WIFI");
printf("\n\n\n\nPer 8 Persons\n\t\tPackage Name >>>> Deluxe");
printf("\n\t\tRs.20,000/= per day");
printf("\n\t\tBed >>>> 3 Large ");
printf("\n\t\t *Tv Available \n\t\t*A/C \n\t\t*WIFI\n\t\t*Local
Travel Guide\n\t\t*Balcony with a view\n\t\t*Writing desk");
printf("\n\n*Press 1 to go back");
getch();
check_in();
break;
}
case 2:{
printf("What package do you want?");
scanf(" %d",&i);
p_tot=p_tot+p_price[i-1];
if(i == 1)
{
printf("You have selected Couple package");
}
else if (i == 2)
{
printf("You have selected Family Package ");
}
else if (i == 3)
{
printf("You have selected Deluxe package");
}
else
{
printf("\n\nWrong input, please refer to packages and try
again.\nPress Enter to select another package");
getch();
check_in();
}
printf("\nEnter First Name:\n");
scanf(" %s",&first_name);
printf("Last Name:\n");
scanf(" %s",&last_name);
printf("How many days do you want to stay?");
scanf(" %d",&days);
printf("Enter your Country:");
scanf(" %s",&Country);
printf("Enter your NIC No:");
scanf(" %d",&NIC);
printf("Enter your Contact No:");
scanf(" %d",&contact_No);
printf("Hello %s %s you have booked a Room for
%d",&first_name,&last_name,days);
getch();
system("cls");
int main();
}
case 3: main();
}
}
void restaurant()
{
int fc[6];
char ans;
char food[8][30]={"Bread","Noodles","Salad","Popcorn","Chocolate ice
cream","Vanilla ice cream","Cold Coffee","Milk Shake"};
int price[8]={180,120,65,55,70,70,110,200};
printf("Press Enter To Continue To The Restaurant ");
getchar();
system("cls");
printf("\n\n\n\n\n\t *********");
printf("\n\t MENU CARD");
printf("\n\t *********\n\n\n");
printf("\n Food Code\t\tprice\t\t Food Name\n");
for(i=0;i<8;i++)
{
printf("\n\t\t%d",i+1);
printf("\t\tRs. %d",price[i]);
printf("\t\t%s",food[i]);
}
printf("\n\n\n\t *PRESS 0 TO GO TO THE MAIN MENU\n\t *PRESS 1 TO ORDER FOOD
: ");
scanf(" %d",&answr);
switch(answr)
{
case 0:
{
main();
break;
}
case 1:do
{
printf("\n\nENTER THE FOOD CODE YOU WANT TO HAVE :: ");
scanf("%d", &z);
if (z < 1 || z > 8)
{
printf("Invalid food code\n");
}
tot=tot+price[z-1];
printf("total so far is Rs.%d\n",tot);
printf("DO YOU WANT MORE(Y/N) ::");
scanf(" %c", &ans);
} while(ans=='y'|| ans=='Y');
printf("\n\nYour bill is Rs.%d",tot);
printf("\nYour bill will be added to the total bill at checkout");
printf("\n\nPress Enter to go back to main menu");
getch();
system("cls");
main();
}
}
void check_out()
{
system("cls");
screenheader();
printf("\n\nAre you sure you want checkout (Y/N)");
scanf(" %c",&choose);
if(choose=='n' || choose=='N')
{
main();
}
else if(choose== 'Y' || choose=='y')
{
system("cls");
screenheader();
g_tot=p_tot+tot;
printf("Total");
printf("%d",g_tot);
}
}
int main()
{
screenheader();
printf("\n\n\nPress Enter To Continue");
getchar();
system("cls");
screenheader();
printf("\n\n\n\n\t\t ************* \n");
printf("\t\t * MAIN MENU * \n");
printf("\t\t ************* \n\n\n");
printf("\t\t\t01. Check In \n");
printf("\t\t\t02.Restaurant\n");
printf("\t\t\t03.Checkout \n");
printf("\n\t\t\t04.Exit");
scanf(" %d",&answr);
switch(answr)
{
case 1:{
check_in();
break; }
case 2:{
restaurant();
break; }
case 3: {
check_out();
}
}
return 0;
}
if condition if I enter value more than 8 it'll bring garbage value to tot.
This is as expected. When z > 8, code attempts to access outside price[] range. Result: undefined behavior (UB). The prior if (z < 1 || z > 8) did not steer code away from price[z - 1]. Rest of code including g_tot = p_tot + tot; is now questionable.
int price[8] = {180, 120, 65, 55, 70, 70, 110, 200};
...
if (z < 1 || z > 8) {
printf("Invalid food code\n");
}
tot = tot + price[z - 1]; // UB here
...
g_tot = p_tot + tot;
Do not access price[z - 1] unless z in the range [1...8].
Other problems exist: Best to enable all compilers warnings and seem them (12+) yourself.
I'm relatively new to coding yet not completely inexperienced. Working on a school assignment regarding financial calculators. Would be great if any of you could take a look at my code for bad practices/possible improvements etc.
I did add a 'animated' startup (with a lot of printf to show "financial calculator" but couldn't fit it in, is it a good idea to do something like that?)
option_2 and option_4 are left as placeholders for the time being while my group works on other 2 calculators.
//ASSIGNMENT_041118
//libraries
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <math.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include <signal.h>
//files
//colours
#define ANSI_COLOR_BLACK "\x1b[30m"
#define ANSI_COLOR_RED "\x1b[31m"
#define ANSI_COLOR_GREEN "\x1b[32m"
#define ANSI_COLOR_YELLOW "\x1b[33m"
#define ANSI_COLOR_BLUE "\x1b[34m"
#define ANSI_COLOR_MAGENTA "\x1b[35m"
#define ANSI_COLOR_CYAN "\x1b[36m"
#define ANSI_COLOR_WHITE "\x1b[37m"
#define ANSI_COLOR_BBLACK "\x1b[90m"
#define ANSI_COLOR_BRED "\x1b[91m"
#define ANSI_COLOR_BGREEN "\x1b[92m"
#define ANSI_COLOR_BYELLOW "\x1b[93m"
#define ANSI_COLOR_BBLUE "\x1b[94m"
#define ANSI_COLOR_BMAGENTA "\x1b[95m"
#define ANSI_COLOR_BCYAN "\x1b[96m"
#define ANSI_COLOR_BWHITE "\x1b[97m"
#define ANSI_COLOR_RESET "\x1b[0m"
//function prototype declaration
int main_menu();
int login();
float compound();
float compound_calc(float n, float initial_savings, float rate, float time);
float option_2();
float mortgage();
float option_4();
int main()
{
system("color 0F");
login();
return (0);
}
int login()
{
char username[20];
char password[20];
int l_option;
printf("=========================================================================================================\n");
printf("Enter your username (case sensitive): ");
scanf("%s", &username);
printf("\nEnter your password (case sensitive): ");
scanf("%s", &password);
if (strcmp(username, "user") == 0)
{
if (strcmp(password, "0000") == 0)
{
system("cls");
return main_menu();
}
else
{
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"ERROR - WRONG PASSWORD\n"ANSI_COLOR_RESET);
do {
printf("---------------------------------------------------------------------------------------------------------\n");
printf("[1]Retry\n[0]Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &l_option);
switch (l_option)
{
case 1:
system("cls");
return login();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("EXIT\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED "INVALID OPTION - CHOOSE AGAIN\n" ANSI_COLOR_RESET);
break;
}
} while (l_option != 1 && l_option != 0);
}
}
else
{
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"ERROR - USER DOESN'T EXIST\n"ANSI_COLOR_RESET);
do {
printf("---------------------------------------------------------------------------------------------------------\n");
printf("[1]Retry\n[0]Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &l_option);
switch (l_option)
{
case 1:
system("cls");
return login();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("EXIT\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED "INVALID OPTION - CHOOSE AGAIN\n" ANSI_COLOR_RESET);
break;
}
} while (l_option != 1 && l_option != 0);
}
}
int main_menu()
{
int option_main;
do {
printf("=========================================================================================================\n");
printf("Choose an option:\n"); //tells user to select an option
printf("---------------------------------------------------------------------------------------------------------\n");
printf(ANSI_COLOR_BGREEN"[1] <Savings Calculator - Compounded Interest> \n"ANSI_COLOR_RESET); //displays options
printf(ANSI_COLOR_BMAGENTA"[2] <place_holder_2> \n"ANSI_COLOR_RESET);
printf(ANSI_COLOR_BYELLOW"[3] <Mortage calculator> \n"ANSI_COLOR_RESET);
printf(ANSI_COLOR_BCYAN"[4] <place_holder_3> \n"ANSI_COLOR_RESET);
printf("\n[0] <Exit system>\n");
printf("=========================================================================================================\n");
scanf("%d", &option_main); //accepts input for function selection
printf("=========================================================================================================\n");
system("cls");
switch (option_main) //switch case for main option
{
case 1:
{
compound();
break;
}
case 2:/*option_2*/
{
option_2();
break;
}
case 3:/*option_3*/
{
mortgage();
break;
}
case 4:/*option_4*/
{
option_4();
break;
}
case 0:/*exit*/
{
printf("=========================================================================================================\n");
printf("<EXIT>\n");
printf("=========================================================================================================\n");
exit(0);
break;
}
default:
{
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"INVALID OPTION - CHOOSE AGAIN\n"ANSI_COLOR_RESET);
break;
}
}
} while (option_main != 1 && option_main != 2 && option_main != 3 && option_main != 4 && option_main != 0);
return (0);
}
float compound() //compound_interest_calculation_self_defined function
{
int compound_type, ci_option;
float n, initial_savings, rate, time, final_savings;
do {
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BGREEN"<Savings Calculator - Compounded Interest>\n"ANSI_COLOR_RESET); //displays option selected (Savings Calculator - Compounded Interest)
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter compound type:\n"); //Prompts user to choose
printf("[1] Monthly\n[2] Quarterly\n[3] Semiannually\n[4] Annually\n\n[9]Return to menu\n[0] Exit\n");//displays options
printf("=========================================================================================================\n");
scanf("%d", &compound_type); //accepts input for option selection
printf("=========================================================================================================\n");
system("cls");
switch (compound_type) //internal switch case for compounded interest calculator
{
case 1: /*monthly*/
n = 12;
printf("=========================================================================================================\n");
printf("<Monthly compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM "); //prompts user for initial saving amount (principle)
scanf("%f", &initial_savings); //accepts input for initial savings
/*printf("Please enter monthly deposit: RM "); //prompts user input for monthly deposit
scanf("%f", &monthly_deposit); */ //accepts input for monthly deposit
printf("Please enter interest rate (decimal): "); //prompts user input for interest rate
scanf("%f", &rate); //accepts input for interest rate
printf("Please enter time (year): "); //prompts input for saving duration
scanf("%f", &time); //accepts input for saving duration
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f \n", final_savings); //dispays final savings amount
printf("=========================================================================================================\n");
break;
case 2: /*quarterly*/
n = 4;
printf("=========================================================================================================\n");
printf("<Quarterly compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM ");
scanf("%f", &initial_savings);
/*printf("Please enter monthly deposit: RM "); //temporarily removed from calculation
scanf("%f", &monthly_deposit);*/
printf("Please enter interest rate (decimal): ");
scanf("%f", &rate);
printf("Please enter time (year): ");
scanf("%f", &time);
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f \n", final_savings);
printf("=========================================================================================================\n");
break;
case 3: /*semiannually*/
n = 2;
printf("=========================================================================================================\n");
printf("<Semiannual compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM ");
scanf("%f", &initial_savings);
/*printf("Please enter monthly deposit: RM "); //temporarily removed from calculation
scanf("%f", &monthly_deposit);*/
printf("Please enter interest rate (decimal): ");
scanf("%f", &rate);
printf("Please enter time (year): ");
scanf("%f", &time);
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f \n", final_savings);
printf("=========================================================================================================\n");
break;
case 4: /*annually*/
n = 1;
printf("=========================================================================================================\n");
printf("<Annual compound>\n");
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Please enter initial amount of savings: RM ");
scanf("%f", &initial_savings);
/*printf("Please enter monthly deposit: RM "); //temporarily removed from calculation
scanf("%f", &monthly_deposit);*/
printf("Please enter interest rate (decimal): ");
scanf("%f", &rate);
printf("Please enter time (year): ");
scanf("%f", &time);
final_savings = compound_calc(n, initial_savings, rate, time);
printf("\nThe final savings is: RM %.2f\n", final_savings);
printf("=========================================================================================================\n");
break;
case 9: /*return to menu*/
return main_menu();
break;
case 0: /*exit*/
printf("=========================================================================================================\n");
printf("<EXIT> \n");
printf("=========================================================================================================\n");
exit(0);
default:/*any other input*/
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"INVALID OPTION - CHOOSE AGAIN\n"ANSI_COLOR_RESET);//When user inputs invalid option for compound type
}
} while (compound_type != 0 && compound_type != 1 && compound_type != 2 && compound_type != 3 && compound_type != 4 && compound_type != 9);
do
{
printf("[1]Back to compound interest calculator\n[9]Return to menu\n[0] Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &ci_option);
switch (ci_option)
{
case 1:
system("cls");
return compound();
break;
case 9:
system("cls");
return main_menu();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("<EXIT>\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:/*any other input*/
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"INVALID OPTION - CHOOSE AGAIN\n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
}
} while (ci_option != 1 && ci_option != 9 && ci_option != 0);
return(0);
}
float compound_calc(float n, float initial_savings, float rate, float time)
{
float CI;
CI = (initial_savings*(pow((1 + rate / n), (n * time))));
return (CI);
}
float option_2()
{
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BMAGENTA"<place_holder_2> selected \n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
return(0);
}
float mortgage()
{
float house_price, down_percentage, interest_rate, monthly_payment, r, p;//variables declaration
int loan_period, n,m_option;
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BYELLOW"<Home mortgage calculator>\n"ANSI_COLOR_RESET); //displays option selected (Savings Calculator - Compounded Interest)
printf("---------------------------------------------------------------------------------------------------------\n");
printf("Insert property price: RM ");//prompt input
scanf("%f", &house_price);//get input
printf("Insert down percentage (decimal): ");
scanf("%f", &down_percentage);
printf("Insert loan period (Years): ");
scanf("%d", &loan_period);
printf("Insert interest rate (decimal):");
scanf("%f", &interest_rate);
r = interest_rate / 12;
n = loan_period * 12;
p = house_price - house_price *down_percentage;
monthly_payment = p *(r*pow((1 + r), n)) / (pow((1 + r), n) - 1);//calculate monthly payment //NOTE:MOVE TO SELF DEFINED FUNCTION
printf("\nYour monthly payment is %.2f \n", monthly_payment);//display output
do
{
printf("=========================================================================================================\n");
printf("[3]Recalculate\n[9]Return to menu\n[0] Exit\n");
printf("=========================================================================================================\n");
scanf("%d", &m_option);
switch (m_option)
{
case 3:
system("cls");
return mortgage();
break;
case 9:
system("cls");
return main_menu();
break;
case 0:
system("cls");
printf("=========================================================================================================\n");
printf("<EXIT>\n");
printf("=========================================================================================================\n");
exit(0);
break;
default:/*any other input*/
system("cls");
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BRED"ERROR: INVALID OPTION \n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
}
} while (m_option != 3 && m_option != 9 && m_option != 0);
return (0);
}
float option_4()
{
printf("=========================================================================================================\n");
printf(ANSI_COLOR_BCYAN"<place_holder_4> selected \n"ANSI_COLOR_RESET);
printf("=========================================================================================================\n");
return(0);
}
Replace your "scanf();" to "fgets();"
char *fgets(char *str, int n, FILE *stream)
Example:
#include <stdio.h>
#include <string.h>
char Name[50];
int main(){
printf("What is your name?\n> ");
fgets(Name,50,stdin); //Gets user input from stdin (not from file)
/* But the problem is that fgets also includes '\n' so we put: */
Name[strcspn(Name,"\r\n")]=0; //Removes '\n'
printf("Your name is: <%s>\n",Name);
return 0;
}
I'm getting an error which I am not able to resolve. I've gone through my code thoroughly with no success. What am I doing wrong? See code below.
Compiler error:
In function 'main':
ou1.c:49:1: error: expected 'while' before 'printf'
printf("End of program!\n");
^
My code:
#include <stdio.h>
int main(void){
int choice;
float price, sum, SUMusd;
float rate =1;
printf("Your shopping assistant");
do{
printf("1. Set exchange rate in usd (currency rate:%f)\n", rate);
printf("2. Read prices in the foreign currency\n");
printf("3. End\n");
printf("\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Give exchange rate: \n");
scanf("%f", &rate);
break;
case 2:
do{
printf("Give price(finsh with < 0)\n");
scanf("%f", &price);
sum =+ price;
}while(price <= 0);
SUMusd = sum*rate;
printf("Sum in foreign currency: %f", sum);
printf("Sum in USD:%f", SUMusd);
break;
default:
printf("Invalid choice\n");
break;
}while(choice != 3);
}
printf("End of program!\n");
return 0;
}
The curly braces of the switch statement need to be closed before the while loop termination.
printf("Invalid choice\n");
break;
}
}while(choice != 3);
printf("End of program!\n");
Corrected full code sample
#include <stdio.h>
int main(void){
int choice;
float price, sum, SUMusd;
float rate =1;
printf("Your shopping assistant");
do{
printf("1. Set exchange rate in usd (currency rate:%f)\n", rate);
printf("2. Read prices in the foreign currency\n");
printf("3. End\n");
printf("\n");
scanf("%d", &choice);
switch(choice){
case 1:
printf("Give exchange rate: \n");
scanf("%f", &rate);
break;
case 2:
do{
printf("Give price(finsh with < 0)\n");
scanf("%f", &price);
sum =+ price;
}while(price <= 0);
SUMusd = sum*rate;
printf("Sum in foreign currency: %f", sum);
printf("Sum in USD:%f", SUMusd);
break;
default:
printf("Invalid choice\n");
break;
}
}while(choice != 3);
printf("End of program!\n");
return 0;
}