Sum the first n numbers

Pages: 12
I need to write a program PPP2 Chapter 5 Exercise 8 for which I have to ask for an input n from the user and then get numbers into a vector for as long as the user hasn't pressed '|' (meaning that the number of numbers entered can be more than n). Then I have to sum the n numbers from the vector and print the result. I've tried doing what I could, but I'm trouble figuring out how to sum just the first n numbers.

Here's my code:
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of 
// numbers, stopping with '|'.  The program will then print the sum of the first
// n numbers.  The program print an error message if the user enters
// less than n numbers.  

#include "../../std_lib_facilities.h"

int get_n();

int main()
{
	cout << "Please enter the numbers of values you want to sum: ";
	int n = get_n();
	int number = 0;
	vector<int> numbers;
	bool stop = false;
	char terminate = '|';
	char input = ' ';
	int sum = 0;
	cout << "Please enter some integers (press '|' to stop): ";
	while (!stop)
	{
		cin >> number;
		cin.ignore();
		numbers.push_back(number);
		if (numbers.size() == n + 1)
		{
			for (unsigned i = 0; i < numbers.size(); ++i)
			{
				sum += numbers[i];
			}
		}
		cin.get(input);
		if (input == terminate)
		{
			stop = true;
			break;
		}
	}
	try
	{
		if (numbers.size() < n)
		{
			error("value of n is too high!");
		}
	}
	catch (const runtime_error &e)
	{
		cerr << "error: " << e.what() << '\n';
		do
		{
			cout << "Enter a value of n not less than " << numbers.size() << '\n';
			cin >> n;
			cin.ignore();
		} 
		while (n > numbers.size());
	}
	cout << "The sum of the first " << n << " values you entered is " << sum << '\n';
	keep_window_open();
}

int get_n()
{
	int n = 0;
	cin >> n;
	cin.ignore();
	return n;
}
Even though the cout say "enter more input or | to terminate:", if the user enter anything that is not a number, then the cin will be in a bad state and the while loop will end.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

int main()
{
	vector<int> nums;
	int n;
	cout << "enter input: ";
	while (cin >> n)
	{
		nums.push_back(n);
		cout << "enter more input or | to terminate: ";
	}
	cout << accumulate(nums.cbegin(), nums.cend(), 0) << endl;
	
	return 0;
}
Last edited on
Well, maybe you actually need to have that '|' check, in which case:

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
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
//** EXTREMELY RUDE CALCULATOR **//
int main()
{
	vector<int> nums;
	int n;
	cout << "enter more input or | to terminate : ";
	while (true)
	{
		//Exit condition
		if (cin.peek() == '|')
		{
			break;
		}

		//Read input
		(cin >> n).ignore();

		//Clear stream if invalid input is read
		if (cin.fail())
		{
			cin.clear();
			cin.ignore(numeric_limits<streamsize>::max(), '\n');
			cout << "enter valid input you moron: ";
			continue;
		}

		//Store valid numbers
		nums.push_back(n);
		cout << "enter more input or | to terminate: ";
	}
	cout << accumulate(nums.cbegin(), nums.cend(), 0) << endl;
	
	return 0;
}

Edit: reading again the thing on top of the page, I realize I missed the point of the question, sorry about that :P
Last edited on
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
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <vector>

using namespace std;

int main()
{
  cout << "Please enter the numbers of values you want to sum : ";
  size_t number_count = 0;
  cin >> number_count;
  vector<int> numbers;

  for (int num; cin >> num;)
  {
    numbers.push_back(num);
  }
  if (numbers.size() > number_count)
  {
    cout << "You entered too many numbers.";
    system("pause");
    return -1;
  }
  else if (numbers.size() < number_count)
  {
    cout << "You entered not enough numbers.";
    system("pause");
    return -1;
  }
  int sum = 0;
  for (int n : numbers)
  {
    sum += n;
  }

  cout << "The sum is: " << sum << "\n\n";

  system("pause");
  return EXIT_SUCCESS;
}
Could you please help me out with the sums first? I'll worry about input termination after that. Thanks.
Could you please help me out with the sums first?

That's the easiest part:
1
2
3
4
5
int sum = 0;
  for (int n : numbers)
  {
    sum += n;
  }


