First value skipped when trying to sum in for loop

Mar 10, 2017 at 3:20pm
The first negative value that is entered is not counted either in the sum or the count. It just happens for the negative values and not positive or zero.
Help is appreciated.


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
  #include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;
int main()
{
	int integer, freq_pos = 0, freq_neg = 0, freq_zero = 0, sum_pos = 0, sum_neg = 0, total = 0, min = 0, max, x, y;
	

	for (y = 0; x <= 7; x++)
	{
	cout << "Please enter an integer" << endl;
	cin >> integer;
	
	if (integer < min)
	{
		min = integer;
	}
	else if(integer == 0)
	{
		freq_zero = freq_zero + 1;
		sum_pos = sum_pos + integer;
	}
	else if (integer < 0)
		{
			freq_neg = freq_neg + 1;
			sum_neg = sum_neg + integer;
		}
	
	else if (integer > 0)
		{
			freq_pos = freq_pos + 1;
			sum_pos = sum_pos + integer;
	    } 
	}

    cout << "There are " << freq_pos << " positive numbers, " << freq_neg << " negative numbers and " << freq_zero << " zeroes" << endl;
	cout << "The lowest number is " << min << endl;
	cout << "The sum of all positive values is " << sum_pos << endl;
	cout << "The sum of all negative values is " << sum_neg << endl;
   return 0;
}
   
  
 

	
	
Mar 10, 2017 at 3:53pm
Hello @coradelaide

When you use
1
2
3
4
if
...
else if
...

you can't process things in both blocks (think about the logic in English). So if the block setting
min = integer;
runs then integer won't be considered in any of the following 'else if' blocks.

I haven't tried it, but I suspect that simply changing 'else if' to just 'if' in line 20 will work.

Could you possibly make your indentation consistent (or are you using a mixture of tabs and spaces)?


Mar 10, 2017 at 4:53pm
Have a closer look at for (y = 0; x <= 7; x++)
Also have a look at your compiler warnings, might need to enable all:
warning C4700: uninitialized local variable 'x' used
Topic archived. No new replies allowed.