Function in C

Block of code or statements is called a function.
 

In C function has three parts.

  • Function declaration
  • Function definition
  • Function call
 

Function declaration

This statement provides information about a function type where we define the name of the function and declare the return type of function.
void msg();

Function definition

This is a block of code where the actual code of function has to be written.
void msg(){
// code
}

Function call

A statement that calls a function or from where the function starts to execute.
msg();

Example of function

#include<stdio.h>
#include<conio.h>
void msg();

int main(){
	
	msg();

	getch();
	return 0;
}
void msg(){
	printf("Hello.");
}

Passing parameters to a function

#include<stdio.h>
#include<conio.h>
void sum(double x, double y);

int main(){
	
	double a, b;
	printf("Enter two number:");
	scanf("%d %d", &a, &b);

	sum(a, b);

	getch();
	return 0;
}
void sum(double x, double y){
	double z;
	z=x+y;
	printf("Sum=%d \n", z);
}

Return statement in C

#include<stdio.h>
#include<conio.h>
int fact(int x);

int main(){
	
	int a, r;
	printf("Enter new number:");
	scanf("%d", &a);

	r= fact(a);
	printf("Factorial: %d \n", r);

	getch();
	return 0;
}
int fact(int n){
	int f, i;
	f=1;
	for(i=n; i>=1; i--){
		f=f*i;
	}
	return f;
}

Recursion in function

A function that calls to itself is called the recursion function.

#include<stdio.h>
#include<conio.h>
int fact(int x);

int main(){
	
	int a, r;
	printf("Enter new number:");
	scanf("%d", &a);

	r= fact(a);
	printf("Factorial: %d \n", r);

	getch();
	return 0;
}
int fact(int n){
	if(n>0){
		return n*fact(n-1);
	}
	else{
		return 1;
	}
}
© 2016 - 2022, All Rights are Reserved.