How to call functions in C - c

I'm working on my final project for my intro to programming class and the assignment is to create a code that will display a menu and will ask the user to enter a choice. After that it will display the total for the order and the name of the item the user chose.
Here's my code:
#include <stdio.h>
#include <stdlib.h>
#define TEQUENOS_PRICE 5.00
#define AREPA_PRICE 3.00
#define CACHAPA_PRICE 2.50
#define EMPANADA_PRICE 2.00
#define SODA_PRICE 0.80
#define QUESILLO_PRICE 1.70
#define DULCE_DE_LECHE_PRICE 1.20
int main()
{
int choice = 0, tequenos = 0, arepa = 0, cachapa = 0, empanada = 0;
int soda = 0, quesillo = 0, dulceDeLeche = 0;
double sum = 0.0, totalPrice;
printf("Welcome to Daniela's Venezuelan emporium.\n");
printf("\nMay I take your order please?\n");
do
{
printf("\n\tMenu");
printf("\n1. Tequenos (5 ct.)\t $%5.2lf", TEQUENOS_PRICE);
printf("\n2. Arepa\t\t $%5.2lf", AREPA_PRICE);
printf("\n3. Cachapa\t\t $%5.2lf", CACHAPA_PRICE);
printf("\n4. Empanada\t\t $%5.2lf", EMPANADA_PRICE);
printf("\n5. Soda \t\t $%5.2lf", SODA_PRICE);
printf("\n6. Quesillo\t\t $%5.2lf", QUESILLO_PRICE);
printf("\n7. Dulce de Leche\t $%5.2lf", DULCE_DE_LECHE_PRICE);
printf("\n8. Done with this order.\n");
printf("\nEnter Item: ");
scanf("%i", &choice);
switch (choice)
{
case 1:
sum += TEQUENOS_PRICE;
tequenos++;
break;
case 2:
sum += AREPA_PRICE;
arepa++;
break;
case 3:
sum += CACHAPA_PRICE;
cachapa++;
break;
case 4:
sum += EMPANADA_PRICE;
empanada++;
break;
case 5:
sum += SODA_PRICE;
soda++;
break;
case 6:
sum += QUESILLO_PRICE;
quesillo++;
break;
case 7:
sum += DULCE_DE_LECHE_PRICE;
dulceDeLeche++;
break;
case 8:
break;
default:
printf("\n\t***ERROR: This is not on the menu.\n");
}
printf("\nTotal so far: $%.2lf\n", sum);
} while (choice != 8);
printf("\nThat's: ");
if (choice = 1)
{
printf(" %i Tequenos\n", tequenos);
}
if (choice = 2)
{
printf("\t %i Arepa\n", arepa);
}
if (choice = 3)
{
printf("\t %i Cachapa\n", cachapa);
}
if (choice = 4)
{
printf("\t %i Empanada\n", empanada);
}
if (choice = 5)
{
printf("\t %i Soda\n", soda);
}
if (choice = 6)
{
printf("\t %i Quesillo\n", quesillo);
}
if (choice = 7)
{
printf("\t %i Dulce De Leche\n", dulceDeLeche);
}
totalPrice = sum;
printf("\nYour total is $%.2lf\n", totalPrice);
printf("\nThank you for coming to Daniela's Venezuelan Emporium.");
printf("\nCome back soon!\n");
system("pause");
return 0;
}
The code works fine but my professor told me that I needed to call functions throughout the entire code, and that main should only be calling other functions. I have been trying but is really confusing for me and I do not know how to do it. I would really appreciate it if you guys could help me.
Thanks!

