Exercise: for cycle and array - c++

I have to write a program that allows to calculate the arithmetic average of an arbitrary numbers of values (chosen by the user)
It will outputs:
Number: 34
Number: 36
Number: 44
Number: //and I choose to stop input pressing
//Outputs:
It was inserted 3 numbers and the avarage is: 38
Of course i've forgot to post what i've done:
for (int x = 0; x < 50; x++){
cout << "Number: ";
cin >> number[x];
cout << "You have inserted the " << x << " element of the array;" << endl;
sum += number[x];
avarage = sum / number[x];
nEelementi = number[x];}
so I run the program, input some numbers, press something like ctrl+d or trying to add something to the code.. but it only goes from the first to the last element of the array with no values, becouse not entered, of course.. and then print absurd avarage and sum.
I know I don't need an array to do this but it's required from the exercise.. also the exercise only request to use for or while loop and arrays.
What I need is a way to stop the input and calculate the sum and avarage of only what I wrote.
edit1.
I've tried to dived by n writing for(x = 0; x < n, x++) because it made sense to me, but i think it "thinks" n, wrote like this, infinite, because the results is 0 (because the limit of a number divided by infinite is 0).. so i've started becoming mad.
Now i've started thinking that it would be easier to use while loop! and wrote
#include <iostream>
using namespace std;
int main() {
int num[50];
double sum = 0;
double average = 0;
int cont;
int end = 0;
while (cont < 50) {
cout << "num: ";
cin >> num[cont];
sum += num[cont];
cont++;
cout << "Want to continue 0 = sì, 1 = no";
cin >> end;
if (end == 1) {break;}
}
average = sum / cont;
cout << "You have insert " << cont << " elements" << endl;
cout << "LThe sum is: " << sum << endl;
cout << "The avarage is: " << average << endl;
return 0;
}
BUT still doesn't work. My professor says you should be able to stop input number by pressing ctrl+d so I'm not doing good.
Sorry for late answer but i have also to translate the code.. hope all translation is good:)
edit2.
#include <iostream>
int main() {
int sum = 0;
int num;
while ( std::cin ) {
std::cout << "Number: ";
std::cin >> num;
}
if ( std::cin >> num ) {
sum += num;
num++;
}
else {
std::cin.clear();
std::cout << "Input interrupted" << std::endl;
}
std::cout << "Sum is " << sum << std::endl;
std::cout << "You have entered " << num << " numbers" << std::endl;
return 0;
}
I love this new code, very simple and understandable to me, but I was not able to add sum operation, it only outputs 0! (leaving out average)
And also I was not able to determinate, and display, how many numbers I've entered. The last row of the code is just an example of what I want to do..
edit3.
Finally I made it.
#include <iostream>
using namespace std;
int main(){
double numero;
int index = 0;
double somma = 0.;
cout << "Inserire un numero: ";
while( cin )
{
if ( cin >> numero )
{
somma = somma + numero;
index++;
cout << "Inserire un numero: ";
}
else
{
cout << "Input interrotto" << endl;
}
}
cout << "Sono stati inseriti " << index << " numeri e la lora media è:
<< somma / index << endl;
return 0;
}
Thanks so much!
P.S. To the end, I don't need to use an array, it's just simple

There are a few problems here. One is that if the stream errors due to being closed or bad input, you don't recover and you just charge through your loop.
So first, make the loop terminate early if necessary. I'm also going to convert it to a while loop in preparation for the next part.
int x = 0;
while( std::cin && x < 50 )
{
std::cin >> number[x++];
}
Now it terminates early if the stream errors. But what if the user typed in "hello"? You could ignore it and continue like this:
if( std::cin >> number[x] )
{
x++;
}
else
{
std::cin.clear();
}
Notice that I didn't compute the sum or anything inside the loop. There's no need, since you are already putting them in an array. You can just do it after the loop. Here, I'm using std::accumulate
double sum = std::accumulate( number, number + x, 0.0 );
double average = 0.0;
if( x > 0 ) average = sum / x;
Now, you have also said you want an arbitrary number of values. Your original code allowed up to 50. Instead of storing them, you can instead just compute on the fly and discard the values.
double sum = 0.0;
int count = 0;
while( std::cin )
{
double value;
if( std::cin >> value )
{
sum += value;
count++;
}
else
{
std::cin.clear();
}
}
double average = 0.0;
if( count > 0 ) average = sum / count;
If you still want to store the values along the way, you can use a vector.
std::vector<double> numbers;
//...
numbers.push_back( value );
And if you want the user to choose the number of values:
std::cout << "Enter number of values: " << std::flush;
std::size_t max_count = 0;
std::cin >> max_count;
std::vector<double> numbers;
numbers.reserve( max_count );
while( std::cin && numbers.size() < max_count )
{
// ...
}

Related

the code still print 0 and it can't calculate the required task

