Can anyone help me solve this problem? pass by reference/value and file i/o should be used..

Write a C++ program which will read in a list of numbers, find the average of all numbers, the average of thepositive and negative numbers, and the largest element. Your program should contain at least four functions -- one to read in the list, one to write it out, one to get the averages, and one to find the largest element.


please help me.. thank you.

What have you tried? Did you encounter any specific problems? Please elaborate on anything that proves you're not a lazy student looking for a hand out.

this the only thing that i've done yet.. i'm just starting it and i don't know if i'm doing it right. by the way, thanks for the reply :)

#include <iostream>
using namespace std;



int main()
{
   void ReadList(int list[], int n);
   return 0;

   void main(){	
	ifstream fin;
	fin.open("input.txt");
	void ReadList;

}

void ReadList(int list[], int n)
{

	cout<<"Enter the number of integers to be read: " << endl;
	cin>>n;
	list[n];
	for (int q=0, q<n, q++)
		cin>> list[q];
		cout<<"Number[q]: " << list[q] << endl;

	
}

//void Avgs (int Array[], int N, int &Ave, int &aveP, int &AveN)
//{
    
//}


//int Large (int Array[], int N)
//{
    
//}


//void Display(int Array[], int N, int Ave, int AveP, int AveN, int Max)
//{
   
//}

Edited 5 Years Ago by Nick Evan: Added [CODE] tags

this one..

#include <iostream>
using namespace std;



int main()
{
	ifstream fin;
	fin.open("input.txt");
	void ReadList;

	return 0;

}

void ReadList(int list[], int n)
{

	cout<<"Enter the number of integers to be read: " << endl;
	cin>>n;
	list[n];
	for (int q=0, q<n, q++)
		cin>> list[q];
		cout<<"Number[q]: " << list[q] << endl;

	
}

//void Avgs (int Array[], int N, int &Ave, int &aveP, int &AveN)
//{
    
//}


//int Large (int Array[], int N)
//{
    
//}


//void Display(int Array[], int N, int Ave, int AveP, int AveN, int Max)
//{
   
//}

Edited 5 Years Ago by Nick Evan: Added [CODE] tags

Next time, put your code in code tags. Like this

std::cout << "Code Tags"'

Edited 5 Years Ago by jackmaverick1: I think that my code was wrong!

#include <iostream>
#include <fstream>
using namespace std;


void ReadList(int Array[], int N)
{
	Array[100];
	cout<<"Enter the number of integers to be read: ";
	cin>>N;
	for (int q=0; q<N; q++)
	{
		cout<<"Number[" << q << "]: ";
		cin>> Array[q];
	}
	
}

void Avgs (int Array[], int N, int &Ave, int &aveP, int &AveN)
{
}

int Large (int Array[], int N)
{
}

void Display(int Array[], int N, int Ave, int AveP, int AveN, int Max)
{
}

void main()
{
	int Array[100], N=0, q=0;
	ReadList(Array,N);
	

}

how about this?

i don't know how to pass by an array to the other function then get its average.. :|

When you define "int Array[100];" actually you are defining a pointer to the first element of the array. So if you "cout << Array" you will see this will print the adress of the first element. It is the same as "cout << &Array[0]". So simply Array is a pointer.

When passing an array to a function you can pass it using "int Array[]" or since it is a pointer you can pass it as "int *Array". In the function you should not try to decleare the same array again like "int Array[100]". You passed the argument so you can should use it without declaring again.

double average(int array[], int sizeOfArray)
{
double avg; // Your return value
int sum = 0;// Sum of all the elements of array
for(int i =0; i < sizeOfArray; i++)// Iterate through array
{
sum += array[i]; // Calculate the sum
}
avg = (double)sum / sizeOfArray; //Cast to double to get a double after calculation
return avg;
}

Edited 5 Years Ago by Tellalca: n/a

Well, technically, you shouldn't use arrays with a size determined through a variable. It should either be a defined constant(int a[5]) or (int a), but not a variable that may get changed. If you don't know the size of the array at the start of the program, you should probably be using vectors. Nevertheless, for now -- seeing as how you're a beginner -- that should be fine.

Always use "int main()" and not some other variation like "void main()". If you're really interested in knowing why, read this.

You passed your variables into ReadList correctly, but if you want to go by proper C++ naming conventions, you'll always use a lower-case first word or using underscores (so ReadList becomes readList or ReadList becomes read_list). The same should apply to the variables you are passing in. Furthermore, using more descriptive variable names would help someone understand your code better in a short time.

Now, for the brutal truth, just because I feel like helping a newbie out.

Read a good C++ book because you are developing horrendous programming habits.

  • learn how to create functions correctly
  • focus on getting a solid "game plan" set before jumping into the coding
  • understand exactly what each line of code is doing and if it's what you want

The way you've currently set up you program, you have your function declarations placed firmly at the top of your file. That is not how to properly declare your functions. Use function prototypes at the top of the file and function declarations underneath the main function. Here's a tidbit on properly declaring functions.

Secondly, I sense you're a bit confused about setting up arrays. In the main() part of code, you set the array Array (see a problem with that? use more descriptive names) to a size of 100 integers. However, when you passed the array into ReadList, you only allow "N" amount of values to be put into the array. If a user enters, for instance, 5 integers into the array, a lot of memory is wasted with 95 elements being unused.

Here's a gentle push (sarcasm) into the right direction. However, by taking this and using it as part of your problem without understanding what is happening with each line, you're short-changing yourself and no one else. Every line is commented to explain what is happening. If you don't have a clue as to what's going on, open up a book, read through the first 4-5 chapters and that should have you understanding most of this program.

Also, develop an algorithm (it shouldn't be hard) on how to find the highest value in the group. If you can properly explain what needs to be done, I'll help you out a little again.

*If I somehow incorrectly explained a part or didn't use proper programming protocol [specifically worried about the array initialization process and if it's frowned upon]... looking at Narue and other helpful programmers, please let me know!*

#include <iostream>

void get_input(int scores[], int& size); // passing array by reference (arrays always pass by address) and size by reference
double get_average(int scores[], int size); // passing array by reference and size by value (which is set in function "get_input()")

int main()
{
    int number = 0;
    int list[number]; // setting size of array to 0 elements

    get_input(list, number); // passing in array and size of array
    std::cout << "Average: " << get_average(list, number); // outputting average (#1 AVERAGE FUNCTION CALL! look at function get_average to understand)

    return 0;
}

void get_input(int scores[], int& size) // size passed by reference (meaning if changed here, changed it everywhere [same explanation three lines down])
{
    std::cout << "Enter the number of scores you wish to enter: ";
    std::cin >> size; // having passed the variable size by reference, it allows us to change the value of number (set at 0 originally) for every function here on out...

    for(int i = 0; i < size; i++)
    {
        std::cout << "Enter a number: ";
        std::cin >> scores[i]; // input value for each element
    }
}

double get_average(int scores[], int size) // size passed by value (meaning if changed here, changed only here)
{
    int sum = 0; // declare sum equal to 0
    double average = 0; // declare average equal to 0

    for(int i = 0; i < size; i++)
        sum += scores[i];  // for the value of each element, add to sum (if first element is 4, sum = 0 + 4...if second element is 8, sum = 4 + 8...)

    average = static_cast<double> (sum) / size; // to get a floating point number for average, you need to convert one of the integers (sum or size) to a double

    return average; // this is what's printed for the average (#1 AVERAGE FUNCTION RETURN VALUE! look at function call get_average(list, number) in main to understand)
}

>>*If I somehow incorrectly explained a part or didn't use proper programming protocol [specifically worried about the array initialization process and if it's frowned upon]... looking at Narue and other helpful programmers, please let me know!*

