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

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

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

Find the minimum and maximum element of 5 different elements in 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.

How do I determine the highest and lowest value using do while loops

I am currently stuck in my homework and the problem is that I need to create a program that will ask for 5 integer numbers from which I should determine the highest and lowest value. I am quite confused as of now, and my initial code is this:
#include<iostream>
using namespace std;
int main(){
int num1,num2,num3,num4,num5,min=0,max=0;
cout << " Enter 1st number : ";
cin >> num1;
cout << " Enter 2nd number : ";
cin >> num2;
cout << " Enter 3rd number : ";
cin >> num3;
cout << " Enter 4th number : ";
cin >> num4;
cout << " Enter 5th number : ";
cin >> num5;
do{
if(num1<num2 && num1<num3 && num1<num4 && num1<num5 ){
max = num1;}
if(num2<num1 && num2<num3 && num2<num4 && num2<num5 ){
max = num2;}
if(num3<num1 && num3<num2 && num3<num4 && num3<num5 ){
max = num3;}
if(num4<num1 && num4<num3 && num4<num2 && num4<num5 ){
max = num4;}
if(num5<num1 && num5<num3 && num5<num4 && num5<num2 ){
max = num2;}
}while(max>0);
cout << " The highest number is : " <<max;
return 0;
}
Any help would be appreciated. Thanks in advance!
You should store your numbers into a std::vector<int> or std::array and then use the std::minmax_element algorithm to obtain the largest and smallest number.
If you are allowed to use std::max and std::min, you can use:
max = std::max({num1, num2, num3, num4, num5});
min = std::min({num1, num2, num3, num4, num5});
to simplify the code in the loop.
This would be my solution without using arrays.
I'd suggest you to try it yourself before. You don't learn when you just copy code.
#include <iostream>
int main() {
int i=0, num, min=INT_MAX, max=INT_MIN;
do {
std::cout << "Enter number: ";
std::cin >> num;
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
i++;
} while (i < 5);
std::cout << "The max number is: " << max << std::endl;
std::cout << "The min number is: " << min << std::endl;
return 0;
}
If you don't need to remember, you can loop for e.g. 5 times, then have a comparison before asking the next number.
so generally (idea, write it yourself and learn):
for (5 times)
ask user input, save as input
if largest number is null, then equal to input
else if largest number is smaller, then set input equal to largest number
Continue for loop times.
Rather than compare all the numbers each time. Simply compare your current smallest against the numbers in sequence.
int data[5];
// read numbers into data.
int min = data[0]; // Guess that number 0 is the smallst number.
// Now check if the guess is correct and update if you are wrong.
for(int loop = 0; loop < 5; ++loop)
{
// check if data[loop] is smaller than your current guess.
// if it is smaller than update your guess.
// when you have checked all the values exit the loop.
}
std::cout << "Smallest: " << min << "\n";
There is no need to use a loop to do this you can do that without it else if it's necessary to use a loop you must use an array or some other data structure

For loop - Magic number program

What changes should I make so that the user of this code can guess at the amount of magic numbers they choose, with three different chances to guess at each magic number? I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly.
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstdio>
using namespace std;
int main()
{
int magic; // This is a random number between 1 and 20
int guess; // This is the guess number being attempted (up to 3 guesses)
int magicguesses; // This is the amount of magic numbers being guessed attempted
int i;
int number; // This is the number the user guessed
bool numberismagic = false; // This is the flag variable
unsigned int seed;
seed = time(NULL);
srand(seed);
magic = rand() % 20 + 1;
cout << "How many magic numbers would you like to guess at today?\n";
cin >> magicguesses;
for (i = 1; i < magicguesses + 1; i++)
{
cout << "This is trial number:" << i << endl;
for (guess = 1; (guess < 4) && (!numberismagic); guess++)
{
cout << "This is guess number:" << guess << endl;
cout << "Guess a number between 1 and 20:" << endl;
cin >> number;
while ((number < 1) || (number > 20))
{
cout << "Your guess is invalid; guess a number between 1 and 20 \n";
cin >> number;
cout << endl;
}
if (number == magic)
{
cout << "You have guessed the magic number correctly! \n";
numberismagic = true;
}
else
{
cout << "Sorry - you guessed incorrectly! \n";
if (number > magic)
cout << "Your guess is too high \n" << endl;
else
cout << "Your guess is too low \n" << endl;
}
}
if (number != magic)
cout << "The magic number is:" << magic << endl;
}
return 0;
}
I'm not sure what your first question is, but for this question "I am also confused on what to change so that the magic number can change once the user guesses the magic number correctly", you should edit the variable magic inside the first for loop so the magic number changes after the user guesses correctly or they run out of tries.
for (i=1;i<magicguesses+1;i++)
{
//magic equals new random number
//the rest of your code
}

