Program Fails to output greatest integer - c++

I am writing a program that takes multiple user inputs, and counts how many prime numbers there are, and which number is the greatest and smallest of the inputs. However, I am stuck. when I run the code, it thinks every new input is the greatest number. for example, if I enter 1, 2, 3, 2... It says the greatest number is 2. It takes the last integer inputted and thinks that is the greatest number. I have no started on the lease common number yet, but if I am able to understand how to get the greatest number, I bet I can get the least. Thanks guys!
#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
int oldnum = 0;
int userinput=0;
int newnum = userinput;
int greatestnum = 0;
int greatestcounter = 0;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (greatestnum > userinput) {
greatestnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}

greatestnum is only assined if it's greater than the user input. Since it's initialized to 0, the if statement,
if (greatestnum > userinput) {
greatestnum = userinput;
}
will be false unless the user input is less than zero. If you want to make it the greatest from all user inputs, flip it to < and move the int greatestnum = 0; to right above the if (begin >= 0) {.
if (greatestnum < userinput) {
greatestnum = userinput;
}

#include <iostream>
using namespace std;
int main() {
int startstop = 1;
cout << "start program?" << endl;
int begin = 0;
int primecounter = 0,greatestnum = 0,oldnum = 0,userinput = 0;
cin >> begin;
if (begin >= 0) {
while (startstop != 0) {
cout << "enter any number, or press Q to process." << endl;
cin >> userinput;
int x;
bool is_prime = true;
if (userinput == 0 || userinput == 1) {
is_prime = false;
}
// loop to check if n is prime
for (x = 2; x <= userinput / 2; ++x) {
if (userinput % x == 0) {
is_prime = false;
break;
}
}
if (is_prime) {
primecounter++;
}
//check if input is greater than previous input
if (userinput > oldnum) {
greatestnum = userinput;
oldnum = userinput;
}
cout << "prime count: " << primecounter << endl;
cout << "greatest num: " << greatestnum << endl;
userinput = 0;
}
return 0;
}
}
Initialize 'oldnum=0' , 'userinput=0' and 'greatestnum=0' outside the loop. And there were some error in logic. If userinput is greater the old num the update greatest num=userinput and oldnum=userinput.

Related

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.

Function that finds prime numbers between two intervals

I have written the bulk majority of the program, I'm just having trouble debugging it. Something must be wrong with my computation of the prime numbers. For anything I try, it says there are 0 prime numbers. Any help would be greatly appreciated. Code and output are below.
Note: For this program, I am not allowed to use vectors or arrays.
#include <iostream>
#include <cmath>
using namespace std;
// FUNCTION PROTOTYPE FOR read_range
void read_range(int &lower, int &upper);
// FUNCTION PROTOTYPE FOR is_prime
bool is_prime(const int num);
// FUNCTION PROTOTYPE FOR display_primes
void display_primes(const string &prime, const int lower, const int upper);
// DO NOT MODIFY THE MAIN ROUTINE IN ANY WAY
int main()
{
int imin(0), imax(0);
// Read in range
read_range(imin, imax);
// Print prime numbers
cout << endl;
display_primes("Primes: ", imin, imax);
return 0;
}
// DEFINE FUNCTION read_range() HERE:
void read_range(int &lower, int &upper){
cout << "Enter minimum and maximum: ";
cin >> lower >> upper;
while (lower < 2 || upper < 2 || lower > upper){
if (lower < 2 || upper < 2) {
cout << "Error. Minimum and maximum must be at least 2." << endl; }
else if (lower > upper) {
cout << "Error. Minimum must be less than maximum." << endl; }
cout << "Enter minimum and maximum: ";
cin >> lower >> upper; }}
// DEFINE FUNCTION is_prime() HERE:
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return 0; } // Is not prime
else {
return 1; }}} // Is prime
// DEFINE FUNCTION display_primes() HERE:
void display_primes(const string &prime, const int lower, const int upper) {
int count = 0;
int commaCheck = 0;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
count = count + 1; }}
if (count == 1) {
cout << "There is " << count << " prime number in this range." << endl; }
else {
cout << "There are " << count << " prime numbers in this range." << endl; }
if (count != 0) {
cout << prime;
for (int i = lower; i <= upper; i++) {
if (is_prime(i)) {
if (count == 1) {
cout << i;}
else {
commaCheck = commaCheck + 1; }
if (commaCheck != count) {
cout << i << ","; }
else {
cout << i; }}}
cout << endl; }
else {
cout << "No primes to display." << endl; }}
Output (with input of 2,3)
Enter minimum and maximum:
There are 0 prime numbers in this range.
No primes to display.
is_prime has two issues.
If sqrt(num) is less than 2 the loop never executes and your function has undefined behaviour as it ends without returning (your compiler probably should have warned you about this issue)
If the number is not even then in the first iteration of the loop you call return 1 which means all odd numbers will be labelled as prime.
Changing your loop to this will work (if not be very efficient, there are much better algorithms for finding prime numbers):
bool is_prime(const int num) {
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
This is one of the default algorithms for checking how many numbers between two intervals are prime numbers, there are many alternatives, but this is what i prefer and is short and easy to remember
#include <iostream>
using namespace std;
int main(){
int i1min, i1max;
int i, j, k = 0;
bool primeTest;
cin >> i1min;
cin >> i1max;
for(i=i1min; i<=i1max; i++) {
primeTest = false;
for (j=2; j<=i/2; j++) {
if (i % j == 0) {
primeTest = true;
break;
}
}
if (primeTest == false)
k++;
}
cout << k;
return 0;
}

display all the Prime numbers which are less than certain number

I've been learning C++ for few weeks, however, I got stuck, I have a function isPrime(), works great to show if the number is prime or no, I need to display all the Prime numbers which are less than 200. But it's not working see line marked with comment
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
if (isPrime(Num))
{
cout << " is a Prime number." << endl;
}
else
cout << " is not a Prime number." << endl;
return 0;
}
//isPrime
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else if
for(int n = 2; n < 200; n++) { // HERE
// isPrime will be true for prime numbers
isPrime = isPrimeNumber(n);
if(isPrime == true)
cout<<n<<" ";
}
return 0;
else
return false;
}
}
}
return false;
}
You added the loop in the wrong place. That function is only for checking a particular number. Either you would need to make another function to print all the prime numbers which are less than 200 or you can directly add the loop in the main() function, like i did.
#include <iostream>
using namespace std;
// Function Prototypes
bool isPrime(int);
int main()
{
int Num;
cout << "This program let you know if the number entered is a "
<< "prime number.\nEnter a number: ";
cin >> Num;
cout << "The number " << Num;
// Check numbers here
for(int n = 2; n < 200; n++) {
if (isPrime(n)){
cout << n << " is a Prime number." << endl;
}
}
return 0;
}
//isPrime - This is your original isPrime Code
bool isPrime(int Num)
{
if (Num > 1)
{
for (int i = 2; i <= Num; ++i)
{
if (Num % i == 0)
{
if(Num == i)
return true;
else
return false;
}
}
}
return false;
}

