Arrays!

We have to write a program with arrays, that use user defined functions to perform different functions. The one I am having an issue with, is finding the lowest value. I looked up another program, and compile it and it worked, but I cannot see the difference, and will never return the correct value. Maybe you guys can find the issue. The whole program is included, and is not finished by any means. I will also include the code that I referenced.
My 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
#include <iostream>
#include <stdlib.h>

using namespace std;

int lowestInteger (int integerArray[], int index)
	{
					
		int smallest = integerArray[0];
		
			for (index = 1; index < sizeof(integerArray)/ sizeof (integerArray[0]); ++ index)
				
			if (integerArray[index] < smallestIndex);
				{
					smallestIndex = integerArray[index];
				}
			return smallest;
	cout << "The integer with the lowest value is: " << smallest << endl;	
	}
		
int main ()
{
	int integerArray [10];
	int index =0;
	int average = 0;	
	
	cout << "First you will enter 5 integers, and then the program will generate 5 random numbers." << endl; 
	cout << "After the integers are entered the program will perform several different functions.\n" << endl;
	for (int i=0; i < 5; i ++)
	{
	     cout << "Enter an integer: ";
	     cin >> integerArray[i];
	}
	
	for (int x =5; x <10; x++)
	{
		integerArray[x] = rand () % 30+1;
								
		cout << "Random number generated was: " << integerArray [x] << endl;
	}
		lowestInteger (integerArray, index);
		
	return 0;
	
}


Referenced code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main ()
{
    int array []= {4,2,3,1,5};

    int smallest = array[0] ;
    for ( int i=1;  i < sizeof(array)/sizeof(array[0]);  ++i )
        if ( array[i] < smallest )
             smallest = array[i] ;

    cout << smallest << '\n' ;

    return 0;
}


Also cannot get the random number generator to not regenerate numbers, so I think I am just going to define the arrays values, or maybe partially, so the user will have something to do instead of just having all these values print up on the screen.
Last edited on
First, a comment.

If you have problems with one routine, then why not post just enough to run and test THAT ROUTINE, not a whole plethora of others which are unfinished. As a general rule,
"minimal compileable code that reproduces the problem" is the most appropriate.


Here's part of the routine that you draw attention to.

1
2
3
4
5
6
7
8
9
10
11
12
for (index = 1; index < sizeof(integerArray)/ sizeof (integerArray[0]); ++ index)
				do
				{
					if (integerArray[index] < smallestIndex);
					{
						smallestIndex = integerArray[index];
					}
				}
				while (integerArray[index] > smallestIndex);
				
		cout << "The integer with the lowest value is: " << smallestIndex << endl;	
		}


First of all, your indentation is inconsistent and confusing, which is asking for trouble.

Then ask yourself what is this piece of code doing. In particular, what role does the do - while loop play? Can you explain it in words to the forum? If not, why are those 2x2 lines there?
1
2
3
4
5
				do
				{
...
				}
				while (integerArray[index] > smallestIndex);



Since you are apparently after a value rather than its index, wouldn't it be more sensible to call it smallest, rather than smallestIndex.


Then, you have declared your function as
int lowestInteger (int integerArray[], int index)
which implies that you are going to return an int. Where do you do that?


Your "random" numbers will come out the same because you have made no call to srand() to seed them.
Last edited on
First of all, on function parameters:
T foo( U bar[] );
means exactly the same as:
T foo( U * bar );

In other words, a function does not take array. It merely takes a pointer to (first) element in array.
A pointer does not now whether the pointed to element is part of array, nor how many elements the array has.

That is why one has to pass the size to function separately:
T foo( U * bar, size_t size );

(The size_t is an unsigned int type. More logical for sizes and indices that should not be negative.)


On reference code you could count from line 6 that the array has exactly 5 elements.
The code, however, does not rely on human eyes and uses sizeof on line 9 to count for you.

On your code the element count is very much known; it is 10.


I'll refactor the reference code into separate function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

int small( int* data, size_t size )
{
  if ( data and 0 < size ) { // sanity check
    int smallest = data[0];
    for ( size_t index=1;  index < size;  ++index )
        if ( data[index] < smallest )
             smallest = data[index];
    return smallest;
  }
  else return 0; // dummy, there was no array
}

