I'm trying to add all the square root answer but why am i getting this output: -858993430

#include <iostream.h>


void main()
{

    int input;
    int sqrt;
    int i, sum, add;

    cout << "Please enter your desire number: ";
    cin  >> input;

    for (i=1; i <= input; i++)
    {
        sqrt = i * i;       
        add = sqrt;
        cout << i << "^2 = " << sqrt<< "\n";
        sum +=  add;
    }   

    cout << "the sum is: " << sum;

}

what could be wrong? hope you could help me with this. thanks!

sum must be initialized to zero.
You don't need the variable add.

And, not related to programming, you're squaring it, not square rooting it.

No, I really meant pow() function.
It is more versatile than sqrt().
You can use pow(N,0.5) rather than sqtr(N)

xD Okay, sorry. I'd suggest sqrt() nonetheless, but it doesn't really matter.

Please. Please
Don't use void main. http://cppdb.blogspot.com/2009/02/sh...t-main-or.html
And yes, you are adding the squares of the integer rather than the square root.
To find the square root, you need to #include <cmath> and use the pow() function. http://www.cppreference.com/wiki/c/math/pow

thanks!

i got it! hmmm.... i cant use other than void... i'm not a pro yet and i must stick with the way my prof has taught us. though yah it would be nice to experiment from time to time but as now i have to stick with it :(. new ways are hard for me to understand especially when you have tones of assignments regarding it! hahaha!

but anyway, i appreciate it! thank a lot everybody!

so here's my code and glad to have it work... after how many paper scratches for computation.. :(

#include <iostream.h>


void main()
{

    int input;
    int sqrt;
    int i, sum, add;


    cout << "Please enter your desire number: ";
    cin  >> input;


    cout << "\n" ;

    for (i=1; i <= input; i++)
    {

        sqrt = i * i;       

        cout << "\n" << i << "^2 = " << sqrt<< "\n";

        sum = sum + sqrt;



    }



    add = 0;

    for (i=0; i <=input; i++)
    {
        sum = i * i;
        add = add + sum;
    }   


    cout << "\nThe sum is: " << add << "\n\n";
}

now my next problem is how to do the sum of powers from 1 to n :(

when the user inputted 4

it should be

1^1 = 1
2^2 = 4
3^3 = 27
4^4 = 256

whew... :(

now it's getting more confusing....

No, I really meant pow() function.
It is more versatile than sqrt().
You can use pow(N,0.5) rather than sqtr(N)

hahaha!

i tried the pow! ya you're right it was much easier to use...

thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.