More arrays! And an overloading question

The code:
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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <climits>
#define SIZE 9
using namespace std;
/*
Develop a function that finds the greatest difference between two 
consecutive elements stored in an array. Develop a 9 element array
of doubles to test your code. Print to the screen which two numbers
have the greatest difference as well as the value of the difference.
Finally include an overloaded version of the function that will work 
if the array is composed of integers. Include your code used to test this
function.(hint: you can create temporary variables)
*/

double Random (double)
{
double i =rand () /20;
return i;
}

int main (void)
{
srand (time(NULL));
double sub = 0;
int max = INT_MIN;
double first = 0;
double next = 0;
double posi = 0;
double posnext = 0;
int i = 0; //counter
int j = 0;
double Diff [SIZE] = {Random (0),Random (1),Random (2),Random (3),Random (4),Random (5), Random (6),Random (7), Random (8)};
for (i = 0; i < SIZE ; i++)
	{
	first = Diff [i];
	next = Diff [i+1];
	sub = first - next;
	if (sub > max)
		{
		max = sub;
		posi = Diff [i];
		posnext = Diff [i+1];
		}
		cout << Diff [i]<< '\t';
	}
	cout << endl;
	cout << "Greatest difference between two consecutive ints " << posi << " & " << posnext << " : " << max << endl;
return 0;
}


With output:
6.846e+07	9.27981e+07	4.82664e+07	1.36067e+06	1.0552e+08	7.55702e+07	8.72133e+07	2.9506e+07	5.30898e+07	
Greatest difference between two consecutive ints 8.72133e+07 & 2.9506e+07 : 57707348


The formatting is much better with just ints, but the question wants doubles, so that's what it gets. I could populate the array myself, with 3.25 and 4.67 or whatever, but the random array each time makes me happier. (Side question, is there a way to restrict the double type to a certain amount of decimal places? I'd like if the Random function would make 4.78's and 9.2's)

I also didn't use the hint at all. I know about new and delete but I haven't quite figured them out yet.

So the first question is solved; the code subtracts one element in the 1d matrix from the next, then compares the outcome to previous and chooses the largest, and then outputs the two numbers subtracted and the difference between the two.

The problem is with next = Diff [i+1] which is great until the last element of the array. Then the code tries to subtract from an index that doesn't exist.

Also, to answer the totality of the question, I clearly don't understand what overloading is or does. I feel like with the clumsiness of my code, I probably overload a lot, without knowing it, but that's not the point. I read http://www.cplusplus.com/doc/tutorial/classes2/ but it's not really making too much sense.

As always, thanks for taking the time!
Develop a function that finds the greatest difference between two
consecutive elements stored in an array.

I see no such function.


I probably overload a lot, without knowing it,

There are no functions in your code other than Random/main, so there is no overloading at all.

1
2
3
4
5
6
7
8
9
double greatest_difference( double* array, unsigned size )
{
     // ...
}

int greatest_difference(int* array, unsigned size)  // now we have overloaded functions.
{
    // ...
}
@macleight

LIne 34 would be better done with a for loop - what if you had 50 numbers in the array.

Then the code tries to subtract from an index that doesn't exist.


Limit the for loop to one less than the size of the array.

Overloaded functions are used to handle different input that does the same thing. For example in C programming there are separate functions for different types that calc the absolute value of a number. In C++, you can have functions with the same name, but with a different combination of argument types, or number of arguments. So with the abs function:

1
2
3
4
abs(int MyInt){}
abs(double MyDouble) {}
abs(long MyLongInt){}


So with your code, you should create more functions that do the separate parts of the problem - Initialise the array, calc differences, and output info. Then you can overload these functions to handle different types.

is there a way to restrict the double type to a certain amount of decimal places?


Read up about setprecision.

HTH



I probably overload a lot, without knowing it,

There are no functions in your code other than Random/main, so there is no overloading at all.



Mostly typed for lulz. Again, I can't figure out what overloading is, so I don't know whether it is happening or not.

I see no such function.



Really? But it does it every time I run it... =(
1
2
3
4
5
6
7
8
9
10
if (sub > max)
		{
		max = sub;
		posi = Diff [i];
		posnext = Diff [i+1];
		}
		cout << Diff [i]<< '\t';
	}
	cout << endl;
	cout << "Greatest difference between two consecutive ints " << posi << " & " << posnext << " : " << max << endl;

