Guys,

I could really use some direction in getting this console program working for a C++ assignment. I'm in my 8th week and although I've been doing good on past projects, this is a multiple file assignment and I'm confusing myself the more I try to understand. I feel like a complete idiot when I read about other people problems and they are WAY over my head most times and I'm stuck on this elementary project.

Background: Write a program that asks the user to input a series of five numbers. Then, average these numbers and output the results. You must have a function called average that is used in main but has a separate average.h file and an average.cpp file associated with it and included into the main program.

The instructions included in the textbook and the instructor's minimal handout on this isn't making the process very clear to me. My .h, and both .cpp aren't making a connection; 99.9% sure it's my coding. Anyway, I'm getting these 2 errors:

1. NumbersInput: undeclared identifier ( althought I believe I declared in AvgFunc.cpp file

2. average" function-style initializer appears to be a function definition. (no idea what this means)

Here are my files, (don't laugh, lol)

AvgFunc.h

#include<iostream>
using namespace std;
int average (int num);

AvgFunc.cpp

#include "AvgFunc.h"

using namespace std;

int average(numbersInput)
{
	int numbersInput, avg;
	cin >> numbersInput;
	avg = numbersInput / 5;
   
return avg;
}

Main.cpp

#include "AvgFunc.h"

int main()
{

int num, avg;

	cout <<"This program will average a group of 5 numbers of your choice." <<endl;
	cout <<"\n\nPlease enter 5 numbers: " <<" "<<endl;

	cin >> num;
	cout <<"The average of the numbers you entered is: "<<avg <<endl;

cin.get();
return 0;
}

Please be gentle with me, lol, but how many things am I doing wrong?

You are close actually.. it's really not that horrible.

Look at average in the .h file, and then at average in the .cpp file.
Now think of it from the compiler perspective, it sees int average( int something ); in the header file, so a function that takes an int and returns an int.

In the .cpp file, it finds int average( numbersInput ); here it has no idea what 'numbersInput' is.. and then in the function body you define numbersInput again by saying 'int numbersInput'.

So the way this works is you need to synchronize the header and the cpp file, except for the argument names, so for example:

.h file:
int average  ( int );
int average2( int thisIsAnIntVariable );
int average3( int myInt );
.cpp file:
int average ( int ) { return 4; }  // Illegal, don't know the name of the variable
int average( int myInt ) { return myInt; } // OK
int average2( int myInt ) { return myInt; } // OK (var names dont need to match)
int average3( double myDouble ) { return 4; } // ERROR

Hope that helped.

Ok, here is the deal. Do you know how to do this with 1 file ?
For example in 1 file, you would do this :

//main.cpp
#include <iostream>
using namespace std;
float calcAverage(int inputs[], const int size); // [1] function prototype
int main(){
 const int NUM_OF_INPUTS = 5;
 int inputs[NUM_OF_INPUTS] = {0};
 for(int i = 0; i < NUM_OF_INPUTS; ++i){
     cin >> inputs[i]; //get the 5 numbers from user
  }
 cout << "Average = " << calcAverage(inputs, NUM_OF_INPUTS) << endl;
}
float calcAverage(int inputs[], const int size) // [2] function definition{
 int sumOfTotalInputs = 0;
 for(int i = 0; i < size; ++i){
   sumOfTotalInputs += inputs[i]; //get the total sum
 }
 //calculate the average, notice average is of type float
 float average= float(sumOfTotalInputs) / size; 
}

Now all you need to do is split the code up, so for example you could do this :

//average.h
void calculateAverage(int inputs[], const int Size); //[1]function prototype
//
//average.cpp
void calculateAverage(int inputs[], const int Size){ //[2] function defintion
  //... code to calculate averge given the array of numbers and its size
}
//main.cpp
int main(){
 const int NUM_OF_INPUTS = 5;
 int Array[NUM_OF_INPUTS] = {0};
 //get inputs from array
 cout << "Average = " << calculateAverage(inputs,NUM_OF_INPUTS)  << endl;
}

Thanks thelamb & firstPerson for taking the time to help me out. However, I am still doing something wrong. Some of the errors I'm getting almost seem that the process wants me to (re)declare my variables in Main.cpp. It as though the variable declarations I have in average.cpp aren't recognized or something. I thought that defeats the purpose of multiple files?

They also say I'm missing " ; " (when I don't think I am), and that I have undeclared identifiers still. I'm getting confused on where to declare these.

