### Perfect numbers

Write a program to find all the perfect numbers from 1 to 2000. A perfect number is an integer which is equal to the sum of all of its divisors.

example: 1 + 2 + 3 = 6
Do I use a for loop, while loop, or do while loop?
 ``123`` ``````for(int i = 0;i < 2000;i++) { }``````
This is as far as I got. how do I add individual values of a? More specifically,

#include <iostream>
using namespace std;
int main()

{

int a;
for(int a =0; a < 2000; a++)
{
cout << a << endl;
}
Edit: Only click this link if you want a working solution.

http://ideone.com/wbaQYL
Last edited on
Typically, a for loop is for when you know how many times you will loop, and a while loop is for when you don't. A do while is for when you want something to happen at least once.

 ``123456789101112131415161718`` ``````for (int i = 0; i < 10; i++) { cout << i '\n'; } int num; ifstream myFile("myData.txt"); while ( myFile >> num) { cout << num << '\n'; } char choice; do { cout "Make a choice, or q to quit: "; cin >> choice; } while (choice != 'q');``````

Last edited on
Why does this not work?
 ``1234567891011121314151617181920212223242526272829303132333435`` `````` #include using namespace std; int sumDiv(int x) { int s = 0; for ( int s = 1; i < x; ++ 1) { if(x % i == 0 ) s += i; } return s; } int main() { for(int i =1; i < 2000; i++) { int a == sumDiv(i); if (a == i) cout << i << endl; } }``````
In sumDiv the for loop should be int i not s.
Topic archived. No new replies allowed.