Uninitialized local variable that is actually initialized? [duplicate] - c++

This question already has answers here:
How can I declare and define multiple variables in one line using C++?
(10 answers)
Comma as separator in variable initialization (not as operator)
(2 answers)
How does the Comma Operator work
(9 answers)
Closed 1 year ago.
I am writing a program that deals with values in an input file. My variables include total, taxtotal, subtotal, etc. & they have already been declared and initialized, yet I am getting two error messages: "uninitialized local variable 'subtotal' used" and the same for the variable "taxtotal".
Here is my source code:
#include "stdafx.h"
#include<stdio.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
ifstream shoppingBasketFile;
shoppingBasketFile.open("HW3_Data.txt");
bool isTaxed = false;
char taxValue = 0;
char inPrice[64];
char name[128];
double price, taxtotal, subtotal, total = 0;
if (shoppingBasketFile.is_open())
{
// display the header info:
cout << "o Thank you for shopping at StuffMart" << endl;
cout << setw(3) << left << "o "
<< setw(20) << left << "Item"
<< setw(12) << "Unit Price"
<< setw(4) << "Tax"
<< endl
<< "o -------------------------------------" << endl;
// parse the input file until end of file;
while (!shoppingBasketFile.eof())
{
// parse the item name:
shoppingBasketFile >> name;
cout << "Name = " << name << endl;
if (name == NULL)
{
// what should we really do here?
continue;
}
// parse the price:
shoppingBasketFile >> price;
if (price < 0 || price > 100000000000) {
continue;
}
cout << "Price = " << price << endl;
// parse the isTax flag:
shoppingBasketFile >> isTaxed;
shoppingBasketFile >> taxValue;
cout << "Is taxed? = " << taxValue << endl;
// if end of file break out of this loop:
if (!shoppingBasketFile.good()) break;
if (isTaxed == true) {
taxtotal = taxtotal + (.085 * price);
taxValue = 'Y';
}
else {
taxValue = 'N';
}
//display tax as Y instead of T/1
if (isTaxed == true) {
cout << "Tax: Y" << endl;
}
else {
cout << "Tax: N" << endl;
}
//compute the subtotals
subtotal = subtotal + price;
// display the item info:
cout << "name" << name << ", price: $" << price << ", is taxed: " << taxValue << endl;
// reset input values:
name, price, isTaxed = 0;
// end of while loop
}
//compute the final total:
total = subtotal + taxtotal;
//output the totals
cout << "o" << setw(37) << "---------------" << endl
<< "o " << setw(26) << "Subtotal $" << fixed << setprecision(2) << right << subtotal << endl
<< "o " << setw(26) << "Tax (8.5%) $" << fixed << setprecision(2) << right << taxtotal << endl
<< "o " << setw(26) << "Total $" << fixed << setprecision(2) << right << total << endl;
}
shoppingBasketFile.close();
return 0;
}
How can I eliminate these error messages? I am using Microsoft's Visual C++ compiler, if that matters.

