Adding numbers between 1 and some parameter.

What I want this program to do is have the user input a number.
After the user inputs a number, the program then it adds all the numbers between 1 and the input number.
So, for example, the program looks something like this:

1
2
3
Hello, how many numbers do you want to add: 3
The sum is: 6
Good bye!


This is my current code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>

using namespace std;

int main()
{
   int x = 1;
   int sum = 0;
   int input;

    cout << "Hello, how many numbers do you want to add: " << endl;
    cin >> input;

    for (x = 1; x <= input; x++)
    {
        sum = sum + x;
           cout << "The result is: " << sum << endl;
    }
       return 0;
}


Problem 1: I don't want it to show every line that it's adding - I just want it to show the final sum.

Problem 2: Instead of using the for(;;) loop, I need to use a function instead.

Help, please?
If you want to get really fancy, you could use recursion and pointers

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 <iostream>

using namespace std;

void calculate_sum(int input, int* sum) {
  if (input > 0) {
    *sum = *sum + (input);
    calculate_sum(--input, sum);
  }
  return;
}

int main()
{
  int sum = 0;
  int input;

  cout << "Hello, how many numbers do you want to add: " << endl;
  cit >> input;

  calculate_sum(input, &sum);

  cout << "The result is " << sum << endl;

  return 0;
}


If you are unsure about how recursion or pointers work, check out these links.

http://cplusplus.com/doc/tutorial/pointers/
http://www.cprogramming.com/tutorial/lesson16.html

EDIT:

Made the code a bit nicer.
Last edited on
@strongdrink: Thank you for both the code and links. Now I just have to learn exactly how recursion and pointers work!
Heh, here is another more optimized version

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

using namespace std;

int calculate_sum(int p_input, int p_sum = 0) {
  return (p_input > 0)
      ? calculate_sum(--p_input, p_sum += p_input)
      : p_sum;
}

int main() {
  int input;

  cout << "Hello, how many numbers do you want to add? ";
  cin  >> input;
  cout << "The result is " << calculate_sum(input) << endl;

  return 0;
}
Topic archived. No new replies allowed.