How to display the all the input string from if else statement? - c

At the end of the program before stating the total cost, I would like the program to list the Item chosen by the user.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct menuDetails {
double total, priceA, priceB, priceC, priceD, priceE, priceF;
} md;
int main()
{
int itemTotal, itemName, itemAll;
int sum=0;
char item;
char itemA[10]= "Nasi Ayam";
char itemB[20]= "Nasi Ayam Merah";
char itemC[15]= "Nasi Kerabu";
char itemD[10]= "Sotong";
char itemE[10]= "Teh Peng";
char itemF[5]= "Kopi";
printf("\t========= Menu =========\n");
printf("Item \t Name \t\t\t Price (RM)\n");
printf("A \t Nasi Ayam \t\t 3.50\n");
printf("B \t Nasi Ayam Merah \t 4.00\n");
printf("C \t Nasi Kerabu \t\t 5.50\n");
printf("D \t Sotong \t\t 2.00\n");
printf("E \t Teh Peng \t\t 2.00\n");
printf("F \t Kopi \t\t\t 2.00\n");
printf("\nHow many items would you like to purchase: ");
scanf("%d", &itemTotal);
printf("You have chose to order %d items\n\n", itemTotal);
for(itemName = 1; itemName <= itemTotal; itemName++)
{
printf("Item %d [Enter Item (A-F)]: ", itemName);
scanf(" %c", &item);
md.priceA = 3.50;
md.priceB = 4.00;
md.priceC = 5.50;
md.priceD = 2.00;
md.priceE = 2.00;
md.priceF = 2.00;
if (item == 'A' || item == 'a') {
printf("%s = RM%.2f\n\n", itemA, md.priceA);
md.total = md.total + md.priceA;
}else if (item == 'B' || item == 'b') {
printf("%s = RM%.2f\n\n", itemB, md.priceB);
md.total = md.total + md.priceB;
}else if (item == 'C' || item == 'c') {
printf("%s = RM%.2f\n\n", itemC, md.priceC);
md.total = md.total + md.priceC;
}else if (item == 'D' || item == 'd') {
printf("%s = RM%.2f\n\n", itemD, md.priceD);
md.total = md.total + md.priceD;
}else if (item == 'E' || item == 'e') {
printf("%s = RM%.2f\n\n", itemE, md.priceE);
md.total = md.total + md.priceE;
}else if (item == 'F' || item == 'f') {
printf("%s = RM%.2f\n\n", itemF, md.priceF);
md.total = md.total + md.priceF;
}
}
printf("The total is RM%.2f", md.total);
time_t my_time = time(NULL);
printf("\nDate: %s", ctime(&my_time));
return 0;
}
The output:
========= Menu =========
Item Name Price (RM)
A Nasi Ayam 3.50
B Nasi Ayam Merah 4.00
C Nasi Kerabu 5.50
D Sotong 2.00
E Teh Peng 2.00
F Kopi 2.00
How many items would you like to purchase: 3
You have chose to order 3 items
Item 1 [Enter Item (A-F)]: a
Nasi Ayam = RM3.50
Item 2 [Enter Item (A-F)]: b
Nasi Ayam Merah = RM4.00
Item 3 [Enter Item (A-F)]: c
Nasi Kerabu = RM5.50
The total is RM13.00
Date: Thu Dec 29 17:02:49 2022
Expected output:
========= Menu =========
Item Name Price (RM)
A Nasi Ayam 3.50
B Nasi Ayam Merah 4.00
C Nasi Kerabu 5.50
D Sotong 2.00
E Teh Peng 2.00
F Kopi 2.00
How many items would you like to purchase: 3
You have chose to order 3 items
Item 1 [Enter Item (A-F)]: a
Nasi Ayam = RM3.50
Item 2 [Enter Item (A-F)]: b
Nasi Ayam Merah = RM4.00
Item 3 [Enter Item (A-F)]: c
Nasi Kerabu = RM5.50
Receipt:
Nasi Ayam
Nasi Ayam Merah
Nasi Kerabu
The total is RM13.00
Date: Thu Dec 29 17:02:49 2022
I want to display the list of item chosen by the user.

