What is difference between calling and returning a function.

what is difference between calling a function from Main function and returing value from different function to main function, you get it what l want to ask?

And how can l call this function from main function?

please help

#include<iostream>
using namespace std;
void Avg()
{
int Max_valuue;
int average=0;
int number;
int x=1;
int sum=0;
cin>>Max_valuue;
while(x<=Max_valuue)
{
cin>>number;
sum+=number;
average=sum/Max_valuue;
x++;

}
cout<<average;
}

int main()
{
int res=Avg();
cout<<Avg();

}
As it stands, the function Avg() does not return a value.
You would call the function from main() like this:

1
2
3
4
int main()
{
    Avg();
}


If you would like it to return a value, there are two (well maybe three) changes to be made.

1. change the type void to the type of the value you want to return. It could be int, but for an average, double might be more suitable.

2. Add a return statement to the function which will return the required result.

The 3rd change might be to remove the cout statement.

Here's an example (I modified the function slightly - there's no need to calculate the average inside the loop, do it at the end).

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>

using namespace std;

double Avg()
{
    int Max_valuue;
    int number;
    int x  = 1;
    double sum = 0;
    
    cin >> Max_valuue;
    
    while (x <= Max_valuue)
    {
        cin >> number;
        sum += number;
        x++;
    }
    double average = sum/Max_valuue;
    return average;
}

int main()
{
    double res = Avg();
    cout << "Average is " << res << '\n';
} 



Also see the tutorial for more explanations and examples:
http://www.cplusplus.com/doc/tutorial/functions/
Last edited on
calling a function from Main function

Note: while main() is a bit special, it is not special in this. Any function can call other functions.

For example, your Avg() calls functions:
cin >> Max_valuue; contains a function call, because that operator>> is actually a function. A member function of a class, for cin is an object whose type is not a primitive like char, int or double.

(There are also standalone operator>> functions, and a bitshift operator>> that is not a function.)



[EDIT]
Fascinating.
Your previous thread saw functional code http://www.cplusplus.com/forum/beginner/224759/#msg1028034
It is good that you don't blindly copy-paste.
It is not so good that your own attempts deviate quite much from examples.
Last edited on
Topic archived. No new replies allowed.