Why is this an error?

I've been writing this Work-Out Program today and I'm still unfamiliar with Array's but I keep receiving an error for both of these functions. I'm trying to just do one little thing at a time. Can someone assist in understanding why this error is taking place?

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
 void readArray(int ary[], int n)
{
   int cnt = 0;
    while(n!=0)
    {
        ary[cnt]=n;
        cnt++;
        inf >> n;
    }
}

void printArray(int ary[], int n)
{
    int cnt=0;
    while(n<cnt)
    {
        out << ary[n] << " ";
        if((n+1)%8==0)
        {
            out << endl;
        }
        n++;//MAY HAVE TO MOVE THIS
    }
}
You are to write a program that will manipulate an array. Your program should handle up to 50 integer numbers
For each print out produced below, label the results. Also print your output in the order listed below.

_____________________________

Read in the values into the array. The last value is a 0 and is NOT one of the values to be used in any calculation below. The input is found in on Blackboard for “numbers.dat” file. Send your output to a file and print it out to hand in.

Print out all the values in the array with no more than 8 numbers per output line.

Print out the average of the numbers.

Print out the total number of values that are larger than the average.

Print out the total number of values that are smaller than the average.

For every odd location in the array, subtract it from the previous even location and store results in the even location. Print out all values in the array (a previous requirement)

Print out the average for the new array.

Convert every negative number to positive number. Print out the array.

Swap the first number in the array with the last number in the array. Print out the array.

Print out the average for the new array.


INFILE DATA:
24
43
63
-72
73
72
9
92
-8
83
-36
73
5
38
56
17
93
26
19
62
72
8
4
38
27
22
27
64
7
44
26
-36
62
78
-67
34
73
93
8
-3
-2
2
27
1
11
12
-73
83
0
Lines 17 & 20....out? did you mean std::cout?

What exactly are the errors you are getting? Post the errors, don't say "I'm getting errors."

Don't post snippets of code we can't compile. You need to provide enough of a framework to allow us to duplicate your errors.

Help us help you. Don't make it hard to understand what you are doing. We do not have crystal balls.
Last edited on
In addition, in printArray, if n is the size of the array, ary[n] is going out of bounds.
Did you mean to loop on (cnt < n) and do ary[cnt] while incrementing cnt?
Last edited on
@Furry Guy,

OP has the habit of defining the file streams in the global scope of the file. So for lines 17 and 20 "out" is the "ofstream" that you do not see defined anywhere.

Hello CodeNovice01,
One can only guess, but I would guess that in "main" you defined "n" as int n;. This only reserves space for the variable, but it tries to use whatever is stored at that address as an "int". On my computer this garbage value is usually "-858993460". Then you most likely call the "readArray" function passing the garbage value to the function.

Looking at your function:
1
2
3
4
5
6
7
8
9
10
11
 void readArray(int ary[], int n)
{
    int cnt = 0;

    while(n!=0)
    {
        ary[cnt]=n;
        cnt++;
        inf >> n;
    }
}

Line 1 defines the function and its parameters. The first parameter will degrade to a pointer, although you will never notice any difference in its use, and parameter two "n" will have the value of "-858993460".

So when you reacch the while loop the first time it would actually look likewhile (-858993460 != 0) which evaluates to true, so you enter the while loop storing "-858993460" in element (0) zero of the array. Which by the time you are finished reading the file the array contains one more element than it should. "cnt" is one larger than it should be and when the function ends so does "cnt" and its value never to be known again unless you wanted to take the easy way out and defined "cnt" as a global variable.

One way to fix this problem is to do the first read of the input file before the while loop then everything will work out. Not the best solution, but it does make it work.

I see no reason to waste time on the "print" function until you get the "read" function working properly and with out a complete program that can compile and run it is only a guess at what you have done so far.

Hope that helps,

Andy

Edit: typo.
Last edited on
OP has the habit of defining the file streams in the global scope of the file.

Not including enough code to make the snippet compilable is a very bad habit. Don't make excuses for poor practices.
Ok, apologies everyone for the lack of information. I assumed the OP would be enough information. Novice mistake, still learning. So I have the code written and for the most part it is working correctly, but there's just one hiccup. My calculations are wrong. I think the error is within the larger than average function.

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

//const int for the possible array size
const int MAXIMUM = 50;

//Function Prototypes
void read_array(int, int);
void print_array(int, int);
double average_array(int, double);
int larger_than_average(int, double, int);
int smaller_than_average(int, double);
int odd_from_even(int, int);
void neg_to_pos(int, int);
void swap_first_with_last(int, int);

