Function
Function
The subprogram posses a self contain components and have well define purpose.
Advantages of function
It is much easier to write a structured program where a large program can be divided into
a smaller, simpler task.
It is easier to debug a structured program where there error is easy to find and fix
1: #include <stdio.h> Arguments/formal parameter
Function names is cube
2: Variable that are requires is
3: long cube(long x); long
4: Return data type The variable to be passed on
5: long input, answer; is X(has single arguments)—
6: value can be passed to
7: int main( void ) function so it can perform the
8: { specific task. It is called
Actual parameters
9: printf(“Enter an integer value: ”);
10: scanf(“%d”, &input);
11: answer = cube(input);
12: printf(“\nThe cube of %ld is %ld.\n”, input, answer);
13: Output
14: return 0;
15: } Enter an integer value:4
16:
17: long cube(long x)
18: { The cube of 4 is 64.
19: long x_cubed;
20:
21: x_cubed = x * x * x;
22: return x_cubed;
23: }
When function is called the program can send the function information in the form of one
or more argument.
Functions often use data that is passed to them from the calling function
Data is passed from the calling function to a called function by specifying the variables in
a argument list.
Argument list cannot be used to send data. Its only copy data/value/variable that pass
from the calling function.
The called function then performs its operation using the copies.
Function prototypes
Provides the compiler with the description of functions that will be used later in the
program
A return type indicating the variable that the function will be return
Function Definitions
It is the actual function that contains the code that will be execute.
declarations;
statements;
return(expression);
}
Function Definition Examples
float fahrenheit;
fahrenheit = celcius*33.8
return fahrenheit;
This function accepts arguments celcius of the type float. The function return a float value.
So, when this function is called in the program, it will perform its task which is to convert
fahrenheit by multiply celcius with 33.8 and return the result of the summation.
Note that if the function is returning a value, it needs to use the keyword return.
char
int
float
long………
Examples:
There is no data transfer between the calling function and called function.
A calling function can pass values to function called , but calling function not
receive any value
Data is transferred from calling function to the called function but no data is
transferred from the called function to the calling function
A function that does not return any value cannot be used in an expression it can be
used only as independent statement.
4. A function with arguments and returning a values
Argument are passed by calling function to the called function
Data returned by the function can be used later in our program for further
calculation.