Home > Mobile >  C Passing a variable to another function
C Passing a variable to another function

Time:12-18

int samuelt1(){
    ela = 80;
    socials = 80;
    total = ela   socials;
    int grade = total / 11.5;
    cout << "Samuel's grade average for term 1 is: " << grade << "%" << endl;
    cout << "Individual Subjects: " << endl;
    cout << "ELA: " << ela << endl;
    cout << "Socials: " << socials << endl;
    return grade;
}

int average(){
    int avg = [samuelt1's grade??] / 1;
    cout << avg;
    return 0;
}

I'd like to pass the grade variable over to the average function; is there a way to do that? Thanks!

CodePudding user response:

In the main function, store the value returned by the function samuelt1 in the variable Grade. Pass Grade as a parameter to the function average, like so

#include <iostream>
using namespace std;

int samuelt1(){
    int ela = 80;
    int socials = 80;
    int total = ela   socials;
    int grade = total / 11.5;

    cout << "Samuel's grade average for term 1 is : " << grade << "%" << endl;
    cout << "Individual Subjects : " << endl;
    cout << "ELA : " << ela << endl;
    cout << "Socials : " << socials << endl;
    return grade;
}

int average(int grade){
    int avg = grade / 1;
    cout << "Average : " << avg;
    return 0;
}

int main(){
    int Grade = samuelt1();
    average(Grade);
}

CodePudding user response:

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!

  •  Tags:  
  • c
  • Related