Functions in C Language

Function is a group of statements which perfoms an specific task.

We have used many functions such as printf(),scanf() and many more while developing a program. The purpose of a function can be understood by the example of printf(). Whenever you want to print anything on the output screen you use the printf() function. Actually to send the output on the screen is a difficult task and a program of multiple statements is need to write but fortunately, this is already done by Dennis Ritchie. So you can print anything by using a single line.

Types of function

In c various function are already created such as printf(),scanf(),sqrt(),pow() etc.These are known as predefined function or library function.

C also provide the facility to create your own function. The functions created by the programmer are known as user defined function.

Every function is followed by a pair of parenthesis(). While working with a function, some input needs to be supplied to the function. The input is given by writing a comma-separated list between the parenthesis. The inputs are also known as argument or parameters. For example, whatever you want to print by using the printf() function you supply it as an argument.

printf("Hello");
//Here printf() is a function and "hello" is the required input means argument. 

Why functions are used?

To understand more about function lets take an example. Suppose you want to find the solution for problem 4!+5!+2!. Here, possible solutions are listed below:

if there is a predefined function for the factorial the use it to calculate the factorial and write the solution as given below

factorial(4)+factorial(5)+factorial(2)

But unfortunately no such function is already defined in C's library.

The second approach is you write the separate code for calculate factorial each time and finally add the results. The solution is given below.

for(i=1,ans1=1;i<=4;i++)
    ans1=ans1*i;

for(i=1,ans2=1;i<=5;i++)
    ans2=ans2*i;
   
for(i=1,ans3=1;i<=2;i++)
    ans3=ans3*i;

ans=ans1+ans2+ans3;

But in the above-given approach every time you need to repeat the specific code that is very inefficient and inconvenient. Because here the logic is limited in 2 or 3 lines and what if the solution of any problem is written in hundred and thousands of line. Then it is very difficult to repeat the logic and make the required changes each time. So this approach can't be used for real-time software development.

The third solution is given below by using the function. In this approach every time write the logic for the general form of the program. For example, in the above example, we calculate the factorial of different numbers. while writing a function consider the general form of a problem that is we want to calculate here the problem is to calculate factorial of n, where n can be any number and the solution is given below.

for(i=1,ans=1;i<=n;i++) {
    ans=ans*i;
}

The above logic is capable to calculate the factorial of any number so group these statements and given a specific name and follow with the pair of parenthesis. Because The group of statements which performs a specific task is called function and every function name is followed by a pair of parenthesis. The solution in the form of the function is given below.

fact(n){
    for(i=1,ans=1;i<=n;i++) {
         ans=ans*i;
    }
}

To work with the above logic the value of n is required so, n is written as an argument that can be supplied later when the function is used. The above-given logic is not a complete version of function so wait and read the program written below.

#include<stdio.h>
long fact(int n) {
 	long f=1;int i;
 	for(i=1;i<=n;i++) {
 		f=f*i;
 	}	
 	return f;
}
int main() {
 	int n;
	long ans;
	printf("Enter any number: ");
	scanf("%d",&n);
 	
 	ans=fact(n);
 
 	printf("Factorial of %d = %ld",n,ans);
 
 	return 0;
}

Output

Enter any number: 5
Factorial of 5 = 120

Program Description

  1. Let's make the discussion complete. In a program whenever program executes the execution begins with main() function and the calls other function within the main to accomplish the task.
  2. Within the main() we first demand the number from the user by using the printf() and scanf() function used in line 12 and 13, and the call the function fact() to calculate the factorial by passing n as an argument.
  3. Whenever function call occurs the control jumps to the function definition with the given input. The argument supplied in the function call is known as actual argument/actual parameter.
  4. In the function definition receive the argument in a variable. The variable used in the function definition to receive the argument are known as a formal argument/formal parameter, and the function body executes.
  5. Whenever function body completes the control again jumps back to the position from wherever the function call happens and start the execution. In our program, the control jumps into the main() and execution again begin from line 16.
  6. Sometimes a function needs to return some output. To do this task within the function definition we use the return statement with the value we want to return. The return value replaces the function call.In the above program statement ans=fact(n); calls the function and output of fact(n) replace it and the variable ans receive the output.
  7. In the above program when fact() completes its execution the control jumps back to the main() at the function call of fact() and at last remaining main() is executing so main() becomes calling function and fact() is known as a called function. It is not necessary that if a function returns a value you need to receive the output if you don't receive the output then the output is discarded.
  8. It is not necessary that every function returns the output value. We will discuss this point in the next few minutes.
  9. If a function returns the output then we have to specify the return type. In the above program the result of factorial number is of type long, so we write the statement(also known as function header or signature) as long fact(int n). In this statement, the long represent the output type/return type.
  10. If a function doesn't specify the return type then the default return type is int. sometimes the can make a wrong output as given in the following program snippet.