You could do this by adding a couple more arrays, and creating a for loop to print out the reciept.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_ITEMS 10
struct menuDetails {
double total, priceA, priceB, priceC, priceD, priceE, priceF;
} md;
int main()
{
int itemTotal, itemName, itemAll;
int sum=0; // you can remove this, it is unused
char item;
char itemA[10]= "Nasi Ayam";
char itemB[20]= "Nasi Ayam Merah";
char itemC[15]= "Nasi Kerabu";
char itemD[10]= "Sotong";
char itemE[10]= "Teh Peng";
char itemF[5]= "Kopi";
// arrays to store the chosen items and their quantities
char chosenItems[MAX_ITEMS];
int quantities[MAX_ITEMS];
int numChosenItems = 0;
printf("\t========= Menu =========\n");
printf("Item \t Name \t\t\t Price (RM)\n");
printf("A \t Nasi Ayam \t\t 3.50\n");
printf("B \t Nasi Ayam Merah \t 4.00\n");
printf("C \t Nasi Kerabu \t\t 5.50\n");
printf("D \t Sotong \t\t 2.00\n");
printf("E \t Teh Peng \t\t 2.00\n");
printf("F \t Kopi \t\t\t 2.00\n");
printf("\nHow many items would you like to purchase: ");
scanf("%d", &itemTotal);
printf("You have chose to order %d items\n\n", itemTotal);
for(itemName = 1; itemName <= itemTotal; itemName++)
{
printf("Item %d [Enter Item (A-F)]: ", itemName);
scanf(" %c", &item);
md.priceA = 3.50;
md.priceB = 4.00;
md.priceC = 5.50;
md.priceD = 2.00;
md.priceE = 2.00;
md.priceF = 2.00;
// store chosen item and the quantity in array
if (item == 'A' || item == 'a') {
printf("%s = RM%.2f\n\n", itemA, md.priceA);
md.total = md.total + md.priceA;
chosenItems[numChosenItems] = 'A';
quantities[numChosenItems] = 1;
numChosenItems++;
}else if (item == 'B' || item == 'b') {
printf("%s = RM%.2f\n\n", itemB, md.priceB);
md.total = md.total + md.priceB;
chosenItems[numChosenItems] = 'B';
quantities[numChosenItems] = 1;
numChosenItems++;
}else if (item == 'C' || item == 'c') {
printf("%s = RM%.2f\n\n", itemC, md.priceC);
md.total = md.total + md.priceC;
chosenItems[numChosenItems] = 'C';
quantities[numChosenItems] = 1;
numChosenItems++;
}else if (item == 'D' || item == 'd') {
printf("%s = RM%.2f\n\n", itemD, md.priceD);
md.total = md.total + md.priceD;
chosenItems[numChosenItems] = 'D';
quantities[numChosenItems] = 1;
numChosenItems++;
}else if (item == 'E' || item == 'e') {
printf("%s = RM%.2f\n\n", itemE, md.priceE);
md.total = md.total + md.priceE;
chosenItems[numChosenItems] = 'E';
quantities[numChosenItems] = 1;
numChosenItems++;
}else if (item == 'F' || item == 'f') {
printf("%s = RM%.2f\n\n", itemF, md.priceF);
md.total = md.total + md.priceF;
chosenItems[numChosenItems] = 'F';
quantities[numChosenItems] = 1;
numChosenItems++;
}
}
printf("The total is RM%.2f\n\n", md.total);
// Print out the receipt
printf("===== Receipt =====\n");
for (int i = 0; i < numChosenItems; i++) {
if (chosenItems[i] == 'A') {
printf("%d x %s\n", quantities[i], itemA, md.priceA);
} else if (chosenItems[i] == 'B') {
printf("%d x %s\n", quantities[i], itemB, md.priceB);
} else if (chosenItems[i] == 'C') {
printf("%d x %s\n", quantities[i], itemC, md.priceC);
} else if (chosenItems[i] == 'D') {
printf("%d x %s\n", quantities[i], itemD, md.priceD);
} else if (chosenItems[i] == 'E') {
printf("%d x %s\n", quantities[i], itemE, md.priceE);
} else if (chosenItems[i] == 'F') {
printf("%d x %s\n", quantities[i], itemF, md.priceF);
}
}
printf("Total \t\t\t RM%.2f\n", md.total);
time_t my_time = time(NULL);
printf("Date: %s", ctime(&my_time));
return 0;
}
Output:
========= Menu =========
Item Name Price (RM)
A Nasi Ayam 3.50
B Nasi Ayam Merah 4.00
C Nasi Kerabu 5.50
D Sotong 2.00
E Teh Peng 2.00
F Kopi 2.00
How many items would you like to purchase: 3
You have chose to order 3 items
Item 1 [Enter Item (A-F)]: a
Nasi Ayam = RM3.50
Item 2 [Enter Item (A-F)]: b
Nasi Ayam Merah = RM4.00
Item 3 [Enter Item (A-F)]: c
Nasi Kerabu = RM5.50
The total is RM13.00
===== Receipt =====
1 x Nasi Ayam
1 x Nasi Ayam Merah
1 x Nasi Kerabu
Total RM13.00
Date: Thu Dec 29 11:11:24 2022

