what is function in c
The C programming language is related to most contemporary programming languages in that it agrees to the use of functions, self-controlled modules of code that receive inputs, perform computation, and generate outputs. A function is defined as “A function is a block of code that performs a particular task”. Every C program has at least one function, which is main(), and all the most trivial programs can define supplementary functions. We can break up or divide up our code into separate functions.
Actually, how we divide up our code among dissimilar functions is up to our concept, but logically the partition is such that each function performs a definite task. C functions are fundamental building blocks in a program. Generally C programs are written using functions to improve re-usability, understandability and to keep track on them. Elaborately we also say that “A function is a section of code that takes information does some calculation, and returns a new piece of information based on the parameter information. C language provides an approach in which you need to declare and define a group of statements once and that can be called and used whenever required.
TYPES OF FUNCTION
In C, functions can be classified into two types such as:
♦ Library functions
♦ User defined functions
Library functions
Library functions are those functions which are defined by C library. For example printf(), scanf(), strcat(), strlen(), gets(), puts(), sqrt() etc. If we want to use library function we just need to include appropriate header files to use these functions. These are already declared and defined in C libraries.
User defined functions
C allows programmer or user to define their individual function according to their prerequisite. These types of functions are known as user-defined functions. User defined functions are those functions which are defined by or developed by the user at the time of writing program. The most important difference between library functions and user defined functions is that library functions are not required to be written by programmer or user, on the other hand a user defined function has to be defined or developed by the programmer or user at the time of writing a program.
We mentioned earlier, a function is a block of code that performs a particular task. We can either use the built-in library functions or we can create our own defined functions. In every C program must have a main function to designate where the program has to start its execution. While it is probable to code any program utilizing only main function, it leads to a number of problems.
In practical, if the program may become too large and difficult then the task of debugging, testing and maintaining becomes difficult. In this case, if a program is divided into more than one functional part, then each part may be separately coded and later combined into a single unit. For removing these complexity of a program we need user define function. Actually user defined functions are extremely necessary for complex programs.
Necessity of user defined function as follows:
1. User defined function provides modularity to the program.
2. The piece of a source program can be reduced by using user defined functions at proper places.
3. It is easy to locate and segregate a defective function for further exploration.
4. User defined functions helps to decompose the large program into small segments which makes programmer easy to understanding, maintaining, debugging and testing.
5. It is easy to code reusability. We just have to call the function by its name to use it from anywhere of a program.
6. A user defined function may be used by many other programs.
FUNCTION PROTOTYPE OR DECLARATION
User defined functions that a programmer writes will generally require a prototype. In programming, a function prototype is a declaration of a function that specifies the function's name and type signature or arguments and return type, but omits the function body. The function prototype gives basic structural information such as (i) It tells the compiler what the function will return, (ii) What the function will be called, and (iii) what arguments the function can be passed. Function prototype is declared before it is defined in a program. Generally it is typed before main function of a program.
The general format for a function prototype or declaration is:
return-type function_name ( data_type arg_1,data_type arg_2 ..., data_type arg_N );
Here, data_type means the data type of arguments or parameters such as int, float, double, char etc. and arg_1, argu_2… arg_N means that how many arguments or parameters are defined in the parameter list.
There can be more than one argument passed to a function or none at all, and also a function does not have to return a value. Functions that do not return values have a return type of void. Let's look at a function prototype or declaration
int addition( int num1, int num2 );
In this declaration or prototype example specifies that the function addition will accept two arguments, both are integers, and function will return an integer type value. Here, do not forget the trailing semicolon (;). Without semicolon the compiler will possibly think that you are trying to write the actual definition of the function.
FUNCTION DEFINITION SYNTAX
The general form of function definition syntax in C programming language is as follows:
return-type function_name( parameter list )
{
function-body
}
In the function definitions, the first line return-type function-name(parameter list) is known as function header and the statement within curly braces { } is called function body. Function body is combination of more than one statement.
We will describe all the parts of a function as follows:
1. return-type: A function may return a value. The return-type is the data type (int, float, char, double) of the value the function returns. If a function performs the desired operations without returning a value, then the return_type is the keyword void.
2. function-name: function name specifies the actual name of a function. The function name is any valid C identifier and therefore must follow the same rule of formation as other variables in C.
3. parameter list: The parameter list declares the variables that will receive the data sent by calling program. A parameter is like a placeholder. When a function is invoked, we pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. These parameters are also used to send values to calling program.
4. function-body: The function body contains a collection of statements and declaration of variables that define what the function does. The body is enclosed within curly braces { } and consists of three parts.
♦ Local variable declaration.
♦ Function statement that performs the tasks of the function.
♦ A return statement that return the value evaluated by the function.
Example:
Given below is the source code for a function called summation(). This function takes two parameters value1 and value2 and returns the summation of two values.
/* function returning the summation of two values */
int summation(int value1, int value2)
{
int result; /* local variable declaration */
result= value1+value2
return result;
}
HOW USER-DEFINED FUNCTION WORKS IN C PROGRAMMING?
We mentioned earlier, that every C program starts from main() function and program starts executing the codes inside main() function. When the control of program reaches to function name inside main() function the control of program jumps to function definition part and executes the codes inside it. When all the codes inside that user-defined function are executed, control of the program jumps to the statement just after function name from where it is called.
FUNCTION CALLING
In C program, whereas creating a function, we give function definition of what the function has to do. To use a function, we will have to call that function to perform the defined task. A function can be called by using the function name in a statement of program.
Example:
Given below is example of a function calling process:
void main()
{
int mulvalue;
mulvalue = multiplication(20,5);
printf(“%d”, mulvalue);
}
When a program calls a function, the program control is transferred to the called function. In the above example, when the compiler encounters a function (multiplication(20,5)) call, the control is transferred to the function multiplication(x,y) which is already defined in program. This function is then executed and returns a value when a return statement is encountered and then the return value is stored or assigned to mulvalue variable.
CATEGORY OF FUNCTIONS
We have already known that, when we write large difficult programs, it becomes difficult to maintain track of the source code of a program. The work of functions is to divide the large program to many separate modules based on their functionality. So a function depending on whether arguments are present or not and whether a value is returned or not, may belong to one of the following categories:
1. Function with no arguments and no return value
2. Function with no arguments and return value
3. Function with arguments and no return value
4. Functions with arguments and return value
FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUE
When a function has no arguments, it does not receive data from the calling function as well as when it does not return value, the calling function does not receive data from the called function. If a function does not return value, we may be used keyword void as return type. The general syntax of this type of function is as follows:
void function_name( )
{
…………………………
Statements or function body
…………………………
}
FUNCTION WITH NO ARGUMENTS AND RETURN VALUE
When a function has no arguments but it may return a value so, we may be used return type. The general syntax of this type of function is as follows:
return_type function_name( )
{
……………………………
Statements or function body
…………………………..
…………………………..
return variable-name/value
}
Here, return_type is data type name which is returned by function. In this type of function after complete all statements of function; the keyword return with value or variable name may be used which is shown in syntax.
FUNCTION WITH ARGUMENTS AND NO RETURN VALUE
In this type of function category a function takes arguments from calling function but it does not return value. In this case, we could make the calling function to read data from the user or terminal and pass it on to the called function.
The general syntax of this type of function is as follows:
void function_name(arguments/parameters)
{
…………………………………
Statements / function body
………………………………..
……………………………….
}
Function With arguments and Return Value
In this type of function category a function takes arguments from calling function and it returns a value to calling function. So in this case, a variable must be used to receive value which is returned form called function. In this category, we could make the calling function to read data from the user or terminal and pass it on to the called function.
The general syntax of this type of function is as follows:
return_type function_name(arguments/parameters)
{
…………………………………
Statements / function body
………………………………..
……………………………….
return value/ variable name;
}
Recursive function in c
In programming language, recursion is a technique or process to calling a function repeatedly. In general, recursion is nothing more than a function that calls itself. When a function calls itself, this type of function is called recursive function. The majority computer programming languages support recursion by allowing a function to call itself within the program text. In programming language, while using recursion, programmers need to be careful to define an exit condition from the function; otherwise it will go into an infinite loop. Therefore, every recursive function must be provided with a way to end the recursion. Recursive functions are very helpful to explain and solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, summation of n numbers etc. Consider the following example to understand the recursion technique, where the program to calculates sum of first n numbers using recursion.
#include <stdio.h>
int summation(int n);
void main( )
{
int number,add;
printf("Enter a positive integer:\n");
scanf("%d",&number);
add= summation (number);
printf("summation of numbers: %d",add);
}
int summation (int n)
{
if(n==0)
return n;
else
return n+ summation(n-1); /*self call to function summation() */
}
Output
Enter a positive integer:
6
summation of numbers: 21
In, this example, summation( ) function is invoked from the same function. If n is not equal to 0 then, the function calls itself passing argument 1 less than the previous argument it was called with. Suppose, user enter the value of n is 6 initially. Then, during next function calls, 5 is passed to function and the value of argument decreases by 1 in each recursive call. When, n becomes equal to 0, the value of n is returned which is the summation of numbers from 6 to 1. So the result will be 21.
For better visualization of recursion in this example is shown in bellow step by step wise:
summation(6)
=6+ summation (5)
=6+5+ summation (4)
=6+5+4+ summation (3)
=6+5+4+3+ summation (2)
=6+5+4+3+2+ summation (1)
=6+5+4+3+2+1+ summation (0)
=6+5+4+3+2+1+0
=6+5+4+3+2+1
=6+5+4+3+3
=6+5+4+6
=6+5+10
=6+15
=21
ADVANTAGES AND DISADVANTAGES OF RECURSIVE FUNCTIONS
Advantages of recursive functions are as follows:
1. Recursion is well-designed and requires few variables which make program clean.
2. It is used to avoidance of unnecessary calling of functions.
3. It is used to as a substitute for iteration where the iterative solution is very complex. For instance to reduce the code size for Tower of Honai application, a recursive function is best suited.
4. Recursion tremendously useful when applying the same solution.
5. Recursion can be used to replace complex nesting code by dividing the problem into the same problem of its sub-type.
6. It is very flexible in data structure such as stacks, queues, linked list and quick sort.
7. The length of the program can be reduced by using recursion technique.
Disadvantages of recursive functions are as follows:
1. Recursion technique is hard to think the logic of a recursive function.
2. It is also difficult to debug the code containing recursion.
3. It needs extra storage space.
4. This type of function is not efficient in execution speed and time
LOCAL AND GLOBAL VARIABLES
We have already known that C allows us to create functions of some sort and also known that functions are used to break up large programs to overcome the program complexity. In programming language, the variables can be categorized depending on the place of their declaration, as internal (i.e., local) or external (i.e., global). A local variable is a variable that is declared inside a particular function. Local variables are also referred to as automatic variables or internal variables. Local variables are declared inside a function and they are created when the function is called and automatically destroyed when the function is exited. Hence, they are called automatic.
Local variable example is shown in below:
main( )
{
int number;
…………
Myfunction( );
}
void Myfunction( )
{
float area;
int value;
……………
}
We can also use the keyword auto to declare automatic/local variables explicitly as follows:
void Myfunction( )
{
auto int value;
…………….
}
In this case, one significant characteristic of automatic variables is that their value cannot be changed
accidentally by what happens in other functions in the program. For this reason, we can declare and use
the same variable name in different functions in same program without causing any puzzlement to the
compiler.
The following illustration shows that how automatic or local variables work in a program:
#include<stdio.h>
#include<conio.h>
void valuetest1( );
void valuetest2( );
void main( )
{
clrscr();
int num=2000;
valuetest2( );
printf(" %d\n",num);
getch();
}
void valuetest1( )
{
int num=20;
printf(" %d\n",num);
}
void valuetest2( )
{
int num=200;
valuetest1( );
printf(" %d\n",num);
}
…………………………………………………………………………
Output
20
200
2000
In this above program has two functions valuetest1( ) and valuetest2( ). This program, num is local variable and it is declared at the beginning of each function. It is (i.e., num variable) initialized to 20,200, and 2000 in valuetest1( ), valuetest2( ) and main function respectively. When executed this program, main calls valuetest2( ) which also calls valuetest1( ). When main is active, then num=2000; but when valuetest2( ) is called, the main’s function num is temporarily put on the shelf and the new local variable num =200 becomes active. Similarly when valuetest1( ) is called, both the previous values of num are put on the shelf and the latest value of num =20 becomes active. As soon as valuetest1()(num=20) is finished , valuetest2( )(num=200) takes over again then, main(m=2000) takes over. For these reasons, the value assigned to num is one function does not affect its value in the other functions and the local value of num is destroyed when it leaves a function. The clear outputs are shown in illustration.
On the other hand, a global variable is a variable that is declared outside all functions. Global variables are also referred to as external variables. It is good practice to declare global variable before main function. Global variables are both alive and active throughout the entire program. For this reason, global variables can be accessed by any function in the program. Once a variable has been declared as global, any function can use it and change its value and then successive functions can reference only that new value.
For instance, the external or global declaration of integer number and float area might appear as:
……………
int number;
float area;
main()
{
…………
…………
}
valuetest1( )
{
………
………
}
valuetest2( )
{
………
………
}
Here, the variables number and area are available for use in all the three functions such as main, valuetest1, valuetest2. If a local variable and a global variable have the same name, in this case, the local variable will have precedence over global variable in the function where it is declared. Consider the following illustration:
……………
int value;
main( )
{
value=10;
…………
…………
}
void valuetest( )
{
int value=20;
…………
…………
value=value+2;
}
Here, we have seen that, global and local variable name (value) is similar. When the valuetest( ) references the variable value, it will be referencing only its local variable, not global variable one. The value of value variable in main function will not be affected.
SCOPE AND LIFE TIME OF VARIABLES IN FUNCTION
We have already studied that how global and local variables are worked in function. In this section we will study about scope and life time of variables in function. Scope is the area where a variable can be accessed is known as scope of variable on the other hand life time is the time period for which a variable exists in the memory is known as lifetime of variable.
Actually, the scope and life time of a variable depends on the location where a variable is declared. Therefore, according to their declaration, variables are classified into the following three (03) categories:
1. Block variables
2. Local or internal variables
3. Global or external variables
Block variables
When variables are declared within a pair of braces { } this procedure is called block variables. A block { } may be a self-governing with any control structure but, not with a f. Consider the following statements of block variable declaration procedure:
……………………
……………………
{
/* independent block */
}
if(x<y)
{
/* block with control structure */
}
Scope of block variables
It is notify that, block variables can be accessed within the block in which they are declared and can also be accessed into the inner block which is within the current block but, can’t be accessed outside the block. Following illustration is shown scope of block variables:
#include<stdio.h>
int main()
{
…………
{ /*outer block*/
int p=20;
{ /*inner block*/
printf(“value of p= %d”,p);
}
printf(“\n value of p= %d”,p);
}
return 0;
}
…………………………………………………
Output
value of p=20
value of p=20
Here p variable is declared in the outer block, disappears only when control come out the outer block.
Hence, it is available for both inner and outer blocks.
Life time of block variables
In this declaration block variables come into view as the control enters into the block and disappears as
the control go out of the block. Hence these variables can’t be accessed outside the block.
#include<stdio.h>
int main()
{
if(20<30)
{
int p=10;
printf("p=%d",p);
}
printf("\np=%d",p); /* can't be accessed */
return 0;
}
………………………………………………………………..
Output
Error: Undefined symbol “p” in function main()
Here, “if statement” has compound statement with a block. There is a conditional expression so the variable p appears as control enters into the block and disappears on exit from the block. Hence variable is not available outside the block.
Scope of local variable
We have already known that a local variable is a variable that is declared inside a particular function. Local variable can be used only in the function in which it is declared. The declaration and access area is called scope of local variable. The visibility of local variables is limited to the home function in which they are declared, local variables belongs to one function can’t be accessed from another function.
Consider the following program example:
#include<stdio.h>
#include<conio.h>
void display_number();
void main()
{
int num=10;
display_number( );
getch();
}
void display_number( )
{
printf("number is=%d",num);
}
…………………………………………………………………………….
Output
Error: undefined symbol “num” in function display_number()
Here, num variable is the local variable to main( ) function, it can’t be accessed from display_number() function, because the scope of num variable is limited to the main( ) function only. For this reason an error will occur.
Again, consider the following program example:
#include<stdio.h>
#include<conio.h>
void display_number ( );
int main()
{
clrscr();
int num=40;
printf("number is =%d",num);
display_number();
printf("\nnumber is =%d",num);
getch();
return 0;
}
void display_number ( )
{
int num=100;
printf("\nnumber is =%d",num);
}
……………………………………………………………………………
Output
nnumber is =40
nnumber is =100
nnumber is =40
Here variable num is declared for two times that is in main( ) function and again in display_number() function. They are different memory locations; visibility of which is limited to their home functions. So we have conclude that, variable belongs to one function can’t be accessed from another function.
Life time of local variables
We know that the time period for which a variable exists in the memory is known as lifetime of variable. Lifetime of local variables starts when control enters the function in which it is declared and it is destroyed when control exists from the function. Local variables of a function do not remain their values from one execution to another of a function because they lose their life at the end of every execution. We have described this procedure in the previous section. Consider the following example as life time of local variables.
#include<stdio.h>
void display_numbers();
int main()
{
display_numbers();
display_numbers();
display_numbers();
return 0;
}
void display_numbers()
{
int num=20;
nump=num+20;
printf("\n number is: %d",num);
}
……………………………………………………………………………..
Output
number is: 40
number is: 40
number is: 40
In this example, num is a local variable to the function display_numbers( ), it doesn’t keep its values for the next execution because it loses its life at the end of every execution. Hence, for every execution num is allocated and assigned with 20. So, the result would be same for every function call.
Scope of global variable
We know that a global variable is a variable that is declared outside all functions. Global variables are also referred to as external variables. The global variable can be used by all functions in the program. These types of variables are globally accessed from any part of the program like function. These are declared before main function. The global variable declaration area is called scope of global variable. The main scope concept of global variables is that, these variables are visible only to the functions, which are down to their definition; these can’t be accessed from the functions above to their definition. Therefore, global variables are declared before main function. Consider the following program example:
#include<stdio.h>
#include<conio.h>
int num=100;
void display_numbers();
void main()
{
printf("number is: =%d",num);
display_numbers( );
printf("\nnumber is: =%d",num);
getch();
}
void display_numbers()
{
num=num+100;
}
………………………………………………………………………………..
Output
number is: =100
number is: =200
Here, in the above example, variable num is declared on top of all the functions. It is global to both the functions main( ) and display_numbers( ). The change in its value (num=num+100) in the function display_nnumbers() reflected the change in main() because num is a common variable to both the functions.
Life time of global variable
We already knew that, the time period for which a variable exists in the memory is known as lifetime of variable. Global variables survive in the memory as long as the program is running. These variables are destroyed from the memory when the program terminates. Therefore, these variables occupy memory longer than local variables.
0 মন্তব্য(গুলি):
একটি মন্তব্য পোস্ট করুন
Comment below if you have any questions