Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

sum of squares of two numbers c program

i’m supposed to write a formula for the sum of squares using the given function and its parameters (i am allowed to add variables) but i can’t seem to get it right. the formula i came up with only computes the summation of the two numbers (not squared). please help, thank you!

/* Suppose nLowerBound is -2 and nUpperBound is 4.
    The function computes:
    (-2)^2 + (-1)^2 + (0)^2 + (1)^2 + (2)^2 + (3)^2 + (4)^2 = 35
    The function returns 35.
*/

int sumOfSquares(int nLowerBound,
                 int nUpperBound) {
    // your code here
    int nSum;
    nSum = ( (nUpperBound * (nUpperBound + 1)) - (nLowerBound * (nLowerBound - 1)) ) / 2;
    
    return nSum;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The simplest way to compute the sum is to use a loop:

int sumOfSquares(int nLowerBound,
                 int nUpperBound) {
    // Initially set the sum as zero
    int nSum = 0; 

    for (int i=nLowerBound; i<=nUpperBound; i++) {
        // for each number between the bounds, add its square to the sum
        nSum = nSum + i*i; 
    }
    
    return nSum;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading