Exits while loop before condition is false? - c++

This is a pretty specific question but my program seems to exiting its while loop before the condition is false. I added in quite a few memory checks for safety when I was debugging and it prints to screen that counter is 4 and SqRoot is 6 at the end which means it should still be looping through (TestNum=32). I definitely know it's getting past the loop with counter<=SqRoot because it prints both "The integer 32 is composite" and "The integer 32 is prime". Any help is very appreciated! Thanks so much
EDIT: I changed the overall logic of program and it is working now. Thanks!
#include <iostream>
#include <cmath>
using namespace std;
//Declare variables.
int TestNum, DivInt, SqRoot, PrintCounter(0), oppcounter;
float DivFloat, counter(2);
int main()
{
//Prompt user for input.
cout << "Input an positive integer to test its primality.";
cin >> TestNum;
//Check if input is positive.
while (TestNum < 0)
{
cout << "Please input a *positive* integer.";
cin >> TestNum;
}
//Square root.
SqRoot = sqrt(TestNum)+1;
//Loop to test if prime.
while (counter<=SqRoot)
{
++counter;
DivFloat = TestNum/counter;
DivInt = TestNum/counter;
oppcounter = TestNum/counter;
if (DivFloat-DivInt == 0)
{
++PrintCounter;
if (PrintCounter==1)
{
cout << "The integer " << TestNum << " is composite.\n " \
<< TestNum << " is divisible by\n";
};
cout << counter << " " << oppcounter;
cout << "counter* " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
}
}
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
cout << "counter " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
//End main.
return (0);
}

I am seeing the opposite behavior of what you are describing, and I can see why. It's possible that the code you have posted is different than the code you are executing.
As an aside, I added the line
cout << endl;
after the line
cout << " DivFloat " << DivFloat;
at couple of places to make the output more readable.
When I enter 32, I see the following output:
The integer 32 is composite.
32 is divisible by
4 8
counter* 4 TestNum 32 DivInt 8 SqRoot 6 DivFloat 8
counter 7 TestNum 32 DivInt 4 SqRoot 6 DivFloat 4.57143
When I enter 17, I see the following output:
counter 6 TestNum 17 DivInt 2 SqRoot 5 DivFloat 2.83333
The reasons for that:
You don't break out of the while loop when you have detected that a number is a composite.
As a result of that, you always break out of the while loop only when counter<=SqRoot evaluates to false. As a result, in the code below,
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
you never execute the line in the if block.
The program should behave correctly if you break out of the while loop when you detect a composite and change the logic in the last if block to:
if (counter > SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}

Why so strange check for prime?
for(int i = 2; i*i <= n; ++i)
{
if (n % i == 0)
{
cout << "not prime";
break;
}
}

Related

Why does the if statement is always the else part even if the if is true?