int main ()
{
    int array []= {4,2,3,1,5};

    int smallest = small( array, sizeof(array)/sizeof(array[0]) );
    std::cout << smallest << '\n' ;

    return 0;
}


Note that C++ Standard Library has a function: http://www.cplusplus.com/reference/algorithm/min_element/
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <algorithm>
int main ()
{
    int array []= {4,2,3,1,5};

    int smallest = *std::min_element( std::begin(array), std::end(array) );
    std::cout << smallest << '\n' ;

    return 0;
}



PS. Your lines 84-89 do not do what you probably expect them to do.
I can see rand being used in your code, but I don't think you seeded it first. So it is probably not working correctly.

Opps, sorry lastchance, it looks like I just repeated you.
Last edited on
Yeah I know the code 84-89 doesn't work, because I've compiled it. I was hoping it would prevent reoccurring numbers, and am going to abandon that anyways and just define the numbers when i initialize the array.

I posted the whole code in case someone wanted to plug it into their compiler and see the outcomes, since a snippet would not do anything for anyone.

I do not have much programming expierence, and was trying different things. My thoughts on the do while loop, was to force the rand () to continue to generate a number, that did not equal any previously entered/ generated numbers, which did not work. I intended on taking out. I do not know what srand is or does, so I will have to look that up.

Also declaring the function as an int, was because of variations where i used return smallestIndex, or integerArray[smallestIndex], neither of which work.

I will edit the post to make it more clear to the suspect code.
hello everyone
I hope that Array is a memory location with same name and same Data type.Array is a container object that hold values of homogenous type. It is otherwise called static information because size of an array must be specified at the time of its declaration.An array can be either primitive or reference type. It gets memory in heap area. Index of array starts from zero to size-1.
@link45jeff,
Maybe you could post your latest piece of code below. (It gets confusing if you amend an earlier post that we have all been commenting on). Keep it to the driver program (main) and the offending routine. You can bring other functions in one by one as you get each to work.

Amongst other things:
- you need to pass the array size to the function, not some spurious index; sizeof() won't help you inside the function (though it could be used in main(), where the array is declared);
- you have an unwanted semicolon at the end of an if statement;
- you are still muddling smallest (a value) with smallestIndex (its position in the array);
- you are trying to output something after returning from the function; informing the user of the smallest value could be done in main once you have returned it.
- I should stick with user values for the array until you have got the function to work. Putting random values in before then is just muddying the water. Do one thing at a time.

Please post modified code BELOW; it will all get very confused if you keep modifying an earlier post.
Last edited on
Well this is what I have now, which gives numbers 1-10 in a random order, I tried to use a larger set of numbers to choose from, but kept getting a random 49 or some other weird anomaly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int lowestInteger( int integerArray[], size_t size )
	{
    	int smallest = integerArray[0];
    		
		for ( size_t index=1;  index < size;  ++index )
		{
        	if ( integerArray[index] < smallest )
        	{
             	smallest = integerArray[index];
            
			}
		}
    return smallest;
	}


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
int main ()
{
	srand(time(NULL));
	int integerArray [10];
	int i, j, temp;
	int average = 0;
	int tempNum;
	bool matching;
	
		for (i=0; i<10; i++)
			integerArray[i] = i+1;
			
		for (i=0; i<10; i++)
		{
			j = rand()%10;
			
			temp = integerArray[i];
			integerArray[i] = integerArray[j];
			integerArray[j] = temp;
		}
		
		display (integerArray);
		cout << "Now we will display the mean of all the integers you entered: " << endl;
		mean (integerArray);
		cout << endl;
		//median (integerArray, index);
		cout << endl;
		lessThanFive (integerArray);
		int smallest = lowestInteger( integerArray, sizeof(integerArray)/sizeof(integerArray[0]) );
    	cout << "The smallest integer is: " << smallest << '\n' ;

		sumOfIntegers (integerArray);
		
	return 0;
	
}
Last edited on
@link45jeff,
Can you please post a single code that we can compile and test.

Can I suggest that you simply fix your integer array to start with, so that one can test individual routines. Something like
int integerArray [10] = { 9, 8, 1, 3, 4, 5, 2, 6, 7, 0 };
and forget the random numbers until everything else is working.

