Array, several functions

Hello!
I'm very new at C++, and programming in general, and have a problem I would love some help with. I have been trying to write a code that asks the user to enter a series of numbers, and end the series with 0. The program should then calculate the sum of the numbers, the average, and print out those and also print out the largest and second largest number.

I have tried to do this by creating an array with a maximum of 100 integers, and getting the entered numbers into this array (called input). I've used bubblesort to sort the numbers, since it is the only sorting algorithm I know so far, and then print out index 99 and 100 to get highest and second highest number.

In order to get the average of the numbers, I needed to know how many numbers was entered, and tried to do so with a while-loop that stops after finding number 0.

The code doesn't work, the program asks for the numbers to be entered, but nothing comes back on the screen. I'm not sure what is wrong here, probably something with having an array as argument for a function, or even more things.

Thank you in advance and I apologize for my English if it's hard to read, it's not my first language.

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

using namespace std;

int bubbleSort(int input[]);
int antalElement(int input[]);

int main(){
    int input[100];
    int sum = 0;
    double average;

    cout << "Specify numbers, 0 to stop: ";

    for(int i = 0; i<100; i++){
        cin >> input[i];
        sum += input[i]; //calculates sum

        if (input == 0){
            break;
        }
    }
    int antal = antalElement(input);
    average = sum / antal;
    cout << "Sum: " << sum;
    cout << "Average: " << average;
    cout << "Largest and second largest number: " << bubbleSort(input);
}

int antalElement(int input[]){
    int antal = 1;
    while (input[antal] != 0){
        antal++;                //calculates how many numbers before 0 in array
    }
    return antal;
}