#include <iostream>
using namespace std;
int main()
{
int n, G;
float num[500], sum=0.0, average,Grades;
cout << "Enter the numbers of data: ";
cin >> n;
while (n > 500 || n <= 0)
{
cout << "Error! number should in range of (1 to 500)." << endl;
cout << "Enter the number again: ";
cin >> n;
}
for(G = 0; G < n; ++G)
{
cout << G + 1 << ". Enter number: ";
cin >> num[G];
sum += num[G];
}
average = sum / n;
Grades = num[G] >= average;
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average : " <<Grades<< endl;
cout << "Number of grades above the Average = "<<(int) Grades;
return 0;
}
i coded this code but the Number of grades above the Average and Grades above or equal the Average don't work it just print 0
i tried to print the Grades >= the avg but it print 0
also num of Grades also print 0
where is the error ?
I think you was trying to do something like this:
...
int grades_on_avg, upper_grades = 0;
for(int i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
average = sum / n;
for(int i = 0; i < n; ++i) // use separate for loop and redefined index
{
if(num[i] == average) // compare to average
grades_on_avg++;
else if(num[i] > average) // if bigger than average
upper_grades++;
}
cout<<endl;
cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average =" << (grades_on_avg + upper_grades) << endl;
cout << "Number of grades above the Average = "<< upper_grades ;
You assign boolean value to Grades variable. Also, you refer to element outside of the array: G variable is equal to n after exiting for-loop, but max index you can use is n - 1 (basic programming rule). So, you should change your code into something like this:
...
int avgGrades{0};
int avgAboveGrades{0};
for(int i{0}; i < n; ++i)
{
if(num [i] == average)
{
++avgGrades;
}
else if(num [i] > average)
{
++avgAboveGrades;
}
}
If you prefer more elegant ways of doing so, you can use std::count_if() function but it's more tricky and requires knowledge about lambdas.

How to take an average of values entered into a C++ program?

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;
}

Greedy Algorithm for coin change c++

So, I'm creating a coin change algorithm that take a Value N and any number of denomination and if it doesn't have a 1, i have to include 1 automatically. I already did this, but there is a flaw now i have 2 matrix and i need to use 1 of them. Is it possible to rewrite S[i] matrix and still increase the size of array.... Also how can i find the max denomination and the second highest and sooo on till the smallest? Should i just sort it out in an highest to lowest to make it easier or is there a simpler way to look for them one after another?
int main()
{
int N,coin;
bool hasOne;
cout << "Enter the value N to produce: " << endl;
cin >> N;
cout << "Enter number of different coins: " << endl;
cin >> coin;
int *S = new int[coin];
cout << "Enter the denominations to use with a space after it" << endl;
cout << "(1 will be added if necessary): " << endl;
for(int i = 0; i < coin; i++)
{
cin >> S[i];
if(S[i] == 1)
{
hasOne = true;
}
cout << S[i] << " ";
}
cout << endl;
if(!hasOne)
{
int *newS = new int[coin];
for(int i = 0; i < coin; i++)
{
newS[i] = S[i];
newS[coin-1] = 1;
cout << newS[i] << " ";
}
cout << endl;
cout << "1 has been included" << endl;
}
//system("PAUSE");
return 0;
}
You could implement it with std::vector, then you only need to use push_back.
std::sort can be used to sort the denominations into descending order, then it's just a matter of checking whether the last is 1 and adding it if it was missing. (There is a lot of error checking missing in this code, for instance, you should probably check that no denomination is >= 0, since you are using signed integers).
#include <iostream> // for std::cout/std::cin
#include <vector> // for std::vector
#include <algorithm> // for std::sort
int main()
{
std::cout << "Enter the value N to produce:\n";
int N;
std::cin >> N;
std::cout << "Enter the number of different denominations:\n";
size_t denomCount;
std::cin >> denomCount;
std::vector<int> denominations(denomCount);
for (size_t i = 0; i < denomCount; ++i) {
std::cout << "Enter denomination #" << (i + 1) << ":\n";
std::cin >> denominations[i];
}
// sort into descending order.
std::sort(denominations.begin(), denominations.end(),
[](int lhs, int rhs) { return lhs > rhs; });
// if the lowest denom isn't 1... add 1.
if (denominations.back() != 1)
denominations.push_back(1);
for (int coin: denominations) {
int numCoins = N / coin;
N %= coin;
if (numCoins > 0)
std::cout << numCoins << " x " << coin << '\n';
}
return 0;
}
Live demo: http://ideone.com/h2SIHs

What is a way to solve this with loops in c++?