If you want to list the items stored by the user, and want to allow the user to order the same thing more than once, then one thing you could do is to add an extra counter variable for every menu item. Or even better, make an array, which I call item_counters in the code below:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
struct menu_item
{
const char *name;
double price;
};
#define NUM_MENU_ITEMS 6
static const struct menu_item menu_items[NUM_MENU_ITEMS] = {
{ "Nasi Ayam", 3.50 },
{ "Nasi Ayam Merah", 4.00 },
{ "Nasi Kerabu", 5.50 },
{ "Sotong", 2.00 },
{ "Teh Peng", 2.00 },
{ "Kopi", 2.00 }
};
int main( void )
{
int total_items;
int item_counters[NUM_MENU_ITEMS] = {0};
double total_cost = 0.0;
//print the menu using a loop
printf("\t========= Menu =========\n");
printf("Item Name Price (RM)\n");
for ( int i = 0; i < NUM_MENU_ITEMS; i++ )
{
printf(
"%-8c %-22s %lf\n",
'A'+i, menu_items[i].name, menu_items[i].price
);
}
printf( "\nHow many items would you like to purchase: ");
if ( scanf( "%d", &total_items ) != 1 )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
printf( "You have chosen to order %d items.\n\n", total_items );
//ask user to select items
for( int i = 0; i < total_items; i++ )
{
char item;
//prompt user to select item
printf( "Item %d [Enter Item (A-%c)]: ", i, 'A'+(NUM_MENU_ITEMS-1) );
//attempt to read one character
if ( scanf( " %c", &item ) != 1 )
{
fprintf( stderr, "Input error!\n" );
exit( EXIT_FAILURE );
}
//make input upper-case, if it is lower-case
item = toupper( (unsigned char)item );
//verify that character is valid
if ( item < 'A' || item > 'A' + (NUM_MENU_ITEMS-1) )
{
printf( "Invalid input!\n" );
exit( EXIT_FAILURE );
}
//increment counter for selected item
item_counters[item-'A']++;
}
//print back the order to the user, and calculate total cost
printf( "\nYou ordered:\n" );
for ( int i = 0; i < NUM_MENU_ITEMS; i++ )
{
if ( item_counters[i] != 0 )
{
double total_cost_for_item;
total_cost_for_item = item_counters[i] * menu_items[i].price;
printf(
"%d %s for %lf\n",
item_counters[i], menu_items[i].name, total_cost_for_item
);
total_cost += total_cost_for_item;
}
}
//print total cost
printf( "\nThe total is RM%.2f\n", total_cost );
//print time
time_t my_time = time(NULL);
printf( "Date: %s\n", ctime(&my_time));
return 0;
}
This program has the following behavior:
========= Menu =========
Item Name Price (RM)
A Nasi Ayam 3.500000
B Nasi Ayam Merah 4.000000
C Nasi Kerabu 5.500000
D Sotong 2.000000
E Teh Peng 2.000000
F Kopi 2.000000
How many items would you like to purchase: 5
You have chosen to order 5 items.
Item 0 [Enter Item (A-F)]: a
Item 1 [Enter Item (A-F)]: b
Item 2 [Enter Item (A-F)]: c
Item 3 [Enter Item (A-F)]: a
Item 4 [Enter Item (A-F)]: d
You ordered:
2 Nasi Ayam for 7.000000
1 Nasi Ayam Merah for 4.000000
1 Nasi Kerabu for 5.500000
1 Sotong for 2.000000
The total is RM18.50
Date: Thu Dec 29 15:54:04 2022
Note that I have modified your program in such a way that you can easily change the number of items in the menu, and the program will automatically adapt. For example, I can simply change
#define NUM_MENU_ITEMS 6
to
#define NUM_MENU_ITEMS 7
and add one item to the list:
static const struct menu_item menu_items[NUM_MENU_ITEMS] = {
{ "Nasi Ayam", 3.50 },
{ "Nasi Ayam Merah", 4.00 },
{ "Nasi Kerabu", 5.50 },
{ "Sotong", 2.00 },
{ "Teh Peng", 2.00 },
{ "Kopi", 2.00 },
{ "Cheese Sandwich", 3.00 }
};
As you can see, the program will adapt itself automatically:
========= Menu =========
Item Name Price (RM)
A Nasi Ayam 3.500000
B Nasi Ayam Merah 4.000000
C Nasi Kerabu 5.500000
D Sotong 2.000000
E Teh Peng 2.000000
F Kopi 2.000000
G Cheese Sandwich 3.000000
How many items would you like to purchase: 5
You have chosen to order 5 items.
Item 0 [Enter Item (A-G)]: A
Item 1 [Enter Item (A-G)]: G
Item 2 [Enter Item (A-G)]: C
Item 3 [Enter Item (A-G)]: G
Item 4 [Enter Item (A-G)]: F
You ordered:
1 Nasi Ayam for 3.500000
1 Nasi Kerabu for 5.500000
1 Kopi for 2.000000
2 Cheese Sandwich for 6.000000
The total is RM17.00
Date: Thu Dec 29 16:00:03 2022
The menu output was automatically adapted and it now asks and accepts input from A to G instead of from A to F. That is the advantage of not hard-coding anything in your program, except in one place.
It is worth noting that this program assumes that the character codes
of the alphabet are stored consecutively in the character
set, which is the case for most character sets, including the ASCII character set. However, this may not be the case on some more exotic platforms. On those platforms, the code would not work.

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