Which checks sub against max, which is initially set to INT_MIN which is from the <climit> library. Which should be changed to double_min or something, probably. But it does look at two consecutive elements in the array, finds the difference, chooses the largest one, and then outputs the two it chose and the difference. Is this not what was asked?

double greatest_difference( double* array, unsigned size )
{
// ...
}

int greatest_difference(int* array, unsigned size) // now we have overloaded functions.
{
// ...
}

int greatest_difference(int* array, unsigned size) // now we have overloaded functions.
{
// ...
}

// now we have overloaded functions.

Huh?
Why? What is it? All you did is change double to int. Who cares?
@TheIdeasMan

Limit the for loop to one less than the size of the array.

Ok.
LIne 34 would be better done with a for loop - what if you had 50 numbers in the array.

Yeah, but my curiosity only extends so far. This was part of a test question, and the tests are timed, so I limited my Random path (ha!) to the 9 elements the question asked for.


Is this not what was asked?

No. A function was asked for. None was supplied.

Why? What is it? All you did is change double to int. Who cares?

You should, since it is what is required of you. But, with the attitude, feel free to figure it out on your own. You said "I don't know what overloading is" which would seem to indicate to me that you haven't done your assigned reading or paid attention in class, and I supplied an example of overloading a function.

Who cares, indeed.
Due to my slow typing - we were all posting a the same time.

Did you see my explanation of overloaded functions? If you read that in conjunction with cire's post it should be clear.

This was part of a test question, and the tests are timed, so I limited my Random path (ha!) to the 9 elements the question asked for.


Yes, but it is better practice to do it the way I described - even if there were 5 elements in the array.

Did you find out about setprecision?
No. A function was asked for. None was supplied.


Subjective vs objective. I (and the test proctors) consider "main" a function. At least, they have so far. They might fail this one, we'll see.

Why? What is it? All you did is change double to int. Who cares?


Again, for lulz. I'm saying, I don't see the difference.

which would seem to indicate to me that you haven't done your assigned reading


I have.

or paid attention in class

It's a distance class.
I supplied an example of overloading a function.

You did, and I thank you. I don't understand it though. You wrote two different functions, one that accepts doubles as a variable type, and one that accepts ints as a variable type. I don't see why these are one overloaded function instead of two separate functions.

Who cares, indeed.


Too much philosophy here. I'm a full time engineer for a nanotech R&D company. I'm also a full time student at a state university, studying engineering. One would think there would be a hint of crossover, but in fact, they have nothing to do with each other, and when I come to my professors with real world problems to solve, they say "Oh, this is theoretical, you can't use this for that." And I say, "Well what is the point then?" And apparently, the point is to create relatively useless tiny programs that will be archived to my laptop until it dies so I can receive a piece of paper that says I am an engineer, despite the fact that I am an engineer for about 60 hours a week every week.

/rant.
Due to my slow typing - we were all posting a the same time.


Yup. I'll take a break here and do some reading. Be back in a minute.
They are two different functions, or at least, the compiler sees them as 2 different functions. What makes them overloaded is the fact that they have the same name. The only thing that determines which function is called is the type and number of arguments passed to them. So calling greatest_difference(double) is different from calling greatest_difference(int). Now, you can actually make one function to handle both types, but that's using templates and a bit ahead of this lesson.

As for main() being the function you developed by you, well, I don't think your teacher will accept it. While it's true main is a function the point of the exercise seems to be to develop a function who sole purpose is to determine the greatest difference contained in the array. The key piece of this is written in the problem here: "Finally include an overloaded version of the function that will work if the array is composed of integers." You can't overload main and he obviously wants you to overload the function you use to find the greatest consecutive difference, ergo you must create and call a separate function.
@TheIdeasMan
All setprecision stuff that I have read so far relates to outputs. In my case, this would mean that Random still sends the same information, but if you request an output and use setprecision, then it will truncate the output, even though the value remains the same. I want the Random function to send truncated numbers to the array. I added a setprecision line to the Random function, it did nothing.

@Raezzor
Thank you, that was very helpful.
I am filled with rage. Just like the last section (cire remembers) this thing is making me feel like a stupid monkey.