Here's your code, refactored slightly to break the major parts of your program out into separate functions.
#include <stdio.h>
#include <stdlib.h>
#define TEQUENOS_PRICE 5.00
#define AREPA_PRICE 3.00
#define CACHAPA_PRICE 2.50
#define EMPANADA_PRICE 2.00
#define SODA_PRICE 0.80
#define QUESILLO_PRICE 1.70
#define DULCE_DE_LECHE_PRICE 1.20
int tequenos = 0,
arepa = 0,
cachapa = 0,
empanada = 0,
soda = 0,
quesillo = 0,
dulceDeLeche = 0;
double sum = 0.0;
void print_header()
{
printf("Welcome to Daniela's Venezuelan emporium.\n");
printf("\nMay I take your order please?\n");
}
int get_menu_choice()
{
int choice;
printf("\n\tMenu");
printf("\n1. Tequenos (5 ct.)\t $%5.2lf", TEQUENOS_PRICE);
printf("\n2. Arepa\t\t $%5.2lf", AREPA_PRICE);
printf("\n3. Cachapa\t\t $%5.2lf", CACHAPA_PRICE);
printf("\n4. Empanada\t\t $%5.2lf", EMPANADA_PRICE);
printf("\n5. Soda \t\t $%5.2lf", SODA_PRICE);
printf("\n6. Quesillo\t\t $%5.2lf", QUESILLO_PRICE);
printf("\n7. Dulce de Leche\t $%5.2lf", DULCE_DE_LECHE_PRICE);
printf("\n8. Done with this order.\n");
printf("\nEnter Item: ");
scanf("%i", &choice);
return choice;
}
void process_menu_choice(int choice)
{
switch (choice)
{
case 1:
sum += TEQUENOS_PRICE;
tequenos++;
break;
case 2:
sum += AREPA_PRICE;
arepa++;
break;
case 3:
sum += CACHAPA_PRICE;
cachapa++;
break;
case 4:
sum += EMPANADA_PRICE;
empanada++;
break;
case 5:
sum += SODA_PRICE;
soda++;
break;
case 6:
sum += QUESILLO_PRICE;
quesillo++;
break;
case 7:
sum += DULCE_DE_LECHE_PRICE;
dulceDeLeche++;
break;
case 8:
break;
default:
printf("\n\t***ERROR: This is not on the menu.\n");
}
printf("\nTotal so far: $%.2lf\n", sum);
}
void take_order()
{
do
{
choice = get_menu_choice();
process_menu_choice(choice);
} while (choice != 8);
}
void print_total_for(char *item_type, int item_count)
{
if(item_count > 0)
printf(" %i %s\n", item_count, item_type);
}
int print_total(double totalPrice)
(
printf("\nYour total is $%.2lf\n", totalPrice);
printf("\nThank you for coming to Daniela's Venezuelan Emporium.");
printf("\nCome back soon!\n");
}
void print_total_header()
{
printf("\nThat's: ");
}
int main()
{
int choice = 0;
print_header();
take_order();
print_total_header();
print_total_for("Tequenos", tequenos);
print_total_for("Arepa", arepa);
print_total_for("Cachapa", cachapa);
print_total_for("Empanada", empanada);
print_total_for("Soda", soda);
print_total_for("Quesillo", quesillo);
print_total_for("Dulce De Leche", dulceDeLeche);
print_total(sum);
system("pause");
return 0;
}
Note: not compiled or tested. And if you copy this code, hand it in as your own, and your instructor flunks you for doing so - that's on you.
Best of luck.

Related

Entering a character except for numbers will make my program to output infinitely. How do I fix this? [duplicate]

