HW help

Hello everyone,

I've been trying to solve this problem for days. I read the text, watched Buckyrooms C++ videos and other videos, unfortunately nothings sticking in my head... I know there has to be a counter, to print out 1., 2., 3., and then add 1 to the last integer but I cant type it out. So frustrating!

Any help would be great!


thx!

Write a program that asks the user to enter a positive integer and displays a table of numbers and
their factors, from 1 up to the number entered.

Below is a sample run:
Enter a positive integer: 8
1: 1
2: 1 2
3: 1 3
4: 1 2 4


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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
 #include <iostream>

using namespace std;

int main() 

4.{

5. 

6. 

7.int count, c, n; // ok

8. 

9.cout << "Enter a positive integer: "; // ok

10.cin >> n; // ok  

11. 

12. 

13. 

14.if (n <= 0) exit(1); // ok

15. 

16.for(count=1;count<=n;count++)  //changed to count

17.{

18.	cout << n;

19.	cout <<endl;

20. 

21.for(int i=1;i<=n;i++)

22. 

23. 

24. 

25.}

26. 

27. 

28.cout << n; 

29.}

30. 

31. 

32.return 0;

33.}

34. 

Two for loops:

Outer loop processes 1 to user entered number.

Inner loop finds factors.
Just what mobotus said.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

void printFactor(int a)
{
    for(int i = 1; i <= a; i++)
        if(a%i ==0)
            cout<<i<<" ";
    cout<<endl;
}
int main()
{
    int n;
    cout<<"Enter the number: ";
    cin>>n;

    for(int i = 1; i <= n; i++)
    {
        cout<<i<<": ";
        printFactor(i);
    }
    return 0;
}
Thank you for this!! quick question how does "void printFactor(int a)" and "printFactor(i)" translate to c++?

This is what I came up with, my factoring is wrong. I am pretty sure I am setting it up wrong.

[code]
int main()
{
int n,a; // declaration ok

cout<<"Enter the number: "; // output ok
cin>>n; // user input

for(int i = 1; i <= n; i++) //increment operator, starting at 1, stops when equal or less than user input.
{
cout<<i<<": "; //prints the users input individually


{
int factor=0; // ?
for(int i = 1; i <= factor; i++) //increment operator, starts at 1, less than a then goes up.
if(a%i ==0) //modulus operation
cout<<i<<": "; //output of the labe.
cout<<a <<" "; //output of the factors
cout<<endl;
}
}
return 0;
}
[code]
Last edited on
if(a%i ==0)

You are trying to use a variable that isn't initialized.

In shadowCODE's code void printFactor(int a) is a function and printFactor(i) is a call to that function.

http://www.cplusplus.com/doc/tutorial/functions/
Topic archived. No new replies allowed.