I clearly don't understand how to pass arrays to a function. I am getting the same errors I was getting when i was trying to pass pointers. This seems to happen about 14 times every time I do an exercise until I stumble upon syntax that makes the compiler happy. I have formatted them exactly like my course documents tell me too.

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

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#define SIZE 9
using namespace std;

/*
Develop a function that finds the greatest difference between two 
consecutive elements stored in an array. Develop a 9 element array
of doubles to test your code. Print to the screen which two numbers
have the greatest difference as well as the value of the difference.
Finally include an overloaded version of the function that will work 
if the array is composed of integers. Include your code used to test this
function.(hint: you can create temporary variables)
*/

int i = 0; //counter
double Random (double);
double Difference (double* Diff, SIZE);
int main (void)
{
srand (time(NULL));
double Diff [SIZE] = {Random (0),Random (1),Random (2),Random (3),Random (4),Random (5), Random (6),Random (7), Random (8)};
for (i = 0; i <= (SIZE-1) ; i++)
	{
		cout << Diff [i]<< '\t';
		cout << endl;
	}
Difference (Diff, SIZE);
return 0;
}
//Functions
double Random (double)
{
double i =rand () /20;
setprecision (2);
return i;
}

double Difference (double Diff [])
{
double sub = 0;
int max = INT_MIN;
double first = 0;
double next = 0;
double posi = 0;
double posnext = 0;
for (int i = 0; i < (SIZE -1); i++)
	{
	first = Diff [i];
	next = Diff [i+1];
	sub = first - next;
	if (sub > max)
		{
		max = sub;
		posi = Diff [i];
		posnext = Diff [i+1];
		}
	}
cout << "Greatest difference between two consecutive ints " << posi << " & " << posnext << " : " << max << endl;
return 1;
}


test8ex3.2.cpp:20: error: expected identifier before numeric constant
test8ex3.2.cpp:20: error: expected ‘,’ or ‘...’ before numeric constant
test8ex3.2.cpp: In function ‘int main()’:
test8ex3.2.cpp:20: error: too many arguments to function ‘double Difference(double*)’
test8ex3.2.cpp:30: error: at this point in file

Sleepy time.
Last edited on
I want the Random function to send truncated numbers to the array. I added a setprecision line to the Random function, it did nothing.


But why? You can't influence how a double is stored, the thing to do is to alter how the value is output. That is what setprecision does - alter the output.

You could convert the double to a string, then truncate that, but I don't see the point in doing that.

You did, and I thank you. I don't understand it though. You wrote two different functions, one that accepts doubles as a variable type, and one that accepts ints as a variable type. I don't see why these are one overloaded function instead of two separate functions.


Again, did you read my explanation? Along with cire's examples, and now Raezzor's explanation, I would have thought it should be crystal clear. Any of those 3 as a standalone explanation should have been enough. You are an engineer, what about this simple concept that is too hard?

Maybe a different example might help.

Consider an Arc in geometry. There are lots of different ways to calculate an Arc, depending on what info is given, here are some (not all) examples:

1
2
3
4
CalcArc(Point2D CentrePt, double Radius, Angle StartAng, Angle EndAng){}
CalcArc(Point2D CentrePt, StartPt2D StartPt, EndPt2D EndPt){}
CalcArc( StartPt2D StartPt, Point2D PtOnArc, EndPt2D EndPt){}


So this shows different ways of calculating an arc, but they all have the same function name. They differ by the types of the arguments, and can also differ by the number of arguments - this is so the compiler can tell which function to call. The example shows different types because of this - you can't have 2 functions which both have 3 points of the same type as arguments.

Function overloading is a form of abstraction, because the user can just think about "Calculate the Arc" rather than worry about how it is done. It is especially handy for pure virtual functions providing an interface for a group of inherited classes.

I would have thought it should be crystal clear


Yeah, I got it after
@Raezzor
Thank you, that was very helpful.


It has been a long day. I will try again tomorrow. Thank you for your help.
As for your problem with the function, that error on the 2nd to last line, you call the function with 2 arguments, but you defined the function with one 1 parameter. Add int size to the definition after the array and you'll be golden there. Only other thing I can see is that your for loop uses the comparison i < (size-1). This won't check the last element of the array since, say your array has 10 elements, you are saying if i is less then 9. Normally for arrays you simply say i < size. Prolly a sleep deprivation mistake from the sound of it. :)
@Raezzor
This won't check the last element of the array since, say your array has 10 elements, you are saying if i is less then 9. Normally for arrays you simply say i < size.


