Functions for programming
Functions for programming
Words like module, subroutine, function are synonymously used to imply the
same concept originating from the idea called structured programming
concept where programs are written following some sets of procedures well
organised to make programming experience easy. Benefits include program
readability, write-ability, reusability, maintainability and so on.
There are 4 functions here, the main() function, f1(), f2() and f3(). main() calls
f1 and f2(), while f2() can also call f3() as the case may require. We do not
want to cram all these tasks into main() alone anymore as we used to do in
the elementary coding class.
A scenario of how f2() may need f3() is this: If function main() calls f2() to
action where f2() needs f3() before it can carry out its entire duty. It simply
means that part of f2() duty is delegated to f3(). And this sub-task is
delegated to f3() so that f2() is not also crammed up with many things. For
instance, if f2() is to fetch students with CGPA of 4.0 and above but should
present the result sorted. f3() could be the sort function doing the sorting
after f2() has fetched the list. You do not have to write a sorting routine inside
Declaring and Defining a function :
1. void displayInfo()
2. {
3. printf(”\n Welcome to the Input Segment”);
4. printf(”\n Please Enter Your Input Value”);
5. printf(”\n Note That Input is within 0-10”);
6. }
• The first line which declared the function is called function header; comprising
2 words, function return type (void) and function name (displayInfo()).
• displayInfo():
This is the name you chose to give the function, followed by a pair of empty
brackets. If there is a need to send information or pass value into a function,
then the pair of brackets will not be empty but will contain the information.
This is the input avenue or medium to the function. Information passed to it
are referred to as parameters during function definition/declaration. These
information or values must also be declared using their data types. For
example, a function to receive a value for factorial is expecting an integer so
it could be defined as follows: int factorial(int n){….}
Declaring a function in C
C language demands that functions may be declared before use especially if you
intend to write the function anywhere in the program. It may not be necessary if the
functions are defined and seen ahead by the program before use. The culture of
declaring a function is simple to follow. Just the same way you declare a variable
before use, you also declare a function before use. The simple way to declare a
function is to copy the function definition header only and add a semicolon as follows:
void displayInfo(); // function now declared
int main()
{
void displayInfo(); // function now declared inside main, seen by main alone
int I, j, count; // other variables local to main() function
----
----
return 0;
}
#include <stdio.h>
void displayInfo(); /* function declared outside main(); now global function
accessible by other functions as well as main() function*/
int main()
{
int I, j, count; // other variables local to main() function
----
----
return 0;
}
Calling a function:
• void main()
• {
• …
• displayInfo(); /* function is called here. The benefit is that you
• need not re-write the 3 lines of code executed by this function
• anytime you want to achieve the same task, just call the function.
*/
•
• scanf(“%d”, &hour);
• …
• }// end of function main()
• void displayInfo()
• {
• printf(”\n Welcome to the Input Segment”);
• printf(”\n Please Enter Your Input Value”);
• printf(”\n Note That Input is within 0-10”);
• }// end of function displayInfo()
Program Example:
24) return 0;
25) }
Calculator: Implementation..contd..
26) // defining the function
27) // values in a and b are sent to x and y as inputs
28) int addition(int x, int y)
29) {
30) int add;
31) add = x+y; //the 3 lines could be summarised
32) return add; //to a line as: return x+y;
33) }
• void main()
• {
• float price, tax, result;
• Scanf(“%f”; &price);
• Scanf(“%f”; &tax);
• result = price * ( 1 + tax /100);
• pintln(“Cost After Tax = %f “, result);
• }
• We can create a function to perform the same calculation to enable us to call the
function at various points in the program where the calculation could be done using
different values passed to the function per each call. This gives the advantage of
code reusability. See below:
• float addTax(float price, float tax)
• {
• float answer;
• answer = price * ( 1 + tax /100);
• return answer;
• }
• The above function is named addTax and it is of type float (return type)
• The variables(price and tax) declared as float within the bracket are called formal
parameters.
• Formal Parameters: are variables created exclusively to hold values sent in from the
calling function(caller). They hold the values of data sent in the order with which
there are arranged in the function parameter declaration. i.e. price first, then tax
second.
PARAMETERS AND PARAMETER PASSING:
This arrangement must be the same with where the function is called. That is,
same order, same variable types and same quantity(number of parameters
passed). Formal parameter variables can answer any name apart from the one
used at where the function is called. What is important is the order of
arrangement and type. The parameter names at the function declaration does
not depend on the name you give the function parameters where it is called. It
means being “formal”, they can receive any value passed as far as the order and
type are not compromised. For now, parameter are said to be passed by value.
In the code above, variable answer is declared float inside the function addTax.
This is called a local variable as far as its scope is concerned. When a variable is
local to a function, it means it is known or valid within that function. For
example, answer is not known to main function in the example below. Similarly,
variable result is local to the main function and is not equally known to function
addTax.
The keyword return ends the function. The function terminates as soon as the
program reaches this point. The keyword return is used to send the result of
computation back to the caller. The control jumps back to the calling function
sending back a value i.e. the result of the computation. Any code written after it
becomes unreachable and that gives a compilation error.
MAKING YOUR OWN FUNCTIONS(USER-DEFINED FUNCTIONS)
1) #include <stdio.h>
2) int main()
3) {
4) float price, tax, result; //variable declarations
5) float addTax(float vprice, float vtax); // function declared
Actual Augment
6) printf("\n Enter the value of Price:");
7) Scanf(“%f”; &price); Line 10 represents a call to addTax()
8) printf("\n Enter the value of Tax:"); function. Here, parameters are passed
9) Scanf(“%f”; &tax); by values, the value of price and tax are
10) result = addTax(price, tax); // call; sent to the function. At line 10, these
11) printf(“Cost After Tax = %f “, result); are called actual argument because a
12) return 0; copy of what is read into price and tax
13) } are passed (to be used by the function
14) // vprice = price = 10.5 outside main()).
15) float addTax(float vprice , float vtax)
16) {
17) float answer; Formal parameter
18) answer = vprice * ( 1 + vtax/100);
19) return answer;
20) }
// SOLVING FOR FACTORIAL USING ONLY MAIN FUNCTION
1) //A C code using iterative procedure to find n! //5! = 5*4*3*2*1 or 1*2*3*4*5
2) #include <stdio.h>
3) int main()
4) {
4) int main()
5) {
6) int n, option; //variable declarations
7) int factorial(int n); //factorial function declared inside main function
8) printf("\nEnter 1 for factorial: \n2 for Square:"); 23) }//factorial function definition
9) scanf("%d", &option); 24) int factorial(int n)
10) printf("\nEnter the value of n:"); 25) {
11) scanf("%d", &n); 26) int i, mult = 1;
12) //selection structure used for user’s choice 27) for(i=1;i<=n;++i)
13) switch(option)
28) {
14) {
15) case 1: printf("\nFactorial of %d = %d",n, factorial(n)); 29) mult = mult*i;
16) break; 30) }
17) case 2: printf("\n Square of %d = %d",n, square(n)); 31) return mult;
18) break; 32) }
19) default: printf("\nValue out of range:"); 33) //square function definition
20) } 34) int square(int n)
21) return 0;
35) {
22) }
36) //operation reduced to a line
37) return n*n;
38) }
/* PROGRAM TO SHOW HOW TO REUSE ALREADY WRITTEN USER-
DEFINED FUNCTIONS ( E.G. FACTORIAL AND SQUARE OF A NUMBER )*/
5) int main()
6) {
7) int x, n;
8) printf("\nEnter the value of x:");
9) scanf("%d", &x);