C++ Factor Program: Outputting Number of Factors Given - c++

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.

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

C++ assignment help on creating codes for reusability?

I've been having trouble doing this assignment. I'm just having a hard time understanding and I am not entirely sure what to do. I've researched and watched videos and havent been able to find the right, specific information. Its a bunch of questions, so I hope someone can not only giveme the answers, but also explain to me so I have a strong understanding :) . Here are the questions:
1)In this exercise we have been given some program code that will accept two integers as inputs
and evaluate which one holds the larger value. This evaluation occurs in multiple places
throughout the code. Write a function that the program could use to perform this same evaluation
instead of duplicating the code over and over. Start by writing a suitable function declaration
towards the beginning of the code file. You will have to decide whether your function will return
some output or not.
2) With your declaration written proceed to define the function, including the appropriate pieces of
code that will evaluate which of the two integers is the largest. If you stated earlier that your
function will return a value, be sure to define what it will return here.
3) Use your result from parts (1) and (2) to reduce the amount of duplicate code in the main function
provided by replacing the multiple instances of the integer comparison with a call to invoke the
function you have created. Remember that the function will require two integers to be passed in
as arguments and if you are returning some value from the function it should be used (stored in
a variable, outputted to screen, etc.). As a word of advice, test your function works correctly after
replacing just one of the evaluations, don’t replace them all at once (if the function works correctly
for the first replacement then it should work for the others).
4) Since the function you have created only compares the values of its parameters and doesn’t write
to them (i.e. change the value stored in them) we should specify in the function declaration and
definition that these parameters should be treated like constants. Make the necessary
modifications to the function and test again to verify the function still works. Confirm the function
will not let you change the data of the parameters by trying to include an operation in the function
that would change the value of one of the variables (e.g. number2 += 10;)
-- Here is the code ( I apologise for the long writing):
#include <iostream>
int main(void)
{
using std::cout;
using std::cin;
using std::endl;
int nNum1 = 10, nNum2 = 11;
cout << "This program will compare two numbers and report which one is larger.\n\n"
<< "Proceeding with evaluation...\n" << endl;
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int numberA = 234;
int numberB = 234;
cout << "\nUsing numbers: " << numberA << " and " << numberB << ", the larger one is: ";
if (numberA > numberB)
cout << numberA << endl;
else if (numberA < numberB)
cout << numberB << endl;
else
cout << "Neither of them! It's a draw." << endl;
int one = 'a';
int two = 'A';
cout << "\nUsing numbers: " << one << " and " << two << ", the larger one is: ";
if (one > two)
cout << one << endl;
else if (one < two)
cout << two << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\nUsing numbers: " << 13 << " and " << 84 << ", the larger one is: ";
if (13 > 84)
cout << 13 << endl;
else if (13 < 84)
cout << 84 << endl;
else
cout << "Neither of them! It's a draw." << endl;
int input1 = 0;
int input2 = 0;
cout << "\nPlease enter a number: ";
cin >> input1;
cout << "\nPlease enter a second number: ";
cin >> input2;
cout << "\nUsing numbers: " << input1 << " and " << input2 << ", the larger one is: ";
if (input1 > input2)
cout << input1 << endl;
else if (input1 < input2)
cout << input2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
cout << "\n\tThank you for running me :3\n" << endl;
return 0;
}
You basically have to refactor the code to replace the duplicate code part in your main function.
If you look closely you will see that code like this repeats:
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
So put that into a function:
void CompareNumbers(int nNum1, int nNum2)
{
cout << "\nUsing numbers: " << nNum1 << " and " << nNum2 << ", the larger one is: ";
if (nNum1 > nNum2)
cout << nNum1 << endl;
else if (nNum1 < nNum2)
cout << nNum2 << endl;
else
cout << "Neither of them! It's a draw." << endl;
}
And call this in your main function instead of duplicating the said code block.

Exits while loop before condition is false?

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

Float Variable Not Working Inside Switch Statment

