Find the minimum and maximum element of 5 different elements in C++ - c++

Need to take out the highest and lowest numbers of 5 judges 0 to 10 on the score
cout << "Please enter the name of the athelete.\n";
getline(cin, name);
cin >> name;
cout << "Please enter the first judge's score below\n";
cout << "Please enter a score between 0 and 10.\n";
cin >> First_Score;

Pseudo code
loop for 5 answers
sort them
sum of middle 3
avg sum / 3
print

The simplest solution would be to create two additional variables. The first, 'lowest', to store the lowest value and the second, 'biggest' to store the biggest value.
int lowest = 0, biggest = 11;
...
cin >> First_Score;
while (First_Score < 0 || First_Score > 10)
{
cout << "That is not a valid input, please pick between 0 and 10.\n";
cin >> First_Score;
cout << "Your selection was " << First_Score << endl;
}
lowest = First_Score;
biggest = First_Score;
...
And then for each judge :
cout << "Please enter the fifth judge's score here below\n";
cin >> Fifth_Score;
while (Fifth_Score < 0 || Fifth_Score > 10)
{
cout << "That is not a valid input, please pick between 0 and 10.\n";
cin >> Fifth_Score;
cout << "Your selection was " << Fifth_Score << endl;
}
if(lowest > Fifth_Score)
lowest = Fifth_Score;
if(biggest < Fifth_Score)
biggest = Fifth_Score;
...
int sum = Avg_Score = (First_Score + Second_Score + Third_Score + Fourth_Score + Fifth_Score);
Avg_Score = (sum - lowest - biggest) / 3;
...

Always separate input and logic.
#include <vector> // std::vector
#include <numeric> // std::sort, std::accumulate
#include <cassert> // assert
auto score(std::vector<double> scores) {
assert(scores.size()>2);
auto n = scores.size() - 2;
// sort ...
// sum ...
return sum / n;
}
int main() {
assert(score({1,5,9}) == 5);
assert(score({5,5,5}) == 5);
assert(score({0,5,0}) == 0);
assert(score({1,2,3,4,5,6}) == 3);
}
I left the actual implementation for you. My implementation fits in three lines.
I hope this inspires you to get a clean implemntation, that you can easily use to write the rest of the program with.

Related

Ask for the condition of guess number game

I am a newbie, i have some question:
I am coding a guessing number game, player enter the random number range, guess number, guess limit. When player enter the guess number out of the random range entered, the program require player to enter the guess number again. However, I tested my code, I entered the number range [ 3,8 ] and the guess number is 1, this number is out of range, the program didn't force me to enter the guess number again but I had to enter the guess limit. Please hint me what's wrong with my code and help me to fix this code. Thanks!
#include iostream
#include cstdlib
using namespace std;
int randnum(int min, int max)
{
return min + (int)(rand() * (max - min + 1.0) / (1.0 + RAND_MAX));
}
int main()
{
int max;
int min;
int guessnum;
int guesscou = 0;
int guesslim;
bool outofguess = false;
cout << " Enter max min of random value range = \n ";
cin >> max >> min;
cout << " Enter your guess number = \n ";
cin >> guessnum;
cout << " Enter your guess limitation = \n";
cin >> guesslim;
// enter guess loop
while (guessnum != randnum(min, max) && !outofguess) {
// guessnum condition
while (guessnum <= max && guessnum >= min) {
cout << " Unvalid number, please enter again ";
cin >> guessnum;
}
// guess limitation
if (guesscou <= guesslim) {
cout << " Please try again \n";
cin >> guessnum;
guesscou++;
}
else {
outofguess = true;
}
}
if (outofguess) {
cout << " you win";
}
else {
cout << " you lose ";
}
}
You want the user to guess again if the number is lower than the minimum or higher than the maximum. But the logic in your while loop says exactly the opposite. It should read
while (guessnum < min || guessnum > max) {
cout << " Unvalid number, please enter again ";
cin >> guessnum;
}

