Array Assistance

Pages: 12
I have this array program, I need some help with reading in. Per instruction my program should handle up to 100 numbers. But there are 80 in the file( I have to stay with 100 I can't alter). Each time I print to the file its reading 106 numbers, which is more than the file size and more than I have my constant. What am I doing wrong?

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

using namespace std;

//Constant for program handling
const int MAX = 100;

//Prototypes
void read_array(int,int);
void print_array(int,int);
void average_array(int,int);

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

//Function to read values into the array
void read_array(int ary[], int b)
{
    int a;
    b=0;
    while(inf >> a && b < MAX)
    {
        ary[b] = a;
        b++;
    }
}

//Function to print the data to the desired file
void print_array(int bry[], int c)
{
    out << setprecision(2) << fixed;
    for(int i=0; i<c; i++)
    {
        out << bry[i] << ", ";
        if((i+1)% 10 == 0)
        {
            out << endl;
        }
    } out << "size= " << c;
}
int main()
{
    int MyArray[MAX], counter;

    out << "\tArray Work-Out Program\n"
        << "First Array: \n";

    read_array(MyArray, counter);
    print_array(MyArray, counter);

    return 0;
}


OUTPUT
1
2
3
4
5
6
7
8
9
10
11
12
13
	Array Work-Out Program
First Array: 
24, 43, 63, -72, 73, 72, 77, 23, 36, 94, 
28, 93, 9, 92, -8, 83, -36, 73, 5, 38, 
56, 17, 93, 80, 99, 26, 19, 62, 72, 8, 
4, 48, 21, 54, 84, 32, 97, 74, 94, 82, 
57, 4, 38, 27, 83, 83, 22, 27, 64, 7, 
44, 26, 45, 66, 83, 62, 52, -7, -36, 62, 
78, -67, 34, 73, 93, 8, -3, -2, 2, 27, 
1, 11, 12, -73, 83, 77, 37, 72, 82, 23,//23 should be the last number read. 
1967222499, -910747399, 4199040, 4199040, 0, 4354592, 7208624, 7208680, 7208908, 1967246528, 
-1130597875, -2, 7208680, 1967222765, 4354592, 7208832, 4354686, 4354592, 114, 8, 
106, 106, 2, 7208832, 4198653, 1, size= 106


your problem is that counter is not passed by reference, so when you call print it is messed up.
but I would personally make read-array return how many it reads instead of pass by reference in.

int counter = read_array(array); //this feels better to me.

but if you fix the pass by reference, I believe it will work 'as is'



Last edited on
Also note that your function prototypes do not match your function definitions.
Your function prototype should be int[] if you are passing an array.

It just happens to not matter here because you have main() defined at the bottom.
I'm confused on how to zero out the even numbers.
How to find the values that are larger/smaller than the average.(right now it's comparing to the total number in the array rather than the avg)

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

using namespace std;

//Constant for program handling
const int MAX = 100;

//Prototypes
void read_array(int[],int&);
void print_array(int[],int&);
float total(int[],int);
float average_array(int[],int);
int larger_than_average(int[],int);
int smaller_than_average(int[],int);
void neg_to_pos(int[],int);
void print_average(int[],int);

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

//Function to read values into the array
void read_array(int ary[], int& b)
{
    int a;
    b=0;
    while(inf >> a && b < MAX)
    {
        ary[b] = a;
        b++;
    }
}

//Function to print the data to the desired file
void print_array(int bry[], int& c)
{
    out << setprecision(2) << fixed;
    for(int i=0; i<c; i++)
    {
        out << bry[i] << ", ";
        if((i+1)% 10 == 0)
        {
            out << endl;
        }
    }
}

float total(int ory[], int z)
{
        int sum=0;
        for(int k=0; k<z; k++)
        {
            sum+=ory[k];
        }
    return sum;
}

float average_array(int gry[], int h)
{
        float sum=0;
        for(int j=0; j<h; j++)
        {
            sum+=gry[j];
        }
    return sum/h;
}

int larger_than_average(int jry[], int g)
{
    int cnt = 0;
    for(int h=0; h<g; h++)
    {
        if(jry[h]>g)
        {
            cnt++;
        }
    }
    return cnt;
}

//Function that calculates the amount of numbers smaller than the average.
int smaller_than_average(int pry[], int i)
{
    int cnt = 0;
    for(int j=0; j<i; j++)
    {
        if(pry[j]<i)
        {
            cnt++;
        }
    }
    return cnt;
}

//Function that converts negative integers to positive.
void neg_to_pos(int ury[], int m)
{
    for(int n=0; n<m; n++)
    {
        if(ury[n]<0)
        {
            ury[n] *= -1;
        }
    }
}

int main()
{
    int MyArray[MAX], counter, sum, large, small;
    float average;

    out << "\tArray Work-Out Program\n"
        << "First Array: \n";

    //Function call to read in the numbers and print to file
    read_array(MyArray, counter);
    print_array(MyArray, counter);

    //Function call to average the array
    average=average_array(MyArray, counter);
    sum=total(MyArray,counter);
    out << "Sum = " << sum << " " << "COUNT = " << counter
        << "\n\tAVERAGE = " << average;

    //Function call for numbers larger/smaller than average
    large=larger_than_average(MyArray, counter);
    out << "\n\nValues LARGER than AVERAGE: " << large;
    small=smaller_than_average(MyArray,counter);
    out << "\nValues SMALLER than AVERAGE: " << small;

    //Function call to change negatives to positive
    out << "\n\nSecond Array: Negatives to Positive\n";
    neg_to_pos(MyArray,counter);
    print_array(MyArray,counter);
    average=average_array(MyArray,counter);
    sum=total(MyArray,counter);
     out << "Sum = " << sum << " " << "COUNT = " << counter
        << "\n\tAVERAGE = " << average;

    return 0;
}


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
	Array Work-Out Program
First Array: 
24, 43, 63, -72, 73, 72, 77, 23, 36, 94, 
28, 93, 9, 92, -8, 83, -36, 73, 5, 38, 
56, 17, 93, 80, 99, 26, 19, 62, 72, 8, 
4, 48, 21, 54, 84, 32, 97, 74, 94, 82, 
57, 4, 38, 27, 83, 83, 22, 27, 64, 7, 
44, 26, 45, 66, 83, 62, 52, -7, -36, 62, 
78, -67, 34, 73, 93, 8, -3, -2, 2, 27, 
1, 11, 12, -73, 83, 77, 37, 72, 82, 23, 
Sum = 3309 COUNT = 80
	AVERAGE = 41.36

Values LARGER than AVERAGE: 16
Values SMALLER than AVERAGE: 63

Second Array: Negatives to Positive
24, 43, 63, 72, 73, 72, 77, 23, 36, 94, 
28, 93, 9, 92, 8, 83, 36, 73, 5, 38, 
56, 17, 93, 80, 99, 26, 19, 62, 72, 8, 
4, 48, 21, 54, 84, 32, 97, 74, 94, 82, 
57, 4, 38, 27, 83, 83, 22, 27, 64, 7, 
44, 26, 45, 66, 83, 62, 52, 7, 36, 62, 
78, 67, 34, 73, 93, 8, 3, 2, 2, 27, 
1, 11, 12, 73, 83, 77, 37, 72, 82, 23, 
Sum = 3917 COUNT = 80
	AVERAGE = 48.96

Last edited on
Hello CodeNovice01,

After going over your program I have made some changes that you may find t obe a better choice.

Looking at your last code I see that you have understood Ganado's advice. To add to that I would suggest that when making the prototypes that you copy the function definition pase it under the "prototypes" and just add the (;) at the end. Having the variable names in the prototype can be helpful.

When it comes to the function definition changing the names of the variables is legal, but most times it is not necessary. Because the scope of the program changes what you defined in "main" looses scope, or in a sense put on hold, and the function gains the new scope. So using the same variable name is OK. Also it helps to understand what you are using saving time to go back to the function call to see what variables you are trying to work with.

When I get to the "larger" and "smaller" functions you will see how proper variable names help you to see what is wrong.

Unless the variable starts with "const" or "constexpr" try to avoid using global variables. Here the "ifstream" and "ofstream" are not a problem, but a regular variable is available to the whole program and could be changed by any function making it hard to track down.

The "ifstream" is only used in the "read" function and should be defined there. When the function ends you no longer have any need for it.

On the other hand the "ofstream" is used in two functions. I defined this in "main" and passed it to the "print" function. This way you only have to define it once and can pass it to any function that would need to use it. Notice that this is passed by reference, which is the only way it works.

This is what I have come up with so far. Some parts that I would change I have not finished yet. But that would be good practice for you to work on.
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

//Constant for program handling
constexpr int MAX{ 100 };

//Prototypes
void read_array(int myArray[], int& counter);
void print_array(ofstream&, const int myArray[], const int counter);
double total(int[], int);
double average_array(int[], const int);
double average_array(double, const int);
int larger_than_average(int myArray[], const int, const double average);
int smaller_than_average(int[], const int, const double average);
void neg_to_pos(int[], const int);
void print_average(int[], const int); // <--- Function not defines. Not sure what you want to do here.

//Function to read values into the array
void read_array(int myArray[], int& counter)
{
	int num;
	counter = 0;
	std::string inFileName{ "Array in.txt" };

	ifstream inf(inFileName);

	if (!inf)
	{
		std::cout << "\n File " << std::quoted(inFileName) << " did not open" << std::endl;
		//std::this_thread::sleep_for(std::chrono::seconds(3));  // <--- Needs header files chrono" and "thread". Optional.
		/*return 1;*/  exit(1);  // If not in "main".
	}


	while (inf >> num && counter < MAX)
	{
		myArray[counter] = num;
		counter++;
	}
}

//Function to print the data to the desired file
void print_array(ofstream& out, const int bry[], const int c)
{
	out << setprecision(2) << fixed;

	out << "\tArray Work-Out Program\n"
		<< "First Array: \n";

	for (int i = 0; i < c; i++)
	{
		out << bry[i] << ", ";
		if ((i + 1) % 10 == 0)
		{
			out << endl;
		}
	}
}

double total(int ory[], int z)
{
	int sum = 0;

	for (int k = 0; k < z; k++)
	{
		sum += ory[k];
	}

	return sum;
}

double average_array(int myArray[], const int counter)
{
	double sum = total(myArray, counter);

	//for (int j = 0; j < h; j++)
	//{
	//	sum += gry[j];
	//}

	return sum / counter;
}

double average_array(double sum, const int counter)
{
	return sum / counter;
}

int larger_than_average(int myArray[], const int counter, const double average)
{
	int cnt{ 0 };

	for (int h = 0; h < counter; h++)
	{
		if (myArray[h] > average)
		{
			cnt++;
		}
	}

	return cnt;
}

//Function that calculates the amount of numbers smaller than the average.
int smaller_than_average(int pry[], const int i, const double average)
{
	int cnt = 0;

	for (int j = 0; j < i; j++)
	{
		if (pry[j] < average)
		{
			cnt++;
		}
	}
	return cnt;
}

//Function that converts negative integers to positive.
void neg_to_pos(int ury[], const int m)
{
	for (int n = 0; n < m; n++)
	{
		if (ury[n] < 0)
		{
			ury[n] *= -1;
		}
	}
}

int main()
{
	int MyArray[MAX]{}, counter{}, large{}, small{};
	double average{}, sum{};
	ofstream out("Array out.txt");

	//Function call to read in the numbers and print to file
	read_array(MyArray, counter);
	print_array(out, MyArray, counter);

	//Function call to average the array
	sum = total(MyArray, counter);

	//average = average_array(MyArray, counter);
	average = average_array(sum, counter);

	out << "\nSum = " << sum << " " << "COUNT = " << counter
		<< "\n\tAVERAGE = " << average;

	//out << "\nSum = " << sum << " " << "COUNT = " << counter
	//	<< "\n\tAVERAGE = " << sum / counter;

	//Function call for numbers larger/smaller than average
	large = larger_than_average(MyArray, counter, average);

	out << "\n\nValues LARGER than AVERAGE: " << large;

	small = smaller_than_average(MyArray, counter, average);

	out << "\nValues SMALLER than AVERAGE: " << small;

	//Function call to change negatives to positive
	out << "\n\nSecond Array: Negatives to Positive\n";

	neg_to_pos(MyArray, counter);

	print_array(out, MyArray, counter);

	sum = total(MyArray, counter);

	//average = average_array(MyArray, counter);
	average = average_array(sum, counter);

	out << "\nSum = " << sum << " " << "COUNT = " << counter
		<< "\n\tAVERAGE = " << average;

	return 0;
}

In the read function I defined the "ifstream" there and the next step is to check and make sure that it is open and usable. Otherwise the function would continue and nothing would be read from the file and your array would contain nothing but the garbage that it started with. This is because the while loop would fail being that the stream is in a failed state and not able to be used.

Notice what I did in the "larger" and "smaller" functions. By using a more proper variable name you can see that you are comparing an element of the array to counter, which is (80), and not the average ,of something around (41). What you did will give you an incorrect count.

In "main" I opened the output file. Checking here, as I did in the "read" function, is not as necessary as the "ofstream" will create the file name if it does not exist. If you would have used a path to the file then checking that the stream is open is a good idea as the path can very easily become a problem.

Some of the function calls I changed the order of. Calling "total" before can reduce the code in the program or even eliminate the need of a function.

One last note: Try to avoid single letter variable names and names like "gry", "jry" and "pry". These may mean something to you, but not to others. A proper name can be of more use than something that is easy to type.

Another thing I have fond over time is that it is generally accepted that regular variable name start with a lower case letter and "camelCaseVariables" are seen more often followed by the old DOS underscore to show a space where a space is not allowed (camel_case_variables). Now as to the second and third work being capitalized I am not sure about that part. For "cases" and "structs" these start with a capital letter. And for variables that are defined as a constant these are in all caps. I tend to think of the all caps as a reminder that it is defined as a constant and can not be changed.

Anything that you do not understand let me know.

Andy
Andy,

Thank you very much for the detailed description of the code. It very valuable information!

Why is the {} used for next to the variables in the "main"?

I kept having issues whenever I tried to write the function for larger than average. I kept receiving an error message, I can't remember what it said exactly, but something along the lines of being unable to use double[double] or invalid conversion from int to int*.

How/when would one know to place three parameters within your function description? IE: int function(int array[]; double sum; int average)
I was always taught to use 2 parameters, as you saw in my code.

How does the function smaller than average have the average value?

Is there any reason to why the average function is duplicated?
Last edited on
invalid conversion from int to int*.

those can be hard to read, but its telling you that you tried to mush a pointer and a thing together, consider:
int x[10];
x = 3; //x is a pointer, 3 is an int, to the compiler, and you get this error
x[0] = 3; //x[0] is an int, this is fine.


you can use as many parameters in your functions as you need. I think you misunderstood what you were taught. Functions can have many parameters, and often do. If you wanted to add 5 numbers without an array, you have to pass in 5 numbers :)

{} .. see https://www.geeksforgeeks.org/different-ways-to-initialize-a-variable-in-c-c/
{} is a zero initialize.

Hello CodeNovice01,

Why is the {} used for next to the variables in the "main"?

The {}s are known as the uniform initializer and are available from the C++ 2011 standards on.

Empty {}s will initialize a "bool" to (0) zero or false, int type variables to (0) zero and doubles to (0.0). "strings", "vectors" and other containers are empty when defined and do not need initialized unless you want to give it a value(s).

It may not be necessary to initialize variables when they are defined, but it is a good idea and so easy with the empty {}s.

I kept having issues whenever I tried to write the function for larger than average. I kept receiving an error message, I can't remember what it said exactly, but something along the lines of being unable to use double[double] or invalid conversion from int to int*.

That's nice, but with out point to the lines of code or showing what you have done along with not copying and showing the exact error message it is hard to tell what happened. Just so you know it is best to post the exact error message and not your interpretation of it as interpretation is often wrong or incomplete. No offense meant its just you are not use to error messages yet.

How/when would one know to place three parameters within your function description? IE: int function(int array[]; double sum; int average)
I was always taught to use 2 parameters, as you saw in my code.
When it comes to a function you are not limited to just two parameters. it would be nice if that is all you needed, but you can have as many function parameters as you need depending on what you need. I have seen function parameters that have covered two and three lines, based on the word wrap of the IDE. You pass the parameters (variables) to the function that you need and the amunt will depend on what you need.

To my knowledge there is no set rule to determine how many parameters a function will need. You will have to decide this when you write the function.

How does the function smaller than average have the average value?

When you look at these lines of code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Function call to average the array
sum = total(MyArray, counter);

//average = average_array(MyArray, counter);
average = average_array(sum, counter);

out << "\nSum = " << sum << " " << "COUNT = " << counter
	<< "\n\tAVERAGE = " << average;

//out << "\nSum = " << sum << " " << "COUNT = " << counter
//	<< "\n\tAVERAGE = " << sum / counter;

//Function call for numbers larger/smaller than average
large = larger_than_average(MyArray, counter, average);

out << "\n\nValues LARGER than AVERAGE: " << large;

small = smaller_than_average(MyArray, counter, average);

By calling the "total" function first the variable "sum" will have a value before the "average" function is called.

These lines of code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
double average_array(int myArray[], const int counter)
{
	double sum = total(myArray, counter);

	//for (int j = 0; j < h; j++)
	//{
	//	sum += gry[j];
	//}

	return sum / counter;
}

double average_array(double sum, const int counter)
{
	return sum / counter;
}

Are known as an overloaded function. Because the parameters are different you can use the same function name and the compiler will know which function to use based on the parameter types and quantity.

The biggest reason I did this is to show you two different ways of writing the function and you can choose which one works best for you since they both do the same thing just in a different way. Choose which one you want and delete the other and the prototype, as it will no longer be needed.

In the first function the for loop to total the array may be slightly different, but you can make use of the "total" function instead of duplicating code. And in the end what it comes down to is that back in "main" you have a value for "sum" and "counter" there is no need to sum the array each time you need it. You already have the values for "sum" and "counter" you just need to use them. Then there is a good chance the compiler will optimize the function to be inline in the "cout" statement, especially the second function. This would be equivalent to lines 10 and 11 of the first bit of code.

Is there any reason to why the average function is duplicated?
See the part about overloaded functions.

I could see in the "larger" and "smaller" functions where you are comparing an "int" to a "double" it could be a problem.

Sorry for the confusion. I was trying to show you a better way to work your program while still keeping with the way your original code was written.

I did my work in VS2017 set to use the C++14 standards. Since I try to use code of the C++11 standards I am not sure what went wrong for you. Best to post the offending code and error message that you received.

Andy

Andy! Thank you very much for the detailed response. I have reworked the code and it's error free up to the point I am at. I've still to create a couple more functions. I need a largest/smallest number and its position. I'm unsure of how to go about writing the function or how to properly compare things. Here's what I have so far.

1
2
3
4
5
6
7
8
9
10
//Function that finds the largest value and its position
double LargestNumber(int num[], int counter)
{
    largest= NegativeToPositive(num,counter);
    if(num < largest)
    {
        out << largest;
    }
}

I know it's rough. How do you figure out what and where to place the proper statements?
If you have an array, say {3, 4, 8, 1, 7}, how would you yourself figure out the largest number? Obviously, it's 8, but how did you come to that conclusion? You looked at each number, then you found 8, and then you made sure no number was greater than 8.
In code, you would iterate through all the numbers in the array, and you would keep track of a "greatest number so far" variable.

e.g. first, assign the "greatest number so far" variable to be the first element of the array.
Then, iterate through the array, and if you spot a number that is greater than the "greatest number so far", set the "greatest number so far" to be that number.
At the end of the iteration, return that variable; that is your greatest number.
Last edited on
Ok, so I've come up with this
1
2
3
4
5
6
7
8
9
10
11
double LargestNumber(int ary[], int counter)
{
    int largest;
    for(int i=0;i<counter;i++)
    {
        while(largest<ary[i])
        largest=ary[i];
    }

    return largest;
}

output
 
Largest Number of the Array is: 4199040


Can you offer a little tip as to what I'm not doing properly?
You have a loop inside a loop. You only need 1 loop. But, your inner loop is funny, because it will only ever iterate 0 times or 1 time. Change it to an if statement.

Your issue is you didn't do a specific part of my previous suggestion:
first, assign the "greatest number so far" variable to be the first element of the array.


Currently, your "largest" variable is uninitialized when you compare it on line 6.
I actually just said this in another thread to a different user, but I'll repeat it here:
Please turn on compiler warnings! It will save you future headaches! On GCC/clang, use at least -Wall. On Visual Studio, see: https://www.learncpp.com/cpp-tutorial/configuring-your-compiler-warning-and-error-levels/

The compiler will warn you if you attempt to use uninitialized variables (if it can detect at compile-time that the variable is uninitialized).
Last edited on
I've got it figured out, thank you for the help. As for the position of that number within the array? I tried to cout the MyArray[counter] Myarray[largest] and its junk. Of course you know that, but what am i doing?
1
2
3
4
5
6
7
8
9
10
11
12
13
//Function that finds the largest value and its position
double LargestNumber(int ary[], int counter)
{
    int largest=MIN;
    for(int i=0;i<counter;i++)
    {
        if(largest<ary[i])
        largest=ary[i];
    }

    return largest;
}


Output
 
Largest Number of the Array is: 99 Position: 7894324
Your function by itself looks fine to me now. (I don't know what MIN is, but I assume it's some really negative number.)
You should also indent line 8, since it's inside the if statement.

I don't how you're actually calling and printing your output just based on the function, so something wrong is happening outside of the function itself.

Have you turned on compiler warnings?
Last edited on
Here's the full code as of now

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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

//Constant for program handling
const int MAX = 100, MIN = 0;

//Prototypes
void ReadArray(int[],int&);
void PrintArray(int[], int&);
double Total(int[],int);
double AverageArray(int[], int);
double AverageArray(double, int);
int LargerThanAverage(int[],int, double);
int SmallerThanAverage(int[], int, double);
void NegativeToPositive(int[],int);
double LargestNumber(int[],int);
double SmallestNumber(int[],int);

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

//Function to read values into the array
void ReadArray(int ary[], int& counter)
{
    int num;
    counter=0;
    while(inf >> num && counter < MAX)
    {
        ary[counter] = num;
        counter++;
    }
}

//Function to print the data to the desired file
void PrintArray(int bry[],int& c)
{
    out << setprecision(2) << fixed;

    for(int i=0; i<c; i++)
    {
        out << bry[i] << ", ";
        if((i+1)% 10 == 0)
        {
            out << endl;
        }
    }
}

double Total(int ory[], int z)
{
        int sum=0;
        for(int k=0; k<z; k++)
        {
            sum+=ory[k];
        }
    return sum;
}

double AverageArray(int gry[], int h)
{
    double sum = Total(gry, h);

    return sum/h;
}

double AverageArray(double sum, int counter)
{
    return sum/counter;
}

int LargerThanAverage(int jry[], int i, double avg)
{
    int cnt=0;
    for(int j=0; j<i; j++)
    {
        if(jry[j]>avg)
        {
            cnt++;
        }
    }
    return cnt;
}

//Function that calculates the amount of numbers smaller than the average.
int SmallerThanAverage(int pry[], int i, double avg)
{
    int cnt = 0;
    for(int j=0; j<i; j++)
    {
        if(pry[j]<avg)
        {
            cnt++;
        }
    }
    return cnt;
}

//Function that converts negative integers to positive.
void NegativeToPositive(int ury[], int m)
{
    out << "\n\nSecond Array: Negative to Positive\n";
    for(int n=0; n<m; n++)
    {
        if(ury[n]<0)
        {
            ury[n] *= -1;
        }
    }
}

//Function that finds the largest value and its position
double LargestNumber(int ary[], int counter)
{
    int largest=MIN;
    for(int i=0;i<counter;i++)
    {
        if(largest<ary[i])
        largest=ary[i];
    }

    return largest;
}

//Function that finds the largest value and its position
double SmallestNumber(int ary[], int counter)
{
    int smallest=MAX;
    for(int i=0;i<counter;i++)
    {
        if(smallest>ary[i])
        smallest=ary[i];
    }

    return smallest;
}

int main()
{
    int MyArray[MAX], counter, large,largest,smallest, small;
    double average,sum;

    out << "\tArray Work-Out Program\n"
         << "First Array: \n";

    //Function call to read in the numbers and print to file
    ReadArray(MyArray, counter);
    PrintArray(MyArray,counter);

    //Function call to average the array
    sum=Total(MyArray,counter);
    average=AverageArray(sum, counter);

    out << "Sum = " << sum << " COUNT = " << counter
        << " AVERAGE = " << average;

    //Function call for number larger/smaller than average
    large=LargerThanAverage(MyArray,counter,average);
    small=SmallerThanAverage(MyArray,counter,average);
    out << "\n\nValues LARGER than AVERAGE: " << large
        << "\nValues SMALLER than AVERAGE: " << small;

    //Function call to change negatives to positive
    NegativeToPositive(MyArray,counter);
    PrintArray(MyArray,counter);
    sum=Total(MyArray,counter);
    average=AverageArray(sum,counter);
    out << "Sum = " << sum << " COUNT = " << counter
        << " AVERAGE = " << average;

    //Function call to determine min/max number of the array.
    largest=LargestNumber(MyArray,counter);
    smallest=SmallestNumber(MyArray,counter);

    out << "\nLargest Number of the Array is: "<<largest
        << " Position: "
        << "\nSmallest Number of the Array is: "<<smallest
        << " Position: ";


    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
	Array Work-Out Program
First Array: 
24, 43, 63, -72, 73, 72, 77, 23, 36, 94, 
28, 93, 9, 92, -8, 83, -36, 73, 5, 38, 
56, 17, 93, 80, 99, 26, 19, 62, 72, 8, 
4, 48, 21, 54, 84, 32, 97, 74, 94, 82, 
57, 4, 38, 27, 83, 83, 22, 27, 64, 7, 
44, 26, 45, 66, 83, 62, 52, -7, -36, 62, 
78, -67, 34, 73, 93, 8, -3, -2, 2, 27, 
1, 11, 12, -73, 83, 77, 37, 72, 82, 23, 
Sum = 3309.00 COUNT = 80 AVERAGE = 41.36

Values LARGER than AVERAGE: 41
Values SMALLER than AVERAGE: 39

Second Array: Negative to Positive
24, 43, 63, 72, 73, 72, 77, 23, 36, 94, 
28, 93, 9, 92, 8, 83, 36, 73, 5, 38, 
56, 17, 93, 80, 99, 26, 19, 62, 72, 8, 
4, 48, 21, 54, 84, 32, 97, 74, 94, 82, 
57, 4, 38, 27, 83, 83, 22, 27, 64, 7, 
44, 26, 45, 66, 83, 62, 52, 7, 36, 62, 
78, 67, 34, 73, 93, 8, 3, 2, 2, 27, 
1, 11, 12, 73, 83, 77, 37, 72, 82, 23, 
Sum = 3917.00 COUNT = 80 AVERAGE = 48.96
Largest Number of the Array is: 99 Position: 
Smallest Number of the Array is: 1 Position: 
Okay, so the output looks like it's correct; the largest number is in fact 99.
Last edited on
The smallest is being compared with the second array, which has zero negatives, the smallest is '1'. I'm conflicted with how to produce the postition of the largest/smallest.
I would suggest passing it by reference as a third parameter to your LargestNumber and SmallestNumber functions
1
2
3
4
double SmallestNumber(int ary[], int counter, int& position)
{
    // ...
}

Assign position inside the loop. Then later print it outside of the function like you do with the largest/smaller numbers.
Last edited on
How would I go about making the function produce a number without initializing smallest and largest with min and max. Such as, initializing it with a number already within the array?
Pages: 12