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:

  1.     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.
  2.      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

Popular posts from this blog

153: Write a program to read an amount (integer value) and break the amount into smallest possible number of bank notes. Note: The possible banknotes are 500, 100, 50, 20, 10, 5, 2, and 1

206: Write a program to create a class named "Circle" which has the property "radius". Define functions to calculate the area and circumference of the circle.

221: // In Task 2, we discussed multilevel inheritance with parameterized constructors for Student, UndergraduateStudent, and GraduateStudent classes in a university management system. Can you explain the advantages of using multilevel inheritance with specific details about the functions and data members in these classes? How were the parameterized constructors (e.g., setting student name, age, and ID) used to ensure that each class in the hierarchy correctly initializes its properties, such as creating an UndergraduateStudent named "John," aged 20, with a student ID of 12345