Introduction to C++ assignment : parallel arrays - c++

I am a beginner student looking for help on a program my professor assigned. The task is to use 2 parallel loops to ask the user 5 different salsas and their cost. Then print out the name, total sold, average, best seller and worst selling. The thing is, I can calculate best and worst selling, but those are ints. I don't understand how I can pull the string instead of int? Any help would be appriciated!#include
#include <string>
#include <cmath>
#include <cstring>
using namespace std;
int main() {
string name[5];
int total[5];
int i, final, counter, high, low;
for(i=0; i<=4; i++){
cout << "Salsa name: ";
cin >> name[i];
cout << "How many of " << name[i] << " were sold? ";
cin >> total[i];
final += total[i];
if(i < 0) {
"Sorry, you cannot have negative sales!";
return 0;
} else {
if(counter == 0) {
low = total[i];
} else if (total[i] < low) {
low = total[i];
} else if (total[i] > high) {
high = total[i];
} counter++;
}
}
cout << "Name Amount Sold\n"
<< "-------------------------\n";
for(int i = 0; i <= 4; i++){
cout << name[i] << " " << total[i] << endl;
}
cout << "Total sold: " << final << endl
<< "Most Sold: " << high << endl
<< "Least Sold: " << low;
return 0;
}
output:
Running /home/ubuntu/workspace/Ch6_Ex3.cpp
Salsa name: salsa1
How many of salsa1 were sold? 10
Salsa name: salsa2
How many of salsa2 were sold? 20
Salsa name: salsa3
How many of salsa3 were sold? 30
Salsa name: salsa4
How many of salsa4 were sold? 40
Salsa name: salsa5
How many of salsa5 were sold? 50
Name Amount Sold
-------------------------
salsa1 10
salsa2 20
salsa3 30
salsa4 40
salsa5 50
Total sold: 32862
Most Sold: 50
Least Sold: -547659664
Process exited with code: 0

Your code has some hiccups:
There is no point in the variable counter because you mean it to have the same value as i, so use i; nor do you initialize it. Comparing counter == 0 is undefined behaviour.
Instead of keeping track of the highest/lowest values in total, you should instead keep track of the indexes of those specific values, because the corresponding value in names is the name of each salsa brand...
Take note of the changes below:
#include <iostream>
#include <string>
#include <cmath>
#include <cstring>
using namespace std;
int main() {
string name[5];
int total[5];
int i;
int final = 0;
int high, low;
high = 0, low = 0;
for(i=0; i<=4; i++){
cout << "Salsa name: ";
cin >> name[i];
cout << "How many of " << name[i] << " were sold? ";
cin >> total[i];
final += total[i];
// if(i < 0) {
// "Sorry, you cannot have negative sales!";
// return 0;
// }
// i is never going to be less than 0.
if (total[high] < total[i])
high = i;
if (total[low] > total[i])
low = i;
}
// ...
cout << "Most-sold salsa: " << name[high]
<< "\nLeast-sold: " << name[low] << "\n";
return 0;
}
Other notes:
I strongly advise against using namespace std; See why
You initially forgot #include <iostream>

Related

How do you compare two variables in an if statement?

I'm creating a program where a user tries to guess the amount of times two dice have to roll to reach the totalsum of 100.
I've finished the loop but now I'm stuck on the point where I want the program to compare the two variables. I've googled but nothing has been coming up regarding the issue.
In regards to the code, here's what I have:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
const int min_value=1;
const int max_value=6;
int die1,die2,sum,totalRolls, totalSum, prediction;
unsigned seed = time(0);
srand(seed);
sum=0;
totalRolls=0;
totalSum=0;
cout << "How many rolls will it take to reach a total of 100?\n";
cin >> prediction;
while (totalSum <= 100)
{
cout << "Rolling the die\n";
die1=(rand() % (max_value - min_value + 1) + min_value);
die2=(rand() % (max_value - min_value + 1) + min_value);
cout << die1 << endl;
cout << die2 << endl;
sum=die1+die2;
totalSum+=sum;
cout << "Your current total is " << totalSum << endl;
totalRolls++;
cout << "Last roll number = " << totalRolls << endl;
}
if (totalRolls <= 5)
{
cout << "Amazing!\n";
}
else if (totalRolls <=10)
{
cout << "Good\n";
}
else if (totalRolls <= 15)
{
cout << "Okay\n";
}
else if (totalRolls <= 20)
{
cout << "Try harder\n";
}
system("Pause");
return 0;
}
I honestly just don't know how to compare the predicted total number of rolls compared to the actual rolls it took.

C++ How do I reprint values from a loop?

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

Not taking the input

I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values..
Heres my code so far:
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin >> num;
numberOfInputs++;
addition = addition + num;
if (num % 2 != 0) {
//my issue is with this part
cout << "ignored" << endl;
}
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
}
}
Solution of your code:
Your code doesn't working because of following reasons:
Issue 1: You adding inputs number without checking whether it's even or not
Issue 2: If would like skip even then your condition should be as follow inside of the loop:
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
Solving your issues, I have update your program as following :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin>> num;
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
numberOfInputs++;
addition = addition + num;
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
break;
}
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int number;
int sum=0;
int average=0;
int inputArray[20]; // will take only 20 inputs at a time
int i,index = 0;
int size;
do{
cout<<"Enter number\n";
cin>>number;
if(number==0){
for(i=0;i<index;i++){
sum = sum + inputArray[i];
}
cout << sum;
average = sum / index;
cout << average;
} else if(number % 2 != 0){
inputArray[index++] = number;
} else
cout<<"skip";
}
while(number!=0);
return 0;
}
You can run and check this code here https://www.codechef.com/ide
by providing custom input