Here are my files again:

average.h

#include<iostream>

using namespace std;

float calculateAverage (int numberInputs[], const int size);  //function prototype

average.cpp

#include "average.h"

using namespace std;

float calculateAverage(int numberInputs[], const int size) //function definition 
{
	int sumOfTotalInputs = 0;
	int i = 0;
	int avg;

	sumOfTotalInputs += numberInputs[i]; //calculation to get the total sum of numbers from user
	avg = sumOfTotalInputs / size;  //to find average 

    return average;
}

Main.cpp

#include "average.h"

using namespace std;

int main()
{

const int NUMBER_OF_INPUTS = 5;
int [NUM_OF_INPUTS] = [0];


cout <<"This program will average a group of 5 numbers of your choice." <<endl;
cout <<"\n\nPlease enter 5 numbers: " <<" "<<endl;
cin >> numberInputs[i];

	for (int i = 0; i < NUM_OF_INPUTS; i++)
	{
		cin >> numberInputs[i];
	}

cout <<"The average of the numbers you entered is: "<<calculateAverage (numberInputs, NUM_OF_INPUTS) <<endl;

cin.get();
return 0;
}

Ok you need to understand 'locality' of a variable.

Your numberInputs is an argument to the function calculateAverage, correct? This means that when you call the calculateAverate function, you will hand over a value for the numberInputs, this value will then be available for use in the calculateAverage function.

I think it's best I write a small example:

int increase( int myInt )
{
    return myInt + 1;
}

int main()
{
    int myInt = 1;              // int variable that is avaiable to main.
    int mySecondInt;        // another int variable that is available to main.
    mySecondInt = increase( myInt );  // hand over the myInt from main to increase and store the result of the function in mySecondInt

}

Note how I am able to use a variable called 'myInt' in both the increase function and in main, the reason is that they are in completely different 'scopes'.

If you make a variable global however, it will be available to all functions:

int myGlobalInt;
void increaseGlobalInt()
{
    myGlobalInt++;
}

int main()
{
   myGlobalInt = 6;
   increaseGlobalInt();
}

Let's write up another example and see what you think will happen:

int main()
{
   int myFirstInt = 1;
   {
          int mySecondInt = 2;
          myFirstInt = myFirstInt + mySecondInt;
    }

   cout << "First int: " << myFirstInt << "\n";
   cout << "Second int: " << mySecondInt << "\n";
}

Your average.h is Good, nice job.

Now your average.cpp, has a logic error. Think of average.h like it declares
a function prototype. And average.cpp actually defines these functions.

The logic error in your average.cpp :

#include "average.h" //good

using namespace std; //does not need this since average.h already has this, but is a good practice

float calculateAverage(int numberInputs[], const int size) //function definition  //good now you define the function you declared in average.h
{
	int sumOfTotalInputs = 0; 
	int i = 0;
	int avg;
       /*--------Below is your logic error--------------------*/
	sumOfTotalInputs += numberInputs[i]; //calculation to get the total sum of numbers from user
       /*----------------------------------------------------------*/
	avg = sumOfTotalInputs / size;  //to find average 

    return average;
}

the place where I marked logic error is your first problem. You need to go through the loop and add up all the values like so :

for(int i = 0; i < size; ++i){
 sumOfTotalInputs += numberInputs[i];
}

Now your other problem is inside your main.
This code

int [NUM_OF_INPUTS] = [0];

is not how to declare an array, this is how you declare an array :

int Array[NUM_OF_INPUTS] = {0};