I'll worry about input termination after that.
ask user for a number n and then have them enter a sequence of
// numbers, stopping with '|'.

There is nothing to worry about.
1
2
3
4
for (int num; cin >> num;)
  {
    numbers.push_back(num);
  }


He actually uses this kind of code in his examples.
I know, but if I did it like that here, input would be terminated whenever cin goes into a bad state, which would happen whenever anything that isn't a number is entered. It wouldn't just be limited to '|'.

That would sum all of the numbers in the vector. I want it to only sum the first n numbers.

A sample run of the program is given like this in the book:

“Please enter the number of values you want to sum:”
3
“Please enter some integers (press ' | ' to stop):”
12 23 13 24 15 |
“The sum of the first 3 numbers ( 12 23 13 ) is 48 .”


Right now, with that same input, the result I get from my program is 22.
Last edited on
Ok, what about this?! (hope I didn't have any bugs, didn't tested it :\)

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <vector>
#include <numeric>
using namespace std;

bool RestoreStream(istream& cin)
{
	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	cout << "clearing stream" << endl;
	return true;
}

int main()
{
	int valueToSum{};
	//////Ask number of inputs//////
	do
	{
		cout << "Please enter the number of values you want to sum:";
               //if the user mess up with the input and the cin fail, then the while
               //evaluate to true and && evaluate the right side restoring the stream
               //otherwise if input is good, we leave this loop
	} while (!(cin >> valueToSum).ignore() && RestoreStream(cin));
	////Get numbers/////////////////
	vector<int> nums;
	int temp{};
	if (valueToSum > 0)
	{

		cout << "Please enter some integers(press ' | ' to stop) :";
		while (!(cin.peek() == '|'))
		{
			(cin >> temp).ignore();
			if (cin.fail())
			{
				RestoreStream(cin);
				continue;
			}
			nums.push_back(temp);
		}
	}
	///Sum if enough numbers where provided////
	if (nums.size() >= valueToSum)
	{
			cout << "The sum of the first " << valueToSum << 
					" numbers is "<< accumulate(nums.cbegin(), (nums.cbegin() + valueToSum), 0) << endl;
	}
	else
	{
		cout << "not enough inputs." << endl;
	}

	return 0;
}


Edit: ok, I've removed 2 bugs and tested, it works and give the correct resoult.
Last edited on
How is vector::begin() different from vector::cbegin()? And what's the <numeric> header for? Could you please explain? Thanks in advance.
Last edited on
@DragonOsman
cbegin() returns a const interator while begin() return a non const, be using cbegin when we do not intend to modify the value is just good practice.
The numeric header is needed to call accumulate(), which will do the running sum from the vector begin() up to but not including the iterator begin()+N.
So if you had 3 as number of input as in the example, accumulate will return you the sum from vector.begin() up to but not including vector.begin()+N which means the sum of vector[0] + vector[1] + vector[2]
Last edited on
Thanks for the info. Now, please help me out in fixing the problem I have now with this:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of 
// numbers, stopping with '|'.  The program will then print the sum of the first
// n numbers.  The program print an error message if the user enters
// less than n numbers.  

#include "../../std_lib_facilities.h"
#include <numeric>

int get_n();
bool clear_stream(istream& cin);

int main()
{
	cout << "Please enter the numbers of values you want to sum: ";
	int n = get_n();
	int number = 0;
	vector<int> numbers;
	if (n > 0)
	{
		cout << "Please enter some integers (press '|' to stop): ";
		while (!(cin.peek() != '|'))
		{
			cin >> number;
			cin.ignore();
			numbers.push_back(number);
			if (cin.fail())
			{
				clear_stream(cin);
				continue;
			}
		}
		try
		{
			if (numbers.size() < n)
			{
				error("too few numbers entered!");
			}
		}
		catch (const runtime_error &e)
		{
			cerr << "error: " << e.what() << '\n';
			do
			{
				cout << "Please enter a value for n not less than the number values entered: ";
				cin >> n;
				cin.ignore();
			} 
			while (n < numbers.size());
		}
		int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);
		cout << "The sum of the first " << n << " numbers is " << sum << '\n';
	}
	keep_window_open();
}

