How do I find the smallest value in an array? I think I'm doing it right, but it outputs zero when I run the program.
I did it the same way in another program and it worked. When this runs, the highest element displays, but the lowest displays as zero.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int ARRAY_SIZE = 12;
double rainfall[ARRAY_SIZE];
double total_year, monthly_average;
double highest = rainfall[0];
double lowest = rainfall[0];
cout << " Input rainfall for each month: \n" ;
for(int index = 0; index < ARRAY_SIZE; index++)
{
cout << " Month " << index+1 << ": " ;
cin >> rainfall[index];
total_year += rainfall[index];
if(rainfall[index] < 0)
{
cout << " Rainfall must equal to 0 or higher: " ;
cin >> rainfall[index];
}
}
for(int x = 0; x < ARRAY_SIZE; x++)
{
if(highest < rainfall[x])
{
highest = rainfall[x];
}
if(lowest > rainfall[x])
{
lowest = rainfall[x];
}
}
cout << fixed << setprecision(2) << endl;
cout << " There was " << total_year << " inches" ;
cout << " of rainfall this year. \n" ;
cout << " The monthtly average was " << total_year / 12 ;
cout << " inches of rainfall.\n";
cout << " The highest rainfall was " << highest << " inches" << endl;
cout << " The lowest rainfall was " << lowest << " inches" << endl;
return 0;
}
Try to declare variables where they are used. Otherwise the code will be less readable.
The array rainfall is not yet initialized
double rainfall[ARRAY_SIZE];
//...
double highest = rainfall[0];
double lowest = rainfall[0];
So using its elements with indeterminate values for the variables highest and lowest does not make sense.
Declare and initialize the variables just before the loop where they are calculated.
double highest = rainfall[0];
double lowest = rainfall[0];
for(int x = 0; x < ARRAY_SIZE; x++)
{
if(highest < rainfall[x])
{
highest = rainfall[x];
}
if(lowest > rainfall[x])
{
lowest = rainfall[x];
}
}
In this loop
for(int index = 0; index < ARRAY_SIZE; index++)
{
cout << " Month " << index+1 << ": " ;
cin >> rainfall[index];
total_year += rainfall[index];
if(rainfall[index] < 0)
{
cout << " Rainfall must equal to 0 or higher: " ;
cin >> rainfall[index];
}
}
move the statement
total_year += rainfall[index];
after the if statement.
for(int index = 0; index < ARRAY_SIZE; index++)
{
cout << " Month " << index+1 << ": " ;
cin >> rainfall[index];
if(rainfall[index] < 0)
{
cout << " Rainfall must equal to 0 or higher: " ;
cin >> rainfall[index];
}
total_year += rainfall[index];
}
I would substitute the if statement for a while statement like
while (rainfall[index] < 0)
{
cout << " Rainfall must equal to 0 or higher: " ;
cin >> rainfall[index];
}
but before using the variable total_year you have to initialize it
double total_year = 0.0;
The variable monthly_average is not used in the code. So its declaration can be removed.
Take into account that there are the following algorithms in C++ std::min_element, std::max_element, std::minmax_element that can be used to find minimum and maximum alements in an array or other container.
Related
I have been coding another programming challenge from a book. It is about asking a user to input n numbers inside an array. Every time the user inputs, the current numbers entered should show up. Numbers less than or equal to zero should not be accepted. I have managed to do the first condition. However, it even shows the "empty" slots. I have tMy code will explain it. Here:
#include <iostream>
using namespace std;
int main() {
int size = 0, input_num [100], i, j;
cout << "Enter an array size: ";
cin >> size;
if (size <= 0) {
while (size <= 0) {
cout << "Enter an array size again: ";
cin >> size;
}
}
cout << "\n\nYou may now enter " << size << " numbers ";
cout << "\n------ ------ ------ ------\n";
for (i = 0; i < size; i++) {
cout << "Enter a number: ";
cin >> input_num [i];
cout << "\nEntered Numbers: ";
for (j = 0; j < size; j++) {
cout << input_num [j] << " " ;
}
cout << "\n";
}
}
In your output section, it should be j <= i, not j < size.
cout << "\nEntered Numbers: ";
for (j = 0; j <= i; j++) {
cout << input_num [j] << " " ;
}
cout << "\n";
I am required to set the minimum value (minValue) equal to -1 in my declarations. How do I, using the || (or condition) within my while loop, extract a minimum value from a positive set of numbers considering that a negative value concludes the program? Also, the double average variable (average), is not calculating the intended value. For example, if the value is supposed to be 35.7789, it is returning 35.0000. I am also intending for the average value to return with no decimal point when unnecessary. For example, if the user enters a negative value first, the average value should be 0 as opposed to 0.0000. How do I manipulate the average variable in order to do so?
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int intVal;
int sum = 0;
int maxValue = -1;
int minValue = -1;
double average = static_cast<double>(0);
int count = 0;
int evenCount = 0;
int oddCount = 0;
cout << endl << "Enter an integer (negative value to Quit): ";
cin >> intVal;
cout << endl;
while(intVal >= 0)
{
if(intVal > maxValue)
maxValue = intVal;
if(intVal < minValue)
minValue = intVal;
count ++;
sum += intVal;
if(intVal > 0)
average = sum / count;
if(intVal % 2 == 0)
evenCount ++;
else
oddCount ++;
cout << "Enter an integer (negative value to Quit): ";
cin >> intVal;
cout << endl;
}
cout << fixed << setprecision(4);
cout << "Values entered:" << setw(8) << right << count << endl;
cout << "Sum of numbers:" << setw(8) << right << sum << endl;
cout << " Average value:" << setw(8) << right << average << endl;
cout << " Maximum value:" << setw(8) << right << maxValue << endl;
cout << " Minimum value:" << setw(8) << right << minValue << endl;
cout << " Even numbers:" << setw(8) << right << evenCount << endl;
cout << " Odd numbers:" << setw(8) << right << oddCount << endl;
cout << endl;
}
I am required to set the minimum value (minValue) equal to -1 in my declarations.
With initialization to -1, all positive numbers will be greater than minValue.
You can set/initialize it with max value or first input value, or handling the special case in the loop:
if (minValue == -1 || intVal < minValue)
minValue = intVal;
Also, the double average variable (average), is not calculating the intended value.
Your average does integer arithmetic, you have to use floating point during the computation:
average = static_cast<double>(sum) / count;
the average value should be 0 as opposed to 0.0000
Remove the call to std::setprecision(4);
So I'm trying to write a program that will read in ten whole numbers and outputs the sum of all numbers greater than zero, the sum of all numbers less than zero,
and the sum of all numbers, whether positive, negative, or zero.
Currently only the total sum and negative sum is adding correctly. My positive sum is always 1 or 0. Any tips to get me in the right direction would help.
Current Code:
#include <iostream>
using namespace std;
int main()
{
int N = 0;
int sum = 0;
int positiveSum = 0;
int negativeSum = 0;
cout << "Number 1" << endl;
cin >> N;
cout << "Number 2" << endl;
cin >> N;
cout << "Number 3" << endl;
cin >> N;
cout << "Number 4" << endl;
cin >> N;
cout << "Number 5" << endl;
cin >> N;
cout << "Number 6" << endl;
cin >> N;
cout << "Number 7" << endl;
cin >> N;
cout << "Number 8" << endl;
cin >> N;
cout << "Number 9" << endl;
cin >> N;
cout << "Number 10" << endl;
cin >> N;
for(int i=0;i<10;i++)
{
if (N >= 0 )
{
positiveSum += N;
}
else
{
negativeSum += N;
}
}
sum = positiveSum + negativeSum;
cout << "The positive sum is= " << positiveSum << endl;
cout << "the negative sum is= " << negativeSum << endl;
cout << "The total sum is= " << sum << endl;
return 0;
}
After entering all Ns and when entring to the loop, you have only the last N. because after assigning the first number to N you don't process the value but you assigning the next value to N again after asking the user to enter it and so on. Use something like the following
#include <iostream>
int main()
{
int N = 0;
int sum = 0;
int positiveSum = 0;
int negativeSum = 0;
for(int i=0;i<10;i++)
{
std::cout << "Number "<<i + 1<< std::endl;
std::cin >> N;
if (N >= 0 )
{
positiveSum += N;
}
else
{
negativeSum += N;
}
}
sum = positiveSum + negativeSum;
std::cout << "The positive sum is= " << positiveSum << std::endl;
std::cout << "the negative sum is= " << negativeSum << std::endl;
std::cout << "The total sum is= " << sum << std::endl;
return 0;
}
And see Why is "using namespace std;" considered bad practice?
I'm new to coding. I wrote the below code in C++ and I am not allow to use array.
You will create a console C++ program that uses a nested loop to enter each archer's individual end scores and then displays the total score for each archer.
I am stuck at how to calculate the total end score:
#include <iomanip>
using namespace std;
int main()
{
int Rounds = 4;
int Archers = 3;
int endScore ;
int average;
for (int a = 1; a <= Archers ; a++)
{
cout << endl << "Number " << a << " score" << endl;
int tEndScore = 0 ;
for(int i=1; i <=Rounds ; i++)
{
cout << "Round " << i << " : " ;
cin >> endScore;
while(cin.fail())
{
cout << endl << "not enter an integer " << endl ;
cout << "Please enter an integer ";
cin >> endScore;
}
tEndScore += endScore;
}
cout << endl << "The total score for 4 ends of Archer Number " << a << " is " << tEndScore << endl;
average =(double) tEndScore/Rounds;
cout << setiosflags(ios::fixed) << setprecision(2) << endl << "The average score of 4 ends of Archer Number " << a << " is " << average << endl;
}
}
This is the result after running. It will only use the last value I entered as tEndScore:
You need to shift tEndScore =+ endScore; this line inside the second for loop as
for(int i=1; i <=Rounds ; i++)
{
...
...
tEndScore += endScore;
}
And it will be a good practice (And mandatory for your code...) to initialize the tEndScore for each player as
for (int a = 1; a <= Archers ; a++)
{
tEndScore = 0;
endScore = 0;
average = 0;
...
...
}
You need to replace totalEndScore to tEndScore and totalRounds to Rounds.
when I run this program is a "Run-Time Check Failure #2 stack around the variable 'numGrades' was corrupted" appears. Also the lowest grade doesn't output the correct answer. Any help would be greatly appreciated!
#include <iostream> // cin, cout
using namespace std;
const int TEN_GRADES = 10; // pre-defined number of grades
int main()
{
int numGrades[10];
double avg, highest = numGrades[0], lowest = numGrades[0], less, greater, grades;
double sum = 0;
// greeting message
cout << "---------------------------------" << endl
<< " Sandro's Statistics Generator " << endl
<< "---------------------------------" << endl << endl;
// requesting number of grades
cout << "Hello Professor, how many grades do I need to analyse this time? ";
cin >> numGrades[10];
if (numGrades[1] == 0)
{
cout << "\nGuess you changed your mind!!!" << endl
<< "Ending program now..." << endl << endl;
return 0;
}
// if user doesn't enter 0 user is ready to begin
cout << "Okay, I am ready. Start..." << endl;
for (int count = 0; count < numGrades[10]; count++)
{
cin >> numGrades[count];
sum += numGrades[10];
}
// to get the average
avg = sum / TEN_GRADES;
// to get the highest and lowest mark
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] > highest)
highest = numGrades[count];
}
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] < lowest)
lowest = numGrades[count];
}
// output requested statistics
cout << "Here are the requested stats for the " << numGrades << " grades." << endl
<< "The class average is " << avg << endl
<< "The highest grade is " << highest << endl
<< "The lowest grade is " << lowest << endl;
return 0;
}
Oh god, I don't even do c++ but I think one of my eyes bled a little.
Please review (or tell whoever coded this to review) how to create and assign values to them.
Then review simple data structures (like arrays) and loops.
One good way to start is to analyze the following WORKING code of your program:
Please mark as correct if it helps, and if you have any questions... Cheers!
#include <iostream>
#include <string>
using namespace std;
const int TEN_GRADES = 10; // pre-defined number of grades
int main()
{
int numGrades[10];
double avg, highest = 0, lowest = 0, less, greater, grades;
double sum = 0;
// greeting message
cout << "---------------------------------" << endl
<< " Newbie Statistics Generator " << endl
<< "---------------------------------" << endl << endl;
// requesting number of grades
cout << "Hello Professor, please enter 10 grades: "<<endl;
//THIS PART: loops ten times to input the grades
for (int count = 0; count < TEN_GRADES; count ++)
{
cout << "Grade number "<<count<<":";
cin >> numGrades[count];
}
//I get what you want to do here, but consider adding another exit condition here, what if the second grade is really 0 ?
if (numGrades[1] == 0)
{
cout << "\nGuess you changed your mind!!!" << endl
<< "Ending program now..." << endl << endl;
return 0;
}
// if user doesn't enter 0 user is ready to begin
cout << "Okay, I am ready. Start..." << endl;
for (int count = 0; count < TEN_GRADES; count++)
{
sum += numGrades[count];
}
// to get the average
avg = sum / TEN_GRADES;
// to get the highest and lowest mark
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] > highest)
highest = numGrades[count];
}
for (int count = 0; count < TEN_GRADES; count++)
{
if (numGrades[count] < lowest)
lowest = numGrades[count];
}
// output requested statistics
cout << "Here are the requested stats for the " << TEN_GRADES << " grades." << endl
<< "The class average is " << avg << endl
<< "The highest grade is " << highest << endl
<< "The lowest grade is " << lowest << endl;
return 0;
}