Help with code

Write a function to compute and return the value of the sum. Assume that the value
of n is an argument of the function.
s = 1 + 3 + 5 + . . . + (2n − 1)
Then in main function use a while loop to read values of the parameter n and print the sum with
each iteration.

This is a bit confusing for me. Please help. Thank you in advance. This is what I have so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include "std_lib_facilities.h"
  s=0;
  for(int i=1;i<2*n;I+=2)
  {
    s+=i;
int main {
while( )
{
  //Some code here

   cout << "s = 1 + " << /something
}

return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

int sum(const int n)
{
    if (n < 1)
    {
        return 0;
    }
    else if (n == 1)
    {
        return 1;
    }
    else
    {
        return (2 * n - 1) + sum (n - 1);
    }

}
int main ()
{
   std::cout << sum (3) << "\n";
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "std_lib_facilities.h"
int main ()
{
    int sum = 0;
    int num=1;
    int a;

    cout << "Enter a value for a: ";
    cin >> a;

    while (num<=a)
    {
        sum+= 2*num-1;
        if(num!=a)
            cout << 2*num - 1 <<  " + ";
        else
            cout << 2*num -1;

        num++;
    }

    cout << " = " << sum << endl;

    return 0;
}


This is the updated code and it runs the way I want it to. However I feel like in the directions that I am given I also need something outside the main function. How can I go about that from here?
Do you need this to be a recrusive function? It is not clear to me reading your question.
Beginning to think it's not recursive function. Blanking out on the name of it though. Any information that I am given is below. I know nothing more and nothing less of this. I'll be honest and say the way my professor explained this really threw me off in class and I'm just trying to get a better understanding of it all.

Write a function to compute and return the value of the sum. Assume that the value
of n is an argument of the function.
s = 1 + 3 + 5 + . . . + (2n − 1)
Then in main function use a while loop to read values of the parameter n and print the sum with each iteration.
The OP has been edited, I remember quite well there was a request for a recursive function in the initial post. Anyways, for
use a while loop to read values of the parameter n and print the sum with each iteration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main ()
{
  std::cout << "Enter n: \n";
  size_t n{}, i{1};
  std::cin >> n;
  int sum{};
  while (i <= n)
  {
    sum  += (2 * i - 1);
    std::cout << "Sum on iteration round: " << i << " = " << sum << "\n";
    ++i;
  }
}
Topic archived. No new replies allowed.