In C++, as in most languages, functions can be created to accept parameters and/or return values. To do this, you just need to specify a type and a name inside the parenthesis. Here is an example:
void printGrade(int grade)
{
cout << grade << endl;
}
int main()
{
int grade = 10;
printGrade(grade);
}
Running that program will print 10 to the screen. One thing to note is that when you pass in an integer parameter, the computer is just creating a copy of the value. This means the original grade variable is not changed or affected. Consider this example:
void printGrade(int grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You may expect this program to print 10, followed by 15. Since a copy of value is created inside the printGrade() function, the value of grade is affected only inside the scope of the printGrade() function. If you need to change the original value inside the printGrade() function, then you must pass the parameters by reference. Here is an example:
void printGrade(int &grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You'll notice in this example, the variable name is preceded with an ampersand. This tells the computer that you want to pass a reference to the grade variable to the function rather than making a copy.
Hopefully this all makes sense!
int average(int gradeArg) {...};and calling it like this:int avg = average(grade);