What is wrong with this C++ code?

#include <iostream>
using namespace std;
int main()
{
char ch;
int n;
do {
cout << "Enter a number:";
cin >> n;
if (n % 2 == 0)
cout << "The number is even.\n";
else
cout << "The number is odd.\n";
bool prime;
for (int i = 2; i < n; ++i) {
if (n % i == 0)
prime = true;
}
if (prime) {
cout << "The number is not prime.";
}
else
cout << "The number is prime.";
cout << "Do you want to continue?[y/n]";
cin >> ch;
} while (ch == 'y' || ch == 'Y');
}
If the loop enters once into if(prime) then it never goes in the else.
On first run of loop if 3 is entered, it outputs prime. Then in next if 4 if entered it show not prime but after that whenever any prime number is entered it shows not prime.
first of all your
bool prime;
is not initialized. Second it should be initialized inside do while() loop and it is better to move that variable declaration there:
bool prime = false; // move it here and initialize
for (i = 2; i < n; ++i) {
if (n % i == 0)
prime = true;
}
and you use boolean flag in reverse, which makes your program unreadable, you better fix that:
bool prime = true; // move it here and initialize
for (i = 2; i < n and prime; ++i) {
if (n % i == 0)
prime = false;
}
if (prime)
cout << "The number is prime.";
else
cout << "The number is not prime.";

Can anyone tell me why these functions are not giving me a result in a reasonable spectrum?

