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

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.

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.

While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0

While getting user input, I set the smallest and largest numbers input into their own variables, but for whatever reason they start out = to 0.
Code:
#include <iostream>
using namespace std;
int main()
{
int num;
string var;
int sum = 0;
int i;
int largest = INT_MIN;
int smallest = INT_MAX;
int j = 0;
int prime = 0;
do {
cout << "Please enter a series of numbers, press (Q or q) to process: ";
cin >> num;
if (cin.fail())
{
cin.clear();
cin >> var;
if (var != "Q" && var != "q")
{
cout << "Invalid input, try again" << endl;
}
}
if (num > largest)
{
largest = num;
}
if (num < smallest)
{
smallest = num;
}
if (num == 0 || num == 1)
{
prime = prime;
}
else
{
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
j = 1;
break;
}
}
if (j == 0)
{
prime++;
}
}
sum += num;
cout << "The corresponding element for the cumulative total sequence is: " << sum << endl;
cin.ignore(sum, '\n');
} while (var != "Q" && var != "q");
cout << endl;
cout << "Largest number: " << largest << endl;
cout << "Smallest number: " << smallest << endl;
cout << "How many prime numbers? " << prime << endl;
cout << "Have a great day!" << endl;
}
Here is an example of the program being run.
Program example
The smallest number here should be 8, and the issue is that it begins at 0. The same thing with the largest number.
Program example #2
Your loop is testing the "num" variable even if the user inputs q or Q, adding an else statement else break; after the if (var != "Q" && var != "q") will fix it.
For the future, always keep in mind that when the "if" function fails, it will move on to the next line, if you need to to not execute, you either need to break out of the loop or change the structure of your code.

Exercise: for cycle and array

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 )
{
// ...
}

Vectors to find Median - homework

