Summing elements from a copied array in c++ - c++

I've written a program that creates a restaurant menu through a text file, is opened up in another program and used to create a customer order.
I have a function which is needed to create the total amount at the end however the total sum is never produced, the program instead produces the total from itemPrice * itemQuantity and prints that instead of summing the final total.
I have the items saved in the menuItem array and am trying to copy them into a billingItems array to sum the prices in parallel. What step am I missing in order for total to sum up the prices, so total at the bottom would equal 44 (16+28) ?
Thank you
Creating the order in main():
int main(){
int i;
Item billingItem[MAX_ORDER];
Item menuItem[MAX_ORDER];
int itemNumber;
int itemQuantity;
int billOpt;
std::ofstream transactionFile;
transactionFile.open("transactionFile.txt");
int count = 0;
for(i = 0; i < MAX_ORDER; i++) {
std::cout << "Item number: ";
std::cin >> itemNumber;
i = itemNumber - 1;
std::cout << "Quantity: ";
std::cin >> itemQuantity;
menuItem[i].saveItemDetails(transactionFile);
std::cout << "\nWould you like to add another item?" << std::endl;
std::cout << "1. Yes\n2. No" << std::endl;
std::cin >> billOpt;
if (billOpt <= 0 | billOpt > 2) {
std::cout << "Error. Please enter a valid number: ";
std::cin >> billOpt;
}
if(billOpt == 2) { break; }
}
billingItem[i] = menuItem[i];
billingItem[i].calculateVAT(count, itemQuantity);
transactionFile.close();
the function within the implementation file:
void Item::calculateVAT(int count, int itemQuantity){
double total = 0.0;
double newItemPrice;
newItemPrice = itemPrice * itemQuantity;
total = newItemPrice + total;
//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
}
what is produced when running the program:
Item: 2| Category: Meat| Description: Pork Chops| Price: £8
COUNT3
ITEM QUANTITY2
TOTAL16
Item: 3| Category: Meat| Description: Ribs| Price: £14
COUNT4
ITEM QUANTITY2
TOTAL28

You could declare total as static in the function so it is only initialized once.
void Item::calculateVAT(int count, int itemQuantity){
static double total = 0.0;
double newItemPrice;
newItemPrice = itemPrice * itemQuantity;
total += newItemPrice ; //
//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
}
Another solution would be to declare a total variable in the main and modify your function signature.
That would imply printing total from your main.
calculateVAT function :
double Item::calculateVAT(int count, int itemQuantity)// No more void
{
double total = 0.0; // this one only serves in the function scope
double newItemPrice;
newItemPrice = itemPrice * itemQuantity;
total = newItemPrice + total;
//extra couts to see what is happening
std::cout << "ITEM QUANTITY" << itemQuantity <<"\n";
std::cout << "TOTAL" << total <<"\n";
return total; // this number will add up in the main
}
Your main :
int main(){
int i;
Item billingItem[MAX_ORDER];
Item menuItem[MAX_ORDER];
int itemNumber;
int itemQuantity;
int billOpt;
double total = 0.0; // this here will serve as the sum of all your items prices
std::ofstream transactionFile;
transactionFile.open("transactionFile.txt");
int count = 0;
for(i = 0; i < MAX_ORDER; i++) {
std::cout << "Item number: ";
std::cin >> itemNumber;
i = itemNumber - 1;
std::cout << "Quantity: ";
std::cin >> itemQuantity;
menuItem[i].saveItemDetails(transactionFile);
std::cout << "\nWould you like to add another item?" << std::endl;
std::cout << "1. Yes\n2. No" << std::endl;
std::cin >> billOpt;
if (billOpt <= 0 | billOpt > 2) {
std::cout << "Error. Please enter a valid number: ";
std::cin >> billOpt;
}
if(billOpt == 2) { break; }
}
billingItem[i] = menuItem[i];
total += billingItem[i].calculateVAT(count, itemQuantity); // modified here``
std::cout << "TOTAL" << total << std::endl;
transactionFile.close();
For reference, I have made a simple code with a basic situation :
void calculateVAT(int count, int itemQuantity) { // Static version, is initialized only once and then only gets updated
static double total = 0;
double newItemPrice;
newItemPrice = 10 * itemQuantity;
total += newItemPrice ;
//extra couts to see what is happening
std::cout << "ITEM QUANTITY " << itemQuantity << "\n";
std::cout << "TOTAL from function " << total << "\n";
}
double d_calculateVAT(int count, int itemQuantity) { // Non void version, returns a sum to a variable in the main
double sum = 0;
double newItemPrice;
newItemPrice = 10 * itemQuantity;
sum += newItemPrice;
return sum;
}
int main()
{
int itemQty = 5;
double sum = 0; // if you want to call it from the main
calculateVAT(0, 4); // void version with static - will update its total variable as 40
calculateVAT(0, 7); // void version with static - will update its total variable as 40 + 70 = 110
sum+=d_calculateVAT(0, 4); // double version - will return sum = 40
sum+=d_calculateVAT(2, 7); // double version - will return sum + 70 = 110
std::cout << "TOTAL from main " << sum << std::endl;
while (1)
{ }
return 0;
}
Also, maybe it's for another purpose, but I don't see the point of the variable "count" sent to calculateVAT, it's not used in the function.

Related

Why am I getting the wrong numbers when putting them in a loop?

I am a beginner programmer specially with functions, my "sum" variable keeps returning ridiculous numbers like 32864 when the numbers that were entered were no more than 100, I tried deleting the if statement in the getgrade function but it doesnt seem to help, help me please.
my code goes like this:
#include <iostream>
void displayIntro();
int getGrade();
int finalAverage(int, int);
int main()
{
int grade, sum, numbOfTests, average;
displayIntro();
for (grade; grade != -1; numbOfTests++)
{
grade = getGrade();
sum = sum + grade;
std::cout << sum << std::endl;
}
average = finalAverage(sum, numbOfTests);
std::cout << "Exam average, including extra credit, "
<< "is: " << average << std::endl;
return 0;
}
void displayIntro()
{
std::cout << "This program will calculate the average(%) of "
<< "exam grades." << std::endl;
std::cout << "It will also add extra credit points to the exam "
<< "average given the course difficulty." << std::endl;
std::cout << "Enter all of the grades for one student. Type (-1) "
<< "when finished with that student." << std::endl;
std::cout << "If you have additional students, you will be prompted"
<< " to repeat the program at the end." << std::endl;
}
int getGrade()
{
int userGrade = 0;
std::cout << "Enter an exam grade (type -1 to quit):" << std::endl;
std::cin >> userGrade;
if (userGrade == -1)
exit;
return userGrade;
}
int finalAverage(int runningSum, int counter)
{
int final;
final = (runningSum / counter) + 3;
return final;
}
You used the value of sum, grade, and numbOfTests without initializing them. Add initialization like this:
int main()
{
int grade, sum, numbOfTests, average;
displayIntro();
sum = 0; // initialization of sum
numbOfTests = 0; // initialization of numOfTests
// initialization of grade
for (grade = 0; grade != -1; numbOfTests++)
{
Instead of this, you can include initialization in the declaration of variables:
int main()
{
// add "=" plus value for used in initialization to initialize variables
int grade = 0, sum = 0, numbOfTests = 0, average;
displayIntro();

assigning a function's output to variables in other function C++

I wrote a code to manage a coffee machine,
I have a function findC that finds the cheapest capsule in the capsule array
a different function of mine findVP that is supposed to use the findC function's output as variables. however, when I pass the variables mp, ind = findC(prices_copy, quantities_copy, SIZE);
and print them it passes them as 0;
but the 2nd cout : cout << findC(prices_copy, quantities_copy, SIZE); prints the correct output.
why is this ? and how can I pass the output of the function to another
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
// Example program
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
#define SLEEVE 10
#define SIZE 10
#define N 5
#define BUDGET 70
//int CapsuleKind[10] = {"JOE","MAC","NES","jamaica","brazil","columbia","MOJO","CLUB","JHON","COF"};
float findMostExpensiveCapsule( float prices[], int size ) // 1
{
float max = prices[0];
int count = 0;
for(int i = 1; i < size; i++)
{
if (prices[i] > max)
{
max = prices[i];
}
}
cout << "The maximum price " << max << " is found on indexes: " ;
for (int i = 0; i < size; i++)
{
if (prices[i] == max)
{
cout << i << " ";
count++;
}
}
cout << endl;
cout << "The maximum number appears " << count << " times." << endl;
return max;
}
int findStrongestCapsuleInStock( int quantities[], int size, int sleeve ) // 2
{
return 0;
}
void SellCapsules( int quantities[], int Qty, int index) // 10
{
quantities[index] = quantities[index] - Qty;
cout << "SOLD " << Qty << " capsules to the Customer, the total now is: " << quantities[index] << endl;
}
float findC( float prices[],int quantities[], int size ) // 9
{
float min = 99999;
int count = 0;
float index=0;
//sort(prices, arr + n);
for(int i = 0; i < size; i++)
{
if (quantities[i] >= SLEEVE)
{
if(prices[i] < min){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
return min, index;
}
void findCheapestSleeve( float prices[],int quantities[], int size )
{
float min = prices[0];
int count = 0;
int index=0;
for(int i = 0; i < size; i++)
{
if (prices[i] < min)
{
if(quantities[i] > SLEEVE){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
}
void showAllCapsulesInStock( int quantities[], float prices[], int size, int sleeve) // 3
{
for (int i = 0; i < size; i++)
{
cout << "capsule kind: " << i << " ---- sleeves available : " << (quantities[i]/sleeve) << " ---- price(for 1 sleeve): " << (prices[i]*sleeve)<< endl;
}
}
float findVP( float prices[], int quantities[], int size, float nis, int sleeve ) //4
{
float mp=0;
float ind =0;
float prices_copy[size];
int quantities_copy[size];
for(int i=0; i<size; i++){
prices_copy[i] = prices[i];
quantities_copy[i] = quantities[i];
}
mp, ind = findC(prices_copy, quantities_copy, SIZE);
cout << "The lowest price sleeve is: " << mp * 10 << " --- the capsule kind is: " << ind <<endl;
cout << findC(prices_copy, quantities_copy, SIZE);
}
void findValueForMoneyPackage( float prices[], int quantities[], int size, float nis, int sleeve )
{
int sleeve_num[size];
float sleeve_price[size];
float min=0;
int index = 0;
int counter=0;
float quant = 0;
for (int i=0; i < size; i++)
{
sleeve_num[i] = (quantities[i]/sleeve);
sleeve_price[i] = (prices[i] * sleeve);
}
//min, quant = findCheapestSleeve(sleeve_price, quantities, 10);
cout << "the cheapest sleeve costs : " << min << " and its of kind :" << quant << endl;
}
void addMoreCapsules( int quantities[], int size ) // 5
{
char answer;
int plus;
for (int i = 0; i < size; i++)
{
cout << "do you want to add capsules to capsule kind " << i << "? (Y/N) " << endl;
cin >> answer;
if (answer == 'Y')
{
cout << "How many capsules do you want to add (inter a number) " << endl;
cin >> plus;
if (plus > 0)
{
quantities[i] = quantities[i] + plus;
cout << "Added " << plus << " capsules to the inventory, the total now is: " << quantities[i] << endl;
}
}
else
{
continue;
}
}
}
// Driver Code
int main()
{
bool flag = false;
int option;
float prices[] = { 1.2, 2.2, 2.5, 1.7, 2.2, 3, 2.8, 2.5, 2.9, 3.7 };
int quantities[] = { 14, 22, 25, 13, 22, 33, 50, 60, 33, 25 };
while (flag != true)
{
cout << "Please choose an option , has to be a number 1-6" << endl;
cin >> option;
if (option == 1)
{
findMostExpensiveCapsule(prices,SIZE);
}
else if ( option == 3)
{
showAllCapsulesInStock(quantities, prices, SIZE, 10);
}
else if (option == 4){
findVP(prices, quantities, SIZE, BUDGET, SLEEVE);
}
else if(option == 5){
addMoreCapsules(quantities,SIZE);
}
else if(option == 9){
findC(prices, quantities, SIZE);
}
else
{
flag = true;
}
}
cout << "GoodBye!" << endl;
return 0;
}
This
return min, index;
doesn't do what you think it does. You obviously think it's going to return two values. But actually it just returns index.
This
mp, ind = findC(prices_copy, quantities_copy, SIZE);
doesn't do what you think it does. You obviously think it's going to assign the two returned values from findC to the variables mp and ind. But actually it's going to return the single value returned by findC to the variable ind and ignore mp.
If you want to know precisely what these constructs do then look up the comma operator, but I guess the moral of the story is that just because you can get some plausible looking code to compile it doesn't mean that it's going to do what you expected it to do.
So the real question is how to return two values from a function in C++. There are actually several possible approaches. Here's a question that reviews some of them, Returning multiple values from a C++ function.

How can I sort in descending order?

I'm trying to sort for the top and second top value of totalRevenue and its name. I've tried to sort them in descending order this way but I could not figure it out how to make it work. Can anyone please help me out?
First two entries:
1002 Hammer 23.65 203
1024 Nails 6.95 400
Here is the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Structure to hold statistics
struct Selling {
int productNumber;
string name;
double price;
int soldNumber;
double totalRevenue[];
};
int main()
{
ifstream statFile;
string productName;
double price;
int productNumber, soldNumber;
Selling *productArray[100];
Selling *aSelling;
int numProduct = 0;
int man = 0;
statFile.open("sales.txt");
while (numProduct < 100 && statFile >> productNumber >> productName >> price >> soldNumber)
{
Selling *aSelling = new Selling;
aSelling->productNumber = productNumber;
aSelling->name = productName;
aSelling->price = price;
aSelling->soldNumber = soldNumber;
aSelling->totalRevenue[] = aSelling->price * aSelling->soldNumber;
productArray[numProduct++] = aSelling;
//cout << aSelling->productNumber<< " " << aSelling->name << " " << aSelling->price << " " << aSelling->soldNumber << " " << aSelling->totalRevenue << endl;
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (aSelling->totalRevenue[i] > aSelling->totalRevenue[j]) {
man = aSelling->totalRevenue[i];
aSelling->totalRevenue[i] = aSelling->totalRevenue[j];
aSelling->totalRevenue[i] = man;
}
}
}
for (int i = 0; i < 2; i++) {
cout << "The top selling product is " << aSelling->name << "with total sales of " << aSelling->totalRevenue[i] << endl;
cout << "The second top selling product is " << aSelling->name << "with total sales of " << aSelling->totalRevenue[i - 1] << endl;
}
}
And there is an unexpected expression error at the line aSelling->totalRevenue[] = aSelling->price * aSelling->soldNumber; which I don't understand.
There is some confusion on the arrays to sort:
you should define totalRevenue as a double, not an array of doubles,
should be sort the first numProduct elements of the array productArray based on the criteria totalRevenue and name, the order is determined by the comparison operator used. Only compare the second criteria if the first criteria give equal values.
Here is a modified version:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Structure to hold statistics
struct Selling {
int productNumber;
string name;
double price;
int soldNumber;
double totalRevenue;
};
int compareSellings(const Selling *a, const Selling *b) {
// sort in decreasing order of totalRevenue
if (a->totalRevenue > b->totalRevenue) return -1; // a comes before b
if (a->totalRevenue < b->totalRevenue) return +1; // b comes before a
// sort in increasing order of name for the same totalRevenue
if (a->name < b->name) return -1; // a comes before b
if (a->name > b->name) return +1; // b comes before a
return 0;
}
int main() {
ifstream statFile;
string productName;
double price;
int productNumber, soldNumber;
Selling *productArray[100];
int numProduct = 0;
statFile.open("sales.txt");
while (numProduct < 100 && statFile >> productNumber >> productName >> price >> soldNumber) {
Selling *aSelling = new Selling;
aSelling->productNumber = productNumber;
aSelling->name = productName;
aSelling->price = price;
aSelling->soldNumber = soldNumber;
aSelling->totalRevenue = price * soldNumber;
productArray[numProduct++] = aSelling;
//cout << aSelling->productNumber<< " " << aSelling->name << " "
// << aSelling->price << " " << aSelling->soldNumber << " "
// << aSelling->totalRevenue << endl;
}
for (int i = 0; i < numProduct; i++) {
for (int j = 0; j < numProduct; j++) {
if (compareSellings(productArray[i], productArray[j]) > 0) {
Selling *aSelling = productArray[i];
productArray[i] = productArray[j];
productArray[j] = aSelling;
}
}
}
cout << "The top selling product is " << productArray[0]->name
<< ", with total sales of " << productArray[0]->totalRevenue << endl;
cout << "The second selling product is " << productArray[1]->name
<< ", with total sales of " << productArray[1]->totalRevenue << endl;
return 0;
}
Further remarks:
you might use a more efficient sorting method
you should free the allocated objects
you should use <algorithms> and dynamic arrays of objects instead of allocating the objects with new and manipulating naked pointers.
you should handle exceptions

Printing a receipt using parallel arrays c++

I have been given this assignment for a lab project, and I have everything working until it gets to the receipt part. The issues I am having are 1) printing the incorrect menu items ordered, and 2) getting -42........ number for the pricing. I've looked through this several times and have spoken with others in the class. This is where we are ALL having issues. My TA said to use array[array1[counter]] for this section, but it doesn't seem to work. Can you help me focus on where things are seriously incorrect?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
const int NUM_MENU_ITEMS = 10; // num items on the menu
const int MAX_ORDER_ITEMS = 5; // max num of items per order
const double DISCOUNT_MIN = 20.00; // min subtotal to get discount
const double DISCOUNT_RATE = 0.25; // disc rate for highest-priced item
// Menu: parallel constant arrays
const string menuItem[NUM_MENU_ITEMS] = {
"Burger", "Hot Dog", "Chicken Fingers", "Fries",
"Tots", "Tea", "Coke", "Diet Coke", "Water", "Cookies" };
const double menuPrice[NUM_MENU_ITEMS] = {
3.50, 2.75, 4.25, 2.50, 3.25,
1.00, 1.25, 1.25, 0.25, 2.50 };
int main()
{
// Order: parallel partial arrays of items ordered
// Each item has an item number, quantity ordered, and total price
// TODO: declare a list of item numbers
// TODO: declare a list of quantities
// TODO: declare a list of item prices (menu price X quantity)
// TODO: declare other variables as needed
double total, subtotal, discount;
// receipt line data
string recName;
int recQty;
int j = 0;
double recPrice;
// print menu
cout << "MENU:\n" << fixed << setprecision(2);
cout << "## Item Price\n";
cout << "-- --------------- -------\n";
// TODO: write a loop to print the menu
int i = 0;
int itemNumber[NUM_MENU_ITEMS] = {
0,1, 2, 3, 4, 5, 6, 7, 8, 9 };
while (i <= 9)
{
cout << setw(2) << itemNumber[i] << " " <<
left << setw(15) << menuItem[i] <<
right << " $ " << setw(5) << menuPrice[i] << endl;
i++;
}
cout << endl;
// get order
int counter = 0;
int itemQuantity[MAX_ORDER_ITEMS];
double itemPrice[MAX_ORDER_ITEMS];
int itemOrder[MAX_ORDER_ITEMS];
string itemName[MAX_ORDER_ITEMS];
do {
cout << "Enter quantity and menu item number (0 0 to end):\n";
cout << "Item 0: ";
cin >> itemQuantity[counter] >> itemOrder[counter];
itemOrder[counter] = itemNumber[counter];
itemPrice[counter] = menuPrice[itemOrder[counter]] *
itemQuantity[counter];
itemName[counter] = menuItem[itemOrder[counter]];
counter++;
} while (counter < MAX_ORDER_ITEMS && itemQuantity[counter] != 0);
// TODO: repeat inputs until quantity is 0 or MAX_ORDER_ITEMS exceeded
//{
// //TODO: add an item to the order parallel arrays
// cout << "Item " << menuItem[i] << ": ";
// cin >> itemQuantity[i] >> itemPrice[i];
//}
double maxItemPrice = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
if (itemPrice[counter] > maxItemPrice)
maxItemPrice = i;
}
// find the subtotal price
// TODO: use a loop to calculate the sum of all order prices
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[counter];
}
// discount highest order line by 25% when total > $20
if (subtotal >= DISCOUNT_MIN)
{
// TODO: add a loop to find the maximum item price
discount = DISCOUNT_RATE * maxItemPrice;
}
else
discount = 0;
// calculate the total price
total = subtotal - discount;
// print the receipt
cout << "\n----------------------------\n";
cout << "Item Qty Price\n";
cout << "--------------- --- -------\n";
// TODO: use a loop to print the lines of the receipt
i = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
recName = itemName[i];
recQty = itemQuantity[i];
recPrice = itemPrice[menuPrice[i]];
cout << left << setw(15) << recName << " "
<< right << setw(3) << recQty << " $"
<< setw(6) << recPrice << endl;
}
cout << "\nSubtotal: $" << setw(6) << subtotal << endl;
cout << "Discount: $" << setw(6) << discount << endl;
cout << "Total Price: $" << setw(6) << total << endl << endl;
system("pause");
return 0;
}
In this line in the do while loop:
} while (counter < MAX_ORDER_ITEMS && itemQuantity[counter] != 0);
you have already incremented counter so your while loop is checking a part of the
itemQuantity
array that has not been input yet.
Also, here
double maxItemPrice = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
if (itemPrice[counter] > maxItemPrice)
maxItemPrice = i;
}
counter is a variable used previously and has not been updated. What is counter representing, and what is i?
And again here,
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[counter];
}
Counter is still the same as it was left in the do while loop. Here it should be
subtotal = 0;
for (i = 0; i < MAX_ORDER_ITEMS; i++)
{
subtotal = subtotal + itemPrice[i];
}
Check array parameters closely and make sure what's written is doing what you want it to do. Best of luck!

Need help calculating AVG of array values (minus the lowest)

So I have succeeded in confusing the hell out of myself in doing this. I am trying to get it to calculate the average of the weights entered into the array minus the lowest weight in the array. I'm using functions and somewhere along the line I confused myself with passing variables. It would be much appreciated if someone could give me a pointer and tell me if I'm way off base or not. Also how would I compare the values entered to a validation code? I have a line commented out that I was fiddling with, but never got working.
#include <iostream>
using namespace std;
int getWeight();
int findLowest(int arrayWeight);
double calcAverage(int weight);
bool askToContinue();
int main(){
do{
int weights = getWeight();
double lowest = findLowest(weights);
double average = calcAverage(weights);
}
while(askToContinue());
}
int getWeight() {
//Variables
int weights[5]; //array
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
cin >> weights[counter];
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
return -1;
/*
do
{
//Gather user input of amount of discs
cout << "How many discs do you wish to purchase?" << endl;
cout << "Please enter a number between 1 and 1,000,000" << endl;
cin >> weights;
cout << endl;
validAmount = (weights > 5) && (weights <= 500); // Tests if the amount entered is valid
if (!validAmount) // Prompts user amount entered was invalid
{
cout << "Invalid Amount. Please try again!" << endl;
}
}
while(!validAmount); // Runs loop again if the amount entered was not valid
return discs;
*/
}
int findLowest(int arrayWeight){
int lowWeight = 999999;
if(lowWeight > arrayWeight)
{
lowWeight = arrayWeight;
}
cout << arrayWeight;
system("PAUSE");
return arrayWeight;
}
double calcAverage(int weight){
//Variables
float avgWeight = 0;
int sumWeight = 0;
//Calls findLowest function to find lowest value
int lowestWeight = findLowest(weight);
//Calculates the average score
return weight;
}
bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits.
{
char userResponse = ' ';
bool validInput = false;
do
{
cout << endl;
cout << "Do you wish to continue?" << endl;
cout << "Enter y for 'yes' or n for 'no'" << endl;
cin >> userResponse;
validInput = (userResponse == 'y') || (userResponse == 'n');
if (!validInput)
{
cout << "Invalid response. Please try again!" << endl;
}
} while (!validInput);
return(userResponse == 'y');
}
You have a number of issues, the first being you need to understand the data types you're working with. You should declare the array once and then pass around a pointer to that array. These are a better set of declarations and for convenience set up a constant for the number of weights.
#include <iostream>
using namespace std;
const int numWeights = 5;
void getWeights(int weights[]);
int findLowest(int weights[]);
double calcAverage(int weights[]);
bool askToContinue();
int main() {
do {
int weights[numWeights];
getWeights(weights);
double average = calcAverage(weights);
cout << "Average: " << average << endl;
}
while (askToContinue());
}
getWeights was mostly ok, but use the passed in array.
void getWeights(int weights[]) {
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
int weight;
cin >> weight;
while (weight < 5 || weight > 500)
{
cout << "Invalid weight, should be between 5 and 500" << endl;
cin >> weight;
}
weights[counter] = weight;
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
}
For findLowest you need to keep track of the lowest value and the lowest index. By remembering the index of the lowest value, you will make the average easier. Your 99999 magic number isn't needed since we know there will always be a lowest value in your set. Start with index 0 and the first value. If you find something smaller, update the value and index. When the loop ends you'll have the first index of the lowest value. Note that the loops starts at 1 (the second item).
int findLowest(int weights[]) {
int lowestVal = weights[0];
int lowestIndex = 0;
for (int i=1; i<numWeights; i++) {
if (weights[i] < lowestVal) {
lowestVal = weights[i];
lowestIndex = i;
}
}
return lowestIndex;
}
For the average find the lowest index, add up all the weights but skip the index of the lowest, convert to double so you can get a good average and return the value.
double calcAverage(int weights[]) {
int lowestIndex = findLowest(weights);
int total = 0;
for (int i=0; i<numWeights; i++) {
if (i != lowestIndex) {
total += weights[i];
}
}
return (double)total/(double)(numWeights-1);
}