The purpose of that was not to overstep the array. It does check the last one because of the next = Diff [i+1];

@macleight

Once you have had some sleep, you can look at the whole thing in new light:

TheIdeasMan wrote:
So with your code, you should create more functions that do the separate parts of the problem - Initialise the array, calc differences, and output info. Then you can overload these functions to handle different types.


You could make use of casting, so that you only need to overload the CalcDifferences function.

HTH
@TIM Ah yup, I dun goofed on that. Looks like I was in the same boat as Mac last night! One other thing I just noticed but not only is SIZE not in the difference() definition, but it's type wasn't declared in the prototype.

Ok.
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

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#define SIZE 9
using namespace std;

/*
Develop a function that finds the greatest difference between two 
consecutive elements stored in an array. Develop a 9 element array
of doubles to test your code. Print to the screen which two numbers
have the greatest difference as well as the value of the difference.
Finally include an overloaded version of the function that will work 
if the array is composed of integers. Include your code used to test this
function.(hint: you can create temporary variables)
*/

int i = 0; //counter
double Random (double);
double Difference (double Diff []);
int Difference (int Diff []);

int main (void)
{
srand (time(NULL));
double Diff [SIZE] = {Random (0),Random (1),Random (2),Random (3),Random (4),Random (5), Random (6),Random (7), Random (8)};
for (i = 0; i <= (SIZE-1) ; i++)
	{
		cout << setprecision (2) << Diff [i] << '\t';
		cout << endl;
	}
Difference (Diff);
return 0;
}
//Functions
double Random (double)
{
double i =rand () /20;
return i;
}

double Difference (double Diff [])
{
double sub = 0;
int max = INT_MIN;
double first = 0;
double next = 0;
double posi = 0;
double posnext = 0;
for (int i = 0; i < (SIZE -1); i++)
	{
	first = Diff [i];
	next = Diff [i+1];
	sub = first - next;
	if (sub > max)
		{
		max = sub;
		posi = Diff [i];
		posnext = Diff [i+1];
		}
	}
cout << "Greatest difference between two consecutive ints " << posi << " & " << posnext << " : " << max << endl;
return 1;
}

int Difference (int Diff [])
{
int sub = 0;
int max = INT_MIN;
int first = 0;
int next = 0;
int posi = 0;
int posnext = 0;
for (int i = 0; i < (SIZE -1); i++)
	{
	first = Diff [i];
	next = Diff [i+1];
	sub = first - next;
	if (sub > max)
		{
		max = sub;
		posi = Diff [i];
		posnext = Diff [i+1];
		}
	}
cout << "Greatest difference between two consecutive ints " << posi << " & " << posnext << " : " << max << endl;
return 1;
}


Now we have a main function that populates an array with random double ints. The output has been cleaned up a little with setprecision, but the random numbers are still just as large.

Then I have three functions after the main. The random function to produce the array's values, and sends them back to the main function. I have one function named Difference, that can be sent both doubles and ints, meaning it is one overloaded function.

I got the arrays to pass to the functions well enough, but what I wrote looks nothing like any examples I have found. I'm glad it seems to work, but I don't understand why.
Better:

1
2
3
4
5
double Random (double)
{
double i =rand () /20000000.5;
return i;
}


13.3	
78.4	
45.9	
1.38	
18.6	
74.1	
36.7	
21.1	
23.1	
Greatest difference between two consecutive ints 45.9 & 1.38 : 44
I have one function named Difference, that can be sent both doubles and ints, meaning it is one overloaded function.


Not really. You have two functions both named Difference, that can be sent either int or double, meaning the functions are overloaded. I know this sounds very pedantic, but it is less confusing IMO.

I'm glad it seems to work, but I don't understand why.


Actually, it is not fulfilling the assignment, because you make a double array, then calculate it's differences. You have a function that deals with ints, but you don't have an array of ints to use it with. So make an array of ints, then call the difference function with the int array.

Then you need an output function to deal with the int array, I was also suggesting you have an output function to deal with the double array.

This sounds like overkill, but when you learn about templates, you will see that templates are a better solution for this. Function overloading is better for something like the Arc calculations I mentioned earlier.

Any way, see how you go.
Last edited on
Topic archived. No new replies allowed.