Hi! I'm a newbie in C++ ('just started a couple of days ago). I'm trying to add different set of numbers and print their sum. Then I put an option whether to perform addition again or not. I got the program working by using DO-loop, but my sum just kept adding up. Here's a "snapshot" of my program:
1 How many numbers would you like to add? <say you entered 2>
2 Enter the numbers: <say you entered 1, 1>
3 The sum is: 2
4 Would you like to start addition again? y or n: <say you entered y>
In lines 1 & 2, say you entered the same values of 2 then 1,1 respectively. Now I get a sum of 4 instead of just 2. That's my problem. I appreciate any help out there. Good day!
-------------------------------------------------------------------------------
Here's my code:
#include <iostream>
#include <new>
using namespace std;
char y;
int i,x,sum=0;
int main()
{
do {
cout << "How many numbers are you going to add?: ";
cin >> x;
cout << "Enter the numbers to add:\n";
int * p;
p=new (nothrow) int[x];
for(i=0;i<x;i++) {
cin >> p[i];
sum+=p[i];
}
cout << "The sum is " << sum;
delete [] p;
cout << "\n";
cout << "Would you like to add again?(enter y for yes & n for no): ";
cin >> y;
cout << "\n";
you might want to initialize sum to zero inside the loop, instead of a out side of the main function.
This is so each iteration of the loop you start with a clean sum for each pass.
#include<iostream>
// don't need <new> for this program.
int main()
{
char y;
int sum;
int i; // it is a good idea to avoid single character variable names to make code more readable
int x;
do
{
// init sum here for each pass of the code...
sum = 0;
y = (char)0;
cout << "How many Numbers are you going to add?" << endl;
cin >> x;
// ... rest of your thoughts which were correct.
} while (y!='n')
return 0;
}