Alternating sum

Okay so here is what I am trying to solve
.
Write a function that computes the alternating sum of all elements in an array. For example, if alternating_sum is called with an array containing
1 4 9 16 9 7 4 9 11
then it computes
1 – 4 + 9 – 16 + 9 – 7 + 4 – 9 + 11 = –2


It seems to get stuck when I try to quit the inputs. If understands then please let me know.

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
#include <iostream>
using namespace std;

int read_inputs(double inputs[], int capacity)
{
   int current_size = 0;
   cout << "Please enter some values, Q to quit: ";
   bool more = true;
   double total = 0;
   while (true)
   {
	  double input;
	  cin >> input;
	  if (cin.fail())
	  {
		  more = false;
	  }
      else if (current_size < capacity)
	  {
	     inputs[current_size] = input;

		    if (current_size % 2 == 0)
		    {
			   total = total + inputs[current_size];
		    }
		    else if (current_size & 2 != 0)
		    {
			   total = total - inputs[current_size];
		    }
			current_size++;
	  }
   }
   return total;
}

int main()
{
   const int capacity = 1000;
   double values[capacity];
   int alt_sum = read_inputs(values, capacity);
   cout << alt_sum;
   return 0;
}
Wow just solved my own problem.....while (true) should have been while (more).......
Last edited on
Topic archived. No new replies allowed.