FUNCTION in C Programming

Page Contents:

Function definition in C
Function prototype
Example of a function prototype
Advantages of Function
Call by value and Call by reference in C
Static function in C
Types of function in C?
RECURSIVE FUNCTIONS

Function definition in C

A function is a self-contained block of statements that performs a given task, So we are going to explain two things a function that calls or activates the function and the function itself

Function prototype

return_type function_name(argument_list)
{
-
statements;
-
} 

1.Example of a function prototype

#include<stdio.h>
void message(); /*function prototype declaration before the main function*/
void main()
{
message();/*function call*/
printf("\nI am fine what about you");
}
void message()/*function defintion*/
{
printf("Hello how are you?");
}

OUTPUT:

Hello how are you? 
I am fine what about you 

2.Example of a function prototype

#include<stdio.h>
void main()
{
void message(); /*function prototype declaration inside the main function*/
message();/*function call*/
printf("\nWell it was good");
}
void message()/*function defintion*/
{
printf("How's you day?");
} 

OUTPUT:

How's your day?  
I am fine what about you

Here we took the above example because you need to understand that a function prototype can be declared from anywhere whether the function prototype is outside the main function or inside the main function

Write a program to call more than one function

#include<stdio.h>
void america();
void brazil();
void India();
void main()
{
printf("\nI am in main");
america();
brazil();
India();
}
void america()
{
printf("\nI am in america");
}
void brazil()
{
printf("\nI am in brazil");
}
void India()
{
printf("\nI am in India");
}

OUTPUT:

I am in main
I am in america
I am in brazil
I am in India

So, there is no limit on the number of functions that can be declared in a C program
Note that a function should not be defined in another function

Identifying the Function element in the C program

#include<stdio.h>
#include<conio.h>
void main()          //Caller function
{
clrscr();
int add(int a,int b);   //Prototype declaration
int n1,n2,sum;
printf("Enter two numbers:");
scanf("%d%d",&n1,&n2);
sum=add(n1,n2);   //Actual Parameters
printf("sum=%d",sum);
getch();
}
int add(int a,int b)   //Called function->add()
{                            //Formal parameters
int c;
c=a+b;
return c;
}

Advantages of Function

1)There is no need for writing the same code, again and again, we can reuse that code with the help of function
2)It also increases the readability of the program and makes it simple to understand and maintain and debug
3)It used to divide a complex problem into simpler ones and gives a modular function e.g. a project can be divided into many programmers
4)If any error occurs in the function it can be tested individually
5)Function keep the program in an organized manner, so the development of a program becomes easy
6)Separating the code into modular functions also makes the program easier to design and understand
7)The control flow can be easily managed because the compiler follows top to down execution

Call by value and Call by reference in C

Call by value:-

1) In this case, the value of parameters is passed to the called function
2)In this case, the actual parameters are not accessible by the called function
3)This is implemented by using simple variable names
4)Hence the actual parameters remain unchanged in case of the call by value

Call by reference:-

1)In this case, the reference of the variable is passed to the function by passing the address of the parameters
2)In this case, since the address of the variables are available, the called function can access the actual parameters
3)This is implemented by the use of pointer variables
4)Hence the actual parameters can be altered if required in case
of the call by reference method

Static function in C

A static function in C is a function that has a scope that is limited to its
object file. This means that the static function is only visible in its object
file. A function can be declared as static function by placing the static
the keyword before the function name.

#include <stdio.h>
static void staticFunc(void) 
{ 
  printf("Inside the static function staticFunc() "); 
} 
int main()
{
    staticFunc();
    return 0;
}

Hence, static functions are those functions that are callable in the same file where they define. Another reason for making functions static can be the reuse of the same function name in other files. Static variables have a property of preserving their value even after they are out of their scope! Hence, static variables preserve their previous value in their previous scope and are not initialized again in the new scope.
A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over.

Static global variables and functions are also possible in C/C++.
The purpose of these is to limit the scope of a variable or function to a file. The static keyword is one among storage classes available in c. Storage class gives us an idea about the scope, lifetime, access time and default value of a variable.

Some important definition you should know

  • Default value: Default value is zero if it not initialized
  • Scope: Scope is within the block if the variable is defined inside a function if not throughout the program.
  • Access: Lifetime is throughout the program.
  • Memory: Memory if it is initialized then occupy the data segment.

Types of function in C?

There are two types of function in the C Programming language
1).Library Function
2).User-defined Function

1)Library function

such as printf(),scanf()
printf():
The format string contains Character set, Blank spaces, Escape Sequences, Field width, Format specifiers
scanf(): The format string contains format specifier, field width, assignment suppression character
library functions are nothing but commonly required functions
grouped functions grouped together and stored in what is called a Library.