Then you do not need this part in your main, just delete it :

cout <<"This program will average a group of 5 numbers of your choice." <<endl;
cout <<"\n\nPlease enter 5 numbers: " <<" "<<endl;
//cin >> numberInputs[i]; //<--- do not need this , you have it inside you for loop

Fix those and you will be better.

BLKelsey,

I could point out some of the problems in your C++, but that would not help you when it comes to your next assignment (or even your next compilation error in this assignment). What you need to do is learn how to approach these problems.

Here are some tips:

1) Look at what the compiler is telling you. Look at the line on which you get the first error message. Ignore everything else - compilers are simple beasts and get confused after the first error. Fix the first error then recompile.

2) Its not magic. Every line of code means something. Don't copy code you don't understand. Look it up!

3) Develop your programs incrementally. Start with a simple program, and add features. Suggested steps for your program are (and this exactly is what I would do if I was asked to code this up in an unfamiliar language):

* a main program that prints "hello world".

* a main program that reads one integer and prints it.

* a main program that reads five integers and prints them all.

* a main program that reads five integers and prints the average.

* take out the averaging into a separate function.

* take out the averaging function into separate .cpp and .h files.

Test each stage before progressing to the next. You won't need that many stages next time!

commented: Nice 1st post +5

Thanks thelamb for continuing to help me. In your example below, the results I expect to see are:

First int to be 3 (since you are adding both int values into myFirstInt)
Second int to be 2 (remained unchanged)


Let's write up another example and see what you think will happen:

int main()
{
   int myFirstInt = 1;
   {
          int mySecondInt = 2;
          myFirstInt = myFirstInt + mySecondInt;
    }

   cout << "First int: " << myFirstInt << "\n";
   cout << "Second int: " << mySecondInt << "\n";
}

dgwsoft,

I appreciate your help in this also. I usually am able to finish my programming assignment by Friday of each week. However, this week, a team assignment was due in my Software Development Lifecycle class. I'm team leader and my two teammates aren't pulling any of their weight, so I had to complete that assignment (plus the individual assignment) all this week.

Just being pushed for time this week has made me pretty nervous because the assignment is due REAL quick. However, I DO appreciate your tips on approaching incremental development and intend to put your suggestions into my folder for future use / reminders.

Thanks again.

BLKelsey,

I could point out some of the problems in your C++, but that would not help you when it comes to your next assignment (or even your next compilation error in this assignment). What you need to do is learn how to approach these problems.

Here are some tips:

1) Look at what the compiler is telling you. Look at the line on which you get the first error message. Ignore everything else - compilers are simple beasts and get confused after the first error. Fix the first error then recompile.

2) Its not magic. Every line of code means something. Don't copy code you don't understand. Look it up!

3) Develop your programs incrementally. Start with a simple program, and add features. Suggested steps for your program are (and this exactly is what I would do if I was asked to code this up in an unfamiliar language):

* a main program that prints "hello world".

* a main program that reads one integer and prints it.

* a main program that reads five integers and prints them all.

* a main program that reads five integers and prints the average.

* take out the averaging into a separate function.

* take out the averaging function into separate .cpp and .h files.

Test each stage before progressing to the next. You won't need that many stages next time!

One little thing: it seems "size" is not the proper parameter to use as the 2nd parameter in Main.cpp as it's a formal parameter in funcAverage.cpp. I didn't think it would work in Main since it's not an actual parameter during the calcAverage call.

However, it now compiles completely without errors and let's me enter the 5 numbers, but when I hit "enter", the console closes without reaching (or performing) the funcAverage call. I'm just learning about arrays and multiple file construction so my logic is still a bit fuzzy but along with all of your help and advice, it's coming along nicely.

So, my question is what constitutes the parameters in the function call in Main? I thought it would be the parameters as IN the function declaration.

average.h

/*=========================*/
//  Function Declaration   //
/*=========================*/


#include<iostream>

using namespace std;

float calcAverage (int numberInputs[], const int size);

