CAN ONLY USE LOOPS & IF/ELSE Statements
So for my assignment I'm given this: Write a program with for loops that asks the user to enter today’s sales for five stores. The program should then display a bar graph comparing each store’s sales. Create each bar in the bar graph by displaying a row of asterisks. Each asterisk should represent $100 of sales.
So it should like:
Store 1: *****
Store 2: ***
Store 3: *******
etc.
I have most of it written up and everything displays properly except for my asterisks. I can't seem to get them to display. Also, I've searched around and there are answers to this, but all of them include arrays and we aren't allowed to use them in this exercise. Here's my code so far:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int sales = 0, sale = 0; //Identfy Variables
for (int i = 1; i <= 5; i++) {
cout << "Enter today's sales for Store " << i << ":" << endl;
cin >> sale;
sales += sale;
sales /= 100; //in a similar manner to +=, /= can be used for division.
}
cout << "SALES BAR CHART:" << endl;
cout << "Each * = $100" << endl;
for (int x = 1; x <= 5; x++) {
cout << "Store " << x << ": ";
for (int s = 0; s < sales; s++) cout << "*";
cout << endl;
}
return 0;
}
Try this.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string star = "";
int sale;
for (int i = 1; i <= 3; i++)
{
cout << "Enter today's sales for Store " << i << ":" << endl;
cin >> sale;
star += "Store " + to_string(i) + string(":");
for(int j= 0; j<sale/100; j++) {
star += "*";
}
star += "\n";
}
cout<<star;
return 0;
}
The problem with your code is that you do not store the data for each store individually. You have one variable called sales, which stores the sales of only the last store the end-user entered. All numbers the user enters before that get written over.
Since you have five stores, sales needs to be an array of five items:
int sales[5], total = 0;
Change your for loop to iterate 0 through 4, inclusive. Print (i+1) to end-users to stay one-based. Read sales numbers into sales[i] array element, then use it in the second loop to print your bar graph:
for (int i = 0 ; i != 5 ; i++) {
cout << "Enter today's sales for Store " << (i+1) << ":" << endl;
cin >> sales[i];
sales[i] /= 100;
total += sales[i];
}
...
// Now print your bar graph using a loop on i, and sales[i]
Your for loop is missing a definition of s:
for (int s; s < sales; s++)
should be:
for (int s = 0; s < sales; s++)
Without this explicit initialization, a variable s is declared, and memory is allocated for it, but its value remains whatever was left in memory from the last time that address was used. It's likely that this left over data was equivalent to an integer larger than sales, and thus your for loop wouldn't run, not even once.
As #dasblinkenlight mentioned, you have a singular variable that stores the "sales" of every store. Each store needs a separate variable, since each store is going to sell a different amount.
You already have the answers, I just want to add two options that would make printing the *'s easier:
using std::fill_n:
std::fill_n(std::ostream_iterator<char>(cout), sales, '*');
cout << endl;
using std::string's constructor overload (2):
cout << std::string(sales, '*') << endl;
Related
I am new to C++ (so, please forgive me for my C++ atrocities) and am asking for help once again to the helpful people at stack Overflow. I have to create a 2D Array program that reads from 2 files, one named after the Months of the year, and the other being a table of integer values.
I have four functions that break off of main in a switch menu. Function One should display the whole chart with the months going down the first column.
Months && Values. So, basically the months are all in the first column[0] and the values line up adjacent to the months (there will be some added flair to the top most row to give a description of what the values are, but I am sure I can figure that part out)
Then the second function takes all the values in column 1 & 2 (so not [0] because that's the months).
Then my third function takes columns [4] & [5] and adds them up and displays the totals, with the months to left of the values.
My fourth and final function will allow a user to input a given month and display the value display in the 1 first column after the months.
All of my output is never ending 0's.
Please if you could give me any tips/advice/code examples/anything would be greatly appreciated, and I thank you for taking your time to read this garbage code, so that I can hopefully get better at programming! Here is my code, I have not finished it yet since I keep having loop errors that display 0's when I try to ask the program to display one of the four options.
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
// Global Array Size
const int ROWS = 12, COLUM = 9;
int parkChart[ROWS][COLUM];
//Function Prototypes
void displayCodes(const int[][COLUM], int);
int totalRecNonRec(const int[][COLUM], int rows, int total);
int tentRvByMonth(const int[][COLUM], int);
int displayMonth(const int[][COLUM], int, string);
int main()
{
// Define variables
const int DISPLAY = 1, REC_NONREC = 2, TENT_RV = 3, PER_MONTH = 4;
int response, total = 0;
string month;
ifstream inputFile;
inputFile.open("Months.txt");
ifstream inputFile2;
inputFile2.open("Vistors.txt");
cout << "Visitors to National Park" << endl;
// Do While Loop to display the menu
cout << "Enter 1 to display data" << endl;
cout << "Enter 2 to display total number of recreation and non-recreational visitors" << endl;
cout << "Enter 3 to display total tent and RV campers by month" << endl;
cout << "Enter 4 to display the number of recreational visitors for a certain month" << endl;
cout << "Enter any other number to exit" << endl << "\n";
cin >> response;
do
{
switch (response)
{
case(DISPLAY):
{
inputFile;
inputFile2;
displayCodes(parkChart, ROWS);
break;
}
case(REC_NONREC):
{
totalRecNonRec(parkChart, ROWS, total);
break;
}
case(TENT_RV):
{
tentRvByMonth(parkChart, ROWS);
break;
}
case(PER_MONTH):
{
displayMonth(parkChart, ROWS, month);
break;
}
default:
{
// Closes the file and exits
inputFile.close();
exit(0);
}
}
} while (response == 1 || response == 2 || response == 3|| response == 4);
system("pause");
return 0;
}
// Four Functions
// Display Function
void displayCodes(const int parkChart[][COLUM], int ROWS)
{
for (int row = 0; row < ROWS; row++)
{
for (int col = 0; col < COLUM; col++)
{
cout << parkChart[row][col] << "\t ";
}
cout << endl;
}
}
// Totals/Display Rec. & Non Rec. Visitors to the park + adds all months for visitors (must equal 3,350,493)
int totalRecNonRec(const int parkChart[][COLUM], int rows, int total)
{
// for loop that adds all the elements in [0-11,1]&&[0-11,2]
for (int col = 0; col < 1; col++)
{
total = 0;
for (int row = 0; row < ROWS; row++)
total += col;
cout << "The total number of recreational and non-recreational visitors: " << total << endl;
}
return total;
}
// Totals/Display Number of Tent & RV Campers by month (needs to add rv + tent) and show all months
int tentRvByMonth(const int parkChart[][COLUM], int rows)
{
for (int row = 0; row < ROWS; row++)
{
int total = 0;
for (int col = 4; col < 5; col++)
{
total += parkChart[row][col];
cout << parkChart[row][col] << " " << (col + 1) << endl;
}
cout << endl;
}
return 0;
}
int displayMonth(const int parkChart[][COLUM], int rows, string month)
{
// Prompt the user to enter a month/Display the number of Rec. Visitors for that month + Failsafe of non-months
// Need a for loop to search for the user given month, and then display the [month, 1]
cout << "Enter the month you want the number of recreational visitors\n";
getline(cin, month);
// search in first column of array
cout << "For the month of " << month << " there were " << " recreational visitors" << endl;
return 0;
}
Consider a program that asks the user for an integer value greater than 10, say 15. The program should then calculate the sum of all positive values up to 15 and now I need to "show the
current sum after adding each number".
For the first part I made everything like this:
#include <iostream>
using namespace std;
int main()
{
int num = 0;
int sum = 0;
cout << " Please enter how many number you'd like to sum up\n";
cin >> num;
while (num <= 10)
{
cout << "Please enter an integer which is more than 10";
cin >> num;
}
for ( int i = 1; i <= num; i++)
{
sum += i;
}
cout << "The total sum is : " << sum;
But now I dont know what should i do?
It should look like this in the end.
You can do this by outputting the values used in the calculation, along with the 'running' total, inside your summation loop:
for (int i = 1; i <= num; i++)
{
cout << sum << " + " << i << " = " << sum + i << "\n";
sum += i;
}
Feel free to ask for further clarification and/or explanation.
I am currently making a cash register that inputs 5 values and then outputs those same 5 values on a receipt with the item tax and subtotal. I then have to add together all the item costs, tax costs and so on to produce a total. So Far I have created code to intake five values and set the frame for my receipt. The issue I have is I have no idea how to get all the values entered from the initial loop and put them on the receipt. The only value that is retained is the final value I input. I'm pretty new so excuse my code and if it's not obvious for myself! Appreciate the help!
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double taxRate = 0.07;
double subtotal = 0;
double total = 0;
float item;
float cost;
float counter = 0;
while (counter != 5) {
for (int num=0; num < item; num++) {
}
counter++;
std::cout <<"Enter the cost of the item: ";
std::cin>>item;
}
cout << endl;
cout << setw(10) << "Item Cost"
<< setw(11) << "Item Tax"
<< setw(19) << "Item Subtotal\n";
cout << "----------------------------------------\n";
std::cout.precision(2);
std::cout.setf(std::ios::fixed);
cout << setw(10) << item << setw(11) << item * taxRate<< setw(17) << (item*taxRate)+item << endl;
return 0;
}
You should start by reading on what vectors are and how they work. Get rid of the while loop. You only need 2 for loops to accomplish the task with the way your code is set up.
vector<float> cash;
......
......
for (int i = 0; i < 5; i++)
{
cout << "Enter the cost of the item: ";
cin >> item;
//push items into vector here
}
.....
.....
for (int i = 0; i < cash.size(); i++)
{
// output like you were doing but with your vector elements
}
With that skeleton code you should be able to accomplish what you want with a little research
I've got a small task I need to complete and I'm rather confused. This task has 3 parts to it which are:
Write a program that dynamically allocates a float array of a size specified by a user (currently working on - if anyone could check my code for this it would be appreciated.
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
Program should print what was saved into the array, the sum, and the average value in the array, and exit.
As you could tell I'm new to C++ and coding in general so please spell it out for me wherever possible. It is mandatory that I am using pointers so I'm afraid I can't change that.
#include <iostream>
using namespace std;
int main()
{
int length;
cout << “Please enter the length of the array: “;
cin >> length;
float * dArray = new float [length];
for (int i = 0; i < length; i++)
{
cin >> dArray[i] = i;
for (int i = 0; i < length; i++)
{
cout << dArray[i] << “ “;
}
cout << ‘/n’;
int sum = 0;
for (int i=0; i < length; i++)
{
sum +=dArray[i];
avg =sum/length;
cout << “Sum is “ << sum << “/nAverage is “ << average;
delete [] dArray;
}
return 0;
}
Please explain the 2nd part.
Thanks in advance.
Regarding
It should then allow the user to input that number of floats, which should be stored in the array. (I have no clue what this means so if I'd appreciate someone explaining it if they could)
It means that you have to let the user input the values to that array. What you are doing is giving them values yourself.
What you need to do is change
for (int i = 0; i < length; i++)
{
dArray[i] = i;
}
to
for (int i = 0; i < length; i++)
{
cin>>dArray[i];
}
Also Note that length should be an int and not a float.
After completion, this would probably be the code you need ( although I would advice you to do the part of finding the sum and average by yourself and use this code I have posted as reference to check for any mistake, as finding the sum and average for this is really easy )
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
float sum = 0 , avg; // variables to store sum and average
cout << "Please enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for (int i = 0; i < length; i++)
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
delete[] dArray;
return 0;
}
EDIT
After getting your comment, I decided to post this new code. ( I am assuming what you meant is that the program should repeat as long as the user wants )
I have done it by using a do while loop.
#include <iostream> // include library
using namespace std;
int main() // main function
{
int length; // changed length to int
char a; // a variable to store the user choice
do
{
float sum = 0 , avg; // variables to store sum and average
cout << "\nPlease enter the length of the array: "; // ask user for array
cin >> length;
float *dArray = new float[length];
cout << "\nEnter " << length << " values to be added to the array\n";
for ( int i = 0; i < length; i++ )
{
cin >> dArray[i]; //accepting values
sum += dArray[i]; // finding sum
}
avg = sum / length; //the average
cout << "\nThe array now contains\n"; // Displaying the array
for ( int i = 0; i < length; i++ ) // with the loop
{
cout << dArray[i] << " ";
}
cout << "\nThe sum of all values in the array is " << sum; // the sum
cout << "\n\nThe average value is " << avg; // the average
cout << "\n\nDo you want to try again ( y/n ) ?\n";
cin >> a;
delete[] dArray;
}while( a =='Y' || a == 'y' ); // The do while loop repeats as long as the character entered is Y or y
return 0;
}
Well, hope this is what you were looking for, if not, please do notify me with a comment... :)
Just so you know, the new code you have posted doesn't even compile. Here are some of the problems.
cin >> dArray[i] = i;
You don't need to use = i here. Just cin >> dArray[i] ; is enough.
The next problem is
cout << ‘/n’;
First of all, its \n and not /n. You also need to enclose it in double quotes and not single quotes. That is cout << "\n";
Next one, you have not defined the variable avg . Also note that you have also used an undefined variable average, which I assume you meant avg.
Now here's one of the main problems , You have not closed the curly brackets you opened. You open the brackets for for loops, but forget to close it. I'm leaving that part to you as you need to learn that part yourself by trying.
Now Here's one problem I don't understand, you have used “ “, which is somehow not the same as " ". I don't know if it's something wrong with my computer, or if it's a totally different symbol. My compiler couldn't recognize it. If its not causing any trouble on your end, then don't mind it.
Well, this sums up the problems I noticed in your code ( the problems that I noticed ).
Your issues are too simple for us to just give you the answers, but I've commented your code with suggestions on how to solve your problem:
#include <iostream>
using namespace std;
int main()
{
float length; //it doesn't make sense for something to be of a float length
//should be size_t instead
cout << "Please enter the length of the array: ";
cin >> length;
float *dArray = new float[length];
for (int i = 0; i < length; i++)
{
dArray[i] = i; //this line is incorrect
//how should we read the data into this array?
//we've used cin before
}
for (int i = 0; i < length; i++)
{
cout << dArray[i] << " ";
}
cout << '\n';
//now we've output the array, just need to output the sum and average value
int sum = 0;
for (int i=0; i < length; i++)
{
sum += //what should go here?
}
int average = //how should we calculate the average?
cout << "Sum is " << sum << "\nAverage is " << average;
delete[] dArray;
return 0;
}
This function is not accurately returning the highest and lowest values entered into the array. I'm not sure what I code I entered for the program to do this. This program needs to return the average of all of the elements entered into the array (the average part works fine) as well as find the highest and lowest values among all of the values entered into the array. Please help!
#include <iostream>
using namespace std;
float temptotal = 0;
float averagetemp = 0;
float temperatures[50];
float average(int);
void highest(int);
void lowest(int);
int main()
{
int days = 0;
cout << "Enter the number of days: ";
cin >> days;
if (days > 50)
{
cout << "You may only enter temperatures for 50 days." << endl;
return 0;
}
average(days);
highest(days);
lowest(days);
}
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
}
averagetemp = temptotal / days;
cout << "The average temperature is: " << averagetemp << endl;
return averagetemp;
}
void highest(int days)
{
int count;
int highest;
highest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] > highest)
highest = temperatures[count];
cout << "The highest temperature is: " << highest << endl;
}
}
void lowest(int days)
{
int count;
int lowest;
lowest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] < lowest)
lowest = temperatures[count];
cout << "The lowest temperature is: " << lowest << endl;
}
}
This function
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
is already wrong because element temperatures[0] will not be uninitialized. You have to write
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i-1];
temptotal += temperatures[i-1];
//...
Or
float average(int days)
{
for (int i = 0; i < days; i++)
{
cout << "Enter the temperature for day number " << i + 1 << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
Functions highest and lowest are also wrong. For example array temperatures has no element with index 50. Moreover the user can enter number of days less than 50. So this statement
highest = temperatures[50];
is wrong.
The functions can be written like this function definition
void highest( int days )
{
int highest = temperatures[0];
for ( int count = 1; count < days; count++ )
{
if ( highest < temperatures[count] ) highest = temperatures[count];
}
cout << "The highest temperature is: " << highest << endl;
}
Take into acccount that there are standard algorithms std::max_element, std::min_element, std::minmax_element declared in header <algorithm> that can be used instead of your functions.
For example function highest can be defined with using standard algorithm std::max_element the following way
#include <algorithm>
//...
void highest( int days )
{
cout << "The highest temperature is: "
<< *std::max_element( temperatures, temperatures + days )
<< endl;
}
Array indices start with a 0
Place the cout statements outside the for loop.
Arrays are indexed from 0 to n-1, where n is the total number of entries in the array. You started the count at 1 in your loop when you should start at 0. If the user entered 50 values, you would have had an out-of-bounds access.
The correction should be:
for (int i = 0; i < days; i++)
Then in your output statement, it should be:
cout << "Enter the temperature for day number " << i+1 << ": ";
The other issue is your highest function. The issue are a few things:
You declared the local variable highest as an int. It should be a float to match the type used in the temperature array.
You should set highest to a very small value, smaller than any you would expect. Or better yet, set it to the first temperature entry before the loop, and start the loop from the second entry.
You named your local variable highest, but your function name is also highest. This will lead to confusion when someone else looks at your code.
If you're interested in another solution, the following computes the highest:
#include <algorithm>
//...
void highest(int days)
{
float theHighest = *std::max_element(temperatures, temperatures + days);
cout << "The highest temperature is: " << theHighest << endl;
}
A little better version from the function 'highest':
void highest(int days)
{
if (days < 1)
{
cout << "No temperatures" << endl;
}
double highest = temperatures[0];
for (int count = 1; count < days; count++)
{
if (temperatures[count] > highest)
{
highest = temperatures[count];
}
}
cout << "The highest temperature is: " << temperatures[highest_index] << endl;
}
All arrays in C++ starting with index 0. In this implementation this point is considered by using the first element (index 0) as thie first highest value. After that the loop has only to deal with the rest, begining at index 1.
The variable 'highest' must be from the type double. Otherwise you may get wrong results, because the highest is a little lower than the real highest due to generaly rounding down (double to int). The next comparison may be assigned even if it is a little lower.
Array indices start with 0 but your loops start at 1. For your loop over days, for instance, this will iterate over the full range:
for (int i = 0; i < days; i++)