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

88: Using switch statement Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: // Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F

205: Book Catalog: Define a struct to represent a book with attributes like title, author, and publication year. Write a program to create a catalog of books by taking user input and display books published after a certain year.

15: Take input of age and name of 3 people by user and determine oldest and youngest among them with his age. -_-_-_-_-_-_-_-_-(line with spaces input concept)-_-_-_-_-_-_-_-_