Is there a way to handle spaces during output in table form for C lang?

This is my code and here I'm unable to manage the spaces in the header in my output when I was converting in table form.
Here is what I did :
#include <stdio.h>
int main()
{
int n;
printf("Enter no of students : ");
scanf("%d",&n);
int marks1[n], marks2[n],rollno[n];
float avg=0, total=0;
char name[5][10];
char grade;
for(int i=0; i<n; i++) {
printf("Enter name %d : ",(i+1));
scanf("%s",name[i]);
printf("Enter roll no : ");
scanf("%d",&rollno[i]);
printf("Enter Marks1 of student %d : ",(i+1));
scanf("%d",&marks1[i]);
printf("Enter marks2 of student %d : ",(i+1));
scanf("%d",&marks2[i]);
}
printf("\n Student Records \n");
printf("Name \t Roll No \t Marks1 \t Marks2 \t Total \t Avg \t Grade \n");
for(int i=0; i < n; i++) {
total = marks1[i] + marks2[i];
avg = (marks1[i] + marks2[i])/2;
if(avg >= 85) {
grade = 'S';
} else if (avg >=70 && avg < 85) {
grade = 'A';
} else if (avg < 70 && avg>=60) {
grade = 'B';
} else if (avg >= 50 && avg < 60) {
grade = 'C';
} else {
grade = 'F';
}
printf("%-8s | %-14d | %-14d | %-9d | %-7.2f | %-8.2f | %-7c\n", name[i], rollno[i], marks1[i], marks2[i], total, avg, grade);
avg=0;
total=0;
}
return 0;
}
Output:
Enter no of students : 1
Enter name 1 : raju
Enter roll no : 22
Enter Marks1 of student 1 : 78
Enter marks2 of student 1 : 98
Student Records
Name Roll No Marks1 Marks2 Total Avg Grade
raju | 22 | 78 | 98 | 176.00 | 88.00 | S
Is there any method to handle the spaces during Input ?
You are using tabs in your header, but explicit widths in the numerical output. It's up to the console how to print tabs. If you want more control over your output, use the same explicit widths for header and data.
For example:
// header
printf("%-8s | %-14s | %-14s | ...\n", "Name", "Roll No", "Marks");
// data rows
printf("%-8s | %-14d | %-14d | ...\n", name[i], rollno[i], marks[i]);

Having trouble detecting my mistake in my coding

