Help with a loop

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.










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
27
#include <iostream>
using namespace 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.

closed account (48T7M4Gy)
For a start,
line 19: missing ;
line 24: "\n" not the word processor quotes you've used. Use endl instead.

Also you only need to ask for one number - the end limit and let the program generate all the numbers up to that limit, summing as you go.

So,
start with n = 1;

input limit value;

do{
add n to total
increment total
}check( n < limit)

display total

Last edited on
closed account (E0p9LyTq)
You can do it with a for loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;
}


or with a while loop;

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 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;
}
closed account (48T7M4Gy)
You should get $20 for that.
Topic archived. No new replies allowed.