60: ***(Syntax)*** Write a program in C++ to find the perfect numbers between the user-defined range.
// Write a program in C++ to find the perfect numbers between the user-defined range.
// The perfect numbers between 1 to 500 are:
// 6
// 28
// 496
// **************************************************************************************************
#include <iostream>
using namespace std;
int main()
{
int start, end;
cout << "\nEnter the starting number of range: ";
cin >> start;
cout << "Enter the ending number of range: ";
cin >> end;
cout << "\n*********************************************************************************\n\n";
int sum;
for (int i = start; i <= end; i++)
{
sum = 0;
for (int j = 1; j < i; j++)
{
if (i % j == 0)
{
sum = sum + j;
}
}
if (sum==i)
{
cout << i << ' ';
}
}
return 0;
}
Note:
- In this code, if you do not write sum = 0 within the loop, this loop won't work. Because, sum must be zero, every time the loop resets.
- If you write j <= i in place of j < i , compiler will also take the number itself as its multiple and the sum of multiples will never be equal to number.
Comments
Post a Comment