I am still new to C programming and I am having a bit of a problem in my coding. I am aware that I can't just ask for help without trying to fix it by myself first, so I tried fixing it and is still having the same problem.
My problem is, my coding displayed an incorrect calculation like below.
ORDER PRICE SUMMARY
===========================================
Customer No. Total Order Price(RM)
===========================================
1 RM 40.00
2 RM 40.00
3 RM 478664371470163710000000000000000.00
===========================================
Grand Total RM 478664371470163710000000000000000.00
===========================================
Customer 1 and 2 showed the correct price but it just got messed up for Customer 3, which affects the grand total.
My coding is below, and it is obvious that I am using the simplest way of writing my code since my goal is to just answer a coding question.
#include <stdio.h>
float calculatePrice(char);
void main()
{
char comboType, addon;
int comboQty, addonQty,i=1,j=1;
float orderPrice = 0.00, comboPrice, addonPrice, grandPrice=0.00; // new float
float customerPayment[3], allPrice[3]; // declare array
printf ("--------------------------------------------------------------\n");
printf (" ~ SATAY RESTAURANT ~ \n");
printf ("--------------------------------------------------------------\n");
printf (" Combo Type Item Price (RM) \n");
printf ("--------------------------------------------------------------\n");
printf (" A 25 Chicken Stay + 25 Beef Satay 40.00\n");
printf (" B 30 Chicken Stay + 20 Mutton Satay 52.00\n");
printf (" C 10 Mutton Stay + 40 Beef Satay 46.00\n");
printf (" Add-On 1 Ketupat 0.60\n");
printf ("--------------------------------------------------------------\n");
for (j=0;j<3;j++)
{
printf("\n Customer %d\n",j+1);
printf("-------------");
printf("\n Enter Combo Type (A/B/C or X to end) : ");
scanf(" %c", &comboType);
while (comboType != 'X' && comboType != 'x') // start while loop
{
comboPrice = calculatePrice (comboType);
printf(" Order Price for Combo %c : RM%.2f \n ", comboType, comboPrice);
printf("\n Enter Combo Type (A/B/C or X to end) : ");
scanf(" %c", &comboType);
allPrice[j] += comboPrice;
}
printf("\n Add-On Ketupat (Y/N) : "); // if X, ask for add-on
scanf(" %c", &addon);
if (addon != 'N' && addon != 'n')
{
printf(" Enter Ketupat Quantity : ");
scanf("%d", &addonQty);
addonPrice = 0.60 * addonQty;
allPrice[j] += addonPrice;
printf(" Order price for Ketupat : RM%.2f\n",addonPrice);
}
printf("\n Total Order Price for Customer %d : RM%.2f\n\n",j+1, allPrice[j]);
customerPayment[j] = allPrice[j];
}
printf("\n\n\n\t ORDER PRICE SUMMARY ");
printf("\n===========================================");
printf("\n Customer No. Total Order Price(RM)");
printf("\n===========================================");
for (i = 0; i<3; i++)
{
printf("\n %d RM %.2f",i+1,customerPayment[i]);
grandPrice += customerPayment[i];
}
printf("\n===========================================");
printf("\n Grand Total RM %.2f",grandPrice);
printf("\n===========================================");
getch ();
}
float calculatePrice (char comboType)
{
float comboPrice, allPrice = 0.00;
int comboQty;
printf(" Enter Quantity : ");
scanf("%d", &comboQty);
if (comboType == 'A' || comboType == 'a')
{
comboPrice = 40.00 * comboQty;
}
if (comboType == 'B' || comboType == 'b')
{
comboPrice = 52.00 * comboQty;
}
if (comboType == 'C' || comboType == 'c')
{
comboPrice = 46.00 * comboQty;
}
return comboPrice;
}
It would be greatly appreciated if someone could help detecting my mistake.
At the beginning , you do not fill allPrice array with zeros, so you add to it what was left from memory.
Just at the start of your main, add allPrice[3] = {0, 0, 0}; and customerPayment[3] = {0, 0, 0};

Is there a function similar to string compare but for integers?