I've been coding all night so my head is in a state of shock. I'm trying to do the following, but I just don't get what our professor wants us to do. "Input an unsigned and call it number.. Then input number double values, then output the sum and product of the numbers. (If number is zero, then 0 doubles will be input; the sum of 0 numbers is 0, and the product of 0 numbers is 1)"
I could really appreciate if someone could help me with this. Thank you.
Edit:
This is what i have so far, The thing I'm currently confused with is on how to make the unsigned variable be the number of double inputs inside of the loop.
unsigned number, x;
double double_num, sum;
cout << "Input the number of value: \n";
cin >> number;
for (x = 0; x > number; x++) {
cin >> double_num;
}
return 0;
What're you having difficulty with?
Here's a start:
// Input an unsigned and
unsigned int g;
cout << "Please Enter an unsigned int value, g" << endl;
cin >> g;
In your loop, you have:
for (x = 0; x > number; x++) {
Which means:
x is set to Zero.
While x is bigger than some-number, keep going...
When do you think zero is bigger than a number such as 5??
How many times do you think that loop will run??
int main(void)
{
unsigned g;
double product(1);
double sum(0);
cout << "Input the number of value: \n";
cin >> g;
for (unsigned x = 0; x < g; x++) {
double n;
cout << "Input a number: " <<endl;
cin >> num;
product *= num;
sum += num;
}
cout << "The product is" << product << "\n";
cout << "The sum is" << sum << "\n" << endl;;
return 0;
}
You need something like the following:
#include<iostream>
#include<cstdlib>
int main()
{
unsigned int n;
std::cin >> n;
double g, p=1, s=0;
while (n-->0 && std::cin >> g) p*=g,s+=g;
return std::cin
? std::cout << s << std::endl << p << std::endl, EXIT_SUCCESS
: (std::cerr << "Failed to read all inputs" << std::endl, EXIT_FAILURE);
}
You should be sure that you understand each statement and be prepared to justify your choices; if not, you probably haven't learnt anything and will be unlikely to pass your course.

C++ Loop to find Min, Max, Avg and Sum of user Inputs

I was asked to write a program to find the minimum, maximum, average and sum of user inputs and I came up with the following program but there seems to be a problem with the loop I'm using because the program just exits when compiled. Can someone please point the errors to me?
Thank you so much.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
bool empty = true;
int max, min, count, avg, sum=0;
char choice;
for (count = 0; count++;)
{
do
{
cout << "Enter a number: ";
int num;
cin >> num;
if (empty)
{
empty = false;
min = num;
max = num;
}
else if (max < num)
{
max = num;
}
else if (num < min)
{
min = num;
}
sum = sum + num;
avg = sum / count;
cout << "Do you want to continue?: ";
cin >> choice;
} while (choice == 'y' || choice == 'Y');
if (!empty)
{
cout << " Maximum is " << max << endl;
cout << " Minimum is " << min << endl;
cout << " Sum is " << sum << endl;
cout << " Average is " << avg << endl;
}
}
return 0;
}
Your for loop is incorrect:
for (count = 0; count++;)
Remember that a for loop is:
for (initialization; expression; update)
count++ adds 1 to count but returns its original value 0, which is converted to false. Because the expression is false, the loop stops.
This is the problematic line
avg = sum / count;
in the first iteration of the loop when count is set to 0.
I suggest you remove that line from the loop and put it after the loop.
I would also change when count is incremented. It needs to be incremented right after you read a number.
You have an error in you for expression.
A for loop is of the form for(<init>; <condition>; <step>){<body>}, the init statement gets executed once at the beginning, then the condition gets checked. If the condition evaluates to true, the body gets executed, and then the step statement. After that we go back to condition, and keep going like that until condition evaluates to true.
In your loop, you have count++ as your condition. An expression of the form value++ first returns value, and then increments value. So in your case, the first time the condition gets executed, it evaluates to 0. 0 is equivalent to false, so the loop exits immediately.
In your program, you don't really seem to need the for-loop. All the looping is being done in the do-while-construct. To fix your code, you should set count to 0 before the do-while loop, and then increment count every time the user has entered a number (so right after cin).
A working version would look something like this:
int main()
{
bool empty = true;
int max, min, count = 0, avg, sum=0;
char choice;
do
{
cout << "Enter a number: ";
int num;
cin >> num;
count++;
if (empty)
{
empty = false;
min = num;
max = num;
}
else if (max < num)
{
max = num;
}
else if (num < min)
{
min = num;
}
sum = sum + num;
avg = sum / count;
cout << "Do you want to continue?: ";
cin >> choice;
} while (choice == 'y' || choice == 'Y');
if (!empty)
{
cout << " Maximum is " << max << endl;
cout << " Minimum is " << min << endl;
cout << " Sum is " << sum << endl;
cout << " Average is " << avg << endl;
}
return 0;
}
How about this which gets rid of the outer loop entirely.
#include <algorithm>
#include <limits>
#include <iostream>
using namespace std;
int main()
{
int max = std::numeric_limits<int>::min(), min = std::numeric_limits<int>::max();
int count = 0, avg = 0, sum = 0;
char choice;
do
{
cout << "Enter a number: ";
int num;
cin >> num;
++count;
max = std::max(max, num);
min = std::min(min, num);
sum += num;
avg = sum / count;
cout << "Do you want to continue?: ";
cin >> choice;
} while (choice == 'y' || choice == 'Y');
if (count > 1)
{
cout << " Maximum is " << max << endl;
cout << " Minimum is " << min << endl;
cout << " Sum is " << sum << endl;
cout << " Average is " << avg << endl;
}
return 0;
}
Initialize all variables (good C/C++ practice).
Use std::min and std::max rather than roll your own.
Remove empty because by setting the initial values of min and max correctly it is no longer required.
Fix the divide by zero error pointed out by R Sahu.