The full code I am using is listed below, it is supposed to simulate a game of craps and print details to the user and allow for betting if the user desires it. Everything functions except for the actual craps game. Instead of looping only while there is not a truth value associated to crapsResult, it finds one real value and an incomprehensible string of a single negative number. Any help would be appreciated.
int main()
{
//Declare the user input variables
int gamesPlayed = 0;
char inputPrint = ' ';
char isBetting = ' ';
int startingBet = 0;
//Declare the variables used by the program
int endingBet = 0;
int currentGame = 0;
bool crapsResult;
int gamesWon = 0;
int gamesLost = 0;
double percentWon = 0;
bool detailPrint = false;
//Prompt the user to input their variables
cout << "Enter the number of games to be played: ";
cin >> gamesPlayed;
while(gamesPlayed < 1)
{
cout << " Error: must be greater than 0" << endl;
cout << "Enter the number of games to be played: ";
cin >> gamesPlayed;
cin.clear();
cin.ignore();
}
cout << "Do you wish to print details (Y/N): ";
cin >> inputPrint;
if(inputPrint == 'y' || inputPrint == 'Y')
{
detailPrint = true;
}
cout << "Do you wish to bet (Y/N): ";
cin >> isBetting;
if(isBetting == 'y' || isBetting == 'Y')
{
cout << "Enter money to start betting with: ";
cin >> startingBet;
while(startingBet < 1)
{
cout << " Error: must be greater than 0" << endl;
cout << "Enter the number of games to be played: ";
cin >> gamesPlayed;
cin.clear();
cin.ignore();
}
}
//Seed the random number generator
srand(time(NULL));
//Set a value for ending bet
if(startingBet == 0)
{
endingBet = 1;
}
else
{
endingBet = startingBet;
}
//Call playcraps to simulate the game for as many games as the user input
for(currentGame = 1; currentGame <= gamesPlayed && endingBet > 0; currentGame += 1)
{
crapsResult = NULL;
crapsResult = playCraps(currentGame, detailPrint, isBetting, startingBet);
if(crapsResult == true)
{
gamesWon += 1;
endingBet = betting(endingBet, crapsResult);
}
if(crapsResult == false)
{
gamesLost += 1;
endingBet = betting(endingBet, crapsResult);
}
if((isBetting == 'Y' || isBetting == 'y') && (detailPrint == true))
{
cout << "Money left is $" << endingBet << endl;
}
}
//Calculate the percentage of games won
percentWon = (double(gamesWon) / double(currentGame-1)) * 100.0;
//Print the results to the user
if(isBetting == 'Y' || isBetting == 'y')
{
cout << "Money at end of games is $" << endingBet << endl;
}
cout << "The number of games played is " << currentGame - 1 << endl;
cout << "The number of games won is " << gamesWon << endl;
cout << "The number of games lost is " << gamesLost << endl;
cout << "The percent of games won is " << fixed << showpoint << setprecision(3) << percentWon << endl;
}
//Simulates the roll of a single die and returns the result
int roll()
{
int rollResult = 0;
rollResult = rand() % 6 + 1;
return rollResult;
}
//Calls roll twice and returns the sum of the two results
int roll2Dice()
{
//Declare variables for this function
int rollOne = 0;
int rollTwo = 0;
int rollSum = 0;
//Find rollOne and rollTwo
rollOne = roll();
rollTwo = roll();
//Find rollSum
rollSum = rollOne + rollTwo;
return rollSum;
}
bool playCraps(int currentGame, bool detailPrint, char isBetting, int startingBet)
{
bool crapsResult = NULL;
int currentGameStorage[100];
int currentRoll = 1;
int point = roll2Dice();
int printingNumber = 0;
currentGameStorage[0] = point;
if(point == 7 || point == 11)
{
crapsResult = true;
}
else if(point == 2 || point == 3 || point == 12)
{
crapsResult = false;
}
else
{
crapsResult = NULL;
}
while(crapsResult != true && crapsResult != false)
{
currentGameStorage[currentRoll] = roll2Dice();
if(currentGameStorage[currentRoll] == point)
{
crapsResult = true;
}
else if(currentGameStorage[currentRoll] == 7)
{
crapsResult = false;
}
currentRoll += 1;
}
if(detailPrint == true)
{
cout << "Game " << currentGame << ": ";
for(printingNumber = 0; printingNumber <= currentRoll; printingNumber += 1)
{
cout << currentGameStorage[printingNumber] << " ";
}
if(crapsResult == true)
{
cout << "win";
}
else if(crapsResult == false)
{
cout << "lose";
}
cout << endl;
}
return crapsResult;
}
int betting(int endingBet, bool crapsResult)
{
if(crapsResult == true)
{
endingBet += 1;
}
else if(crapsResult == false)
{
endingBet -= 1;
}
return endingBet;
}
Just skimmed and didn't read all of your code (so there may be other things wrong too), but this line is definitely problematic:
while(crapsResult != true && crapsResult != false)
It is logically impossible for crapsResult to simultaneously be both true and false, so that loop will never be entered.
Turix got the right bug I believe, but I would put the emphasis on a different spot:
bool crapsResult = NULL;
You are trying to use crapsResult for three different values (true, false and NULL). However, NULL usually has a integer value of 0, which translates to a boolean value of false, so your loop will never be entered.
Then a second bug comes into play: currentRoll is 1 at this time, so you try to print the contents of currentGameStorage from index 0 to 1 (inclusive), currentGameStorage[1] hasn't been assigned yet. This is why you get the cryptic numer in your output. This is a general mistake: Your code always tries to print one item too much. Use < instead of <= in the loop head to fix that:
for(printingNumber = 0; printingNumber < currentRoll; printingNumber += 1)