When you put up you entire compileable code, please state carefully what errors you are getting.

Not having any issues now, except that I wanted a more diverse set of random numbers. I do have to figure out the median function still, and that's my next goal. I did some youtube-ing, and got the random numbers to work, and also the lowest integer bit. Also, I do not know why my code has inconsistencies in the tabbing, I am very particular at the organization of the code.

Now I cannot figure out how to get a double number, from the median function. It works except for that. You will see that I tried to typecast, which I guess didn't work, so maybe I did it wrong. Any help with that would be 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
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
#include <iostream>
#include <stdlib.h>
#include <iterator>
#include <algorithm>
#include <time.h>
#include <bits/stdc++.h>

using namespace std;

void display (int integerArray[])
	{
		cout << "The numbers were: " << endl;
		for (int i=0; i <10; i++)
			printf("  %d", integerArray[i]);
			cout << endl;
	}
void mean (int integerArray[])
	{
		double sum = 0;
	for (int i =0; i <10; i ++)
		{
			sum = sum + integerArray[i];
		}
		double average = sum /10 ;
	cout << "The average of the integers entered is: " << average << endl;		
	}	
	int median (int integerArray[])
	{
		int length = 10;
		double median;
		if (length % 2 != 0)
			{
				median = (double) integerArray[length/2];
				cout << "The median of the array is: " << median << endl;
			}
		else
		{ 
			median = (double)((integerArray[(length/2)-1] + integerArray[length/2])/2);
			cout << "The median of the array is: " << setprecision(2) << fixed << showpoint << median << endl;;
		}
	}
	
	void lessThanFive (int integerArray[])
	{
		cout << "The Following values are less than five: " << endl;
		for (int i = 0; i <10; ++ i )
		{
			if (integerArray[i] < 5)
			{
				cout << integerArray[i] << endl;
			}
		}
	}
	
	int minimum( int integerArray[], size_t size )
	{
    	int smallest = integerArray[0];
    		
		for ( size_t index=1;  index < size;  ++index )
		{
        	if ( integerArray[index] < smallest )
        	{
             	smallest = integerArray[index];
            
			}
		}
    return smallest;
	}
		
	int sumOfIntegers (int integerArray[])
	{
		int sum =0;
		
		for (int index = 0; index <10; index ++)
		{
				sum = sum + integerArray[index];
		}
		
		cout << "The sum of the integers is: " << sum << endl;	
	}
int main ()
{
	srand(time(NULL));
	int integerArray [10];
	int size = sizeof(integerArray)/sizeof(integerArray[0]);
	int i, j, temp;
	
		for (i=0; i<10; i++)
			integerArray[i] = i+1;
			
		for (i=0; i<10; i++)
		{
			j = rand()%10;
			
			temp = integerArray[i];
			integerArray[i] = integerArray[j];
			integerArray[j] = temp;
		}
		display (integerArray);
			cout << endl;
		mean (integerArray);
			cout << endl;
		median (integerArray);
		cout << "The median is: " << median << endl;
			cout << endl;
		lessThanFive (integerArray);
			cout << endl;
		int smallest = minimum(integerArray, size);
    	cout << "The smallest integer is: " << smallest << '\n' ;
    		cout <<endl;
		sumOfIntegers (integerArray);
			cout << endl;
		
	return 0;
	
}
Last edited on
This is what you do:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int median()
{
  double median;
  median = (double)( (7 + 42) / 2 );
}

int main ()
{
  median();
  std::cout << "The median is: " << median << '\n';
  return 0;
}

And this is what a compiler says about the code:
 In function 'int median()':
5:10: warning: variable 'median' set but not used [-Wunused-but-set-variable]
7:1: warning: no return statement in function returning non-void [-Wreturn-type]
 In function 'int main()':
12:37: warning: the address of 'int median()' will always evaluate as 'true' [-Waddress]

It is a bit unnerving that you can use a variable name 'median' within function that has name 'median' without a compiler remark. When two different things have same name, which one do you refer to when you write that name?

Line 7. Your function is supposed to return a value. Line 3 says clearly int. The function has no return statement. What value should be returned? Previous posters have pointed out the same issue.

Line 11. You do call the function, but you don't store the returned value. Even if your function would return the correct result, you would ignore it.

