C++ Core dump error

Hello,

I am trying to find max and average from a 1D array. No problemo. HOWEVER I get a core dump error and all the numbers are all messed up when I run my code! I'm not sure what is wrong.
There are 8 Numbers in the .txt file. I did set the size to 8 and tried 7. I'm not sure what number that is supposed to be.

Any help will be much 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
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
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;

float calcAvgArray(float numArray[], int A_SIZE);
float calcMaxArray(float numArray[], int A_SIZE);

const int  A_SIZE = 7;
int main()
{

int i = 0;
float numArray[A_SIZE];
float average;
float max;

cout << fixed << showpoint << setprecision(2)<< endl;

ifstream inFile;
inFile.open("programming1_1.txt");
if(!inFile)
{
 cout << "Error opening file" << endl;
 return 1;
}

while(inFile) //Reading in Array
{
 i++;
 inFile >> numArray[i];
 cout << numArray[i] <<endl;
}

average = calcAvgArray(numArray, A_SIZE);
max = calcMaxArray(numArray, A_SIZE);


cout << "The average of the numbers is: " << average << endl;
cout << "The maximum of the numbers is: " << max << endl;

inFile.close();
return 0;
}



float calcAvgArray(float numArray[], int  A_SIZE)
{
int i =0;
int temp =0;
float average;

for(i = 0; i < A_SIZE; i++)
{
 numArray[i] = temp;
 average = average + temp;
}
average = average/A_SIZE;
return average;
}

float calcMaxArray(float numArray[], int A_SIZE)
{
int i =0; 
float temp1 = 0, temp2 =0;
float max;


while(i < A_SIZE)
{
 numArray[i] = temp1;

	if(temp1 > temp2)  // if temp1 is greater than temp2 then it becomes the max
	{
 	 max = temp1;
	}
 i++;
}

return max;
}
Hi !
Always initialize variables...'max' and 'average' are not.

Be careful with attempting direct conversion assignments like on line 56. The compiler should give a warning about that.

Also, lines 56 and 72 are backwards. You want to assign an element to temp, not temp to the element in the array.
GOT IT!! Thank you!
Last edited on
A_SIZE should be set to 8.
Does L 32 print out all the numbers from *txt correctly?
In your last function temp1 will always be > temp2 (initialized to 0). How does that help to get max?
Think a for loop would be more straight forward here.

1
2
3
4
5
6
7
8
for(i=0;i<A_SIZE;i++)
 
{max=numArray[i] ;//max assigned 1st number (when i=0)
    
      if(numArray[i]>max) max=numArray[i];
 
}
     return max;

hope this helps.
Topic archived. No new replies allowed.