So this program is supposed to collect weather temperatures over 7 days using a for loop and then basically just print them back out to the user with an average temperature and the highest recorded temperature. Keep in mind, the following piece of code is a part of a much larger program. Anyway, the problem seems to be the "highest_temp1" float variable. When I run the program it produces some sort of error code instead of the highest temperature. This piece of code was tested in a separate source file and it works no problem.
switch (choice)
{
case 3:
int n;
float temperatures [7];
float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
float highest_temp1, highest_temp2;
float accumulated_temp1, accumulated_temp2;
system("CLS");
cout << "____________Weather Data____________" << endl << endl;
for (n = 0; n<7; n++)
{
cout << "What is the temperature for Day " << n+1 << " ?" << endl;
cin >> temperatures[n];
if (highest_temp1 < temperatures [n])
{
highest_temp1 = temperatures [n];
}
if (highest_temp2 < lastweektemp [n])
{
highest_temp2 = lastweektemp [n];
}
accumulated_temp1 = accumulated_temp1 + temperatures[n];
accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
}
cout << endl << " Day This Week Last Week" << endl;
for (n=0; n<7; n++)
{
cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
}
system("CLS");
cout << " Weather Report" << endl;
cout << " --------------" << endl << endl;
cout << "Current Week: " << endl;
cout << "-------------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << temperatures[n] << endl;
}
cout << endl << " Average: " << accumulated_temp1 / 7 << endl;
cout << " Highest Temperature: " << highest_temp1 << endl;
cout << "Last Week: " << endl;
cout << "----------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
}
cout << endl << " Average: " << accumulated_temp2 / 7 << endl;
cout << " Highest Temperature: " << highest_temp2 << endl;
system("PAUSE");
}
The highest temperature in current week is 24 but it is printing "Highest Temperature: 3.45857e+032"
This exact 'error-code' is appearing every time I run the program it doesn't change.
I am a newbie hence why I can't upload a photo.
Any help would be appreciated. I'm doing a small assignment in college. This is my first question so go easy !!
You have not assigned any value to teh variable highest_temp1 and you are comparing it with another value.
Basically you will need to assign it a value first before you compare..
highest_temp1 = 10.00
(or anything that it is supposed to contain)
You have not initialised highest_temp1 (or highest_temp1 for that matter: after that I stopped looking).
Same for accumulated_temp, which gets not initialised. can be done via
float accumulated_temp1(0);
Initialize variables before using them
float highest_temp1(-FLT_MAX); // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX); // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);
For float number condition use if statements switch is not able to work in case of float number, switch only work for integer number.

Maybe a syntax issue here?

Homework problem I am helping one of my mentees out with (check my history, I have previously asked help with Java in more advanced programs. This is something simple I can't help her figure out). We need to use a while loop to read in numbers, keep track of the count, and keep summing up the numbers entered. We keep getting an error in line 24. Even when I comment it out and run it, the programs doesn't do what it is supposed to do. Been forever since I've done a program in C++ and I need the help of you guys!
#include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
int count = 0;
float avg;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num; //
while (num != 999)
{
cout << "Number entered is" << num << endl;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num;
sum = sum + num;
count++;
}
cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
return 0;
}
cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
Change those +'s to <<'s.
cout << "Total numbers entered: " << count << endl;
cout << "Sum of numbers entered is " << sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" << avg << endl;
#include<iostream>
using namespace std;
int main()
{
int num,count;
float sum,average;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
count=0;
sum=0;
while (num!=999)
{
cout<<"Number entered is"<<num<<endl;
++count;
sum+=num;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
}
if (count==0) {
count=1;
}// if the first number you enter is 999 count should be 1
// , otherwise avg will be (sum/0 ),which doesn't make sense.
cout << "Total numbers entered: " <<count << endl;
cout << "Sum of numbers entered is " <<sum << endl;
average = sum/count;
cout << "Average of numbers entered:"<<average << endl;
// use << not + because "Total..." is string type and count is int type
system("pause");
return 0;
}
You should pay attention to the type of variable when you do something,which often can cause small errors.