I need to know how to add using an increment value up to a certain number in c++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I am having a hard time trying to add the starting value with the increment value up until it reaches the ending value or it cant add again because it would exceed the max value(the end value).
Ok I am just going to get straight to it, here is my assignment.
In this assignment, you will complete a C++ program that sums up the integers in a range of values and prints the result. This will be done two different ways: using a while loop and using a for loop.
For this assignment, you have more freedom in choosing the local variables that you need to declare and in figuring out what source code to write. However, your program needs to follow the coding standards of this course and fulfill the software requirements described in the next section.
Below is an example execution of the program. In this case, the program added up the numbers 8, 25, 42, 59, 76, 93, and 110. Your program shall follow the same format shown below for prompting the user and printing the results.
Enter a starting integer value: 8
Enter an ending integer value: 121
Enter a positive increment: 17
Sum (using a while loop): 413
Sum (using a for loop): 413
Here is what I have for code so far
#include <iostream>
using namespace std;
int main(){
//while loop sum
int sumw = 0;
//for loop sum
int sumf = 0;
//starting integer
int nums;
//ending integer
int nume;
//increment integer
int numi;
cout <<"Please enter a starting value: " << endl;
cin >> nums;
cout <<"Please enter an ending value: " << endl;
cin >> nume;
cout <<"Please enter a positive increment value: " << endl;
cin >> numi;
if (numi <= 0 || nums > nume) cout << "Error ";
if (numi <= 0 || nums > nume) return 0;
for (int i = 1; i <= numi; i++){
sumf =+ numi;
}
cout << "Sum(using for loop): " << sumf;
return 0;
}
If someone could help me with this that would be great!!! Thank you!!
This is probably what you are looking for
for (int i = nums; i <= nume; i = (i + numi)){
sumf += i;
}
Start with nums until you are less than or equal to nume and increment i in steps of numi i.e. i = i + numi
Additionally, you can combine:
if (numi <= 0 || nums > nume) cout << "Error ";
if (numi <= 0 || nums > nume) return 0;
to
if (numi <= 0 || nums > nume){
cout << "Error ";
return 0;
}
Assumed the starting number as greater than or equal to 1(>=1).
Using while loop:
#include <iostream>
using namespace std;
int main()
{
int totalSum = 0, startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting number: " << endl;
cin >> startingNumber;
cout <<"Enter the ending number: " << endl;
cin >> endingNumber;
cout <<"Enter the positive increment: " << endl;
cin >> positiveIncrement;
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
totalSum = startingNumber;
while ((startingNumber + positiveIncrement) <= endingNumber)
{
startingNumber += positiveIncrement;
totalSum += startingNumber;
}
cout << "Total Sum = " << totalSum;
return 0;
}
Using for loop:
#include <iostream>
using namespace std;
int main()
{
int totalSum = 0, startingNumber, endingNumber, positiveIncrement;
cout <<"Enter the starting number: " << endl;
cin >> startingNumber;
cout <<"Enter the ending number: " << endl;
cin >> endingNumber;
cout <<"Enter the positive increment: " << endl;
cin >> positiveIncrement;
if ((startingNumber <= 0) || (startingNumber > endingNumber))
{
cout<<"Error in input provided"<< endl;
return 0;
}
for ((totalSum = startingNumber);((startingNumber + positiveIncrement) <= endingNumber);(startingNumber += positiveIncrement))
{
totalSum += (startingNumber+positiveIncrement);
}
cout << "Total Sum = " << totalSum;
return 0;
}
See definition of for statement in a good reference:
for ( initializer, terminating condition, increment)
The third parameter is the increment.
You could do something like:
for (int i = nums; i < nume; i = i + numi)
{
}
Inside the loop, you'll have figure out what you need to sum and how to do it.
welcome to the world of computer science and programming :)
several points:
it is unclear what it is you need help with, posting your assignment is not a good way to get help. with your next question, try using this as a guide line on how to ask a question: https://stackoverflow.com/help/how-to-ask
here is a list of operators in C++, and how to use them, https://www.geeksforgeeks.org/operators-c-c/ you will notice =+ is not there, becuase it is not a valid operator.
what you do have, is:
“+=”:This operator is combination of ‘+’ and ‘=’ operators. This
operator first adds the current value of the variable on left to the
value on right and then assigns the result to the variable on the
left.
Example: (a += b) can be written as (a = a + b)

C++ - Check if there are no even numbers in given interval

