While loop problems

Sep 2, 2014 at 9:43pm
I can't get this loop to return the values for i, ma, and mi. It does however return N. Why isn't this working?
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
  //Mark Cook
//Prog1b
//Aug 28, 2014
#include <cmath>
#include <iostream>
#include <limits>

using namespace std;

int main()
{
    int N = 0;
    int i = 0;
    int ma = 0;
    int mi = 10000;
    int k = 0;
    cout << "Please enter integer values:";
    while (cin >> k)
    {
        int k = 0;
        if (k > ma)
        {
            ma = k;
        }
        if (k < mi)
        {
            mi = k;
        }
        i = i + k;
        N++;
    }
    cout << "N = " << N << "\n";
    cout << "sum = " << i << "\n";
    cout << "max = " << ma << "\n";
    cout << "min = " << mi << "\n";
}

Here is my input/output:
1
2
3
4
5
6
7
8
9

Please enter integer values:1
2
3
4
N = 4
sum = 0
max = 0
min = 0
Sep 2, 2014 at 9:47pm
At line 20, you create a new local variable k within the scope of the while loop. This is a different variable to the one that holds the value the user inputted, that was declared at line 16. The new variable hides the older one.

At lines 23 and 27, you set the values of ma and mi to be the value of the second k - which you initialised to 0 at line 20.
Sep 2, 2014 at 9:52pm
Wow, thank you for showing me that. I should have seen that sooner. Thank you so much!
Sep 2, 2014 at 9:53pm
You're welcome! It's easy to miss things like that :)
Topic archived. No new replies allowed.