2).User-defined Function
such as Goa(),Indian(),Book(),etc.

What is a function call in C?

When a function call is encountered and the arguments are to be passed i.e
from the left to right or right to left. The arguments are passed to a function
in right to left order and the stack is cleaned up by the called function

Swap function in C

Swap two numbers using a function.Pass the values to be swapped to this function using call-by-value method

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int a,int b);
clrscr();
printf("Enter two number");
scanf("%d%d",&a,&b);
printf("The values of a and b in the main function before calling the swap function are %d and %d\n",a,b);
swap(a,b);
printf("The values of a and b in main function after calling the swap function are %d and %d\n",a,b);
getch();
} 
void swap(int a,int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("The values of a and b in the swap function after swapping are %d and %d\n",a,b);
}

OUTPUT:

Enter two numbers:4
5
The values of a and b in the main function before calling the swap function are 4 and 5
The values of a and b in the swap function after swapping are 5 and 4
The values of a and b in the main function after caling the swap function are 4 and 5

2) Swap two number using a function pass the values to be swapped to function using call by reference method

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b;
void swap(int *p1,int *p2);
clrscr();
printf("Enter two numbers:");
scanf("%d%d",&a,&b);
printf("The values of a and b in the main function  before calling the swap function are %d and %d\n",a,b);
swap(&a,&b);
printf("The values of a and b in main function after calling the swap function are %d and %d\n",a,b);
getch();
}
void swap(int *p1,int *p2)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
printf("The values of a and b in the swap function after swapping are %d and %d\n",*p1,*p2);
}

OUTPUT:

Enter two number:4
5
The values of a and b in main function before calling the swap function are 4 and 5
The values of a and b in the swap function after swapping are 5 and 4
The values 

Write a program on factorial function in C

#include<stdio.h>
#include<conio.h>
void main()
{
int no,factorial;
int fact(int no);
clrscr();
printf("Enter a number");
scanf("%d",&no);
factorial=fact(no);
printf("Factorial=%d",factorial);
getch();
}
int fact(int no)
{
int i,ans;
for(i=1,ans=1;i<=no;i++)
{
ans=ans*i;
}
return ans;
}

OUTPUT:

Enter a number:4
Factorial=24

Write a program on Fibonacci series in C using function

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i;
int fibo(int,int,int);
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
printf("0\n");
for(i=1;i<=n-1;i++)
{
printf("%d\n",fibo(0,1,i));
}
getch();
}
int fibo(int a,int b,int i)
{
if(i==1)
return b;
else
return (fibo(b,a+b,--i));
}

OUTPUT:

Enter the number of elements:10
0
1
1
2
3
5
8
13
21
34

Write a program on factorial using the function in C

#include<stdio.h>
#include<conio.h>
void main()
{
int no,factorial;
int fact(int no);
clrscr();
printf("Enter a number:");
scanf("%d",&no);
factorial=fact(no);
printf("Factorial=%d",factorial);
getch(); 
}
int fact(int no)
{
int i,ans;
for(i=1;ans=1;i<=no;i++)
{
ans=ans*i;
}
return ans;
}

OUTPUT:

Enter a number:4
Factorial=24

Write a program to check palindrome without using string functions in C

#include<stdio.h>
#include<conio.h>
void  main()
{
int n=0,i;
char a[100],rev[100];
clrscr();
printf("Enter a string:");
gets(a);
while(a[n]!='\0')
{
n++;
}
for(i=0;i<(n-1);i++)
{
rev[n-i-1]=a[i];
}
for(i=0;i<n-1;i++)
{
if(a[i]!=rev[i])
break;
}
if(i==n)
printf("The string is palindrome");
else
printf("The string is nor palindrome");
getch();
}

OUTPUT:

Enter a string:Abhishek
The string is nor palindrome

Write a program on Factorial using recursion in C

#include<stdio.h>
#include<conio.h>
void main()
{
int no,factorial;
int fact(int no);
clrscr();
printf("Enter a number");
scanf("%d",&no);
factorial=fact(no);
printf("Factorial=%d",factorial);
getch();
}
int fact(int no)
{
if(no==1)
return 1;
else
return (no*fact(n-1)); 
}

OUTPUT:

Enter a number:5
Factorial=120

Write a program to find the length of string using strlen() function

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int l;
char a[100];
clrscr();
printf("Enter a string\n");
gets(a);
l=strlen(a);
printf("The length of the entered string is :%d",l);
getch();
}

OUTPUT:

Enter a string 
Hello
The length of the entered string is:5