I have to write a program on C++ which finds all even numbers in range given by user. Here's the code I have written so far:
#pragma hdrstop
#pragma argsused
#include <tchar.h>
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>
void main() {
int m, n, j = 1; // m and n- numbers entered by user, j- product of all even numbers in interval
char atbilde; // A letter entered by user, of which system decides wether to continue or to stop programme
do {
j = 1;
cout << "Enter the min number of interval! ";
cin >> n;
cout << "Enter the max number of interval! ";
cin >> m;
if (n > m) { // Detects wether „n” is larger than „m”
cout << "Max number of interval has to be larger than min number!";
do { // If max number is larger than min number, screen is cleared
cin.clear();
cin.ignore();
cout << "Enter the numbers again!";
cout << "\n Enter the min number of interval! ";
cin >> n;
cout << "\n Enter the max number of interval! ";
cin >> m;
}
while (n > m);
}
cout << "Even numbers in given interval: ";
for (; n <= m; n++)
{
if (n % 2 == 0)
{ // Detects, wether there are even numbers in given interval
if (n != 0) {
cout << n << " ";
j *= n;
}
if ((n == m) && (n % 2 != 0)) {
j=0;
}
}
}
cout << "\n The product of found even numbers: " << j << " ";
cout << "\n Repeat? (Y/N) ";
cin >> answer;
system("cls");
}
while (tolower(answer) != 'n');
}
But I have a small problem, so I can't get the program 100% done because of the problem.
Like, user enters range, whose min and max number is the same and it's odd. In that case program has to print out a sentence "there were no even numbers in interval" in place of "The product of found even numbers:". I have searched the solution in internet, but haven't found it.
I hope you'll know the right solution.
Some hints to help you along the way: If there was no even number in the range, you will not enter into the loop. What will j be then? How do you react on that value?
I tried to fix your code, I did the best I could from what I understood you were tring to do.
I cleaned it up, fixed spelling and grammer, I deleted unnecessary stuff, I also made it more compact and nice to look at.
#include <iostream>
int main() {
int max=0, min=1, sum=0; product = 1, amount = 0; // max, min - entered by user, product - product of all even numbers in interval, sum - sum of all even numbers in interval. amount - amount of even numbers in interval
char x=Y; // Entered by user to know if to quit or continue to continue.
while ((x == Y) || (x == y))
{
while (min > max) { // System detects whether minimum is bigger than maximum
cin.clear(); // Clears screen so if this part runs again it wouldn't get messy.
cin.ignore();
cout << "Max has to be larger than min!";
cout << "\n Enter the min number of interval! ";
cin >> min;
cout << "\n Enter the max number of interval! ";
cin >> max;
}
for (; min <= max; min++)
{
if (min % 2 == 0)
{
sum+=n;
count++;
product*=n;
}
}
if (count == 0)
{
product=0;
cout << "There are no even numbers in interval!";
}
else
{
cout << "\n The amount of the even numbers in interval: " << amount << ",the product of the even numbers: " << product << ",the sum of the even numbers: " sum << "\n\n";
}
cout << "Repeat? (Y/N) ";
x=getchar;
system("cls");
}
return 0;
}

Nested loops in C++ and user input

