How would you call a function that returns a value


return value from function
return value from function

The function that returns a value can be called for execution in any one of the following ways:

Function can be called in an expression and the returned value can vet assign to a variable. For example:

X = sum (3, 5) * 10;

In the above assignment statement, the function is called in an expression at the right of assignment operator (=). The above statement will be executed as;


The sum function will be called for executing and control will be transferred to function’s definition with two parameter values.

After executing the statements of function, control returns back to the calling function, the returned value will be multiplied by 10 and the result will be assigned to variable “x”.

Function can be called in an output statement and the returned value can be sent directly to an output device for example, to display the returned value by function directly on the screen, the function “sum” is called as

Printf (“sum =%d”, sum (2,3));

Program example

A program example is given below to compute the cube of a number by using the function

#include <studio . h>
Main (){
Int x, res;
Int cube (int);
Printf(“enter an integer value ?”);
Scanf (“%d”, &x);
Res = cube(x);
Printf(“cube of %d is %d”, x,res);
}
/*cube()function definition*/
Int cube(int n){
Int c;
C = n * n *n;
Return c;
}

In the above program the function cube is called for execution through main () function. The call statement to execute this function is as follows:

Res = cube(x)

The above statement is an assignment statement. When the function is executed, the control will be transferred to the function definition. The value of x will be assigned to “n” in the function definition. The value of “n” is used in te body of function to compute the cube of given number through the statement.

C             =             n * n * n

The calculated result (i.e cube of number) will be assigned to “c”. The return statement will transfer the control back to the calling function along with the value of “c”. The value returned by function will be assigned to variable “res”

The output of program will be as:

Enter an integer value? 3
Cube of 3 is 27

How would you call a function that returns a value How would you call a function that returns a value Reviewed by JD Ahmad on June 18, 2018 Rating: 5

No comments:

Powered by Blogger.