I'm a relatively new learner to C++ and I've been having some trouble. If you guys read the title, this is a homework problem (just letting you guys know out there) and I'm not really sure as to where my error is. Using GIT Bash, I can't see why this isn't compiling (or maybe i just don't know how to read it). I feel like i've touched upon all the bases and would appreciate a quick look over to see if my mistake is blaringly obvious. I've done a couple looks through stackoverflow and so the inputting values into a vector was used from another post but i've modified it a bit. In addition, I added in a sort for the vector from smallest to largest.
Also, how can I change the for statement to allow for variable #'s in the vector?
#include <iostream>
#include <vector>
using namespace std;
double showMedian(const vector<int> & vecmedian, int size)
{
int middle;
double average, median;
middle = size / 2.0;
if (size % 2 == 0)
{
median = (vecmedian[middle] + vecmedian[middle + 1]) / 2.0;
cout << "The median is: " << average << endl;
}
else
{
median = vecmedian[middle + 0] / 1.0;
cout << "The median is: " << median << endl;
}
return median;
}
int main()
{
int n,input, i;
vector<int> vecmedian;
vector<int>::iterator itr;
cout << "Enter the amount of numbers: ";
cin >> n;
cout << "Enter your numbers to be evaluated: " << endl;
while (vecmedian.size() < n && cin >> input){
vecmedian.push_back(input);
}
for(i = 1; i < 10; ++i){
for(itr = vecmedian.begin(); itr != vecmedian.end(); ++itr){
if(vecmedian[i] < *itr){
vecmedian.insert(itr, vecmedian[i]);
break;
}
}
if(itr == vecmedian.end())
vecmedian.push_back(vecmedian[i]);
}
showMedian();
return 0;
}
Point 1
When making function prototypes, you need to keep them consistent with the actual definition of the function.
You have:
void showMedian();
As a function-prototype but you have:
double showMedian(int *vecmedian, int size)
As the actual definition. They both need to be consistent.
Since you have not declared an array, maybe change the parameters of showMedian to:
double showMedian(const vector<int> & vecmedian, int size)
Point 2
if(nums[i] < *itr)
Where is nums declared?
Point 3
If you want to use the definition of showMedian, then use the parameters that it uses assuming you made the changes above (and assuming n is size).
showMedian(vecmedian, n);
Edit
With all the consulting in the comment section and the new updated OP Question, here is a fairly solid program which finds the median in a vector:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
double showMedian(const vector<double> & vecmedian, int num);
int main()
{
unsigned int n;
double input;
vector<double> vecmedian;
// cout << "Enter the amount of numbers: ";
do {
cout << "Enter the amount of numbers: ";
while(!(cin >> n)){
cout << "Wrong input" << endl;
cout << "Enter the amount of numbers: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (n == 0)
{
cout << "Invalid, size must be greater than 0" << endl;
}
} while (n == 0);
// cout << "Enter your numbers to be evaluated: " << endl;
for (int i = 1; i <= n; ++i)
{
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
while(!(cin >> input)){
cout << "Wrong input" << endl;
cout << "Enter number here (" << ((n + 1) - i) << " number/s remaining): ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
vecmedian.push_back(input);
}
// while (vecmedian.size() < n && cin >> input){
// vecmedian.push_back(input);
// }
sort(vecmedian.begin(), vecmedian.end());
showMedian(vecmedian, vecmedian.size());
return 0;
}
double showMedian(const vector<double> & vecmedian, int num)
{
int middle;
double median;
middle = (num / 2);
if (num % 2)
median = vecmedian[middle];
else
median = (vecmedian[middle - 1] + vecmedian[middle]) / 2.0;
cout << "The median is: " << median << endl;
return median;
}

Need help calculating AVG of array values (minus the lowest)

So I have succeeded in confusing the hell out of myself in doing this. I am trying to get it to calculate the average of the weights entered into the array minus the lowest weight in the array. I'm using functions and somewhere along the line I confused myself with passing variables. It would be much appreciated if someone could give me a pointer and tell me if I'm way off base or not. Also how would I compare the values entered to a validation code? I have a line commented out that I was fiddling with, but never got working.
#include <iostream>
using namespace std;
int getWeight();
int findLowest(int arrayWeight);
double calcAverage(int weight);
bool askToContinue();
int main(){
do{
int weights = getWeight();
double lowest = findLowest(weights);
double average = calcAverage(weights);
}
while(askToContinue());
}
int getWeight() {
//Variables
int weights[5]; //array
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
cin >> weights[counter];
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
return -1;
/*
do
{
//Gather user input of amount of discs
cout << "How many discs do you wish to purchase?" << endl;
cout << "Please enter a number between 1 and 1,000,000" << endl;
cin >> weights;
cout << endl;
validAmount = (weights > 5) && (weights <= 500); // Tests if the amount entered is valid
if (!validAmount) // Prompts user amount entered was invalid
{
cout << "Invalid Amount. Please try again!" << endl;
}
}
while(!validAmount); // Runs loop again if the amount entered was not valid
return discs;
*/
}
int findLowest(int arrayWeight){
int lowWeight = 999999;
if(lowWeight > arrayWeight)
{
lowWeight = arrayWeight;
}
cout << arrayWeight;
system("PAUSE");
return arrayWeight;
}
double calcAverage(int weight){
//Variables
float avgWeight = 0;
int sumWeight = 0;
//Calls findLowest function to find lowest value
int lowestWeight = findLowest(weight);
//Calculates the average score
return weight;
}
bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits.
{
char userResponse = ' ';
bool validInput = false;
do
{
cout << endl;
cout << "Do you wish to continue?" << endl;
cout << "Enter y for 'yes' or n for 'no'" << endl;
cin >> userResponse;
validInput = (userResponse == 'y') || (userResponse == 'n');
if (!validInput)
{
cout << "Invalid response. Please try again!" << endl;
}
} while (!validInput);
return(userResponse == 'y');
}
You have a number of issues, the first being you need to understand the data types you're working with. You should declare the array once and then pass around a pointer to that array. These are a better set of declarations and for convenience set up a constant for the number of weights.
#include <iostream>
using namespace std;
const int numWeights = 5;
void getWeights(int weights[]);
int findLowest(int weights[]);
double calcAverage(int weights[]);
bool askToContinue();
int main() {
do {
int weights[numWeights];
getWeights(weights);
double average = calcAverage(weights);
cout << "Average: " << average << endl;
}
while (askToContinue());
}
getWeights was mostly ok, but use the passed in array.
void getWeights(int weights[]) {
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
int weight;
cin >> weight;
while (weight < 5 || weight > 500)
{
cout << "Invalid weight, should be between 5 and 500" << endl;
cin >> weight;
}
weights[counter] = weight;
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
}
For findLowest you need to keep track of the lowest value and the lowest index. By remembering the index of the lowest value, you will make the average easier. Your 99999 magic number isn't needed since we know there will always be a lowest value in your set. Start with index 0 and the first value. If you find something smaller, update the value and index. When the loop ends you'll have the first index of the lowest value. Note that the loops starts at 1 (the second item).
int findLowest(int weights[]) {
int lowestVal = weights[0];
int lowestIndex = 0;
for (int i=1; i<numWeights; i++) {
if (weights[i] < lowestVal) {
lowestVal = weights[i];
lowestIndex = i;
}
}
return lowestIndex;
}
For the average find the lowest index, add up all the weights but skip the index of the lowest, convert to double so you can get a good average and return the value.
double calcAverage(int weights[]) {
int lowestIndex = findLowest(weights);
int total = 0;
for (int i=0; i<numWeights; i++) {
if (i != lowestIndex) {
total += weights[i];
}
}
return (double)total/(double)(numWeights-1);
}