Pretty new here to programming, and I have an assignment where I need to achieve the following:
ask for total amount of people
get each of their names
allow user to enter up to 5 scores for each person
if there are less than 5 scores for a given person, inputting -100 will stop it
So far I have written this:
#include <iostream>
using namespace std;
int main() {
string personName;
int totalPerson, personScoreCounter;
double personGrade, personGradeTotal;
cout << "Input total amount of people: ";
cin >> totalPerson;
for (int person = 1; person <= totalPerson; person++)
{
cout << "Input name for person " << person << ": ";
getline(cin, personName);
cin.ignore();
while ( (personGrade != -100) && (personScoreCounter <= 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
if (personGrade >= 0 && personGrade <= 100) // valid range of scores
{
personGradeTotal += personGrade;
personScoreCounter++;
}
else
{
cout << "Input only scores from 0-100" << endl;
}
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
}
}
// calculate averages and other stuff in here.
return 0;
}
After getting their name, only the last cout inside the while loop seems to execute first, then it starts from the top and so on until the for loop hits the end depending on totalPerson. I know I'm missing a few things in here, probably in the order of operations and also the way I am executing my loops, but I just can't see it. Could any of you guys with experience in the language please give me any pointers as to what's happening here and how I can fix it? Thank you.
Inside your while group, you only want to use your cout line once (at the beginning looks good).
Your first check should be for ==-100 or similar, since as it is now, you'll get a "Input only scores from 0 to 100" message if you enter -100.
You should keep a cin.ignore(); call after each use of cin >> VARIABLE, since then you will drop the EoL character.
Example code:
#include <iostream>
using namespace std;
int main() {
int totalPerson;
cout << "Input total number of people: ";
cin >> totalPerson;
cin.ignore();
for (int person = 1; person <= totalPerson; person++)
{
int personScoreCounter=0;
double personGrade = -1, personGradeTotal=0;
string personName;
cout << "Input name for person " << person << ": ";
std::getline(cin, personName);
while ( (personGrade != -100) && (personScoreCounter < 5) )
{
cout << "Input up to 5 scores for " << personName << " (-100 to end): ";
cin >> personGrade;
cin.ignore();
if (personGrade == -100) {
break;
} else if (personGrade >= 0 && personGrade <= 100) {
personGradeTotal += personGrade;
personScoreCounter++;
} else {
cout << "Input only scores from 0-100" << endl;
}
}
// calculate averages and other stuff in here.
double avg = personGradeTotal / personScoreCounter;
cout << "Avg = " << avg << endl;
}
return 0;
}
Some of your variables also needed to move inside the for loop.
Additionally I changed the limits on the personScoreCounter to [0:4] rather than [1:5] - this way you can use it for averaging more easily.
You might also try cin.getline() instead of getline(std::cin , ... ):
int max_length = 30;
std::cin.getline(personName, max_length, '\n'); // \n is option termination.
This allows whitespaces in the input also.
http://www.cplusplus.com/reference/istream/istream/getline/

Counter not working?

I am writing a program for a homework assignment that calculates rental car rates based on make, days rented and miles driven. Overall the program works except, when the user is prompted for the number of cars to be calculated, the program continues to prompt the user for input after the number has been exceeded. Also, the formatting for the miles is correct for the first vehicle entered but changes for subsequent entries.
Any help with these two issues would be greatly appreciated!
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
// Change the console's background color.
system ("color F0");
// Declare the variables.
char carType;
string brand, f("Ford"), c("Chevrolet");
int counter = 0, cars = 0;
double days, miles, cost_Day, cost_Miles, day_Total;
cout << "Enter the number of cars you wish to enter: ";
cin >> cars;
cin.ignore();
while (counter <= cars)
{
cout << "Enter the car type (F or C): ";
cin >> carType;
cin.ignore();
cout << "Enter the number of days rented: ";
cin >> days;
cin.ignore();
cout << "Enter the number of miles driven: ";
cin >> miles;
cin.ignore();
if (carType == 'F' || carType == 'f')
{
cost_Day = days * 40;
cost_Miles = miles * .35;
day_Total = cost_Miles + cost_Day;
brand = f;
}
else
{
cost_Day = days * 35;
cost_Miles = miles * .29;
day_Total = cost_Miles + cost_Day;
brand = c;
}
cout << "\nCar Days Miles Cost\n";
cout << left << setw(12) << brand << right << setw(6) << days << right << setw(8) << miles
<< fixed << showpoint << setprecision (2) << setw(8) << right << "$" << day_Total << "\n\n";
counter++;
}
system ("pause");
}
You have started counting from 0 int counter = 0, cars = 0;
You then count until you are equal to the number that was entered (the "or equal to" bit of while (counter <= cars)).
As a worked example, if I want 3 entries:
Start: counter = 0, cars = 3.
0 <= 3: true
End of first iteration: counter = 1
1 <= 3: true
End of second iteration: counter = 2
2 <= 3: true
End of third iteration: counter = 3
3 <= 3: true (the "or equal" part of this)
End of FORTH iteration: counter = 4
4 <= 3: false -> Stop
We have completed 4 iterations instead of 3. If we only checked for "strictly less than" (counter < cars), the condition at the end of the third iteration would be false, and we'd have ended there.
The heading of your while loop should be:
while(counter < cars)
rather than
while(counter <= cars)