funcAvg.cpp

/*==========================*/
//   Function Definition    //
/*==========================*/


#include "average.h"


float calcAverage(int numberInputs[], const int size) 
{
	int sum = 0;
	int i = 0;
	float average = sum / size;  //to find average

	for (int i = 0; i < size; ++i)
	{
		sum += numberInputs[i]; //calculation to get the total sum of numbers from user
	}
	return average;
}

Main.cpp

#include "average.h"
                       
using namespace std;      
                    
int main()
{
int numberInputs [5];
int userInput;
int size = 5;     // not sure if this is necessary. Takes place of const int size in average.h?

cout <<"This program will average a group of 5 numbers of your choice." <<endl;
cout <<"\n\nPlease enter 5 numbers: " <<" ";
cin >> userInput;
cout <<"\nThe average of the numbers you entered is: ";
cout << calcAverage(numberInputs, size) <<endl;            /*--------------------------------------------/
											                //  not sure what to put as second parameter //
                                                           /*-------------------------------------------*/

cin.get();
cin.get();
return 0;
}

Well, I guess I got the 2nd parameter error to stop complaining but now it says, "the variable average is being used without being initialized." On a better note, I got it to read the next cout statement that says, cout << "The average of the numbers you entered is: "; but that's when I get the "average not being intialized" error. I declared it in funcAvg.cpp but how do I initialize it? I cant initialize it to 0 or any number. When I do, the console closes after I enter 5 numbers and hit ENTER. If I don't initialize it, I at least can get it to read the next cout statement.

Can somebody explain why I'm getting this error?

Here is my latest funcAvg.cpp (both average.h & Main.cpp remain unchanged from above).

funcAvg.cpp

/*==========================*/
//   Function Definition    //
/*==========================*/


#include "average.h"


float calcAverage(int numberInputs[], const int size) 
{
	int sum = 0;
	int i = 0;
	float average;
	
	for (int i = 0; i < size; ++i)
	{
		sum += numberInputs[i]; //calculation to get the total sum of numbers from user
		float average = sum / size;  //to find average
	}
	
	return average;  // <---- statement ERROR is found: "the variable 'average' is being used without being initialized."
}
}

Look closely at my previous posts, I posted a code snippet there and asked you what you think would happen... you shouldn't just ignore that :P But here we go again:

int main()
{
     float myFloat = 0;
     {
          float myFloat2 = 5;
          myFloat = myFloat + myFloat2;
     }
     cout << "myFloat: " << myFloat << "\n";
     cout << "myFloat2: " << myFloat2 << "\n";
}

And another one to think about:

int main()
{
     float myFloat = 0;
     float myFloat2 = 3;
     {
          float myFloat2 = 5;
          myFloat = myFloat + myFloat2;
     }
     cout << "myFloat: " << myFloat << "\n";
     cout << "myFloat2: " << myFloat2 << "\n";
}

What do you think (without trying to run it) will be the output in the 2 cases?

Oh no sir, I didn't ignore your first code snippet example:

Here what I said:

Thanks thelamb for continuing to help me. In your example below, the results I expect to see are:

First int to be 3 (since you are adding both int values into myFirstInt)
Second int to be 2 (remained unchanged)


Look closely at my previous posts, I posted a code snippet there and asked you what you think would happen... you shouldn't just ignore that :P But here we go again:

int main()
{
     float myFloat = 0;
     {
          float myFloat2 = 5;
          myFloat = myFloat + myFloat2;
     }
     cout << "myFloat: " << myFloat << "\n";
     cout << "myFloat2: " << myFloat2 << "\n";
}

And another one to think about:

int main()
{
     float myFloat = 0;
     float myFloat2 = 3;
     {
          float myFloat2 = 5;
          myFloat = myFloat + myFloat2;
     }
     cout << "myFloat: " << myFloat << "\n";
     cout << "myFloat2: " << myFloat2 << "\n";
}

What do you think (without trying to run it) will be the output in the 2 cases?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.