I need help with an assignment that I've been trying to do for around two hours. Here is the question:
This program asks the user to enter a positive integer number (say n) and displays the summation of all the numbers from 1 to n (1+2+3+ ā¦+n).
For example, if n is 100, the summation is 5050; if n is 4, the summation is 10
All I've managed to do is create some infinite loop where it constantly adds one to my input. I've no idea how to make the program stop at a certain number and put together the summation as the question asks me to. Any helpful advice? I appreciate the help.
#include <iostream>
usingnamespace std;
int main()
{
int number;
int sum = 0;
int n;
cout << "Please enter a positive number:";
cin >> number;
cout << "Enter a final number:";
cin >> n;
do
{
cout << "value of number:" << number << endl;
number = number + 1
} while (n);
cout << "The sum of number 1 to number " << number << " is " << sum << ā\nā;
return 0;
}
Line 21: Your loop is never going to terminate as long as the user enters n as a non-zero number. You want to compare number and n to terminate your loop.
while (number <= n);
As for the summation, you never add number to sum. You need to do that inside your loop.
#include <iostream>
int main()
{
int sum = 0;
int number;
std::cout << "Enter a final number: ";
std::cin >> number;
for (int i = 1; i <= number; i++)
{
std::cout << "value of number:" << i << "\n";
sum += i;
}
std::cout << "\nThe sum of 1 to " << number << " is " << sum << "\n";
return 0;
}
#include <iostream>
int main()
{
int sum = 0;
int number;
int i = 1;
std::cout << "Enter a final number: ";
std::cin >> number;
while (i <= number)
{
std::cout << "value of number:" << i << "\n";
sum += i;
++i;
}
std::cout << "\nThe sum of 1 to " << number << " is " << sum << "\n";
return 0;
}