Write a c++ program to check whether a given number is a perfect number or not.
Flowchart of perfect number program
C++ Source code of the perfect number
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 |
#include<iostream> #include<conio.h> using namespace std; int main() { int i,mid,num,sum=0; cout<<"enter the num"; cin>>num; mid=num/2; i=1; do { if(num%i==0) sum=sum+i; i++; } while(i<=mid); if(sum==num) { cout<<num<<"is a perfect number"; } else { cout<<num<<"is not a perfect num"; } getch(); } |
Output
enter the num 5
5 is a perfect number
Excercise
Find the possible mistakes in the following Shamilâs Flow Table of the program to check whether a given number is a perfect number or not.
Â
loop |
Â
Line which executed |
Â
Actual work to do |
Â
I=1 |
Â
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 25, 16 |
N%i==0
6%1==0 Sum=sum+i Sum=0+1=1 |
Â
I=2 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 25,16,17, 11,12,13,14,25,16, Â |
N%i==0
6%2==0 Sum=sum+i Sum=1+2=3 |
I=3
 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 25,16,17, 11,12,13,14,25, 16,17,11,12,13,14,25,16, Â |
N%i==0
6%3==0 Sum=sum+i Sum=3+3=6 |
I=4
 |
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 25,16,17, 11,12,13,14,25, 16,17,11,12,13,14,25,16,17,18 Â Â |
 |
 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 25,16,17,11, 12,13,14,25, 16,17,11,12,13,14,25,16,17, 18,19,20,21,26,27 Â |
Sum=6
Is a perfect number |