In this declaration:
double price, taxtotal, subtotal, total = 0;
the type name double applies to all 4 variables, but the = 0 initialization applies only to total.
As others have said, the most direct fix is:
double price = 0, taxtotal= 0, subtotal = 0, total = 0;
but it's better style to declare each variable on its own line:
double price = 0.0;
double taxtotal = 0.0;
double subtotal = 0.0;
double total = 0.0;
Note that using 0 is perfectly valid (the int value will be implicitly converted to the double value 0.0), but using a floating-point constant is more explicit.
(I've chosen to align the initializers vertically. Some might prefer not to do that.)
I'm guessing you haven't gotten to pointers yet. When you do, you'll encounter another reason to declare each variable on its own line. This:
int* x, y, z;
defines x as an int*, but y and z as int. Using one declaration per line, as for the initializers above, avoids this opportunity for error and confusion:
int* x;
int* y;
int* z;
Once you get your code to compile, you'll have a problem with this line:
name, price, isTaxed = 0;
That's a valid statement, but it doesn't do what you think it does.
, is the comma operator. It evaluates its left and right operands in order, and yields the value of the right operand, discarding the value of the left operand. The statement evaluates and discards the current value of name, then evaluates and discards the current value of price, then assigns the value 0 to isTaxed. (Thanks to user4581301 for pointing this out.)
You could write this as:
name = price = isTaxed = 0;
(since an assignment yields the value that was assigned) or, more simply, as:
// name = 0;
price = 0.0
isTaxed = false;
I've commented out the assignment to name, since it's an array and you cannot assign a value to an array object. I won't show a corrected version because I don't know what you're trying to do here.
Suggestion: Start small, keep it simple, and confirm at each step that your code works before adding new code. I think you've tried to write too much code at once. You have nearly 100 lines of code that won't even compile. I've been programming for a long time and I wouldn't write that much code without making sure it compiles and runs.

It looks like you declared subtotal in your statement here:
double price, taxtotal, subtotal, total = 0;
but only initialized total with value 0, causing its use on the right side of the assignment to trigger the error:
subtotal = subtotal + price;
To initialize multiple items simply add the "=" explicitly.
Example:
double price = 0, taxtotal = 0, subtotal = 0, total = 0;

Related

Doing while loop properly until "0" input to stop the loop?

I need help. I'm currently learning C++ programming and I'm still at the beginner level. I'm still figuring out how to make the while loop working. My idea is when inserting the correct code input, the switch statement choose the right case statement and loop back to insert another input until 0 inserted to stop the loop and calculate for the final output in main() constructor.
I know I have few kinks to fix soon but I'm still struggling to figure out this particular part.
#include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;
double sst = 0.06, total = 0, grandTotal, price, discount, newPrice, totalSST;
int quantity, count, code;
string name, ech;
void item001(){
name = "Rice (5kg)";
price = 11.5;
discount = 0;
}
void item002(){
name = "Rice (10kg)";
price = 25.9;
discount = 0;
}
void item003(){
name = "Sugar (1kg)";
price = 2.95;
discount = 0;
}
void item_cal(){
cout << "Please enter the quantity of the item: ";
cin >> quantity;
newPrice = (price + (discount * price)) * quantity;
cout << "\nItem: " << name << " || Quantity: " << quantity << " || Price: RM" << newPrice << endl;
}
void input(){
cout << "Welcome SA Mart\n" << "Please insert the code. Press 0 to stop: ";
while (code != 0){
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
}
}
}
int main(){
input();
totalSST = total * sst;
grandTotal = total + totalSST;
cout << fixed << setprecision(2);
cout << "Total: RM" << total << " ||SST: RM" << totalSST << " || Grand Total: RM" << grandTotal << endl;
return 0;
}
The only functional issue I see in your code is that there is a chance that the code variable will initialize to 0 (depends on the compiler/randomness). If that happens, your input method will return before it enters the loop. Other than that it looks like it will work. Of course, programming is not just the art of "making it work," style and readability are important too. In general, you want to confine variables to the smallest scope in which they are referenced. 'code' should not be a global variable, it should live in the input method. As for the loop, there are several ways it could be implemented: a "while(true)" loop could be used, in which case the variable may be defined inside the loop; on the other hand a "do while" would guarantee one loop runs (perhaps that would be a good fit here), but the variable must live outside of the loop, at least int the scope of conditional check. The way you choose is often a matter of style. Below, I use a "while(true)."
In programming, readability matters (a lot). I think this program would be easier to read if the data were broken up into a few structs, perhaps "Bill," and "Food." Another thing to consider is how to broaden the usage of your program, without introducing significant complexity. For example, it could work for any grocery store (any set of food items/prices). This is often a matter of determining an appropriate set of parameters to feed your program.
To do these things you might write something like this:
#pragma once
#include <string>
#include <map>
using namespace std;
namespace market {
const double& sst = 0.06;
struct Bill {
double total = 0;
double totalSST = 0;
double grandTotal = 0;
};
struct Food {
const char* name;
double price;
double discount;
Food(const char* name, double price, double discount = 0)
: name(name), price(price), discount(discount) {}
double result_price() const {
return price - price * discount;
}
};
struct GroceryStore {
const char* name;
std::map<int, Food> inventory;
GroceryStore(const char* name, std::map<int, Food> inventory)
: name(name), inventory(inventory) { }
};
void shop(const GroceryStore& store, Bill& bill, bool show_menu = false, int exit_code = 0) {
// check error conditions
if (store.inventory.find(exit_code) != store.inventory.end()) {
// that's the 'exit_code' code silly!
cout << "Bad store. Come back another time." << endl;
return;
}
cout << "Welcome to " << store.name << endl;
if (show_menu) {
cout << "The following items are available for purchase:" << endl;
for (auto p : store.inventory) {
cout << "\t" << p.first << ") " << p.second.name << "(" << p.second.result_price() << endl;
}
}
cout << "Enter the product code of the item you wish to purchase:";
int code;
cin >> code;
while (true) {
auto food_it = store.inventory.find(code);
if (food_it == store.inventory.end()) {
cout << "Thanks for stopping by." << endl;;
break;
}
cout << "Please enter the quantity of the item: ";
uint32_t quantity;
cin >> quantity;
auto& food = food_it->second;
auto disc_price = food.price - (food.discount * food.price);
bill.total += disc_price * quantity;
cout << "\nItem: " << food.name << " || Quantity: " << quantity << " || Price: RM" << disc_price << endl;
cout << "Would you like anything else? Enter the product code, or press " << exit_code << " to proceed to check-out." << endl;
cin >> code;
}
}
void ring_up(Bill& bill) {
bill.totalSST = bill.total * sst;
bill.grandTotal = bill.total + bill.totalSST;
}
void run() {
int code = 1;
GroceryStore store("SMart", {
{ code++, Food("Rice (5kg)", 11.5, 0) },
{ code++, Food("Rice (10kg)", 25.9) },
{ code, Food("Sugar (1kg)", 2.95, 0) }
});
Bill bill;
shop(store, bill, true);
ring_up(bill);
cout << "Total: RM" << bill.total << " ||SST: RM" << bill.totalSST << " || Grand Total: RM" << bill.grandTotal << endl;
}
}
Firstly there is a bug in input when u will input 0 then also it won't break while loop as code that is checked contains the previous value.
for example:
input is
3
0
but according to your code when the code will run the second time and while condition is checked code still contains 3 as value and code will run one more time
Try initialising code to some value, for example, -1. I'm not really sure but I think for global int variables, they initialise int variables to 0. So your first loop doesn't run. Or another way to do it is using do while loops instead of while loop.
do {
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
} while (code != 0);
}
This makes sure that the loop will run at least once, making code initialised.
Hope it helps you! Have fun programming!

