C Programming:
I am working on the problem below and have got all of the code down, except for one part I can't figure out.
The logic for the calculation where the the total at each shop is giving after each iteration of the loop.
this is the formula I've got:
ingredientPrice += ingredient1;
It calculates the total for the first shop properly, but for the shops that follow it gives a cumulative total rather than the singular total for shops #2, 3, 4 etc.
I hope I am clear enough, hoping someone can help me with the formula
Prompt:
Your mentor has tasked you with going to several different stores to place orders. This program should ask for the total number of shops that will be visited. At each shop, ask for the number of ingredients that need to be purchases. For each ingredient, ask for the price. Keep track of the total for the order so that you can write it down before leaving the shop. This program should also track with order was the cheapest and which shop the cheapest order was at. This will help your mentor decide who to keep doing business with!
Sample Run:
How many shops will you be visiting?
3
You are at shop #1.
How many ingredients do you need at shop #1?
2
How much is ingredient #1?
3.5
How much is ingredient #2?
10
Your total at shop #1 is $13.50.
You are at shop #2.
How many ingredients do you need at shop #2?
3
How much is ingredient #1?
2.75
How much is ingredient #2?
3
How much is ingredient #3?
1.25
Your total at shop #2 is $7.00.
You are at shop #3.
How many ingredients do you need at shop #3?
2
How much is ingredient #1?
4
How much is ingredient #2?
5
Your total at shop #3 is $9.00.
Your cheapest order was at shop #2 and cost $7.00.
Here is the code for you:
#include <stdio.h>
int main()
{
int numOfShops;
printf("How many shops will you be visiting? ");
scanf("%d", &numOfShops);
float subTotal = 0;
float cheapestTotal = 0;
float ingredient;
int cheapestShopIndex = 1;
int numOfIngredients;
for(int i = 1; i <= numOfShops; i++)
{
printf("You are at shop #%d.\n", i);
printf("How many ingredients do you need at shop #%d? ", i);
scanf("%d", &numOfIngredients);
subTotal = 0;
for(int j = 1; j <= numOfIngredients; j++)
{
printf("How much is ingredient #%d? ", j);
scanf("%f", &ingredient);
subTotal += ingredient;
}
if(i == 1)
cheapestTotal = subTotal;
if(subTotal < cheapestTotal)
{
cheapestTotal = subTotal;
cheapestShopIndex = i;
}
printf("Your total at shop #1 is $%.2f.\n", subTotal);
}
printf("Your cheapest order was at shop #%d and cost $%.2f.\n",
cheapestShopIndex, cheapestTotal);
}
And the output screenshot is:
Get Answers For Free
Most questions answered within 1 hours.