int get_n()
{
	int n = 0;
	cin >> n;
	cin.ignore();
	return n;
}

bool clear_stream(istream& cin)
{
	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	return true;
}


I get a Debug Assertion Failure error after I enter my numbers for the vector, and the error message saying that I entered too few numbers is printed to the console window.
Well, you are using your variable "n" both to store the number of input we want to sum in the end (3, according to the example from the book), and to store the following several inputs from the user in
1
2
cout << "Please enter a value for n not less than the number values entered: ";
			cin >> n;


So if the last user input is 55, in the call to

int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);

you are trying to accumulate up to vector[54] which is madness xD

And on top of it, this
while (!(cin.peek() != '|'))

if you enter a number, then (cin.peek() != '|') will evaluate true, the !() will reverse it to false, so you actually never enter the while and your number vector is always empty.
Last edited on
Sorry I didn' read the exercise carefully enough.
To sum only some of the numbers you need to use a different loop.
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
28
29
30
31
32
33
#include <iostream>
#include <vector>

using namespace std;

int main()
{
  cout << "Please enter the numbers of values you want to sum : ";
  size_t number_count = 0;
  cin >> number_count;
  vector<int> numbers;

  for (int num; cin >> num;)
  {
    numbers.push_back(num);
  }
  if (numbers.size() < number_count)
  {
    cout << "You entered not enough numbers.";
    system("pause");
    return -1;
  }
  int sum = 0;
  for (size_t i = 0; i < number_count; ++i)
  {
    sum += numbers[i];
  }

  cout << "The sum is: " << sum << "\n\n";

  system("pause");
  return EXIT_SUCCESS;
}


OUTPUT:
Please enter the numbers of values you want to sum : 3
1 2 3 4 5 |
The sum is: 6

Press any key to continue . . .
@Marcus: Yeah, I guess I shouldn't have put != in there. It should've been == because of the ! outside the parentheses.

As for using n to store an input again, that's for handling a case where the user inputs numbers greater than the value of n. If the exception is caught, I'm trying to handle the error by having the user enter a "valid" value for n: a value that's less than the number of items in the vector.

Edit: But yeah, I noticed that the sign is wrong in the do-while loop's condition. I changed that. It works fine now.

Edit 2: I need to modify the program following these two guidelines now:
9. Modify the program from exercise 8 to write out an error if the result
cannot be represented as an int .
10. Modify the program from exercise 8 to use double instead of int . Also,
make a vector of double s containing the N–1 differences between adjacent values and write out that vector of differences.


I don't understand what it means by the N-1 differences between adjacent values, though. Could someone please explain?
Last edited on
9   7   1   10  3

Given the above numbers, the vector of N-1 differences (where N = 5), would be
2   6   -9  7

Basically, take the ith and i+1th number and subtract them.
Alright, thanks for the reply. How about the part where I have to detect if the sum of a given N is larger than what can be represented in an int?

This my code right now (for reference):

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of 
// numbers, stopping with '|'.  The program will then print the sum of the first
// n numbers.  The program print an error message if the user enters
// less than n numbers.  

#include "../../std_lib_facilities.h"
#include <numeric>

int get_n();
bool clear_stream(istream& cin);

int main()
{
	cout << "Please enter the numbers of values you want to sum: ";
	int n = get_n();
	int number = 0;
	vector<int> numbers;
	if (n > 0)
	{
		cout << "Please enter some integers (press '|' to stop): ";
		while (!(cin.peek() == '|'))
		{
			cin >> number;
			cin.ignore();
			numbers.push_back(number);
			if (cin.fail())
			{
				clear_stream(cin);
				continue;
			}
		}
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
		try
		{
			if (numbers.size() < n)
			{
				error("too few numbers entered!");
			}
		}
		catch (const runtime_error &e)
		{
			cerr << "error: " << e.what() << '\n';
			do
			{
				cout << "Please enter a value for n not less than the number values entered: ";
				cin >> n;
				cin.ignore();
			} 
			while (n > numbers.size());
		}
		int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);
		cout << "The sum of the first " << n << " numbers is " << sum << '\n';
		try
		{
			if (sum > numeric_limits<int>::max())
			{
				error("The sum is too high");
			}
		}
		catch (const runtime_error &e)
		{
			cerr << "error: " << e.what() << '\n';
			keep_window_open();
			return 1;
		}
	}
	keep_window_open();
}