Line 12. Prints out the address of function 'median'. Function addresses do not show as hexadecimal addresses but as bool value true. The true shows as '1' by default.

You do use C-style cast syntax. Prefer C++ casts. They are more specific and easier to spot.
static_cast<double>( foo ) rather than (double)foo

You do cast the result of (49/2). That is an int (24). You should cast one of the operands of the operator/, not the result. In this case your divisor is literal '2' and could as well a literal double '2.0'.
@keskiverto
Sometimes I feel like people reference arbitrary things like numbers instead of using my code and trying things out for themselves, which is extremely un-helpful. Using your example I should obviously be easily able to static cast numbers, but I am having issues with arrays, and if you tried the your fixes in my code you would have found that they do not yield the correct result. Thanks for the suggestions, but I did try those. Also tried using 2.0, doesn't work, also tried chaning length % 2, to length / 2 (and use a double on length) which isn't allowed either. I am out of ideas. Also my compiler apparently doesn't care so much as yours because I get 0 errors when I compile my code, even if I have an int function not return a value. If I have a return statement it absolutely will not compile. I tried using a return statement, and it throws errors.

Error] invalid conversion from 'int (*)(int*)' to 'int' [-fpermissive]
[Error] invalid conversion from 'int (*)(int*)' to 'int' [-fpermissive]

That is what happens when I use a return statement like you suggest. I also tried static casting, and that also did not work either. It still will not return a the correct value.

When using the return statement, it does not even return the correct value either, so I am not sure why that does not work either. I had issues when I had a project of all user defined functions as well until I used the & for the variables.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void median (int integerArray[])
	{
		int length = 10;
		double medianValue;
		if (length % 2 != 0)
			{
				medianValue = static_cast<double> (integerArray[length/2]);
				cout << "The median of the array is: " << (medianValue)<< endl;
			}
		else
		{ 
			medianValue = static_cast <double> ((integerArray[(length/2)-1] + integerArray[length/2])/2);
			cout << "The median of the array is: " << setprecision(1) <<fixed << (medianValue) << endl;;
		}
	}


Note: I fixed it myself, I had to static cast both of the array[] variables, because otherwise it didn't care the variables were already calculated.

fix:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void median (int integerArray[])
	{
		int length = 10;
		double medianValue;
		if (length % 2 != 0)
		{
			medianValue = (integerArray[length/2]);
			cout << "The median of the array is: " << (medianValue)<< endl;
		}
		else
		{ 
			medianValue = ((static_cast <double> (integerArray[(length/2)-1]) + static_cast<double>(integerArray[length/2]))/2);
			cout << "The median of the array is: " << setprecision(1) <<fixed << (medianValue) << endl;;
		}
	}
Last edited on
@limk45jeff,
All of @keskiverto's comments were highly pertinent. It is difficult to "try out" a code which manifestly doesn't work and, in your earlier posts, wasn't actually complete enough to compile.

Now you have a code that assumes a dataset size of 10. That's great ... for those datasets that have size 10. What is it going to do for others? And if always 10, then half of your if blocks would be redundant.

The median is a double, so ... set the return type to double ... and return it!

Incidentally, you could avoid any explicit casting by multiplying by 0.5 rather than dividing by 2. Your call.

You can actually reduce the entire function to one not particularly long line.
When using the return statement, it does not even return the correct value

Do we see how did you use it?
No, we do not know what was actually wrong in that attempt.

The code that I did post had all the relevant features of your code; the errors without distracting fluff.
For example, your code had /2 total of four times. Three of them were fine. The last one was essential for the int|double and that I did keep.


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

double median( int * values, size_t size );

int main ()
{
  int arr[] = {7, 42};
  const double med = median( arr, sizeof(arr)/sizeof(arr[0]) );
  std::cout << "The median is: " << std::setprecision(1) << std::fixed << med << '\n';
  return 0;
}


double median( int * values, size_t size )
{
  if ( 0 == size ) return 0; // genuinely arbitrary value

  const size_t midway = size / 2;
  const int rhs = values[midway];
  if ( size % 2 ) {
    return rhs;
  }
  else {
    const int lhs = values[midway-1];
    return (lhs + rhs) * 0.5; // the average
  }
}
Topic archived. No new replies allowed.