int bubbleSort (int input[]){
    int temp;
    int i;

    for (i = 1; i<= 100; i++){
        for(int j=99; j>i; j--){
            if(input[j-1] > input[j]){
                temp = input[j-1];
                input[j-1] = input[j];
                input[j] = temp;
            }
        }
    }
    return input[100], input[99];   //returns largest and second largest number
}
if (input == 0){

using input on its own is the pointer to where the first element in the array sits in memory, NOT the currently entered number you want to test for.

On line 16 read the user input into a variable first, then add it to the array, and *then* use that variable in your if on line 19 for testing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
.....

	int num = 0;

	cout << "Specify numbers, 0 to stop: ";

	for(int i = 0; i<100; i++){
		cin >> num; 
		input[i] = num;

		sum += input[i]; //calculates sum

		if (0 == num){
			break;
		}
	}

.....
Last edited on
Line 19: "input" probably returns the memory address of the array and that is never 0.
1
2
3
4
5
6
7
int i = 0; int sum = 0; int value = 0;
while ( i < 100 && cin >> value && 0 != value )
{
  input[i] = value;
  // other code
  ++i;
}

Both while and for loops can be used. Loop will do at most 100 iterations.
Logical && is lazy; if left side is false, right side is not evaluated.
Operator << returns istream object. istream converts implicitly to boolean. It is true, if stream is good.
If you get to the third test, the read operation has succeeded and 'value' has a new valid number.
0 is not stored to the array.

Line 31: Why 1? The array could be empty.
Line 32: I just did type 100 numbers, so 0 was never written to the array. Your loop can proceed beyond the array, where unknown values can exists.
Overall, you could have a counter in the input loop, so separate function is not needed.
Yes, C-strings (a char array) terminate with 0, but that convention is not usually used for other datatypes.

Line 42: from 1 to 100?
j must be larger than i, and j starts at 99, so 100 is definitely too much.
First iteration. i==1. j==2. This is the smallest j you will get. input[1] > input[2]. You never look at input[0].

Line 51:
* Function returns one value only. The line compiles, because the comma operator returns one value. Do you know what is the result of (7, 42) ?
* There is no element input[100] in the array.

Line 38:
* Functions take array parameters by reference. 'input' in the function is not a copy; it is the same memory as 'input' in main. Tip: using same name in different context is confusing.
* Sort sorts. Your function both sorts and (attempts to) return maximum value. Two tasks for one function. Simpler is better.

Line 24: integer division discards remainder. double foo = static_cast<double>(sum) / count;
Thank you for your answers! I have changed the code after your suggestions, and I now get the sum of numbers and the average as output. I'm not sure how to get the largest and second largest number out though. My idea was that with a bubblesort sorting an array with 100 elements (after the user has stopped entering numbers, the other places in the array would be filled with 0), the largest and second largest would end up in [99] and [100]. I tried to make a bubble sort in descending order instead, and output input[0] and input[1], but I'm not even getting "Largest and second largest number: " on the console.

And I know that I didnt have to have a separate function to count the number of elements, I just wanted to make some functions. I might remove that one to make it simpler.

This is the code now, I know it's 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
56
57
58
#include <iostream>

using namespace std;

int bubbleSort(int array[]);
int antalElement(int array[]);

int main(){
    int input[100];
    int sum = 0;
    double average;
    int num = 0;

    cout << "Specify numbers, 0 to stop: ";

    for(int i = 0; i<100; i++){
        cin >> num;
        input[i] = num;
        sum += input[i]; //calculates sum

        if (num == 0){
            break;
        }
    }
    int antal = antalElement(input);
    average = sum / antal;
    cout << "Sum: " << sum << endl;
    cout << "Average: " << average << endl;
    cout << "Largest and second largest number: " << bubbleSort(input) << endl;
}

int antalElement(int array[]){
    int antal = 1;
    while (array[antal] != 0){
        antal++;                //calculates how many numbers before 0 in array
    }
    return antal;
}

int bubbleSort (int array[]){
    int temp;
    int i;
    int numbers;

    for (i = 0; i<= 100; i++){
        for(int j=99; j<i; j--){
            if(array[j-1] > array[j]){
                temp = array[j-1];
                array[j-1] = array[j];
                array[j] = temp;
            }
        }
    }

    numbers = array[0] && array[1];

    return numbers;   //returns largest and second largest number
}


I didn't realize a function could only return one value, but I tried to put array[0] and array [1] in another variable, but that didn't work. How do i put those two in one "something" that can be returned? Or am I completely in the wrong here?
Last edited on
you could put your 2 numbers in an array and return that I guess?
Last edited on


Use a structure, see a similar post I answered regarding returning multiple information from a function:

http://www.cplusplus.com/forum/beginner/125960/

Thank you! I will implement a structure, seems like a practical thing to learn!
struct/class are practical to learn, but so are std::pair and std::tuple too: http://www.cplusplus.com/reference/utility/pair/pair/

You do know that your array has 'antal' elements. Tell that to bubbleSort. Do not blindly do 100, if the user had only 7 values. You did not initialize the array to 0, so the value of the unfilled elements is undefined.

You could int input[100] { 0 };

Your 'sum / antal' is still an integer division. 19/10 is 1, not 1.9.
I'm still trying to get it to work to return the two numbers from the function, but I changed the sum/antal to average = (double) sum / antal; thank you for that.

bubbleSort is
1
2
3
4
5
6
for (i = 0; i<= antal; i++){
        for(int j= (antal - 1); j<i; j--){
            if(array[j-1] > array[j]){
                temp = array[j-1];
                array[j-1] = array[j];
                array[j] = temp;



I noticed you are still having problems returning more than one value so i put together a bare minimum example to show you how:

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


#include <iostream>
using namespace std;

// struct
typedef struct {
	int lowerNum;
	int upperNum;
} myReturnStruct;

// function prototype.
myReturnStruct ExampleFunction();

int main()
{

	// before we can receive struct information from a function
	// we need to create one where will will store the return
	// values.

	myReturnStruct myReturnValues;

	// ok call the function and get its return values.
	myReturnValues = ExampleFunction();

	// display them
	cout << "lowerNum = " << myReturnValues.lowerNum << ", UpperNum = " << myReturnValues.upperNum;

	return 0;

}


myReturnStruct ExampleFunction()
{
	// before we can populate and return
	// a struct we need to create one.
	
	myReturnStruct val;		// create it

	// now populate it with values.
	val.lowerNum = 5;
	val.upperNum = 115;

	// return it
	return val;
}
Thank you Softrix, what I've done now is put the bubble sorting algorithm inside the structure, but now it doesn't print out the largest and second largest number. This is what my entire code looks like now (some names are now in Swedish, because I thought it would work, I hope it makes sense otherwise I'll change it to make it more understandable):

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

using namespace std;

int antalElement(int array[]);
int antal = 0;

typedef struct {
    int naststorst;
    int storst;
} nummer;
nummer storsta(int array[]);  //funktionsprototyp

int main(){
    int input[100] { 0 };
    int sum = 0;
    double average;
    int num = 0;
    int *p;

    cout << "Specify numbers, 0 to stop: ";

    for(int i = 0; i<100; i++){
        cin >> num;
        input[i] = num;
        sum += input[i]; //calculates sum

        if (num == 0){
            break;
        }
    }
    int antal = antalElement(input);
    average = (double) sum / antal;
    cout << "Sum: " << sum << endl;
    cout << "Average: " << average << endl;

    nummer varden;
    varden = storsta(input);
    cout << "Nast storst: " << varden.naststorst << endl;
    cout << "Storst: " << varden.storst << endl;
}

int antalElement(int array[]){
    while (array[antal] != 0){
        antal++;                //calculates how many numbers before 0 in array
    }
    return antal;
}

nummer storsta(int array[]) {

    int temp;
    int i;
    int numbers;

    //bubble sorting
    for (i = 0; i<= antal; i++){
        for(int j= (antal - 1); j<i; j--){
            if(array[j-1] > array[j]){
                temp = array[j-1];
                array[j-1] = array[j];
                array[j] = temp;
            }
        }
    }

    nummer val;

    val.naststorst = array[0];
    val.storst = array[1];

    return val;
};


I tried putting the bubbleSort function inside the structure since google said I could put a function in a struct, but I couldn't make it work. So I just put the bubble sorting inside the struct. It's late now so I might just take a break for tonight and look at it again in the morning.
I got an exception on line 62 when debugging your code. It seems your running past the last available index of your array. Shouldn't line 57 be: for (i = 0; i< antal; i++){ because if you have 100 numbers, 0 - 99 would be the 100, not 0-100 as that would be 101.

Oh wow, I just got it to work! I removed the <= in i < antal and now it works perfectly! Thank you so much!
Last edited on
Method inside struct:

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
struct Nummer
{
  int naststorst;
  int storst;
  Nummer() :  naststorst( 0 ), storst( 0 ) {}
  void bubbly( int array[], size_t size );
};

int main()
{
  const size_t N { 3 };
  int input[N] { 4 };
  Nummer val;
  val.bubbly( input, N );
  cout << val.storst << " och " << val.naststorst << '\n';
  return 0;
}

void Nummer::bubbly( int array[], const size_t size )
{
  if ( 2 <= size ) {
    storst = array[0];
    naststorst = array[1];
  }
}


Your welcome :)
Topic archived. No new replies allowed.