//I/O File in and out.
ifstream inf("workout.in");
ofstream out("workout.out");

//Function Reads the InFile
void read_array(int ary[], int& i)
{
   int f;
   i=0;
    while(inf >> f && i < MAXIMUM)
    {
        ary[i] = f;
        i++;
    }
}

//Function Prints the data to the out file.
void print_array(int ary[], int n)
{
    out << setprecision(2) << fixed;

    for(int j=0; j<n; j++)
    {
        out << ary[j] << ", ";
        if((j+1) % 8 == 0)
        {
            out << endl;
        }
    }
}

//Function to find the average
double average_array(int ary[], double k)
{
    double sum = 0;
    for(int i=0; i<k; i++)
    {
        sum += ary[i];
    }
    out << "\nThe AVERAGE is: " << sum/k << endl;
}

//Function that calculates the amount of numbers larger than the average.
int larger_than_average(int ary[], double n)
{
    int cnt = 0;
    for(int u=0; u<n; u++)
    {
        if(ary[u]>n)
        {
            cnt++;
        }
    }
 out << "\nThe NUMBER of VALUES LARGER than AVERAGE: "
     << cnt;
}

//Function that calculates the amount of numbers smaller than the average.
int smaller_than_average(int ary[], double n)


{
    int cnt = 0;
    for(int m=0; m<n; m++)
    {
        if(ary[m]<n)
        {
            cnt++;
        }
    }
 out << "\nThe NUMBER of VALUES SMALLER than AVERAGE: "
     << cnt << endl;
 }

//Function that takes every odd and subtracts it from previous even and stores in the even location.
int odd_from_even(int ary[], int i)
{
    out << "\nODD from EVEN:\n";
    for(int j=1; j<i; j+=2)
    {
        ary[j-1] -= ary[j];
    }
    print_array(ary,i);
}

//Function that converts negative integers to positive.
void neg_to_pos(int ary[], int k)
{
    out << "\nSign CHANGE:\n";
    for(int i=0; i<k; i++)
    {
        ary[i] *= -1;
    }
    print_array(ary,k);
}

//Function that swaps the first integer digit with the last.
void swap_first_with_last(int ary[], int x)
{
    out << "\nSwapping FIRST with LAST:\n";
    int temp = ary[0];
    ary[0] = ary[x - 1];
    ary[x - 1] = temp;
    print_array(ary, x);
}

//Function main, which performs all the work
int main()
{
    if(!inf)
        cout<<"error opening file!";
    //Variables
    int MyArray[MAXIMUM], counter, small, large, change;
    double average, average2, average3;

    out << "\t\tWork-Out Program\n"
        << "\nFirst Array: \n";
    //Function calls
    read_array(MyArray, counter);
    print_array(MyArray, counter);
    average = average_array(MyArray, counter);
    large = larger_than_average(MyArray, counter);
    small = smaller_than_average(MyArray, counter);
    out<<"\nSecond Array:";
    change = odd_from_even(MyArray, counter);
    average2 = average_array(MyArray, counter);
    out<<"\nThird Array:";
    neg_to_pos(MyArray, counter);
    out<<"\n\nFourth Array:";
    swap_first_with_last(MyArray, counter);
    average3 = average_array(MyArray, counter);

    //Flush buffer and close files.
    out.close();
    inf.close();
    return 0;
}


OUTPUT:
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
		Work-Out Program

First Array: 
24, 43, 63, -72, 73, 72, 9, 92, 
-8, 83, -36, 73, 5, 38, 56, 17, 
93, 26, 19, 62, 72, 8, 4, 38, 
27, 22, 27, 64, 7, 44, 26, -36, 
62, 78, -67, 34, 73, 93, 8, -3, 
-2, 2, 27, 1, 11, 12, -73, 83, 
0, 
The AVERAGE is: 28.04

The NUMBER of VALUES LARGER than AVERAGE: 16
The NUMBER of VALUES SMALLER than AVERAGE: 33

Second Array:
ODD from EVEN:
-19, 43, 135, -72, 1, 72, -83, 92, 
-91, 83, -109, 73, -33, 38, 39, 17, 
67, 26, -43, 62, 64, 8, -34, 38, 
5, 22, -37, 64, -37, 44, 62, -36, 
-16, 78, -101, 34, -20, 93, 11, -3, 
-4, 2, 26, 1, -1, 12, -156, 83, 
0, 
The AVERAGE is: 10.20

