Hello,
Following is the algorithm that I'm trying to work out in C++:
step 1. Set the value of Sum to 0
step 2. Input the first number N
step 3. While N is not negative do
step 4. Add the value of N to Sum
step 5. Input the next data value N
step 6. End of the loop
step 7. Print out Sum
step 8. Stop
Here is the code I have so far (don't laugh, I'm new to C++)
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
int sum = 0;
int n;
while (n >= 0)
{
cout << "Enter a value for n: ";
cin >> n;
cout << (n + sum) << endl;
}
system ("pause");
return 0;
}
The program terminates if I enter a negative value, which is what I want. The problem is getting (n + sum) to be added to the new value of n.
Any help would be greatly appreciated!
Thank you
#include <iostream>
usingnamespace std;
int main()
{
int sum = 0;
int n;
while(1){
do
{
cout << "Enter a value for n: ";
cin >> n;
if (n >= 0)
{
sum=n+sum;
}
else
{break;}
}
cout<< sum;
system ("pause");
return 0;
}
Following the algorithm, and comparing it with your code,
You missed out this step 2. Input the first number N
That's a serious omission as at the first pass through the loop, n is not initialised and the behaviour is unpredictable.
Also, you don't do this: step 4. Add the value of N to Sum
note, this expression (n + sum) adds the two values together, but the result is not assigned to any variable, so it is lost. You should have something like sum = sum + n; or more concisely, sum += n;
As well as that, note that after the loop ends, you need to do this: step 7. Print out Sum
That looks better, but you still did not follow the instructions of the original algorithm:
1 2 3 4 5 6 7 8
step 1. Set the value of Sum to 0
step 2. Input the first number N
step 3. While N is not negative do
step 4. Add the value of N to Sum
step 5. Input the next data value N
step 6. End of the loop
step 7. Print out Sum
step 8. Stop
Your code instead does this:
1 2 3 4 5 6 7 8
step 1. Set the value of Sum to 0
step 2. Input the first number N
step 3. While N is not negative do
step 4. Add the value of N to Sum
step 4A. Print out Sum
step 5. Input the next data value N
step 6. End of the loop
step 8. Stop