How would I calcuate the total of all the items entered to then calculate the total price?

Hi there apologise if my question is poorly worded, I'm struggling to find a solution to my problem.
The purpose of my program is to allow the user to enter predefined bar codes that associate with items and a price. The user enters as many barcodes as they want, and when they're done they can exit the loop by pressing "F" and then total price for all the items is displayed.
This is my code so far, I'm very new to programming..
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
while (true){
cout << "Please enter a barcode (Type 'F' to finish): ", cin >> newBarcode;
int index = index_of(barcode, newBarcode, (sizeof(barcode) / sizeof(barcode)[0]));
cout << "\n>> Name of item: " << item[index] << endl;
cout << ">> Price of item: \x9C" << setprecision (4)<< price[index] << endl;
cout << ">> " <<item[index] << " has been added to your basket. \n" << endl;
float total = 0 + price[index];
cout << ">> Your current basket total is: \x9C" << setprecision(4) << total << endl;
/*float total = 0;
float newtotal = 0;
price[index] = total;
total = newtotal;
cout << ">> " << "Basket total: " << newtotal << endl; */
}
return 0;
}
You will need to iterate over all items and add their value to a variable. You can do it the old way:
float sum = 0;
for(int i = 0; i < SIZE; i++) {
sum += price [i];
}
Or the C++11 way:
float sum = 0;
for(float p : price) {
sum += p;
}
However I must point out a few important issues with your code:
Your array has a fixed size but user can enter as many entries as he wants. To avoid this issue, use vector. It behaves like array but has dynamic size. Simply use push_back() to add a new element.
Don't use separate containers (arrays) for the same group of objects. It's a bad coding practice. You can define a structure for product which will contain name, barcode and price, then make one container for all of the products.
Edit
I'm sorry, I misunderstood your problem. There are many ways to solve this, the most elegant way is to create a map where key is the bar code and value is your product object or just a price.
map<int, float> priceMap;
priceMap.insert(pair<int, float>([your bar code here], [your price here]))
Afterwards just create a vector of bar codes, fill it with user data and iterate over it sum all prices:
float sum = 0;
for(int b : userBarcodes) {
sum += priceMap.at(b);
}
You are trying to read from cin into an int. As you decide to put a stopping condition on 'F' input you must read into a string. Then decide what to do with the value. You will need to check if the input is an int or not. You can do it as given here or here.
Or you may change the stopping condition to a less likely integer like -1. And make sure you always read an int into newBarcode.
There are various small errors which are hard to list out. I have changed them in the code below which is implementing point 2 (You have to add the stopping condition).
One of the error or wrong practice is to declare new variables inside a loop. In most cases you can declare the variables outside and change there values in the loop.
I replaced (sizeof(barcode) / sizeof(barcode)[0] with SIZE as the lists are predefined and unchanging. Anyways you should use (sizeof(barcode) / sizeof(barcode[0]) for length calculation.
#include <iostream>
#include <iomanip>
using namespace std;
int index_of(int arr[], int item, int n) {
int i = 0;
while (i < n) {
if(arr[i] == item) {
return i;
}
i++;
}
return -1;
}
const int SIZE = 10;
int main()
{
string item [SIZE] = {"Milk", "Bread", "Chocolate", "Towel", "Toothpaste", "Soap", "Pen", "Biscuits", "Lamp", "Battery"};
int barcode [SIZE] = {120001, 120002, 120003, 120004, 120005, 120006, 120007, 120008, 120009, 120010};
float price [SIZE] = {10.50, 5.50, 8.00, 12.10, 6.75, 5.20, 2.00, 4.45, 20.50, 10.00};
cout << "*************************************************************" << endl;
cout << "WELCOME TO THE CHECKOUT SYSTEM" << endl;
cout << "Please scan a barcode or manually enter the barcode ID number" << endl;
cout << "*************************************************************\n" << endl;
int newBarcode;
float total = 0;
int index;
while (true){
cout << "Please enter a barcode (Type -1 to finish): \n";
cin >> newBarcode;
while(cin.fail()) {
cout << "Not an integer" << endl;
cin.clear();
cin.ignore(100,'\n');
cin >> newBarcode;
}
index = index_of(barcode, newBarcode, SIZE);
cout << index;
if (index == -1) {
cout << "Apologies here for unsupported barcode\n";
continue;
} else {
cout << ">> Name of item: " << item[index] << endl;
cout << ">> Price of item: " << price[index] << "\n";
cout << ">> " <<item[index] << " has been added to your basket. \n";
total = total + price[index];
cout << ">> Your current basket total is: " << total << "\n";
}
}
return 0;
}
Your question could be more helpful to others if you find out what is wrong with your implementation and ask implementation specific questions which will probably be already answered. Asking what is wrong with my code is not quite specific.

Why is my output wrong?

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double COUNTY_TAX = 0.02;
const double STATE_TAX = 0.04;
double totalSales;
void countyTax(double newCountyTax);
void stateTax(double newStateTax);
void total(double newTotal);
int main ()
{
cout << "Please enter the total dollar amount of sales: $";
cin >> totalSales;
countyTax(1);
stateTax(1);
total(1);
return 0;
}
void countyTax(double newCountyTax)
{
double newCountyTaxA;
newCountyTaxA = totalSales * COUNTY_TAX;
cout << "The county tax is: $" << newCountyTaxA << endl;
}
void stateTax(double newStateTax)
{
double newStateTaxA;
newStateTaxA = totalSales * STATE_TAX;
cout << "The State tax is: $" << newStateTaxA << endl;
}
void total(double newTotal)
{
double newTotalA, newStateTaxA, newCountyTaxA;
newTotalA = newStateTaxA + newCountyTaxA;
cout << "The total is: $" << newTotalA << endl;
}
hello guys! I am getting into modules in C++ and the above code compiles correctly but I can't seem to figure out why my output is wonky. I get the county tax and state tax to show properly but when the total shows I get "$nan" i was wondering if i could get some feedback on this? does it possibly have to do with the fact that within the module i am not using any global variables like i do with the totalSales and COUNTY_TAX and SALES_TAX and that when i declare newTotalA newStateTaxA newCountyTaxA they are declared but not assigned? just a tad confused here..THANKS!!!
the variables newStateTaxA and newCountyTaxA that are created and computed in countyTax and stateTax are local to those functions. Once the functions complete, those variables, and the values they contain, go away. In total you create new local variables with the same names. These have no relationship with the previously defined variables, apart from sharing names, and will not store the values previously computed in the other two functions.
The easiest solution, although not considered the most robust, is to create the two variables at the global scope, along with totalSales so that the values that they are assigned to in the two functions persist.
If you do not wish to use global variables (which I also don't care to use), you can declare them in your main function, and modify your other functions to return the calculated values:
double countyTax(double newCountyTax)
{
double newCountyTaxA;
newCountyTaxA = totalSales * COUNTY_TAX;
cout << "The county tax is: $" << newCountyTaxA << endl;
return newCountytaxA;
}
The calls in main() would then read:
newCountyTaxA = countyTax(1);
Your are doing a fundamental mistake here in the following code :
void total(double newTotal)
{
double newTotalA, newStateTaxA, newCountyTaxA;
newTotalA = newStateTaxA + newCountyTaxA;
cout << "The total is: $" << newTotalA << endl;
}
The Variables that you have created here "newStateTaxA", and "newCountyTaxA" does not have any relation to the other variables that you have created and assigned in the other methods, they are local for each method. You need to either make them global or return valued from those functions.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double COUNTY_TAX = 0.02;
const double STATE_TAX = 0.04;
double totalSales;
void Taxes();
int main ()
{
cout << "Please enter the total dollar amount of sales: $";
cin >> totalSales;
Taxes();
return 0;
}
void Taxes()
{
double countyTax, stateTax, total;
countyTax = totalSales * COUNTY_TAX;
stateTax = totalSales * STATE_TAX;
total = countyTax + stateTax;
cout << "The County Tax is: $" << fixed << setprecision(2) << countyTax << endl;
cout << "The State Tax is: $" << fixed << setprecision(2) << stateTax << endl;
cout << "The total is: $" << fixed << setprecision(2) << total << endl;
}
here is what I came up with. Everything works and outputs as desired. I guess now I am wondering if this type of setup with one module and multiple calculations inside it considered good programming?

How to call user defined functions in C++?

Below you will find my dismal attempt to create a user defined function. I am trying to do an assignment that calculates the area and cost of installing carpet for various shapes. I am also suppose to keep a running total of them. In addition the assignment requires that I use a used defined function. Right now all it does is accept the input of 1 and ask "What is the length of the side: ". It then loops back to the selection menu. It does not calculate a total much less keep track of the total. What am I doing wrong in creating the user defined function and how can I incorporate it to keep a running total till they exit?
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath>
using namespace std;
void square(double);
const double UNIT_PRICE = 2.59;
const double LABOR_COST = 32.5;
const double PIE = 3.14;
const double TAX = .0825;
int main() {
int selection;
int sqrSide = 0;
// declare and initialize the variables for the shape
int sqrTot = 0;
do {
// get input from user as to what they want to do
cout << "Carpet Area Shape" << endl;
cout << "1. Square" << endl;
cout << "2. Rectangle" << endl;
cout << "3. Circle" << endl;
cout << "4. Triangle" << endl;
cout << "5. Done" << endl;
cout << "Type a number to continue: ";
cin >> selection;
cout << endl;
// loop through the solutions based on the user's selection
switch (selection) {
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
case 2:
case 3:
case 4:
case 5: // exit
system("cls");
break;
default:
"You have made an invalid selection. Please choose a number from the "
"list.";
cout << endl;
}
// loop through if the user is still making a valid selection
} while (selection != 5);
system("pause");
return 0;
}
void square(double) {
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
// get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
When you declare the prototype of the function you can omit the parameter but in the implementation you must place it.
change:
void square(double)
{
double sqrSide = 0;
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
to:
void square(double sqrSide)
{
double sqrTot = 0;
double sqrArea;
sqrArea = sqrSide * 4;
//get the total area and store it as a variable
sqrTot += sqrArea;
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
}
and also change:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
if (sqrTot > 0) {
cout << "Shape: Square" << endl;
cout << "Side: " << sqrSide << endl;
cout << "Area: " << sqrTot << endl;
}
cout << endl;
system("pause");
break;
to:
case 1:
cout << "What is the length of the side: ";
cin >> sqrSide;
square(sqrSide);
system("pause");
break;
As mentioned by πάνταῥεῖ in a comment, it seems that you've a few misconceptions regarding scope of variables, about parameters and about return values. Let's see if we can't dispel some of those.
First of all, lets talk about scope. When we declare a variable inside a block delimited with { and }, the variable only exists inside that block. Code that follows the block cannot access the variable.
So, this is okay:
int a = 3;
int b = 2;
int c = a*b;
But, this is not, since the values of a and b are no longer available:
{
int a = 3;
int b = 2;
}
int c = a*b;
Next, lets talk about parameters. These are the inputs to functions which the function will use in order to complete its task. While their name is irrelevant and essentially meaningless, it will certainly help you and others of you give them meaningful names. Some programming languages and indeed, students of some disciplines don't follow this maxim and can produce code that's harder to follow than it need be. The implementation of Basic found in 20 year old Texas Instruments calculators and physicists, I'm looking at you!
Consider the following functions, (whose bodies I've ommitted for brevity):
double calcArea(double a)
{
...
}
double calcArea(double b)
{
...
}
They both suck. What's a stand for, how about b?
A far better pair might resemble:
double calcArea(double radius)
{
...
}
double calcArea(double sideLenOfSquare)
{
...
}
Lastly, lets talk about return values. In each of the 4 preceding functions, the declaration begins with double. This means that we can expect to get back a value of type double from the function. However, this is just coding - there's no magic and as such, we need to actually let the compiler know what this value will be. Extending the two previous functions, we might come up with some something like the following:
double calcArea(double radius)
{
return 3.1415926535 * (radius * radius);
}
double calcArea(double sideLenOfSquare)
{
return sideLenOfSquare * sideLenOfSquare;
}
Now as it turns out - even these two simple functions are not all they've cracked-up to be. Namely, the first function uses a constant - π (Pi or 3.141....) This already exists (and with far better precision than I've used) in the math.h header file. If this file is included, we then have access to the #defined constant, M_PI.
Next, both of these functions have the same name and take the same number of parameters of identical type. The compiler can't possibly know which one you'd like to invoke. At a minimum, they should have different names. Perhaps something like calcCircleArea and calcSquareArea. Now, the compiler knows which function you're referring to and will happily compile this part of the code. Errors may exist elsewhere, but these are a different matter.
A little research on function overloading will provide resources that can explain the problem and solution to functions with the same name far better than I am both able and inclined to try. :)

How could I improve this c++ program without vectors?

**Guidelines:**get 3 seperate lists of data(array) for head of household, annual income, and household members, then get all annual incomes and average them together. Display in a neat table.
This is from a school project I wasn't allowed to use anything very advanced but I'd like to go back and improve it now. I'd like ti make it cleaner and particularly like to find more that I can take away from it than add to it.
// <Program Name> Programming Project #3 Average Income (Using Functions and Arrays)
// <Author> Brendan Jackson
// <Date of Programs Release> 08/05/15
// <Program Description> takes 3 arrays and displays them with average income
#include <iostream> // allows cin and cout statements
#include <iomanip> //allows setprecision
#include <string> //allows strings
using namespace std; // Namespace std allows program to use entities from <iostream>
int input(string[], int[], double[]); //function 1
double calculate_average_income(double[], int); //function 2
void display_survey_data(string[], int[], double[],int , double); //function 3
int main() // main function
{
//variables for functions
string name[10];
int members[10];
double income[10];
int count_of_households;
double average;
//get input
count_of_households = input(name, members, income);
//calculate average
average = calculate_average_income(income, count_of_households);
//output all data in table
display_survey_data(name, members, income, count_of_households, average);
return 0;
}
int input(string name[], int members[], double income[]) //function 1
{
// get household info
int count_of_households = 0;
cout << "How many house holds were there? ";
cin >> count_of_households;
//TODO: handle bad input (characters and decimals)
if (count_of_households >= 11 || count_of_households < 0)
{
cout << "must enter valid # " ; //TODO: more description
count_of_households = 0; //set back to safe value
}
else
{
//cycle through arrays
for (int count = 0; count < count_of_households; count++) //TODO: take out (count + 1) start from 1 alternatively
{
// get survey info for names
cout << "Enter household #" << (count + 1) << "'s head of household name\t" ;
cin.ignore() ; // ignores keyboard buffer characters
getline (cin, name[count]) ;
// get survey info for income
cout << "Enter household #" << (count + 1) << "'s annual income\t" ;
cin >> income[count];
// get survey info for members
cout << "Enter household #" << (count + 1) << "'s household members\t" ;
cin >> members[count];
}
}
return count_of_households;
}
double calculate_average_income(double income[], int count_of_households) //function 2
{
//add incomes together
double total = 0.0;
double average = 0.0;
//loop over income
for (int count = 0 ; count < count_of_households; count++)
{
//add income to runnning total
total += income[count];
}
// save calculations
average = total / count_of_households;
return average;
}
void display_survey_data(string name[], int members[], double income[],int count_of_households, double average) //funtion 3
{
//print out header
cout << setw(30) << ""
<< setw(30) << ""
<< setw(30) << "NUMBER OF\n" ;
cout << setw(30) << "HOUSEHOLD NAME"
<< setw(30) << "ANNUAL INCOME"
<< setw(30) << "HOUSEHOLD MEMBERS\n" ;
cout << setw(30) << "--------------------"
<< setw(30) << "---------------"
<< setw(30) << "------------------------\n" ;
///loop over values
for (int count = 0 ; count < count_of_households; count++)
{
cout << setw(30) << name[count]
<< setw(30) << setprecision(2) << fixed << showpoint << income[count]
<< setw(30) << members[count]
<< endl;
}
// display average
cout << endl
<< setw(30) << "AVERAGE INCOME"
<< setw(30) << average
<< endl;
}
You could use std::array
This is simply an array on the stack, just like you used, but has iterators, type safe, bound safe, use value semantics and work with most stl algorithm.
It is declared like this:
array<string, 3> myArray;
And it must be passed by reference, because passing by value will copy it's content:
void doSomething(array<int, 6>& aArray) {
// do something
}
Notice that you must specify the length of the array, since it's a template parameter. If you want to have an array of any size, use tempaltes:
template<size_t length>
void foobar(array<double, length> theArray) {
// do something else
}