What is wrong with this???Plss help

Hello Community!
I want to create a program which can find out if a number is perfect or not.
The perfect number are numbers like(e.g number 6 whose divisors are 1+2+3=6)


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
28
  #include <iostream>
using namespace std;
int  main(){
	int i;
	int n;
	int s=0;
	
cout<<"Vendosni numrin per te pare nese eshte perfekt apo jo"<<endl;
cin >>n;
while(i=1 && i<n){

 if(n%i==0){
  s+=i;
}
i++;
   
  
}
  if(s==n){
  cout<<"1";
  }
  else{
  	cout <<"0";
  }
   
   
 return 0;  
}

I can also write it with some little modification like so:
[code]
#include <iostream>
using namespace std;
int main(){
int i;
int n;
int s=0;

cout<<"Vendosni numrin per te pare nese eshte perfekt apo jo"<<endl;
cin >>n;
for(i=1;i<n;i++){
if(n%i==0){
s+=i;
}
}
if(s==n){
cout<<"1";
}
else{
cout <<"0";
}


return 0;
}

</code]
Hello Ergis,

I write this more to show you what is wrong, so that you can learn from it.

In your first code you should always initialize you variables. "i" was a problem when I first ran your code.

Line 10 the while loop: "i = 1" along with "i < n". You are setting I = to 1 which will always be true and "i" will always be < n which makes he condition always true. This will give you an endless loop. I think your intent is "i == 1", but all you really need for the while condition is "i < n". Inside the while loop adding "i" to "s" is nice, but does not do much.

Following the while loop the if statement will print a "1" and chances are it will never print "0".

The following is how I changed your code. It makes a little more sense. Unfortunately it works for 6, but not for 24. I need to work on that a bit.

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
28
29
30
31
32
33
34
35
36
37
38
39
  #include <iostream>
using namespace std;
int  main()
{
	int i{ 1 };
	int n{ 0 }, total{ 0 };
	int s = 0;

	std::cout << "Vendosni numrin per te pare nese eshte perfekt apo jo" << std::endl;
	std::cin >> n;

	while (i < n)
	{

		if (n % i == 0)
		{
			s += i;
                        //  <--- Added these lines to show what was happening.
			std::cout << i;
			total += i;
			std::string op = (total < n) ? " + " : " = ";
			std::cout << op;  // <--- Not quite right. still working.
			if (total == n)
				std::cout << total;
		}
		i++;


}
	if (s == n)
        {
		std::cout << "\n 1";  // <--- Added the \n to print on a new line,
	}
	else
        {
		std::cout << "\n 0";
	}
        return 0;  
}


A place to start from.

Hope that helps,

Andy
Topic archived. No new replies allowed.