Write a program to find the largest of three number using the function

#include<stdio.h>
#include<conio.h>
void main()
{
int largest(int a[],int n);
int n=3,i,a[100],large;
clrscr();
for(i=0;i<=2;i++)
{
printf("Enter a value");
scanf("%d",&a[i]);
}
large=largest(a,n);
printf("The largest number is %d",large);
getch();
}
int largest(int a[],int n)
{
int i,large;
large=a[0];
for(i=1;i<=2;i++)
{
if(large<a[i])
large=a[i];
}
return large;
}

OUTPUT:

Enter the number of elements:3
Enter a value:2
Enter a value:33
Enter a value:12
The largest number is 33

Write a program to show the sum of the natural number using recursion

#include<stdio.h>
#include<conio.h>
void main()
{
int no,sum;
int recursion(int no);
clrscr();
printf("Enter a number:");
scanf("%d",&no);
sum=recursion(no);
printf("Sum of number from 1 to n is %d",sum);
getch();
}
int recursion(int no)
{
if(no==1)
return 1;
else
return (no+recursion(no-1));
}

OUTPUT:

10
Sum of number from 1 to n is 55

Write a program on bubble sort in C using function

#include<stdio.h>
#include<conio.h>
void main()
{
int n,i,a[100];
void ascend(int a[],int n);
clrscr();
printf("Enter the number of elements:");
scanf("%d",&n);
for(i=0;i<=n-1;i++)
{
printf("Enter a value:");
scanf("%d",&a[i]);
}
ascend(a,n);
getch();
}
void ascend(int a[],int n)
{
int i,j,temp;
for(i=0;i<=n-2;i++)
{
for(j=0;j<=n-2;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("After sorting\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",a[i]);
}
}

OUTPUT:

Enter the number of elements:5
Enter a value:3
Enter a value:4
Enter a value:9
Enter a value:1
Enter a value:2
After sorting
1
2
3
4
9

What is Insertion sort in C?

Insertion sort is a very simple sorting algorithm in which the sorted array is built one element
at a time. We all are familiar with this technique of sorting, as we usually use it for the ordering of a deck
of cards while playing bridge.
Insertion sort is the main idea behind is that it inserts each item into its proper place in the final list. To save memory, most implementations of the insertion sort algorithm work by moving the current data element past the already sorted values and repeatedly interchanging it with the preceding value until it is in its correct position.

How does insertion sort work?

1)The array of values to be sorted is divided into two sets. One that stores sorted values and another that contains unsorted values
2)The sorting algorithm will proceed until there are elements in the unsorted set
3)Initially, the element with index 0 is sorted set. During each iteration of the algorithm, the first element in the unsorted set is picked up and inserted into the correct position in the sorted set

Advantage of insertion sort

1.It is easy to implement and efficient to use on small sets of data
2.It can be efficiently implemented on data sets that are already substantially sorted
3.It performs better than algorithms like selection sort and bubble sort.Insertion sort algorithm is simpler than shell sort,with only a small trade-off
in efficiency.It is over twice as fast as the bubble sort and almost 40% faster than the selection sort.
4.It requires less memory space

Write a program to sort an array using the insertion sort algorithm

