Problem Solving using C Language

0 of 50 lessons complete (0%)

Functions

Functions

A function is a self-contained block of statements that perform a coherent task of some kind. If you have a task that is always performed in the same way than instead of putting the same functionality at every point we should make function and can call by just declaring function name.

#include<stdio.h>
void func1();
int main()
{
	func1();
	printf("\nthis is first program with funtion");
	return 0;
}
void func1()
{
	printf("\nthis is func1");
}
 
Output:
This is func1
This is the first program with function

Important points about function

  •  A function gets called when the function name is followed by a semincolon.
  • A function is defined when function name is followed by a pair of braces in which one or more statements may be present.
  • Any function can be called from any other function. Even main can be called from other function.
  • A function calls itself such process known as recursion.

3 Elements of Functions

  • Function Definition
  • Function Call
  • Function Declaration

Definition of Function

  • Function Definition-
  • Function name
  • Function type
  • List of parameters
  • Local variable declaration
  • Function statement
  • A return statement
int func1()
{
	int a;
	printf("\nthis is func1");
	return 0;
}

Function Call

——————————-

Function Declaration

——————————

Return values and their type

A function may or may not send back any value to the calling function. If it does it is done through return statement. Called function can only return only one value per call.

return;
or
return(expression)

return: will not return any value but will return the control back to the calling function.

If(error)
{
     return(0);
}

Return expression: will return some value of the function back to the called function.

return(p);
return(x*y);

So basically, return serves two purpose

  • On executing the return statement, it immediately transfers the control back to the calling function.
  • It returns the value present in the parentheses after return, to the calling function.

Passing values between functions

Passing the vales to the function allows us to communicate with the function. Using this we can pass our values in order to get the results, for that we need to specify the function name with arguments.

Example:
	void main()
	{
		Funtion1();
		Function2(a);
	}
	Function1()
	{ }
	Function2(int a)
	{ }

Categories of Function

Functions with no arguments and no return value.

Functions with arguments and no return value.

Functions with no arguments and return a value.

Functions that return multiple return values.