Need help and explications with my code

So I almost finished the code,but I've got problem with displaying the results.It just does not display anything even tough I introduce good values.
The problem asks me to display all of the natural numbers that are equal with the sum of their figures to square.Example:81...8+1=9 and 81=9*9;
Also,there is a hint that such number can't contain more than 4 digits(for example 12345 is not corect);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
  int n,s,c,i,a;
    cout<<"n=";cin>>n;
    for(i=1;i<=n;i++)
    {
        s=0;
        cout<<"a=";cin>>a;
        while(a<1000&&a!=0)
        {
            c=a%10;
            a=a/10;
            s=s+c;
        }
        if(a==s*s)cout<<"The natural numbers with this property are  "<<a<<endl;
    }
Last edited on
Line 6: why are you inputting a number here? Why not just set a=i?
Line 13: By the time you get here, a==0. You need to remember the original number and use it here. If you take my first suggestion then you can use i instead of a.
I do not see much sense in doing that considering that there is only one number of up to four digits that satisfies these conditions (89). By the way, if you separate each integer of the number and store it in a string of integers, this may make the algorithm easier. Check the code I did.

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
#include <iostream>

using namespace std;

int main ()
{
    int aux = 1;
    int numbers[4] = {0, 0, 0, 0}; // Array of integers

    for (int i=11;i<99;i++)
    {
        int value = i;
        int aux = 1;
 
        // The loop below separate each digit of the integer and store it in the string numbers[]
        while (value > 0)
        {
            int digit = value%10;
            numbers[aux] = digit;
            aux--;
            value = value/10;
        }
       // End of the procedure

        if ( i==(numbers[0]+numbers[1]) * (numbers[0]+numbers[1]))
        cout << i
         << "  is equal to the sum of its figures to square" << endl;
  }

}
Last edited on
Topic archived. No new replies allowed.