For or While loop with 2 max variables, one of which being an array (Programming I) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have the following assignment for my Programming I class:
Prompt for the price of each item. Store each item price in the array named prices. When the user has reached $1,000 or 5 items,
print out how much was spent, how many items were bought, how much is left, and the average price.
Print a table of the prices of the items bought.
My original attempt got very mangled:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int cost = 1;
int total = 0;
int i = 0;
const int MAXNUM = 5;
int prices[MAXNUM];
while (total < 1000 && cost !=0 && i < MAXNUM)
{
for (int x = 0; i < MAXNUM; i++)
{
cout << "Please enter the price of the item you are purchasing:"<< endl << i+1 << "." <<"$";
cin >> cost;
total+=cost;
}
// total += cost;
}
/*
// cout << \n << "Name: ";
// cin >> name;
} */
cout << "You spent $" << total << " by purchasing " << /* **************** << */ " items, you have $" << 1000-total <</* " leftover, and your average price was $" << total/ ******** << */ "." << endl;
return 0;
}
So I started over from scratch and so far I have this:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
const int NUMELS = 5;
int i, prices[NUMELS];
string items [NUMELS];
for (i = 0; i < NUMELS; i++)
{
cout << "Enter the name of the product: ";
cin >> items[i];
cout << "Enter the price of the product: $";
cin >> prices[i];
}
cout << endl;
for (i = 0; i < NUMELS; i++)
cout << items[i]<< " cost you $"<< prices[i]<< endl;
return 0;
}
My biggest difficulty right now is trying to have the program check so that the price doesn't go over $1000 (Which I've written a program for in the past) while ALSO checking to make sure the user purchases no more than 5 items. There are more steps after all of this but once I figure out the base I should be able to build the rest on my own.
I tried putting if (acc > 1000)
break; at the end of my for loop, but then this happened...
Thanks in advance!!
Your attempt using break was not a bad idea, but the loop that prints the result should use the amount of elements entered , not the fixed value 5.
int main()
{
const int NUMELS = 5;
int TotalPrice = 0;
int i, j, prices[NUMELS];
string items [NUMELS];
for (i = 0; i < NUMELS; i++)
{
if (TotalPrice >= 1000)
break;
cout << "Enter the name of the product: ";
cin >> items[i];
cout << "Enter the price of the product: $";
cin >> prices[i];
TotalPrice += prices[i];
}
cout << endl;
for (j = 0; j < i; j++)
cout << items[j]<< " cost you $"<< prices[j]<< endl;
return 0;
}
if I get you, you'll like to also check if the user has exceeded $1000 in the loop that checks if user has bought 5 item. If that is, maybe this should work.
for (int i = 0, exceed = 0; i < NUMELS && exceed < 1000; i++){
cout << "Enter the name of the product: ";
cin >> items[i];
cout << "Enter the price of the product: $";
cin >> prices[i];
exceed += prices[i];
}
Try this
you can use
while(){}
cycle
write something like this
int count = 0, sum = 0;
while(count < 5 && sum <= 1000)
{
cout << "Enter the name of the product: ";
cin >> items[count ];
cout << "Enter the price of the product: $";
cin >> prices[count ];
sum += prices[count ];
count++;
}
cout << endl;
for (int i = 0; i < count; i++)
cout << items[i]<< " cost you $"<< prices[i]<< endl;

Using arrays and strings together

So I'm trying to create an array that contains some user inputted names, and then associate those names with letter grades from tests (ex: A, B, C, D, F). My question is, how would I use an array to accept the user inputted names?
EDIT:
Sorry this is a bit long, I don't know what part to put that would help out. Totally new to C++ and I can't seem to find anything online regarding the matter, lol.
Here is some code. This program currently asks the user for test scores, then displays and drops the lowest test score, and finally, calculates the average of the scores without the lowest one. The end goal is to ask the user for 5 students names, and 4 scores for each student, then dropping the lowest score for each student and calculating the averages of ALL scores inputted regardless of student.
#include <iostream>
#include <string>
using namespace std;
void getScore(int &);
int findLowest(int [], int);
void calcAverage(int [], int);
int main () {
const int NUM_SCORES = 5;
int scores[NUM_SCORES];
cout << "Welcome to test averages." << endl;
cout << "Please enter scores for " << NUM_SCORES << " students." << endl;
cout << endl;
for (int i = 0; i < NUM_SCORES; i++) {
getScore(scores[i]);
}
for (int i = 0; i < NUM_SCORES; i++) {
cout << "Score " << (i + 1) << ": " << scores[i] << endl;
}
cout << endl;
cout << "The lowest of these scores is " << findLowest(scores, NUM_SCORES) << endl;
calcAverage(scores, NUM_SCORES);
return 0;
}
void getScore(int & s) {
s = -1;
cout << "Please enter a test score: ";
cin >> s;
while (s < 0 || s > 100) {
cout << "Score range must be from 0-100" << endl;
cout << "Please re-enter a score: ";
cin >> s;
}
}
int findLowest(int theArray [], int theArraySize) {
int lowest = theArray[0];
for (int i = 1; i < theArraySize; i++) {
if (theArray[i] < lowest) {
lowest = theArray[i];
}
}
return lowest;
}
void calcAverage(int theArray [], int theArraySize) {
int sum = 0;
for (int i = 0; i < theArraySize; i++) {
sum += theArray[i];
}
double average = (sum - findLowest(theArray, theArraySize)) / (theArraySize - 1.0);
cout << "The average is " << average << endl;
}
Try getline from #include <string>
std::string names[5];
for (int i = 0; i < 5; ++i){
getline(std::cin, names[i]);
}