fun(){
	retrun 5.4;
}
main()
{
	int ans=fun();
	printf("Result=%d",ans);
}
//Result=5
Because we don't specify the type function is able to return only integer the value is automatically converted into int.

To correct the above output we need to write the function as follows

float fun(){
	retrun 5.4;
}

Lets Take one more example to cover some facts and for better understanding.

Program to find the max of 2 numbers using function.

#include<stdio.h>
int max(int,int);//function declaration
int main() {
 	int a,b,m;//variable declaration
	printf("Enter any two numbers: ");
	scanf("%d %d",&a,&b);
	m=max(a,b);//function call
	printf("Maximum=%d",m);
 	return 0;	
}
int max(int x,int y)//function definition
{
	int t;
	if(x>y)
 		t=x;
	else
		t=y;
	return t;
} 

Output

Enter any two numbers: 5 8
Maximum=8

Program Description

  1. To find the maximum of two function we create a function max() which receive two integer value and returns an integer as an output. The function body have straight forward logic to find the max of two numbers and store the result in local variable t and return the result stored in t.
  2. The little difference in the previous example and in this example is that In the above-given example we define the function after main(). So we need to declare the function before main(). The statement int max(int, int) is known as a function declaration. In the function declaration, it is optional to write the name of the variable.we can write as int max(int x, int y).
  3. Function declaration is required when the function is used before the function definition. If we omit the function declaration in the above program. Then some compiler reports a warning or some report an error. Because during the compile time compiler expects that function is defined before use and if the compiler doesn't find the definition then gives a warning or error. To solve this problem either define the function before it is used or declare the function before the function use.
  4. Function declaration is used by the compiler to check the grammar on the compile time whether the input supplied to input/output and name of the function is correct or not. If correct then OK otherwise gives an error.
  5. For the predefined function the function declaration is written in the header file so we need to include those file which function we use in the program.
  6. After the compilation process all the function definition are linked with the function call and no need of any function header. To link the function definition with function call with function definition is called linking process.
  7. The above-given code can be written many more other ways some of them are given below
    int max(int x,int y)
    {
    	if(x>y)
    		return x;
        else
    		return y;	
    }
    
  8. In the above logic the maximum is directly written in the main() without storing in a local variable.
    int max(int x,int y)
    {
    	if(x>y)
    		return x;
    	return y;	
    }
    
  9. A little difference in the above snippet is that we eliminate the else statement. when the return statement appears the control immediately don't wait that all the function statements are executed or not. so in the above example if x>y returns x and return y is skipped otherwise return y is executes.
    int max(int x,int y)
    {
    	return (x>y?x:y);
    }
    
    
  10. The above program snippet use the conditional operator to find the max.
x>y? return x:return y; This is an error. we can't return a value with conditional operator as given above.

Call by value

To understand the call by value lets take an example

Program to swap two numbers

#include<stdio.h>
void swap(int,int);
int main() {
	int x,y;
 	printf("Enter any two numbers: ");
 	scanf("%d%d",&x,&y);
	swap(x,y);	
 	printf("x= %d y=%d",x,y);
 	return 0;
}
void swap(int a,int b) {
	int t;
	t=a;
 	a=b;
 	b=t;
 	printf("a= %d b= %d\n",a,b);
} 

Output

Enter any two numbers: 4 7
a= 7 b= 4
x= 4 y=7

Program Description

  1. In the above program to swap two numbers,we call the swap() with two arguments x and y in line 9 and the arguments x and y passed from main are gets collected in a and b in function definition.
  2. Remember that in the function call actual arguments and the formal argument gets different memory space whether their names are same or different.
  3. In the above function the swap() function definition swap the a and b and print them and returns back to main().Within the main() function the x and y again get printed.
  4. This is actually interesting to see the output that the value of x and y after calling the swap() remains same. This happens because when a function is called the copy of the actual arguments are passed to the formal arguments and if formal arguments get changed the actual arguments doesn't affect because by changing in a copy the original value doesn't affect.
  5. This type of function call, in which the copy of actual arguments are passed to the formal argument, is known as call by value.

Comments

Popular posts from this blog

Overview of Go lang

Arrays in C Language

Data Types in Go language

Creating your first html page

Say Hello world in Go lang

Arrays in Go lang

Installing go lang

String in golang

Decision Making in Go lang

Floating point Data types in Go lang