Third Array:
Sign CHANGE:
19, -43, -135, 72, -1, -72, 83, -92, 
91, -83, 109, -73, 33, -38, -39, -17, 
-67, -26, 43, -62, -64, -8, 34, -38, 
-5, -22, 37, -64, 37, -44, -62, 36, 
16, -78, 101, -34, 20, -93, -11, 3, 
4, -2, -26, -1, 1, -12, 156, -83, 
0, 

Fourth Array:
Swapping FIRST with LAST:
0, -43, -135, 72, -1, -72, 83, -92, 
91, -83, 109, -73, 33, -38, -39, -17, 
-67, -26, 43, -62, -64, -8, 34, -38, 
-5, -22, 37, -64, 37, -44, -62, 36, 
16, -78, 101, -34, 20, -93, -11, 3, 
4, -2, -26, -1, 1, -12, 156, -83, 
19, 
The AVERAGE is: -10.20


Can someone help me understand the Swap first with last function, how it works?
Last edited on
Hello CodeNovice01,

I loaded your code into my IDE and when I tried to compile it I found that it was full of errors. Did you even try to compile the code and fix the errors before you posted it?

When I did finally get it to run I found the first problem is with the "read_array" function. Your instructions say:
Read in the values into the array. The last value is a 0 and is NOT one of the values to be used in any calculation below.
But your function not only reads that value of (0) zero it also puts that value into the array, adds one extra number to "counter" and trows off the rest of the program. I changed the function to:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void read_array(int ary[], int& counter)
{
	int f;

	counter = 0;  // ,--- If you initialize the variable in "main" you will not need this line.

	while (inf >> f && counter < MAXIMUM)
	{
		if (f == 0)	break;

		ary[counter] = f;

		counter++;
	}
}

Your original line of: void read_array(int ary[], int& i). It is legal to rename you variables if you choose, but most times there is not much need to do so. Calling "int& i" "int& counter" works just fine and is much easier to follow. Whether you define the variable as a parameter of the function or inside the {}s of the function it becomes a local variable to the function and there is no conflict with what is defined in "main".

Since (0) zero is not to be a part of the array I added the if statement in the while loop to know when to stop. Otherwise the while condition and the rest of the while loop is OK. Now it reads 48 numbers and "counter" has a value of 48 as it should.

In the function void print_array(int ary[], int n). Again changing the variable name to "n" is acceptable, but using tha name "counter" makes the function easier to read. The line out << setprecision(2) << fixed;, but you may find that this works better std::cout << std::fixed << std::showpoint << std::setprecision(2);. This line only needs done once and is best put in "main". This will stay in effect until it is changed. The other reason it should not be in the "print" function is that the array you are print is "int"s, so "setprecision" has no effect on "int"s. It only works on "double"s.

For "average_array" function two things. First a function should do only one thing. you have it doing two. the line out << "\nThe AVERAGE is: " << sum / counter << endl; should be in "main" not in the function. Second: you have used the variable names "i", "n" and now "k" to represent "counter". This is very confusing. The rest of the function is OK except you are returning a "double" and later this really does not make much difference.

for the function "larger_than_average" there are several problems. Now you are back to "n" to represent "counter" and you have changed it to a "double" which has no use. To adjust the function to something that makes more sense it would look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int larger_than_average(int ary[], int counter)
{
	int cnt = 0;

	for (int u = 0; u < counter; u++)
	{
		if (ary[u] > counter)
		{
			cnt++;
		}
	}

	out << "\nThe NUMBER of VALUES LARGER than AVERAGE: "  // <--- Should be in "main".
		<< cnt;
}

The for loop is fine, but do you see a problem with the if statement? This will produce an incorrect value for "cnt".

I have not fixed "smaller_than_average" yet, but it has the same problem.

By using a proper name for the variables do you see anything missing? Do you see the problem with the if condition?

The function should have three parameters not two.

I have only worked on the functions down to "larger_than_average" and taken a brief look at the others, but not yet tested them.

The function "odd_from_even" says it returns an "int", but the function body returns nothing. This is an error that needs fixed. I am thinking that this should be a "void" function as I did not see where the value returned to "main" was ever used or what you need it for.

Shortly I will be checking the other functions to see how they work out.

I also noticed in "main" you have defined the variables "average", "average2" and "average3". The way "main" is written you can reuse "average" and 2 and 3 are not needed, but you can leave them if it helps.

Hope that helps,

Andy
Topic archived. No new replies allowed.