How to evaluate number greater than and less than in the same while loop?

// DiceRollProject.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <time.h>
using namespace std;
int diceRoll(int max); // function definition
int getValidInteger();// function definition
int main() {
srand(time(0)); // seed the random number generator
int exitProgram = 0;
int guess, rollValue;
int maxRollValue = 6;
cout << "Hello! Let's play a dice game. Let me do the first roll for you.\n" << endl;
rollValue = diceRoll(maxRollValue);
cout << "In this roll, you got: " << rollValue << "\n" << endl;
do {
rollValue = diceRoll(maxRollValue);
cout << "What's your guess for the next roll? Enter an integer between 1 and " << maxRollValue << ": ";
guess = getValidInteger();
// TODO: Validate input
if (guess > rollValue)
{
cout << "The guess was too high!";
}
if (guess < rollValue)
{
cout << "The guess was too low!";
}
if (guess == rollValue)
{
cout << "You guessed correctly, congrats!";
}
cout << "In this roll, you got: " << rollValue << "\n" << endl;
// TODO: Evaluate result
cout << "Enter 1 to exit or any other integer to continue rolling ";
exitProgram = getValidInteger();
cout << "\n";
if (exitProgram == 1)
{
cout << "Sorry to see you go. Have a wonderful day!\n" << endl;
}
} while (exitProgram != 1);
return 0;
}
// Roll the die
int diceRoll(int max) {
int rollValue;
rollValue = (rand() % max) + 1;
return rollValue;
}
// Check if user entered an integer
int getValidInteger() {
int userInput;
cin >> userInput;
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
if (cin.fail()) {
cin.clear();
cin.ignore();
cout << "Please enter an Integer only ";
cin >> userInput;
cout << "\n";
}
return userInput;
}
I have a dice roll guessing game, I'm trying to evaluate the users input, to make sure that they can't enter a number less than 1 and greater than 6, unfortunately, with just my if statements, they can still enter these numbers, although a string is displayed that the input is not valid, I want to make a while loop that keeps asking them to enter a valid number equal or greater than 1 and equal to and less than 6, if the user keeps inputting an incorrect number, the while loop will keep asking them for a valid number, until they do enter one, which will then run the program as normally.
First of all, inside the while loop you have dead code.
while (userInput < 1) {
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}
Within the loop body, the first if is always true and the second one is always false. You should enter in a loop when the user writes an invalid input. This happens when (userInput < 1 or userInput > 6)
After the evaluation of the while's condition, you should ask the user to write input
do {
cout << "Please enter an Integer only ";
cin >> userInput;
if (userInput < 1)
{
cout << "Please enter a number greater than or equal to 1\n";
}
if (userInput > 6)
{
cout << "Please enter a number less than or equal to 6\n";
}
}while(userInput < 1 || userInput > 6);
So your condition that will keep you in the while loop is if the person guesses too high or too low. Inside the while loop I would add the updating condition or statement that you would like to repeat. So in your case, "your guess is too high" or " your guess is too low" and ask for their input again. I am not a pro but I would keep it simple by constructing 2 while loops, one for too high and one for too low just like your if statements. literally you can just change your first two if statements to while loops and adding an few extra lines of cout to ask the person to guess again and validate their input. I hope this helped.
from what I've understood you are looking for something like this:
int main (){
int my_magic_number=(rand()%6)+1,usernumber=-1;
bool state;
while (usernumber!=my_magic_number){
cin>>usernumber;
state = (usernumber<1||usernumber>6);
while (state) {
cout<<"You entered a number outside the range [1,6] please try again\n";}
cin>>usernumber;
state = (usernumber<1||usernumber>6);
}
if (usernumber!=my_magic_number) {/* do whatever you want */}
} //while loop
} // main