Finding Factors with a twist

Total programming newbie here looking for some guidance.

So I have this assignment where I need to write a program that takes numbers from an input file and spits out said numbers factors. The catch is as soon as the read hits a negative number, the program is supposed to break the loop and end, even if there are values in the input file after the negative number.

I tried inserting another "if" statement within the "for" loop to no avail and I don't think changing the statements in the "for" loop would work.

Below is my working code so far.

Thanks in advance.

[b]#include <iostream>

#include <iomanip>

using namespace std;

int main()

{

int number;

int data_count;

cin >> number;

while (cin)

{

data_count=0;

cout << "factors of " << number << " are"<< endl;

for (int i=number; i>=1; i--)

if (number % i == 0)

{

data_count++;

cout << setw(5) << i;

if (data_count%6==0)

cout << endl;

}

cout << endl;

cin >> number;

}

return 0;

}

I noticed if the number is larger than 9999, your code "cout << setw(5) << i;" isn't effective, you might use a tab instead. or some other spacing for large numbers.

For numbers up to 7 digits, try
cout << "\t" << i;


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream> 
#include <iomanip> 
using namespace std; 

int main() 
{ 
int number; 
int data_count;
cout << "A Number please: "; 
cin >> number; 
while (number >=0)
// while (cin)
{ 
data_count=0; 
cout << "factors of " << number << " are"<< endl; 
for (int i=number; i>=1; i--) 
if (number % i == 0) 
{ 
data_count++; 
cout << setw(5) << i; 
if (data_count%6==0) 
cout << endl; 
} 
cout << endl;
cout << "A Number please: ";  
cin >> number; 
} 

return 0;

}
Last edited on
1
2
3
4
5
6
7
8
int number ;

// while a. we have been able to read a number from the input stream
//       b. and the number is non-negative
while( ( std::cin >> number ) && ( number > 0 ) )
{
    // find the factors of the number and print them out
}

Thank you both. Got all working to how I need to for the assignment.

Enjoy the weekend.
Topic archived. No new replies allowed.