Unintialized local variable? what

It says the variable in my class member FindTotal is unitialized local variable


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
#include <iostream>
#include <ctime>

using namespace std;

class FIVE
{
private: int x[7];
public:
	FIVE()
	{
		time_t p;
		time(&p);
		cout << ctime(&p) << endl;
	}
	void Read()
	{
		cout << "Enter 7 integer data: " << endl;
		for (int i = 0; i < 7; i++)
		{
			cin >> x[i];
		}
	}
	void Display()
	{
		cout << "All data: ";
		for (int i = 0; i < 7; i++)
		{
			cout << x[i] << " ";
		}
		cout << endl;
	}
	void FindMaxMin(int &mx, int &mn)
	{
		for (int i = 0; i < 7; i++)
		{
			if (x[i] > mx)
			{
				mx = x[i];
			}
			if (x[i] < mn)
			{
				mn = x[i];
			}
		}
	}
	int FindTotal()
	{
		int tots;
		for (int i = 0; i < 7; i++)
		{
			tots += x[i];
		}
		return tots;
	}
	~FIVE() //deconstructor 
	{

	}
};

int main()
{
	FIVE p;

	int max, min, total;
	max = 0;
	min = 0;



	p.Read(); //let user enter data
	p.Display(); //show data 
	p.FindMaxMin(max, min); //find the max and min

	total = p.FindTotal();

	cout << "The Maximum is: " << max << ", the minimum is: " << min << endl;
	cout << "The Total is: " << total << endl;


	system("PAUSE");
	return 0;
	
}
A local variable has a random value when declared.

So you can't do (tots += x[i];) unless you first initialise it, zero I presume in your case.
Initialise tots to zero before using it:

1
2
3
4
5
6
7
8
9
	int FindTotal()
	{
		int tots = 0;
		for (int i = 0; i < 7; i++)
		{
			tots += x[i];
		}
		return tots;
	}
Topic archived. No new replies allowed.