// progtam to input some integer values and get their sum.
#include <iostream>
using namespace std;
int main() {
int a[1000]; // Declare an array of 1000 ints
int n = 0; // Number of values in a.
int sum =0;
cout << " Input some positive values (for exit input a character) : " << endl;
while (n!='\n'{
sum = sum + a[n];
n++;
}
cout << "The sum of " << n << " numbers is : " << sum << endl;
thanks for the replies. but my code is not working. i get n as 10 always and sum - some garbage value. i want to enter some integer values and after hitting return i want to see the result to show no of entries - n and sum.
#include <iostream>
usingnamespace std;
int main()
{
int a[1000]; // Declare an array of 1000 ints
int n = 0; // Number of values in a.
while (n != '\n')
{
// Modify by HawkOfWinter 2009-09-12 begin
cin >> a[n];
n++;
// Modify by HawkOfWinter 2009-09-12 end
}
int sum = 0; // Start the total sum at 0.
for (int i=0; i<n; i++)
{
sum = sum + a[i]; // Add the next element to the total
}
cout << n << " , " << sum << endl;
return 0;
}
An empty line (a newline) is not a numerical value, which is what cin >> a[n] expects
I would try a different exit condition, like when a 0 introduced...
#include <iostream>
#include <string>
#include <stdlib.h>
usingnamespace std;
int main() {
int a[1000]; // Declare an array of 1000 ints
int n = 0; // Number of values in a.
std::string inputLine;
bool finished = false;
int i;
while (!finished && n <= 1000) {
getline(cin, inputLine);
if (inputLine.length() == 0 || (*inputLine.c_str()) == '\n') {
// Newline was pressed, so check if the current line is empty
finished = true;
} else {
//transform the provided input into an integer
i = atoi(inputLine.c_str());
a[n++] = i;
//std::cout << "Input was: " << inputLine << " - Transformed to: " << i << std::endl;
//clearing up the input line
inputLine = std::string();
i = 0;
}
}
int sum = 0; // Start the total sum at 0.
for (int i = 0; i < n; i++) {
sum = sum + a[i]; // Add the next element to the total
}
cout << "Number of inputs: "<< n << " - Summing up to " << sum << endl;
return 0;
}
Biggest difference is the use of getline() instead of the ">>" operator. And the use of atoi for transforming the input into a numeric value.
#include <iostream>
#include <string>
#include <sstream>
usingnamespace std;
int main()
{
string input;
stringstream strStream;
int a[1000]; // Declare an array of 1000 ints
int n = 0; // Number of values in a.
getline(cin,input);
strStream.str(input);
while (strStream >> a[n]) //hopefully no user will type more than 1000 numbers
{
n++;
}
int sum = 0; // Start the total sum at 0.
for (int i=0; i<n; i++)
{
sum += a[i]; // Add the next element to the total
}
cout << n << " , " << sum << endl;
}
thank u friends for ur positive feed backs. i am marking this topic as solved. but i want to have some modifications to my program. can any one help. pl see the new topic - modifications required