int get_n()
{
	int n = 0;
	cin >> n;
	cin.ignore();
	return n;
}

bool clear_stream(istream& cin)
{
	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	return true;
}
Last edited on
To detect if the input is a double, how about this?
and ofc, you also need to check against INT_MIN and INT_MAX -> http://www.cplusplus.com/reference/climits/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

//write out an error if the result cannot be represented as an int .

int main()
{
	double d;
	cin >> d;

	if (d - int(d))
	{
                cout << "error" << endl;
		//if we are here, then the double minus the truncated int still had
		//some remainder, so it cannot be represented as an int without
		//losing precision.
	}
	return 0;
}
Last edited on
I think it's asking to print an error message if the sum is too large to fit in an int (right?).

And in case you missed it, I'll post my code in its current state again here:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// chapter5ex8.cpp : Defines the entry point for the console application.
// Osman Zakir
// 1 / 1 / 2017
// Bjarne Stroustrup: Programming: Principles and Practice Using C++ 2nd Edition
// Chapter 5 Exerice 8
// Program to ask user for a number n and then have them enter a sequence of 
// numbers, stopping with '|'.  The program will then print the sum of the first
// n numbers.  The program print an error message if the user enters
// less than n numbers.  

#include "../../std_lib_facilities.h"
#include <numeric>

int get_n();
bool clear_stream(istream& cin);

int main()
{
	cout << "Please enter the numbers of values you want to sum: ";
	int n = get_n();
	int number = 0;
	vector<int> numbers;
	if (n > 0)
	{
		cout << "Please enter some integers (press '|' to stop): ";
		while (!(cin.peek() == '|'))
		{
			cin >> number;
			cin.ignore();
			numbers.push_back(number);
			if (cin.fail())
			{
				clear_stream(cin);
				continue;
			}
		}
		cin.clear();
		cin.ignore(numeric_limits<streamsize>::max(), '\n');
		try
		{
			if (numbers.size() < n)
			{
				error("too few numbers entered!");
			}
		}
		catch (const runtime_error &e)
		{
			cerr << "error: " << e.what() << '\n';
			do
			{
				cout << "Please enter a value for n not less than the number values entered: ";
				cin >> n;
				cin.ignore();
			} 
			while (n > numbers.size());
		}
		int sum = accumulate(numbers.cbegin(), (numbers.cbegin() + n), 0);
		cout << "The sum of the first " << n << " numbers is " << sum << '\n';
		try
		{
			if (sum > numeric_limits<int>::max())
			{
				error("The sum is too high");
			}
		}
		catch (const runtime_error &e)
		{
			cerr << "error: " << e.what() << '\n';
			keep_window_open();
			return 1;
		}
	}
	keep_window_open();
}

int get_n()
{
	int n = 0;
	cin >> n;
	cin.ignore();
	return n;
}

bool clear_stream(istream& cin)
{
	cin.clear();
	cin.ignore(numeric_limits<streamsize>::max(), '\n');
	return true;
}
Then you just need the climits header ->http://www.cplusplus.com/reference/climits/
Which btw, I think it get included indirectly by <iostream> so the code should work without any extra #include

1
2
3
4
5
6
7

long long num;
cin >> num;
if(num < INT_MIN || num > INT_MAX )
{
     //crash the users computer
}
Last edited on
std::numeric_limits<int>::max() wouldn't work? I'm trying to use that currently.

And why would you want to crash the user's computer? Just print an error message. The book also just says to print an error message of the sum of the N numbers the user asks for is too large to fit in an int.

Edit: For the N-1 differences, what am I doing wrong here?

1
2
3
4
5
6
7
for (unsigned i = 0; i < numbers.size(); ++i)
{
	difference = numbers[i] - numbers[i - 1];
	differences.push_back(difference);
	cout << difference << ' ';
}
cout << '\n';


I'm getting an exception thrown. I'm guessing it's because std_lib_facilities.h adds range-checking in the vector's operator[], but I'm not sure where it's being triggered other than that the fact that it's somewhere in the code I've posted here.
Last edited on
Pages: 12