Read input into array & find mean and median

Hi, I'm having trouble figuring out how to write this program. I'm supposed to only gather user input (up until a nondigit or 100 characters) and read them into an array in main(). I also have three more functions, called Mean(), Sort(), and Median() where I find the average, sort the input into ascending order, and then find the median. Right now I am having trouble with the array section of main(), mainly with combining the loop for the array with this tidbit of code containing a while statement that I was given (to ensure that I only receive digits as input):
1
2
3
4
5
6
int n;
while (std::cin >> n)
{
  // do whatever appropriate with n, which is ensured to be of type int
}
// after all ints are read, execution picks up here 


So far this is what I have in main, but I don't think I'm combining these two concepts correctly. Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main()
{
  int SIZE = 100;
  int array[SIZE];

  int n; 

  std::cout << "Please enter integers ('x' to quit): ";

  for (int i = 0; i < SIZE; i++)
  {
	while (std::cin >> input)
	{
		std::cin >> array[i];
	}
        std::cout << array[i]; //just to check array
  }
}
Last edited on
closed account (2UD8vCM9)
Yeah, you don't want what your code is doing.

It is basically saying this.

Go through each integer we're going to input.

So let's say we start at subscript 0, array[0].

While you are typing in a valid number, put it in that slot. If you type an invalid number, go to the next slot.

So if I type in 3, hit enter, 5 hit enter, 7 hit enter, X hit enter. array[0] will now be 7, and now we move to array[1].

Instead of doing a while loop, you should just have an if statement with the same conditions. You can have an else for the if statement so that if the user enters an invalid input, you can break out of the loop. It would look something like this.

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 main()
{
  int SIZE = 100;
  int array[SIZE];

  int n; 

  std::cout << "Please enter integers ('x' to quit): ";

  for (int i = 0; i < SIZE; i++)
  {
	if (std::cin >> input)
	{
		std::cin >> array[i];
	}
	else
	{
		break;
	}
        std::cout << array[i]; //just to check array
  }


This would end the for loop for the first non-integer character they type in.

Does that help?
Thank you for helping me figure out that loop. But whenever I have it reprint the input of the array to the screen, it prints out a bunch of random numbers. Here's my code now with the updated loop.

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>                                                             
                                                                                
int main()                                                                      
{                                                                               
  int input, SIZE=100;                                                          
                                                                                
  int array[SIZE];                                                              
                                                                                
  std::cout << "Please enter integers ('x' to quit): ";                         
                                                                                
  for (int i = 0; i < SIZE; i++)                                                
  {                                                                             
      if (std::cin >> input)                                                      
     {                                                                            
        std::cin >> array[i];                                                     
      }                                                                           
      else                                                                        
      {
         break;                                                                    
      }                                                                           
  }                                                                             
                                                                                
  std::cout << "Data as entered: ";                                             
  for (int i = 0; i < SIZE; i++)                                                
    std::cout << array[i];                                                      
}                                                                               
 


Is there something that I'm doing wrong that you can see? Thanks for your help!
Also, if I'm going to be finding the mean later on in another function, how do I keep track of how many numbers are input? Is there any way to send the amount of numbers to another function (maybe the counter on i in the for loop)?
Last edited on
closed account (2UD8vCM9)
Yes, the problem is that your array is 100 elements long and you are printing all 100 even though you have not filled 100 elements. This results in you printing out data that was never filled in.

So at the beginning, you declare int array[SIZE]; which is really the same as just int array[100];

[Note: You should change int SIZE=100; to const int SIZE=100; I don't even know how that compiles for you, but it doesn't compile for me.]

What we need to do to properly output the data is have an integer to hold the number of entries.

There was also one last reason your code wasn't working.

I was tired when I had posted that code, but I forgot to mention that in the if statement we had where we call cin and in the scope for that if statement where we call cin again that doesn't make any sense. We should only call cin for one input. By calling it twice, we were grabbing two inputs.

The code should look like this.
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
#include <iostream>                                                             

int main()
{
	int input;
	const int SIZE = 100;
	int NumberOfEntries = 0; //Number of entries
	int array[SIZE];

	std::cout << "Please enter integers ('x' to quit): ";

	for (int i = 0; i < SIZE; i++)
	{
		if (std::cin >> array[i])
		{
			//We don't actually need to do anything here, because the if statement put the contents into array[i]
		}
		else
		{
			NumberOfEntries = i;
			break;
		}
	}

	std::cout << "Data as entered: ";
	for (int i = 0; i < NumberOfEntries; i++) //Change for loop to iterate up to NumberOfEntries instead of the whole 100 numbers
		std::cout << array[i] << " "; //Add a space after each number.

	return 0;
}
Another way:
1
2
3
4
...
while (NumberOfEntries < SIZE && (std::cin >> array[NumberOfEntries])) {
    ++NumberOfEntries;
}


You will need to pass both array and NumberOf Entries into Mean(), Sort() and Median().

Have you learned about vectors? If you used vectors then you wouldn't have to use a separate variable to track the count, nor would you have a limit on the number of entries.
Thank you both for your help! It's correctly storing the input in the array. However, I have finished the rest of my code and I am having some issues with it. If you don't mind, would you take a quick look to see if anything stands out? Thanks! And no, dhayden, I haven't learned about vectors yet, so I pretty sure I'm supposed to use an array.

So I have three files for this program (that are all compiled together in unix): 1) stats.h, which contains the prototypes for my mean, median, and sort functions 2) stats.cpp, where I am supposed to implement these three functions, and 3) main.cpp, with my main function. And then my two main issues are at the bottom.

