1

I am trying to find the sum of each digit in an integer squared, and for any integer that is input to sqdnumber, it outputs 0 to sqdNumber_result, and I can't figure out why.

Also, this is through edX, but I have been stuck for a week or so on this problem, and I have looked at a lot of different topics, but haven't found anything of use to me.

I used codeblocks to write this, but the system testing it uses codeboard

void squaredSum(int sqdnumber,int &sqdNumber_result) {
for (int i=1; i>1; i++){
    if (sqdnumber >= ((10^(i-1))-1)){
        int rem = (sqdnumber % (10^i));
        int rem1 = (sqdnumber % (10^(i-1)));
        int temp = (rem - rem1);
        sqdNumber_result = sqdNumber_result + (temp^2);
    }

    else{
        break;
    }
}
}

I am new to coding, and just learning to do loops in C++.

This is the first iteration of the loop I have gotten their system to actually give me an output for it(I've written and rewritten it 20 or so times), but it isn't giving me an output that makes sense.

I wouldn't ask but I am at my wit's end.

4 Answers4

5

In C++, ^ is the xor operator, not the nth power. for that, you should use pow.

Dutow
  • 5,638
  • 1
  • 30
  • 40
3

The for statement does not loop. The condition is false the first iteration

EFenix
  • 831
  • 4
  • 11
  • 1
    Note to OP: This would be super easy to see by running a debugger and stepping through the function. – chris Jul 21 '16 at 16:59
1

There are two issues:

for (int i=1; i>1; i++){

This loop will not loop at all, since the condition i>1 is never met.


The second issue is the usage of ^ to do a power operation. The ^ in C++ is not a power operator, it is the exclusive-or operator.

So the answer at first glance would be to use the std::pow function to compute powers. However there can be drawbacks using it if the exponent is an integer. The reason is that pow is not guaranteed to work perfectly for integer powers.

See this as to dangers of using pow() for integral exponents

It is advised to just use a simple array of values with the powers of 10 and doing a lookup.

Community
  • 1
  • 1
PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
-3

you said you were new to C++ so I tried to get a solution without using the for loop and tried to make it as simple as I could. Let me know if this was any help.

//Code to calculate the sum of each digit squared//
#include<iostream>

using namespace std;
int main ()
{
    int integer1,integer2,sum, square;

    cout<<"Please enter two integers"<<endl;

    cin>>integer1>>integer2 ;

    cout<<"The sum of your integers is"<<" "<<endl;

    sum = (integer1+integer2);

    cout<<sum<<endl;

    cout<<"The square of your sum is"<<" "<<endl;

    square = (sum*sum);

    cout<<square<<endl;

return 0;
}
Enamul Hassan
  • 5,266
  • 23
  • 39
  • 56
  • And the explanation for "Why is this loop outputting 0 every time to sqdNumber_result?" is where? Your answer seems to be totally unrelated. – J.J. Hakala Jul 21 '16 at 18:15