• C

writing a function

Write the function odd_sum that accepts a positive integer N as a parameter and returns the sum of the first N odd numbers. A call to odd_sum of the form:

           sum = odd_sum(5);

will return the value 25 since 1+3+5+7+9=25

thank in advance!
beachbummAsked:
Who is Participating?
 
imladrisCommented:
int odd_sum(int n)
{   int i,sum;

    sum=0;
    for(i=1; i<n*2; i+=2)sum+=i;
    return(sum);
}
0
 
ZoppoCommented:
or, simple and fast

int odd_sum( int n )
{
 return (n*n);
}

ZOPPO
0
 
ZoppoCommented:
Proof:

sum <0...n> (2n + 1) =
sum <0...n> (2n)   + sum <0...n> (1) =
2((n*(n+1))/2)     + (n+1) =
n*n + 2n + 1 =
(n+1)*(n+1)

so, odd_sum(5) = sum<0...4>(2n+1) = n*n                           :o)

ZOPPO
0
Simplify Active Directory Administration

Administration of Active Directory does not have to be hard.  Too often what should be a simple task is made more difficult than it needs to be.The solution?  Hyena from SystemTools Software.  With ease-of-use as well as powerful importing and bulk updating capabilities.

 
deightonprogCommented:

*/optimized code/*

int odd_sum(int n)
{
        return n * n;
}
0
 
deightonprogCommented:
oops zoppo already thought of that.
0
 
ZoppoCommented:
sorry, meant 5*5 instead of n*n in last line .....
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.