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!
#include <iostream>
usingnamespace 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.
#include <iostream>
usingnamespace 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.
#include <iostream>
usingnamespace 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;
}