This question already has answers here:
Validate the type of input in a do-while loop
(5 answers)
Closed last month.
When I enter any characters except numbers in the "Enter your choice" it will infinitely loop. For example:
Typing in a character.
Result
As, you can see it will just infinitely loop, unless I input a number between 1 to 10 as represented for each product choice. Or when typing in any number not between numbers 1 to 10, it will be recognized as an Invalid choice.
P.S. Newbie Coder.
This is the code of the program.
#include <stdio.h>
int main(void)
{
int choice, quantity, total = 0, price = 0;
char end;
do
{
printf("\nWelcome to our store!\n\n");
printf("Welcome to our store!\n");
printf("Please select a product from the following list:\n");
printf("1. Oishi Prawn Crackers - 7 PHP\n");
printf("2. Piattos - 16 PHP\n");
printf("3. Coca-Cola - 40 PHP\n");
printf("4. Sting Energy Drink - 25 PHP\n");
printf("5. Gatorade - 43 PHP\n");
printf("6. Nature Spring 500mL - 10 PHP\n");
printf("7. KitKat - 30 PHP\n");
printf("8. Snickers - 44 PHP\n");
printf("9. Oishi Prawn Crackers - 7 PHP\n");
printf("10. M&M's - 80 PHP\n");
printf("Enter 0 to finish.\n");
printf("\nProduct Quantity Price\n");
printf("----------------------------------------\n");
do
{
printf("Enter your choice: ");
scanf(" %d", &choice);
if (choice == 0)
{
break;
}
printf("Enter the quantity: ");
scanf(" %d", &quantity);
switch (choice)
{
case 1:
printf("Oishi Prawn Crackers %d %d\n", quantity, price = 7 * quantity);
total += 7 * quantity;
break;
case 2:
printf("Piattos %d %d\n", quantity, price = 16 * quantity);
total += 15 * quantity;
break;
case 3:
printf("Coca-Cola %d %d\n", quantity, price = 40 * quantity);
total += 40 * quantity;
break;
case 4:
printf("Sting Energy Drink %d %d\n", quantity, price = 25 * quantity);
total += 25 * quantity;
break;
case 5:
printf("Gatorade 500mL %d %d\n", quantity, price = 43 * quantity);
total += 43 * quantity;
break;
case 6:
printf("Nature Spring 500mL %d %d\n", quantity, price = 10 * quantity);
total += 10 * quantity;
break;
case 7:
printf("KitKat %d %d\n", quantity, price = 30 * quantity);
total += 30 * quantity;
break;
case 8:
printf("Snickers %d %d\n", quantity, price = 44 * quantity);
total += 44 * quantity;
break;
case 9:
printf("M&M's %d %d\n", quantity, price = 40 * quantity);
total += 40 * quantity;
break;
case 10:
printf("Pringles %d %d\n", quantity, price = 80 * quantity);
total += 80 * quantity;
break;
default:
printf("Invalid choice.\n");
break;
}
} while (choice != 0);
printf("----------------------------------------\n");
printf("Total cost: %d PHP\n", total);
printf("Thank you for shopping with us!\n");
printf("\nWant to Buy Again?\n");
printf("Y if Yes\n");
printf("Type any key if No\n");
scanf(" %c", &end);
switch (end) {
case 'Y':
printf("\nOK!\n");
break;
default:
printf("\nBYE!\n");
break;
}
} while (end == 'Y');
return 0;
}
So, I typed in numbers from 1 to 10 and it seems to recognize every product and it will ask for the quantity. And typing in any numbers it will do what it should and will output Invalid Choice. I tried changing the variables expecting it to be fixed but it won't work at all. It seems that I overlooked something but I don't know where.
Consider using a structure to store the name and cost of each product. That will avoid errors in repetitions.
scanint and scanchar will scan and discard pending characters in the input stream. Extra non-whitespace characters will cause a re-prompt.
#include <stdio.h>
typedef struct item item_t;
struct item {
char const *name;
int cost;
};
int scanint ( char const *prompt);
int scanchar ( char const *prompt);
void menu ( size_t items, item_t product[]);
int main(void)
{
item_t products[] = {
{ "Oishi Prawn Crackers", 7}
, { "Piattos", 16}
, { "Coca-Cola", 40}
, { "Sting Energy Drink", 25}
, { "Gatorade", 43}
, { "Nature Spring 500mL", 10}
, { "KitKat", 30}
, { "Snickers", 44}
, { "Pringles", 7}
, { "M&M's", 80}
};
int choice = 0;
int quantity = 0;
int total = 0;
char end = 0;
size_t items = sizeof products / sizeof *products;
do {
printf("\nWelcome to our store!\n\n");
menu ( items, products);
while ( 1) {
choice = scanint ( "Enter your choice: ");
if (choice == 0) {
break;
}
--choice;
if ( choice < items) {
quantity = scanint ( "\tEnter the quantity: ");
printf ( "%-22s%3d %7d\n"
, products[choice].name
, quantity
, products[choice].cost * quantity);
total += products[choice].cost * quantity;
}
else {
printf("Invalid choice.\n");
}
}
printf ( "----------------------------------------\n");
printf ( "Total cost: %d PHP\n", total);
printf ( "Thank you for shopping with us!\n");
end = scanchar ( "\nWant to Buy Again?\nY if Yes\nType any key if No\n");
switch (end) {
case 'Y':
printf("\nOK!\n");
break;
default:
printf("\nBYE!\n");
break;
}
} while (end == 'Y');
return 0;
}
void menu ( size_t items, item_t product[]) {
printf ( "Please select a product from the following list:\n");
for ( int each = 0; each < items; ++each) {
printf ( "%2d. %-22s%3d PHP\n"
, each + 1, product[each].name, product[each].cost);
}
}
int scanint ( char const *prompt) {
char newline[2] = "";
int extra = 0;
int scanned = 0;
int value = 0;
do {
printf ( "%s", prompt);
fflush ( stdout);
scanned = scanf ( "%d", &value);
if ( scanned == EOF) {
return 0;
}
extra = 0;
scanf ( "%*[ \f\t\v]"); // scan and discard whitespace except newline
scanf ( "%*[^\n]%n", &extra); // scan discard and count not a newline
scanned += scanf ( "%1[\n]", newline);
} while ( value < 0 || scanned != 2 || extra != 0);
return value;
}
int scanchar ( char const *prompt) {
char newline[2] = "";
int extra = 0;
int scanned = 0;
char value = 0;
do {
printf ( "%s", prompt);
fflush ( stdout);
scanned = scanf ( " %c", &value);
if ( scanned == EOF) {
return 0;
}
extra = 0;
scanf ( "%*[ \f\t\v]"); // scan and discard trailing whitespace except newline
scanf ( "%*[^\n]%n", &extra); // scan discard and count not a newline
scanned += scanf ( "%1[\n]", newline);
} while ( scanned != 2 || extra != 0);
return value;
}
Here you go:
#include <stdio.h>
int main(void)
{
int choice = 0, quantity, total = 0, price = 0;
char end;
do
{
printf("\nWelcome to our store!\n\n");
printf("Welcome to our store!\n");
printf("Please select a product from the following list:\n");
printf("1. Oishi Prawn Crackers - 7 PHP\n");
printf("2. Piattos - 16 PHP\n");
printf("3. Coca-Cola - 40 PHP\n");
printf("4. Sting Energy Drink - 25 PHP\n");
printf("5. Gatorade - 43 PHP\n");
printf("6. Nature Spring 500mL - 10 PHP\n");
printf("7. KitKat - 30 PHP\n");
printf("8. Snickers - 44 PHP\n");
printf("9. Oishi Prawn Crackers - 7 PHP\n");
printf("10. M&M's - 80 PHP\n");
printf("Enter 0 to finish.\n");
printf("\nProduct Quantity Price\n");
printf("----------------------------------------\n");
do
{
int choice = 0;
printf("Enter your choice: ");
scanf(" %d", &choice);
while ( getchar() != '\n' );
if (choice == 0 || choice > 10)
{
break;
}
printf("Enter the quantity: ");
scanf(" %d", &quantity);
switch (choice)
{
case 1:
printf("Oishi Prawn Crackers %d %d\n", quantity, price = 7 * quantity);
total += 7 * quantity;
break;
case 2:
printf("Piattos %d %d\n", quantity, price = 16 * quantity);
total += 15 * quantity;
break;
case 3:
printf("Coca-Cola %d %d\n", quantity, price = 40 * quantity);
total += 40 * quantity;
break;
case 4:
printf("Sting Energy Drink %d %d\n", quantity, price = 25 * quantity);
total += 25 * quantity;
break;
case 5:
printf("Gatorade 500mL %d %d\n", quantity, price = 43 * quantity);
total += 43 * quantity;
break;
case 6:
printf("Nature Spring 500mL %d %d\n", quantity, price = 10 * quantity);
total += 10 * quantity;
break;
case 7:
printf("KitKat %d %d\n", quantity, price = 30 * quantity);
total += 30 * quantity;
break;
case 8:
printf("Snickers %d %d\n", quantity, price = 44 * quantity);
total += 44 * quantity;
break;
case 9:
printf("M&M's %d %d\n", quantity, price = 40 * quantity);
total += 40 * quantity;
break;
case 10:
printf("Pringles %d %d\n", quantity, price = 80 * quantity);
total += 80 * quantity;
break;
default:
printf("Invalid choice.\n");
break;
}
} while (choice != 0);
printf("----------------------------------------\n");
printf("Total cost: %d PHP\n", total);
printf("Thank you for shopping with us!\n");
printf("\nWant to Buy Again?\n");
printf("Y if Yes\n");
printf("Type any key if No\n");
scanf(" %c", &end);
switch (end) {
case 'Y':
printf("\nOK!\n");
break;
default:
printf("\nBYE!\n");
break;
}
} while (end == 'Y');
return 0;
}

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

Check for bad practices/improvements

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

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