After telling the OP that you can't use a variable to declare an array-size, you did exactly the same in your code. Adding the word const should fix it. You can't however declare an array of size 0, it's illegal in C++.
Use vectors or new-delete to change the size of the array. Your current method won't compile.

Edited 5 Years Ago by Nick Evan: n/a

sorry for not telling you this earlier..
we were given specific names and descriptions of the functions that we will use.

by the way, I want to thank for the comments, they really helped me alot. :)

these are the given functions and their descriptions..


void ReadList(int Array[ ], int N)
This will read in a list of N values, where N is already known

void Avgs (int Array[], int N, int &Ave, int &aveP, int &AveN)
Array is a one-dimensional array of integers and N is the number of elements in that array. Both of these are input parameters to the function. The function must calculate 1) the average of the N integers in Array and return the result in Ave, 2) the average of the positive numbers (> 0) and return the result in AveP, and 3) the average of the negative numbers (< 0) and return the result in AveN.

int Large (int Array[], int N)
Array is a one-dimensional array of signed integers and N is the number of elements in that array. The function returns the value of the largest element in the array.

void Display(int Array[ ], int N, int Ave, int AveP, int AveN, int Max)
This will display the list of values (nicely formatted) together with the averages and the largest value.
Use the following test data (there are two sets):
A) 4 -30 0 7 42 -20 18 400 -123 -6
B) 2 17 -5 0 20 15 -16 -3 -2 14 -1 12 1 -5 -100 15 22 -5 68 -13