I'm having a problem with the if statement at the end.
**if the sum of the cubs of the number a user inputs, is equal to the number itself, say "....". Else, say "....." **
The problem is that it always jumps the if part to the else.
Its a task from the uni, no homework or nothing, just training. IF you have suggestions on how to better I would appreciate that too.
Thank you!
{
int n;
cout << "Write a number different from 0 -> ";
cin >> n;
while (n == 0)
{
cout << "Choose another number -> ";
cin >> n;
}
cout << "Good number " << n << " is!" << "\n";
cout << "lets separate each digit:" << "\n" << " -----------------------------------" << endl;
Sleep(1000);
vector<int> vecN;
while (n != 0)
{
int digit = n % 10;
n /= 10;
cout << n << endl;
cout << "Digit: " << digit << endl;
vecN.push_back(digit);
Sleep(750);
}
cout << "There you go!" << endl;
Sleep(1000);
cout << "Next stage, let's find the cubes for each one of the digits!" << endl;
Sleep(2500);
vector<int> sums;
for (auto i = vecN.begin(); i != vecN.end(); i++)
{
Sleep(500);
int Cubes = pow(*i, 3);
cout << Cubes << endl;
sums.push_back(Cubes);
}
Sleep(1300);
cout << "Now let's sum the cubs and see if the number is an Armstrong Number" << endl;
Sleep(3000);
int armSum = accumulate(sums.begin(), sums.end(), 0);
if ( armSum == n )
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's an Armstrong Number!" << "\n"
"The sum of the cubs of each digit in the number is equal to that same number!" << endl;
}
else
{
cout << "Sum: " << armSum << endl;
Sleep(500);
cout << "That's not an Armstrong Number!" << endl;
}
return 0;
} ```
When the if-part is entered, the else-part won't be entered any more. Note that your if/else is not surrounded by a loop. So when control passes by once, e.g. when having entered n==0, then it has passed by and won't step into neither the if nor the else-part a second time.
Try something like
while (n==0) {
cout << "Choose another number -> ";
cin >> n;
}
// continue here; n is != 0

Create a program that counts number of odd, even and zero numbers C++

#include <iostream>using namespace std;
const int LIMIT=10;
int main () {
float counter;
int number=0;
int zeros=0;
int odds=0;
int evens=0;
cout << "Please enter " << LIMIT << " integers, " << "positive, negative, or zeros." << endl;
cout << "The numbers you entered are:" << endl;
for (counter=1; counter <=LIMIT; counter++) {
cin>>number;
switch (number / 2) {
case 0: evens++;
if (number=0) zeros++;
case 1: case -1: odds++;
}
}
cout << endl;
cout << "There are " << evens << " evens, " << "which includes " << zeros << " zeros." << endl;
cout << "The number of odd numbers is: " << odds << endl;
return 0;
}
Hi All,
I have a varsity question which has had me stumped all day. I need to amend the above script to allow me to enter 10 variable integers and the program must return me the total number of even numbers, total number of odd numbers and total number of zeros.
I have tried multiple solutions including (number % 2 == 0) in order to make my cases work under my switch parameter however I am missing something.
Please can someone assist pushing me into the right path.
(I know i need to remove the negative case but I wanted to post the raw code incase I take something out or ammend something that is needed)
#include <iostream>using namespace std;
const int LIMIT=10;
int main () {
float counter;
int number=0;
int zeros=0;
int odds=0;
int evens=0;
int n=0;
cout << "Please enter " << LIMIT << " integers, " << "positive, negative, or zeros." << endl;
cout << "The numbers you entered are:" << endl;
for (counter=1;
counter <=LIMIT;
counter++) {
cin>>number;
n=(number%2);
switch (n) {
case 0: evens++;
if (number==0) zeros++;
break;
case 1: odds++;
}
}
cout << endl;
cout << "There are " << evens << " evens, " << "which includes " << zeros << " zeros." << endl;
cout << "The number of odd numbers is: " << odds << endl;
return 0;
}
Thanks to papagaga managed to get it working - i think i was far too tired :)
std::vector<int> myvec = {0, 2, 3, 5, 0, 0, 5, 4, 9};
std::vector<int> zeros;
std::vector<int> evens;
std::vector<int> odds;
for (auto i : myvec) {
if (i % 2 == 0) {
if (i == 0) zeros.push_back(i);
else evens.push_back(i);
}
else
odds.push_back(i);
}
std::cout << zeros.size();
std::cout << evens.size();
std::cout << odds.size();
return 0;
}
If you don't want zeros to be in the evens vector, this will work.

c++ cast int to double not working

int main(){
srand(time(0));
int numOfTimes;
int randNum;
int oneRoll = 0, twoRoll = 0, threeRoll = 0, fourRoll = 0, fiveRoll = 0, sixRoll = 0;
int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent;
int count = 0;
cout << "How many times would you like to roll the dice?\n";
cin >> numOfTimes;
while (numOfTimes <= 0){
cout << "Invalid entry enter a number greater than 0\n";
cout << "How many times would you like to roll the dice?\n";
cin >> numOfTimes;
}
while (count < numOfTimes)
{
randNum = rand() % 6 + 1;
switch (randNum)
{
case 1:
oneRoll++;
break;
case 2:
twoRoll++;
break;
case 3:
threeRoll++;
break;
case 4:
fourRoll++;
break;
case 5:
fiveRoll++;
break;
case 6:
sixRoll++;
break;
default:
cout << "\n";
}
count++;
}
onePercent = (int)((oneRoll*100.0) /numOfTimes);
twoPercent = (int)((twoRoll*100.0) / numOfTimes);
cout << " # Rolled # Times % Times" << endl;
cout << "--------- -------- --------" << endl;
cout << "1 " << oneRoll << " " <<double (onePercent) << endl;
cout << "2 " << twoRoll << " " << "" << endl;
cout << "3 " << threeRoll << " " << ""<< endl;
cout << "4 " << fourRoll << " " <<"" << endl;
cout << "5 " << fiveRoll << " " <<"" << endl;
cout << "6 " << sixRoll << " " <<"" << endl;
I need it to print out the the one percent as a double. So I converted it as an int then to a double so it only prints two zeros like this (14.00) but its not converting at all its only printing 14
The main problem, just as Barmar mentioned in his comment, is that although you want the value to be printed to 2 decimal points, you round off the number in onePercent when you do:
onePercent = (int)((oneRoll*100.0) /numOfTimes); // Casting to "int" rounds off the number
Also, the declared data type for onePercent is int from the start:
int onePercent, twoPercent, threePercent, fourPercent, fivePercent, sixPercent; // onePercent is an "int" here
So you don't need a typecast of int, because you're casting an int to an int.
Therefore, even if you print onePercentwith 2 decimal-point precision, you will always get .00 as a result.
I would recommend taking off the (int) cast from that expression itself, and changing the initial data type of onePercent to type double. If you do not want to change the data types for the other variables declared alongside onePercent, then declare onePercent as a double on another line. That way, the precision of the value after the calculation will be maintained, and you will be able to output it to 2 decimal places.
As an aside, to specify the number of decimal places to output, the setprecision() function can be used:
cout << setprecision(2) << ... << endl; // The value passed to "setprecision" is up to you.

C++ Factor Program: Outputting Number of Factors Given

I am writing a simple program that finds the factors of a list of integers through Linux Redirection. I am almost done, but I am stuck on one part. Here is my program so far:
#include<iostream>
using namespace std;
int main()
{
int counter = 0;
int factor;
cin >> factor;
while (cin)
{
if (factor < 0)
break;
cout << "The factors of " << factor << " are " << endl;
for(int i=factor; i>=1; i--)
if (factor % i == 0)
{
counter++;
cout << i << endl;
}
cout << "There are " << " factors." << endl;
cout << endl;
cin >> factor;
}
return 0;
}
Now the problem I have is in the line " cout << "There are " << " factors." << endl; ". I'm not sure how to calculate the number of factors output by the program.
For example:
The factors of 7 are
1
7
There are 2 factors.
How would I go about calculating and outputting the "2" in this example.
Help is greatly appreciated.
Instead of
cout << "There are " << " factors." << endl;
use
cout << "There are " << counter << " factors." << endl;
If you do that, you have to move the line where you define counter.
Instead of it being the first line in main, it needs to be moved to be the first line in the while loop.

How do I make spaces between numbers in a random number generated app in C++?

I need to be able to have spaces come up between each number. Here is my code. Any help would be awesome! This app allows you too have 6 rows of 6 numbers generated for your insta pick numbers between 1 - 49, it has to pick two rows of 6 numbers, 1 - 49 for twist and 1 row of 6 numbers for tag.
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
int main()
{
{
cout << "*** LOTTO MAX INSTA PICK ***" << endl;
cout<< " " << endl << endl;
}
{
cout << "Your Insta Pick Numbers" << endl;
cout<< " " << endl << endl;
}
for (int counter = 1; counter <= 24; ++ counter)
{
cout << setw(1) << (1 + rand() % 49);
if (counter % 6 == 0)
cout << endl;
}
{
cout<< " " << endl << endl;
cout<< " " << endl << endl;
}
{
cout << "Your Twist Numbers" << endl;
cout<< " " << endl << endl;
}
for (int counter = 1; counter <= 12; ++ counter)
{
cout << setw(1) << (1 + rand() % 49) , " ";
if (counter % 6 == 0)
cout << endl;
}
{
cout<< " " << endl << endl;
cout<< " " << endl << endl;
}
{
cout << "Your Tag Numbers" << endl;
cout<< " " << endl << endl;
}
for (int counter = 1; counter <= 6; ++ counter)
{
cout << setw(1) << (1 + rand() % 12);
if (counter % 6 == 0)
cout << endl;
}
{
cout<< " " << endl << endl;
cout<< " " << endl << endl;
}
{
cout << "Thank you for playing!! please check ticket a year minus a day from date of purchase" <<endl;
}
};
You almost had it when you did
cout << setw(1) << (1 + rand() % 49) , " ";
but that doesn't do what you think it does. It evaluates two expressions, separated by a comma - cout << setw(1) << (1 + rand() % 49) and " ". The first does the setw and prints (1 + rand() % 49), and the second one just evaluates to itself and has no effect. Remember that << is the output operator for cout, so you just need to change the comma to a <<:
cout << setw(1) << (1 + rand() % 49) << " ";
The same thing goes for the other places you are printing numbers.
Use cout << setw(1) << (1 + rand() % 49) << " "; in your loop. (Note that , was replaced with <<.