1) stats.h (I was given these prototypes to work with)
1
2
3
4
//not sure if I need to include anything at top
float Mean (const int* array, size_t size);
float Median (int* array, size_t size);
void Sort (int* array, size_t size);


2) stats.cpp
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
#include <stats.h>       //only include header file with prototypes?
                                                                                
//function to find the mean that should be called by main()                                         
float Mean (int NewArray[], size_t size)                                        
{                                                                               
  float sum, mean = 0.0;                                                        
                                                                                
  for (int i = 0; i < size; i++)                                                
  {                                                                             
    sum += NewArray[i];                                                         
  }                                                                             
  mean = ((float)sum)/size;
                                                             
  return mean;                                                                  
}

//function to find median that should be called by main()
float median;
{ 
  //not sure how to call sort (void) function and return new sorted array to median function
 
  if(size % 2 == 0)                                                             
 {                                                                             
    median = (NewArray[size/2] + NewArray[size/2-1])/2.0f;                      
  }                                                                             
  else                                                                          
  {                                                                             
    median = NewArray[size/2];                                                  
  }                                                                             
  return median;  //return median to main()                                                      
}                                                                               

// void function to sort array in ascending order and called by median()                     
Sort(int NewArray[], size_t size)                                               
{                                                                               
  for (i = 0; i < size; i++)                                                    
  {                                                                             
    for(int j = 0; j < size-1; j++)                                             
    {                                                                           
        if(NewArray[j] > NewArray[j+1])                                         
        {     
	  int temp = NewArray[j+1];                                             
          NewArray[j+1] = NewArray[j];                                          
          NewArray[j] = temp;                                                   
        }                                                                       
    }                                                                           
  }                                                                             
}                                                                               


3) And main.cpp (which is the same as above with these calls added at the bottom)
1
2
3
4
5
6
7
8
std::cout << "Mean: " << float Mean (array[SIZE], NumberOfEntries);           
                                                                                
  std::cout << "Median: " << float Median (array[SIZE], NumberOfEntries);       
                                                                                
  std::cout << "Data after sort: ";                                             
                                                                                
  return 0;                                                                     
}


Okay, so there are my three files and there are two main problems that I am having:
1) I want to make sure that I am passing the array[] and its size correctly to each of the three functions.
2) I was given the prototypes for my three functions (including the void Sort function) and I was told to call the Sort function in the Median function. I don't really understand how to update the old array in the Median function if I can't return the sorted array in the Sort function (if that makes sense).
Nice job with the code. A lot of beginners struggle with this stuff.

1) I want to make sure that I am passing the array[] and its size correctly to each of the three functions.
1
2
std::cout << "Mean: " << Mean(array, NumberOfEntries);     
std::cout << "Median: " << Median(array, NumberOfEntries);      


2) I was given the prototypes for my three functions (including the void Sort function) and I was told to call the Sort function in the Median function.

The first thing that Median() does should be:
Sort(NewArray, size);

By the way, line 18 of your stats.cpp file should be the beginning of Median:
float Median(int *NewArray, int size)
Thanks! I'm a bit rusty with passing arrays to functions, so I just wanted to make sure I was doing them right. As far as the Median and Sort question, I thought about just calling the Sort function, but how can I return the new sorted array back to Median if it is a void function?

And oops, thank you for catching that!
how can I return the new sorted array back to Median if it is a void function?

When you pass as a parameter to a function, you're really passing the address of the first element. So arrays are, for all purposes, passed by reference, not by value. That means that Sort() will modify the original array that you pass.
Topic archived. No new replies allowed.