?
Solved

writing a function

Posted on 2000-03-01
6
Medium Priority
?
214 Views
Last Modified: 2010-04-15
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!
0
Comment
Question by:beachbumm
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 16

Accepted Solution

by:
imladris earned 100 total points
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 31

Expert Comment

by:Zoppo
ID: 2573109
or, simple and fast

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

ZOPPO
0
 
LVL 31

Expert Comment

by:Zoppo
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
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 18

Expert Comment

by:deighton
ID: 2573134

*/optimized code/*

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

Expert Comment

by:deighton
ID: 2573138
oops zoppo already thought of that.
0
 
LVL 31

Expert Comment

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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you thought about creating an iPhone application (app), but didn't even know where to get started? Here's how: ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ Important pre-programming comments: I’ve never tri…
Summary: This tutorial covers some basics of pointer, pointer arithmetic and function pointer. What is a pointer: A pointer is a variable which holds an address. This address might be address of another variable/address of devices/address of fu…
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.
Suggested Courses

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question