This is a question i am working on:
Prompt the user to enter five numbers, being five people's weights. Store the numbers in a vector of doubles. Output the vector's numbers on one line, each number followed by one space.
Also output the total weight, by summing the vector's elements.
Also output the average of the vector's elements.
Also output the max vector element.
So far this is the code i have
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
int maxWeight = 0;
int temp = 0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": ";
cout << inputWeights[i]<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++) {
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
When i run this code, whatever inputs i use(for the cin>>(...)), i get all zero's as output and i do not know why. can i get some help please.
update
cleaned up the code a little by getting rid of the cout<< inputWeights[i]<< endl;
and by adjusting vector inputWeights; at the beginning of the program.But the outputs are still not exactly what they are supposed to be. Instead, only the first 2 inputted values make it as outputs. Any reason why? thanks
update this is the right or correct code. Hope it helps someone in future.
#include <iostream>
#include <vector>
using namespace std;
int main() {
const int NEW_WEIGHT = 5;
vector <float> inputWeights;
int i = 0;
float sumWeight = 0.0;
float AverageWeight = 1.0;
float maxWeight = 0.0;
float temp = 0.0;
for (i = 0; i < NEW_WEIGHT; i++){
cout << "Enter weight "<< i+1<< ": "<< endl;
cin>> temp;
inputWeights.push_back (temp);
}
cout << "\nYou entered: ";
for (i =0; i < NEW_WEIGHT- 1; i++){
cout << inputWeights.at(i)<< " ";
}
cout<< inputWeights.at(inputWeights.size() - 1) << endl;
for (i =0; i < NEW_WEIGHT; i++){
sumWeight += inputWeights.at(i);
}
cout <<"Total weight: "<< sumWeight<< endl;
AverageWeight = sumWeight / inputWeights.size();
cout <<"Average weight: "<< AverageWeight<< endl;
maxWeight= inputWeights.at(0);
for (i =0; i < NEW_WEIGHT- 1; i++){
if (inputWeights.at(i) > maxWeight){
maxWeight = inputWeights.at(i);
}
}
cout<< "Max weight: "<< maxWeight << endl;
return 0;
}
You're making a vector of size 5:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
// == 0, 0, 0, 0, 0
Then, in your input loop, you're adding new values to the end:
inputWeights.push_back (42);
// == 0, 0, 0, 0, 0, 42
Then you're outputting the first five elements which were always zero.
You need to choose one thing or the other: either set the size of the vector at the start of the program, or grow the vector with push_back for as long as there's input. Both are valid options.
You can clean up your code and fix the problems by adopting modern C++ (as in, C++11 and later) idiom. You don't need to fill your code with for(int i = 0; i < something; i++) any more. There's a simpler way.
// Size fixed in advance:
vector<float> weights(NUM_WEIGHTS);
for (auto& weight : weights) { // note it's `auto&`
cout << "\nEnter next weight: ";
cin >> weight; // if it was plain `auto` you'd overwrite a copy of an element of `weight`
}
// Size decided by input:
vector<float> weights; // starts empty this time
cout << "Enter weights. Enter negative value to stop." << endl;
float in;
while (cin >> in) {
if(in < 0) {
break;
}
weights.push_back(in);
}
In either case, you can then play with the filled vector using another range-based for:
cout << "You entered: ";
for (const auto& weight : weights) {
cout << weight << " ";
}
You'll also need to remove the cout << inputWeights[i] << endl; line from your input loop if you resize the vector during input - as written you'd be reading elements which don't exist yet, and will probably get an array-index-out-of-bounds exception.
When you create define your inputWeights you are putting 5 items into it with default values.
vector<float> inputWeights(NEW_WEIGHT);
Change it to be just
vector<float> inputWeights;
And get rid of this line in your code or comment it out
cout << inputWeights[i]<< endl;
This is what you are looking for from the requirements of your program.
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
unsigned i = 0;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " ";
}
std::cout << std::endl;
double totalWeight = 0.0;
std::cout << "The total of all weights is: ";
for ( i = 0; i < weights.size(); ++i ) {
totalWeight += weights[i];
}
std::cout << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: ";
double max = weights[0];
for ( i = 0; i < weights.size(); ++i ) {
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << max << std::endl;
return 0;
}
The culprit to your problem for seeing all 0s as output is coming from these two lines of code:
const int NEW_WEIGHT = 5;
vector<float> inputWeights(NEW_WEIGHT);
which is the same as doing this:
vector<float> inputWeights{ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
you are then looping through up to 5 elements using NEW_WEIGHT when it would be easier to use inputWeights.size() when traversing through containers.
Edit - Condensed Version
#include <vector>
#include <iostream>
int main() {
std::vector<double> weights;
double currentWeight = 0.0;
const unsigned numberOfWeights = 5;
unsigned i = 0;
std::cout << "Enter " << numberOfWeights << " weights" << std::endl;
for ( ; i < numberOfWeights; ++i ) {
std::cin >> currentWeight;
weights.push_back( currentWeight );
}
double totalWeight = 0.0;
double max = weights[0];
std::cout << "These are the weights that you entered: " << std::endl;
for ( i = 0; i < weights.size(); ++i ) {
std::cout << weights[i] << " "; // Print Each Weight
totalWeight += weights[i]; // Sum The Weights
// Look For Max Weight
if ( weights[i] > max ) {
max = weights[i];
}
}
std::cout << std::endl;
std::cout << "The total of all weights is: " << totalWeight << std::endl;
std::cout << "The average of all the weights is: " << (totalWeight / numberOfWeights) << std::endl;
std::cout << "The max weight is: " << max << std::endl;
return 0;
}
Related
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.
I need to transfer elements from the total costs (int totalCosts) into a new array to be called costs[]. I tried doing this at the end of the code but when I tried to access the first element in the array, it shows ALL the total costs from the output. I only needed to access the first one.
// ******** CREATE "example.txt" IN THE FOLDER THAT HAS THE PROJECT'S .CPP FILE ********
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <iterator>
using namespace std;
class vehicle_capacities {
public:
int lw, vw;
};
double nearest_ten(double n)
{
return round(n / 10.0 + 0.4) * 10.0;
}
bool cmp_fn(int a, int b)
{
return a > b;
}
int main()
{
int cw;
vehicle_capacities cap;
cap.lw = 30;
cap.vw = 10;
ifstream myfile("example.txt");
if (myfile.is_open()) {
myfile >> cw;
myfile.close();
}
else {
cout << "Unable to open file" << endl;
}
cout << "Amount of cargo to be transported: " << cw;
cw = nearest_ten(cw);
cout << "(" << cw << ")" << endl;
int maxl = cw / cap.lw; // maximum no. of lorries that can be there
vector<pair<int, int>> solutions;
//vector<int> costs;
vector<int>::iterator it;
// for the inclusive range of 0 to maxl, find the corresponding no. of vans for each variant of no of lorries
for (int l = 0; l <= maxl; ++l) {
bool is_integer = (cw - l * cap.lw) % cap.vw == 0; // only if this is true, then there is an integer which satisfies for given l
if (is_integer) {
int v = (cw - l * cap.lw) / cap.vw; // no of vans
solutions.push_back(make_pair(l, v));
}
}
cout << "Number of mini-lorries: ";
for (auto& solution : solutions) {
cout << solution.first << " ";
}
cout << "\n";
cout << "Number of vans: ";
for (auto& solution : solutions) {
cout << solution.second << " ";
}
cout << "\n";
cout << "Total cost: ";
// LORRY COST = $200, VAN COST = $45
for (auto& solution : solutions) {
int totalCosts = (solution.first * 200) + (solution.second * 45);
cout << totalCosts << " ";
}
/*for (auto& solution : solutions) {
int totalcosts = (solution.first * 200) + (solution.second * 45);
costs.push_back(totalcosts);
for (it = costs.begin(); it < costs.end(); it++) {
cout << *it << " ";
}
}*/
cout << endl;
// Comparison between both vehicles, highest amount = trips needed
cout << "Trips Needed: ";
for (auto& solution : solutions) {
int a = solution.first;
int b = solution.second;
if (a > b) {
cout << a << " ";
}
else if (b > a) {
cout << b << " ";
}
else if (a == b) {
cout << a << " ";
}
}
cout << endl;
cout << "Lowest #1: ";
for (auto& solution : solutions) {
int totalCosts[] = { (solution.first * 200) + (solution.second * 45) };
int elements = sizeof(totalCosts) / sizeof(totalCosts[0]);
sort(totalCosts, totalCosts + elements, cmp_fn);
for (int i = 0; i < elements; ++i) // print the results
cout << totalCosts[i] << " ";
cout << totalCosts[0] << " ";
}
// *** FOR SORTING ELEMENTS IN ARRAY LOW TO HIGH ***
/*int array[] = { 1,10,21,55,1000,556 };
int elements = sizeof(array) / sizeof(array[0]); // Get number of elements in array
sort(array, array + elements);
for (int i = 0; i < elements; ++i) // print the results
cout << array[i] << ' ';*/
return 0;
}
Do update if you have any solutions, thank you.
(Note that you have to create "example.txt" in project file.
You need to dynamically allocate your array.
int elements = solution.size();
int *totalCosts = new int[elements];
int j= 0;
// transfer data
for (auto& solution : solutions) {
totalCosts[j++] = (solution.first * 200) + (solution.second * 45);
}
sort(totalCosts, totalCosts + elements, cmp_fn);
for (int i = 0; i < elements; ++i) // print the results
cout << totalCosts[i] << " ";
cout << totalCosts[0] << " ";
delete[] totalCosts;
Here is what I have. I have notes in the code where I'm having trouble towards the bottom. I'm trying to find the total average of the grades entered by the user. The user has put in four different grades near the bottom. They are weighted as 10% of the grade.
The Programs are 30% and the exercises are 10%. The final Exam is 30%. Please just give me advice on what to do. Don't tell me the code. I want to try and figure the code out on my own before asking for additional help so that I learn this. I just want advice on what steps to take next. Thanks.
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
using namespace std;
float average(const vector<float> &values);
int main()
{
cout << "Kaitlin Stevers" << endl;
cout << "Program 11" << endl;
cout << "December 8th 2016" << endl;
cout << endl;
cout << endl;
vector<float> exerciseGradesVector;
float exerciseGrades;
cout << "Enter the grades for the Exercises. Type 1000 when you are finished." << endl;
while ( std::cin >> exerciseGrades && exerciseGrades != 1000 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
cout << endl;
cout << "You entered " << exerciseGradesVector.size() << " grades." << endl;
cout << endl;
cout << "The Exercise grades you entered are : ";
for(int i=0; i < exerciseGradesVector.size(); i++)
{
cout << exerciseGradesVector[i] << " ";
}
cout << endl;
float averageExerciseGrades = average( exerciseGradesVector );
cout << "The average of the Exercise grades is: " << averageExerciseGrades << endl;
cout << endl;
vector<float> programGradesVector;
float programGrades;
cout << "Enter the grades for the Programss. Type 1000 when you are finished." << endl;
while ( std::cin >> programGrades && programGrades != 1000 )
{
programGradesVector.push_back (programGrades);
}
cout << endl;
cout << "You entered " << programGradesVector.size() << " grades." << endl;
cout << endl;
cout << "The Program grades you entered are : ";
for(int i=0; i < programGradesVector.size(); i++)
{
cout << programGradesVector[i] << " ";
}
cout << endl;
float averageProgramGrades = average( programGradesVector );
cout << "The average of the Program grades is: " << averageProgramGrades << endl;
cout << endl;
float midTermTest;
float midTermProgram;
float finalExamTest;
float finalExamProgram;
cout << "Please enter the Midterm Exam score for the multipule choice section. " << endl;
cin >> midTermTest;
cout << "Please enter the Midterm Exam score for the Programming section. " << endl;
cin >> midTermProgram;
cout << "Please enter the Final Exam score for the multipul choice section. " << endl;
cin >> finalExamTest;
cout << "Please enter the Final Exam score for the Programming section. " << endl;
cin >> finalExamProgram;
///////I need to find the average off ALL the grades.. All the 4 inputs above and the two vectors need to be in the average.
///////I am not sure if I need to read the 3 numbers before the last one into a vector because each is worth 10 percent and then do the next step or what. Would that mess it up? Advice please?
vector<float> allGradesVector;
float totalaverageGrade = average( allGradesVector ); //This is obviously not finished. Just ignore it..
}
float average( const vector<float> &values )
{
float sum = 0.0;
for ( size_t i = 0; i < values.size(); i++ ) sum += values[i];
return values.size() == 0 ? sum : sum / values.size();
}
I would suggest to rewrite the loops like this
do
{
cin >> exerciseGrades;
exerciseGradesVector.push_back (exerciseGrades);
}
while (exerciseGrades != 1000);
the following way
while ( std::cin >> exerciseGrades && exerciseGrades != 1000 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
In this case there is no need to use a strange variable like dropOne.
To find the average is easy. The function can look the following way
float average( const std::vector<float> &values )
{
float sum = 0.0f;
for ( float x : values ) sum += x;
return values.size() == 0 ? sum : sum / values.size();
}
Or if the compiler does not support the range-based for loop you can write
float average( const std::vector<float> &values )
{
float sum = 0.0f;
for ( size_t i = 0; i < values.size(); i++ ) sum += values[i];
return values.size() == 0 ? sum : sum / values.size();
}
To call the function you can write for example in main
float averageExerciseGrades = average( exerciseGradesVector );
The function must be declared before its usage that is for example before main
float average( const std::vector<float> &values );
though it may be defined after main.
A simple for loop will do the trick.
float total = 0;
int count = 0
for(int i = 0; i < dropOnee; i++)
{
total+= programGradesVector[i];
count++;
}
cout << "The average is: " total/count << endl;
I'd also recommend using more descriptive name's for the counts.
You can use std::accumulate
float average = accumulate(programGradesVector.begin(), programGradesVector.end(), 0.0) / programGradesVector.size();
I would suggest to use while to replace do while. Because you may input 1000 firstly.
You can write like this:
while ( std::cin >> exerciseGrades && fabs(exerciseGrades - 1000) < 0.000001 )
{
exerciseGradesVector.push_back (exerciseGrades);
}
I use fabs function to solve float is inaccuracy in sometime.
About averages function:
You can use std::accumulate:
float average = accumulate(programGradesVector.begin(), programGradesVector.end(), 0.0) / programGradesVector.size();
or implement it by yourself like this:
float average( const std::vector<float> &values )
{
float sum = 0.0f;
int nSize = values.size();
for(int i = 0; i < nSize; ++i)
{
sum += values[i];
}
return nSize == 0 ? sum : sum / nSize;
}
I'm trying to do some of my C++ homework, but I seem to have run into an issue. I need to make it so that the user inputs 8 numbers, and those said 8 get stored in an array. Then, if one of the numbers is greater than 21, to output said number. The code is below, and it's kind of sloppy. Yes, first year C++ learner here :p
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
// Determine sum
sumVal = 0;
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Don't reinvent the wheel, use standard algorithms:
std::copy_if(std::begin(userVals), std::end(userVals),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
I improved the rest of your program as well:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <vector>
auto constexpr count = 8;
int main() {
std::vector<int> numbers(count);
std::cout << "Enter " << count << " integer values...\n";
std::copy_n(std::istream_iterator<int>(std::cin), numbers.size(), numbers.begin());
std::copy_if(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\n"),
[] (auto x) { return x > 21; });
auto sum = std::accumulate(numbers.begin(), numbers.end(), 0);
std::cout << "Sum: " << sum << '\n';
return 0;
}
See it live on Coliru!
Ok, I'm going to explain this to you and keep it simple. This loop
`for (int i = NUM_ELEMENTS - 1; i > 21; i--)`
will never execute because in your first iteration you are checking if (NUM_ELEMENTS-1=7)>21. You are then decrementing i so this will take the series (6,5,4,...) and nothing would ever happen here.
If you have to sum the numbers greater than 21, which I presume is what you need then you will have to remove the above loop and modify your second loop to:
for (i = 0; i < NUM_ELEMENTS; i++) {
if(userVals[i]>21)
sumVal = sumVal + userVals[i];
}
This way, you add the numbers in the array that are only greater than 21. The index of userVals is determined by the i variable which also acts as a counter.
You're on the right track. There's just a few things wrong with your approach.
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8;
int userVals[NUM_ELEMENTS];
int i = 0;
int sumVal = 0;
int prntSel = 0;
int size = sizeof(userVals) / sizeof(int); // Get size of your array
// 32/4 = 8 (ints are 4 bytes)
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
for(int i = 0; i < size; i++) {
if(userVals[i] > 21) { // Is number > 21?
cout << userVals[i] << endl; // If so, print said number
exit(0); // And exit
}
else
sumVal += userVals[i]; // Else sum your values
}
cout << "Sum: " << sumVal << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
const int NUM_ELEMENTS = 8; // Number of elements
int userVals[NUM_ELEMENTS]; // User numbers
int i = 0; // Loop index
int sumVal = 0; // For computing sum
int prntSel = 0; // For printing greater than 21
// Prompt user to populate array
cout << "Enter " << NUM_ELEMENTS << " integer values..." << endl;
for (i = 0; i < NUM_ELEMENTS; ++i) {
cin >> userVals[i];
}
// for (int i = NUM_ELEMENTS - 1; i > 21; i--)
// cout << "Value: " << sumVal << endl;
for( i = 0; i < NUM_ELEMENTS; ++i )
{
if( userVals[ i ] > 21 )
{
cout << "Value: " << i << " is " << userVals[ i ] << endl;
}
}
for (i = 0; i < NUM_ELEMENTS; ++i) {
sumVal = sumVal + userVals[i];
}
cout << "Sum: " << sumVal << endl;
return 0;
}
Try
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
to
for (i = 0; i < NUM_ELEMENTS; ++i) {
if(userVals[i] > 21)
cout << "Value: " << userVals[i] << endl;
}
This line isnt needed as well, as you arent using it.
int prntSel = 0; // For printing greater than 21
for (int i = NUM_ELEMENTS - 1; i > 21; i--)
cout << "Value: " << sumVal << endl;
Here you are printing the value of sumVal, not the value of the array in the position i. The line should be:
cout << "Value: " << usersVals[i] << endl;
Also that that your for is not doing what you think it does. for doesn't use the condition you gave to decide if will execute the current iteration or not, it uses the condition to decide if the loop should continue or not. So when you put i > 21, means that it will continue running while i is bigger than 21. To achieve your goal, you should make a test (if statement) inside the loop.
The final result it would be:
for (i = 0; i < NUM_ELEMENTS; ++i) {
if (usersVals[i] > 21) {
cout << "Value: " << usersVals[i] << endl;
}
}
The problem is:
A Class of 40 students has received their grades for 5 exams. Implement a function that calculates the worst average grade and display the the IDs of all students having the worst average grade.
I already calculated the average but do not know how to calculate the WORST average ( as in the lowest average of the 40 students) and displaying the ID numbers that have this number.
This is what I have written so far:
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
Something like this:
Note: I have added some important statements!
#include<iostream>
#include <iomanip>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
float AVG[MAX_NUM];
int worstIDCount = 0;
int main()
{
float avg, min = 1001;
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
avg = 0;
total = 0;
cout << "Enter an ID number: " << endl;
cin >> x[i];
cout << "Enter 5 grades: " << endl;
for (int j = 0; j < 5; j++)
{
cin >> y[j];
while (y[j]>100)
{
cout << "Please enter a valid grade that is less than a 100: " << endl;
cin >> y[j];
}
total += y[j];
}
avg = total / 5;
AVG[i] = avg;
if(avg < min)
min = avg;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg << endl;
}
for(int i = 0; i < MAX_NUM; i++)
{
if(AVG[i] == min)
cout << "Student with WORST Average: ID" << x[i] << endl;
}
};
So you want to store these averages in a std::vector<float>, std::sort it and get the lowest. Then go back and find the students that have that average.
working example
#include <iostream>
#include <vector>
#include <functional> // mem_fn
#include <algorithm> // sort, upper_bound
#include <iterator> // ostream_iterator
struct Student_average {
int student_id;
float average;
};
bool compare_student_averages(Student_average const &lhs,
Student_average const &rhs) {
return lhs.average < rhs.average;
}
int main() {
std::vector<Student_average> averages;
// collect the data and populate the averages vector
// ...
sort(begin(averages), end(averages), compare_student_averages);
std::cout << "The worst average is: " << averages.front().average << '\n';
auto end_of_worst_student_averages =
upper_bound(begin(averages), end(averages), averages.front(),
compare_student_averages);
std::cout << "The IDs of the students with the worst averages are:\n";
transform(begin(averages), end_of_worst_student_averages,
std::ostream_iterator<int>(std::cout, "\n"),
std::mem_fn(&Student_average::student_id));
}
Here is a more C++ way of doing this using std::accumulate and std::min_element (I removed the check for anything > 100, for brevity):
#include <iostream>
#include <algorithm>
#include <numeric>
using namespace std;
const int MAX_NUM = 6;
int x[MAX_NUM];
int y[5];
int main()
{
float avg[5];
float total = 0;
for (int i = 0; i < MAX_NUM; i++)
{
cin >> x[i]; // ID
for (int j = 0; j < 5; ++j)
cin >> y[j]; // grades
// compute the average for this student
avg[i] = std::accumulate(y, y + 5, 0) / 5.0F;
cout << "ID: " << x[i] << endl;
cout << "Average: "<< avg[i] << endl;
}
// compute the worst average
float* worst_average = std::min_element(avg, avg + MAX_NUM);
// get the position in the array where the worst is found
int position = std::distance(avg, worst_average);
// output results
cout << "This person has the worst average: " << x[position]
<<". The average is " << *worst_average << "\n";
}
Note that the averages are stored in an array. The way the average is computed for each person is to use std::accumulate to add up the y array values, and then divide by 5.0.
Since we now have the averages in an aray, we want to find the smallest item in the array. To do that, min_element is used to get us the position of where the element is stored.
The trick here is that min_element returns a pointer to the smallest item, so we need calculate how far this pointer is located from the beginning of the avg array. To do this, the std::distance function is used. This now gives us the position of the smallest item.
The rest of the code just outputs the results.
As you can see, the only loops involved were the input loops. The calculation of the average and the worst average were done using accumulate and min_element, respectively.