Store this information in a file and have your program read this data from that file. ( Input.txt)

>>*If I somehow incorrectly explained a part or didn't use proper programming protocol [specifically worried about the array initialization process and if it's frowned upon]... looking at Narue and other helpful programmers, please let me know!*

After telling the OP that you can't use a variable to declare an array-size, you did exactly the same in your code. Adding the word const should fix it. You can't however declare an array of size 0, it's illegal in C++.
Use vectors or new-delete to change the size of the array. Your current method won't compile.

Yeah. Thanks for the heads up. I created the file in gedit without compiling (bro's PC) so I clearly didn't get a chance to test it. See? Learned a new thing today -- array's can't be set to a size of 0 -- and that's not something my book told me. Thanks for the lesson, Nick.

Also, should const be used when passing the array into functions other than get_input() to make sure there is no way to change its values?

Well, technically, you shouldn't use arrays with a size determined through a variable.

Technically you can't. C++ doesn't presently support array sizes that aren't compile time constants. If it happens to work, it's due to a compiler extension, and thus not portable.

You passed your variables into ReadList correctly, but if you want to go by proper C++ naming conventions, you'll always use a lower-case first word or using underscores (so ReadList becomes readList or ReadList becomes read_list).

There are no "proper" naming conventions in C++, it's all across the board depending on the style guidelines one uses.It's not uncommon to match the style of the standard library as closely as possible, but that's tricky because then you run the risk of stomping all over the implementation's name space for internal or future identifiers.

The way you've currently set up you program, you have your function declarations placed firmly at the top of your file. That is not how to properly declare your functions. Use function prototypes at the top of the file and function declarations underneath the main function.

Both are perfectly valid. Just because defining functions ahead of main doesn't suit your style doesn't make it wrong.

If a user enters, for instance, 5 integers into the array, a lot of memory is wasted with 95 elements being unused.

Yes, that's generally how one handles variable length input with arrays: define an array with enough space for the upper limit of input and write off any wasted space as the cost of not doing dynamic allocation.

int list[number]; // setting size of array to 0 elements

Not valid C++. number isn't a compile time constant and the value of number is 0. But it gets better, and for the sake of argument, let's assume that this array is valid. You immediately pass the array and the size to get_input, which then overwrites the value of number and overflows the array (because the array doesn't resize itself simply by assigning to an out of range element). The whole of get_input is undefined behavior and demonstrates a confusion of fundamental concepts where arrays are concerned.

If you want to shrink wrap the array size to input from another function, some form of dynamic memory is necessary here. For example (using new[] and delete[]):

#include <iostream>

int get_input(int*& scores);
double get_average(int *scores, int size);

int main()
{
    int *scores;
    int size;

    size = get_input(scores);
    std::cout<<"Average: "<< get_average(scores, size) <<'\n';

    delete[] scores;

    return 0;
}

int get_input(int*& scores)
{
    int size = 0;

    std::cout<<"Enter the number of scores you wish to enter: ";
    
    if (std::cin>> size && size > 0) {
        scores = new int[size];

        std::cout<<"Enter the scores: ";

        for (int i = 0; i < size; i++)
            std::cin>> scores[i];
    }

    return size;
}

double get_average(int *scores, int size)
{
    int sum = 0;

    for (int i = 0; i < size; i++)
        sum += scores[i];

    return static_cast<double>(sum) / size;
}

Of the much preferred std::vector:

#include <iostream>
#include <vector>

std::vector<int> get_input();
double get_average(const std::vector<int>& scores);

int main()
{
    std::vector<int> scores = get_input();

    std::cout<<"Average: "<< get_average(scores) <<'\n';

    return 0;
}

std::vector<int> get_input()
{
    std::vector<int> result;
    int score;

    std::cout<<"Enter the scores: ";

    while (std::cin>> score)
        result.push_back(score);

    return result;
}

double get_average(const std::vector<int>& scores)
{
    int sum = 0;

    for (std::vector<int>::size_type i = 0; i < scores.size(); i++)
        sum += scores[i];

    return static_cast<double>(sum) / scores.size();
}

Well, this just became a very embarrassing situation *cough*. Nevertheless, taking down notes. :P

Edited 5 Years Ago by floatingDivs: n/a

This article has been dead for over six months. Start a new discussion instead.