954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Print results of multiple series based on input by user

Hi
I'm trying to write a program that will print the results of the series
sqrt(1), sqrt(1)+sqrt(2), sqrt(1)+sqrt(2)+sqrt(3),...., sqrt(1)+sqrt(2)+sqrt(3)+...+sqrt(n)
where n is chosen by the user. The output should look something like
1, 2.414, 4.146, 6.146, 8.382, 10.831, .....
Here's what I have so far

#include <iostream>
#include <cmath>

using namespace std;
void sumN();
double count;
int Q;
int i;

int main() {
cin>>Q;
for (i=1;i<=Q;i++)
    cout<<sumN(i)<<" ";
}

void sumN()
{

    for(int i=0;i<=Q;i++){
        sumN(i)+=sqrt(i);}

}

Any help would be appreciated
Thanks

coroche
Newbie Poster
7 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

Your'e missing many points.

At line 13 you try to pass i to your function, although the function doesn't take any parameter.
Plus you tell cout to print a void value. (See the return value of your function)

At line 20 you assign a float (sqrt(i)) to a void function.

So try this :

void sumN(int); // declaration

void sumN(int i){}; // definition


For your approach you actually only need this :

for (int i = 0;i < Q;i++)
    {
        float result = 0;

        for (int j = 0;j < i;j++)
        {
            result += sqrt(j);
        }

        cout << result << " ";
    }


Output for Q = 6 would look like this :

0 0 1 2.41421 4.14626 6.14626
Dman01
Light Poster
25 posts since Aug 2010
Reputation Points: 20
Solved Threads: 3
 

Thanks
Your solution returns the result I'm looking for but we were asked to use the function sumN() in our code to generate the series and output the result of running the series n times in main()

coroche
Newbie Poster
7 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 
Thanks but we were asked to use the function sumN() in our code to generate the series and output the result of running the series n times in main()

Then you only have to put the code into sumN.
You could either pass n to the function or use a global variable, so you now how many times the for-loop will calculate the sqrt();

Dman01
Light Poster
25 posts since Aug 2010
Reputation Points: 20
Solved Threads: 3
 

Thanks a lot

coroche
Newbie Poster
7 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You