Solved

writing a function

Posted on 2000-03-01
166 Views
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

0
Question by:beachbumm
• 3
• 2

LVL 16

Accepted Solution

ID: 2573009
int odd_sum(int n)
{   int i,sum;

sum=0;
for(i=1; i<n*2; i+=2)sum+=i;
return(sum);
}
0

LVL 30

Expert Comment

ID: 2573109
or, simple and fast

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

ZOPPO
0

LVL 30

Expert Comment

ID: 2573133
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

LVL 18

Expert Comment

ID: 2573134

*/optimized code/*

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

LVL 18

Expert Comment

ID: 2573138
oops zoppo already thought of that.
0

LVL 30

Expert Comment

ID: 2573141
sorry, meant 5*5 instead of n*n in last line .....
0

Featured Post

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.
The goal of this video is to provide viewers with basic examples to understand how to create, access, and change arrays in the C programming language.