I want to allow the user to enter a variable amount, and then compare that amount to my array of percentages. And then display ALL amounts in my percentages array equal to OR greater than that number the user entered. I would also like to do this for a lower amount, but they should be the same I would think. If anyone can provide any insight I would appreciate it! Code will be attached underneath.. (Please let me know if I can clarify anything)
/*
10/31/2017
FOOTBALL STATS
*/
#include <stdio.h>
#define NUM_TEAM 30
#define LEN_NAME 40
void displayWelcome(void);
void calcPercent(double percentages[], int elements, int wins[], int losses[], int ties[]);
void showAll (char name[], char league[], char division[], int wins, int losses, int ties, double percentages);
void displayExit(void);
int main (void)
{
//Display welcome message
displayWelcome();
char name[NUM_TEAM][LEN_NAME] = {0};
char division[NUM_TEAM][LEN_NAME] = {0};
char league[NUM_TEAM][LEN_NAME] = {0};
char line[LEN_NAME];
char menu, again;
int wins[NUM_TEAM] = {0};
int losses[NUM_TEAM] = {0};
int ties[NUM_TEAM] = {0};
int i = 0, count, sum, percentQuery;
double percentages[NUM_TEAM] = {0};
;
FILE * filePtr;
filePtr = fopen("C:\\Users\\thoma\\NFLTeams.txt", "r");
if (filePtr == NULL)
{
printf("Unable to open file\n");
}
else
{
while (i < NUM_TEAM && fgets( line, sizeof(line), filePtr) != NULL)
{
sscanf(line, "%s%s%s%i%i%i",name[i], league[i], division[i], &wins[i], &losses[i], &ties[i]);
i++;
}
fclose(filePtr);
count = i;
}
//^ end reading in file
//Calculate win percentages
calcPercent( percentages, count, wins, losses, ties);
//Main menu loop
do
{
//Ask user how they would like to search
printf("Please choose an option from the following menu:"
"\n-Enter 'a' to display all information contained in the database"
"\n-OR Enter 'b' to search by league"
"\n-OR Enter 'c' to search by division"
"\n-OR Enter 'd' to search by wins above a certain percentage"
"\n-OR Enter 'e' to search by wins below a certain percentage: ");
scanf("\n%c", &menu);
//If user chooses a
if (menu == 'a')
{
//Display all of database
for (i = 0; i <= count - 1; i = i + 1)
{
showAll(name[i], league[i], division[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
//If user chooses b
else if (menu == 'b')
{
// Propmt user to choose AFC or NFC
printf("\nPlease choose from the following menu:\nEnter 'a' to search for teams in the AFC league \nOR enter 'b' to search for teams in the NFC league: ");
// scan for what the user entered
scanf("\n%c", &menu);
//Display option for AFC
if (menu == 'a')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (league[i], "AFC") == 0)
{
printf("Here are the standings for the teams in the AFC division:\n");
printf("Team Name: %s \nLeague: %s\nDivision: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], division[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else
//Display option for NFC
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (league[i], "NFC") == 0)
{
printf("Here are the standings for the teams in the NFC division:\n");
printf("Team Name: %s \nLeague: %s\nDivision: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], division[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
}
//If user chooses c
else if (menu == 'c')
{
printf("\nPlease choose an option from the following menu: \nEnter 'a' if you would like to search for North division standings\n"
"OR enter 'b' to search for East division standings\nOR enter 'c' to search for South division standings\nOR enter"
" 'd' to search for West division standings: ");
scanf("\n%c", &menu);
if (menu == 'a')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "North") == 0)
{
printf("Here are the standings for the teams in the North division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else if (menu == 'b')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "East") == 0)
{
printf("Here are the standings for the teams in the East division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else if (menu == 'c')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "South") == 0)
{
printf("Here are the standings for the teams in the South division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
else if (menu == 'd')
{
for (i = 0; i < count; i = i + 1 )
{
if (strcmp (division[i], "West") == 0)
{
printf("Here are the standings for the teams in the West division:\n");
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}
}
}
//if user chooses d
else if (menu == 'd')
{
/* UNFINISHED.. COULD NOT FIGURE OUT SYNTAX
My goal was to compare my percentages array to the value that the user inputted (which was stored in the variable 'percentQuery' and display values that were greater than or equal to my percent
Query
printf("In this menu, you may search for a win percentage above a certain amount.\n"
"Please enter the amount you would like to search ABOVE: ");
scanf("\n%d", &percentQuery);
for (i = 0; i < count; i = i + 1 )
{
//I could not figure out the syntax for comparing to see if it was greater than or equal to percentQuery
if (strcmp (percentages[i], percentQuery) == 0)
{
printf("Here are the standings for the teams with a win percent above %i%%"), percentQuery;
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}*/
}
//if user chooses e
else if (menu == 'e')
{
/* UNFINISHED.. COULD NOT FIGURE OUT SYNTAX
My goal was to compare my percentages array to the value that the user inputted (which was stored in the variable 'percentQuery' and display values that were less than or equal to my percent
Query
printf("In this menu, you may search for a win percentage below a certain amount.\n"
"Please enter the amount you would like to search BELOW: ");
scanf("\n%d", &percentQuery);
for (i = 0; i < count; i = i + 1 )
{
// I could not figure out the syntax for comparing to see if it was less than or equal to percentQuery
if (strcmp (percentages[i], percentQuery) == 0)
{
printf("Here are the standings for the teams with a win percent below %i%%"), percentQuery;
printf("Team Name: %s \nLeague: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name[i], league[i], wins[i], losses[i], ties[i], percentages[i]);
}
}*/
}
//Prompt user for replay of main menu
printf("\nWould you like to return to the main menu?\n"
"Enter (y)es or (n)o: ");
scanf("\n%c", &again);
}
while (again == 'y');
//whatever the user types in, strcmp to our data base and set it equal to that.
displayExit();
return 0;
}
void displayWelcome(void)
{
printf("Welcome to my Football Stats.\n\n");
}
void calcPercent(double percentages[], int count, int wins[], int losses[], int ties[])
{
int i, sum;
for (i = 0; i <= count -1; i = i + 1)
{
sum = wins[i] + losses[i] + ties[i];
percentages[i] = ((double) wins[i] / sum) * 100;
}
}
void showAll (char name[], char league[], char division[], int wins, int losses, int ties, double percentages)
{
printf("Team Name: %s \nLeague: %s\nDivision: %s\nWins: %i Losses: %i Ties: %i\nWin Rate: %.2lf%%\n\n", name, league, division, wins, losses, ties, percentages);
}
void displayExit(void)
{
printf("\nThese results were brought to you by.");
}
Just use the >= operator for "above or equal" and < for "below":
if (percentages[i] >= percentQuery) {
/* ... */
}
percentages is an array of doubles, not strings.

invalid conversion from 'char*' to 'char' [-fpermissive]

i want to make cashier program by C language. i using structure for record but the problem is when i try to display the receipt of payment by defined name of item detail[i].name and price detail.[i].price for looping, i got this message
[Error] invalid conversion from 'char*' to 'char' [-fpermissive]
this is my script
#include<stdio.h>
#include <stdlib.h>
struct item{
char name[10];
int price;
int barcode;
};
struct item detail[10]={
"item1",10,1,
"item2",20,2,
"item3",30,3,
"item4",40,4,
"item1",50,5,
"item2",60,6,
"item3",70,7,
"item4",80,8,
"item3",90,9,
"item4",100,10
};
int main(){
int ibarcode[10];int qty[10];char b[10];int price[10];int ju[10];int tot[10];
int j,i,k,grand;
char a;
printf("Cashier program\n");
for(j=0;j<10;j++){
printf("enter barcode : ");scanf("%d",&ibarcode[j]);
for(i=0;i<10;i++){
if(ibarcode[j]==detail[i].barcode){
printf("item name: %s\n",detail[i].name);
printf("price : %d\n",detail[i].price);
printf("Quantity : ");scanf("%d",&qty[j]);
tot[j]=detail[j].price*qty[j];
}
if(ibarcode[j] > 10){
printf("Barcode not valid\n");
j--;
break;
}
}
printf("\nDo you want to buy again? [Y/N] = ");scanf("%s", &a);
b[j] = detail[i].name;
ju[j] = detail[i].price;
if(a=='Y'||a=='y'){
continue;
} else {
break;
}
}
grand = 0; system("cls");
printf("\n name Kasir = Addzifi Moch G\n");
printf(" Tanggal = 03 januari 2017\n");
printf(" Jam = 14:05 WIB\n\n");
printf("+-------------------------------------------------------------------------------------------------+\n");
printf("| Barcode | name item\t\t\t| price \t\t| Quantity\t| Total |\n");
printf("+-------------------------------------------------------------------------------------------------+\n");
for(k=0; k<=j; k++){
grand += tot[k];
printf("| %d \t | %s\t | %d\t\t | %d\t\t\t| %d |\n", ibarcode[k], b[k], ju[k], qty[k], tot[k]);
}
printf("+-------------------------------------------------------------------------------------------------+\n");
printf("|\t\t\t\t\t\t\t Total Yang Harus Dibayarkan = %d |\n", grand);
printf("+-------------------------------------------------------------------------------------------------+\n");
}
I bet that happens on the line
b[j] = detail[i].name;
and that is because b is an array of characters and name is a string, so you want to assign to b[j], a char, a string.
use strcpy:
strcpy(b, detail[i].name);

Resources