#include<stdio.h>
#include<conio.h>
#define size 5
void insertion_sort(int arr[],int n);
void main()
{
int arr[size],i,n;
printf("\n Enter the number of elements in the array:");
scanf("%d",&n);
printf("\n Enter the elements of the array:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
insertion_sort(arr,n);
printf("\n The sorted array is: \n");
for(i=0;i<n;i++)
printf("%d\t",arr[i]);
getch();
}
void insertion_sort(int arr[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=arr[i];
j=i-1;
while((temp<arr[j])&&(j>=0))
{
arr[j+1]=arr[j];
j--;
}
arr[j+1]=temp;
}
getch();
}

OUTPUT:

Enter the number of elements in the array:5
Enter the elements of the array:6
7
9
2
5
The sorted array is:
2  5  6  7  9

Write a program to find the prime number using the function

#include<stdio.h>
#include<conio.h>
void main()
{
int n;
void prime(int n);
clrscr();
printf("Enter a number");
scanf("%d",&n);
prime(n);
getch();
}
void prime(int n)
{
int i=2;
while(n%i!=0)
{
i++;
}
if(n==i)
{
printf("Prime number");
}
else
{
printf("Not a prime number");
}
getch();
}

OUTPUT:

17
Prime Number

What is a linear search in C

It searches the element in a sequence wise so it is also called a sequential search, it is a very simple method to searching an element from an array

So how it works?

It works by comparing the value to be searched with every element of the array one by one in a sequence until a match is found. Linear search is mostly used to search an unordered list of elements.

Write a program to search an element in an array using the linear search technique

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define size 20 //Added so the size of the array can be altered more easily
int main(int argc, char *argv[])
{
int arr[size],num,i,n,found=0,pos=-1;
printf("\nEnter the number of elements in the array:");
scanf("%d",&n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\n Enter the number that has to be searched:");
scanf("%d",&num);
for(i=0;i<n;i++)
{
if(arr[i]==num)
{
found=1;
pos=i;
printf("\n %d is found in the array at position=%d",num,i+1);
/*+1 added in line 23 so that it would display the number in the first place in the array as in position 1 instead of 0*/
break;
}
}
if(found ==0)
printf("\n %d does not exist in the array",num);
return 0;
}

OUTPUT:

Enter the number of elements in the array:5
Enter the elements:1
6
7
9
8
Enter the number that has to be searched:6
6 is found in the array at position 2

Write a program to reverse a number using the function

#include<stdio.h>
int main()
{
int num,reverse;
printf("Enter any number:");
scanf("%d",&num);
reverse=rev(num);
printf("Reverse of number: %d",reverse);
return 0;
}
int rev(int num)
{
static sum,r;
if(num)
{
r=num%10;
sum=sum*10+r;
rev(num/10);
}
else
return 0;
return sum;
}

OUTPUT:

Enter any number:456
Reverse of number:654

The function of Header file math.h

math.h header file in C
math.h header file

sqrt(x)

  • This function finds the square root of the parameter passed to it and the result is returned to the caller function
  • It is available in math.h header file
  • this function also accepts a double as input parameter and returns the result also of double data type
  • The prototype of the function is as given as double sqrt(double x)

pow(x,y)

  • This function is available in the header file “math.h”
  • This function calculates and returns the value of x^y
  • The parameters as well the answer returned are a double data type
  • But it can also accept parameters of different data type
  • The prototype of the function is as given as double pow (double x, double y)

cell(x)

  • This function returns the smallest integral value of the parameter passed to the function
  • It rounds the value of x upward and returns the value
  • This function is also in the header file math.h
  • The parameter accepted and returned of the data type double
  • The prototype of the double ceil(double x)

floor(x)

  • This function returns the largest integral value of the parameter passed to the function
  • It rounds the value of x downward and returns the value
  • This function is also in the header file math.h
  • The parameter accepted and returned is of double data type
  • The prototype of the given function is: double floor(double x)

abs()

  • abs() function in C returns the absolute value of an integer
  • The absolute value of a number is always positive
  • Only integer values are supported in C
  • “stdlib.h” header file support abs() function in C language
Syntax for abs() function in C is:
int abs(int n);

Insalnum()

  • Insalnum() function in C checks if the ASCII value passed in has a character equivalent to a number of letters
  • It returns non-zero for true, and zero for false
  • Syntax for Insalnum() function : int Insalnum(int ch);
  • ctype.h header file supports insalnum() function

Program to add two number using the function

#include<stdio.h>
#include<conio.h>
void main()
{
int n1,n2;
void add(int a,int b);
clrscr();
printf("enter two numbers:");
scanf("%d%d",&n1,&n2);
add(n1,n2);
getch();
}
void add(int a,int b)
{
int c;
c=a+b;
printf("sum=%d",c);
}
OUTPUT:
enter two numbers:4
5
sum=9

Find the factorial using a function

#include<stdio.h>
#include<conio.h>
void main()
{
int n,factorial;
int fact(int no);
clrscr();
printf("enter a number");
scanf("%d",&n);
factorial=fact(no);
printf("factorial=%d",factorial);
getch();
}
int fact(int no)
{
int i,ans=1;
for(i=1;i<=no;i++)
{
ans=ans*i;
}
return ans;
}

OUTPUT:

enter a number:4
factorial=24

RECURSIVE FUNCTIONS :

A function that calls itself is called a recursive function. A recursive function must definitely have a condition that exits from calling the function again. hence there must be a condition that calls the function itself if that condition is true.if the condition is false then it will exit from the loop of calling itself again.

Recursive function
Recursion function

Find out the Fibonacci series using recursion.

#include<stdio.h>
#include<conio.h>
int fibo(int)
void main()
{
int n,i,c=0;
printf("enter the no:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
printf("%d",fibo(c));
c++;
}
} 
int fibo(int c)
{
if(c==0||c==1)
return c;
else
return
fibo(c-1)+fibo(c-2)
}
OUTPUT:
enter the number
n=5
0
1
1
2
3

Translate »