Functions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

FUNCTIONS

A function is a group of statements that together perform a task. Every C program has at least
one function, which is main(), and all the most trivial programs can define additional functions.
You can divide up your code into separate functions. We can divide up our code among
different functions , but logically the division is such that each function performs a specific task.
A function declaration tells the compiler about a function's name, return type, and parameters.
A function definition provides the actual body of the function.
The C standard library provides numerous built-in functions that your program can call. For
example, strcat() to concatenate two strings, memcpy() to copy one memory location to
another location, and many more functions.

Defining a Function
The general form of a function definition in C programming language is as follows
return_type function_name( parameter list ) {
body of the function
}
A function definition in C programming consists of a function header and a function body. Here
are all the parts of a function −
 Return Type − A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and the
parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you 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.
 Function Body − The function body contains a collection of statements that define what
the function does.
Example
Given below is the source code for a function called max(). This function takes two parameters
num1 and num2 and returns the maximum value between the two −
/* function returning the max between two numbers */
int max(int num1, int num2) {
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}

Function Aspects
There are three aspects of a C function.
o Function declaration A function must be declared globally in a c program to tell the
compiler about the function name, function parameters, and return type.

o Function call Function can be called from anywhere in the program. The parameter list
must not differ in function calling and function declaration. We must pass the same
number of functions as it is declared in the function declaration.

o Function definition It contains the actual statements which are to be executed. It is the
most important aspect to which the control comes when the function is called. Here, we
must notice that only one value can be returned from the function.
Functions Aspects Syntax

1Function declaration return_type function_name (argument list);


2Function call function_name (argument_list)
3Function definition return_type function_name (argument list) {function body;}

Function Arguments
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function.
Formal parameters behave like other local variables inside the function and are created upon
entry into the function and destroyed upon exit.
While calling a function, there are two ways in which arguments can be passed to a function –
Call Type & Description
1. Call by value-This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside the function
have no effect on the argument.

2. Call by reference-This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual argument used in
the call. This means that changes made to the parameter affect the argument.

By default, C uses call by value to pass arguments. In general, it means the code within a
function cannot alter the arguments used to call the function.
A scope in any programming is a region of the program where a defined variable can have its
existence and beyond that variable it cannot be accessed. There are three places where variables
can be declared in C programming language −
 Inside a function or a block which is called local variables.
 Outside of all functions which is called global variables.
 In the definition of function parameters which are called formal parameters.

Local Variables
Variables that are declared inside a function or block are called local variables. They can be
used only by statements that are inside that function or block of code. Local variables are not
known to functions outside their own.
The following example shows how local variables are used. Here all the variables a, b, and c are
local to main() function.
#include <stdio.h>

int main () {

/* local variable declaration */


int a, b;
int c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;

printf ("value of a = %d, b = %d and c = %d\n", a, b, c);


return 0;
}

Global Variables
Global variables are defined outside a function, usually on top of the program. Global variables
hold their values throughout the lifetime of your program and they can be accessed inside any of
the functions defined for the program .A global variable can be accessed by any function. That
is, a global variable is available for use throughout your entire program after its declaration.
The following program show how global variables are used in a program.
Live Demo
#include <stdio.h>

/* global variable declaration */


int g;

int main () {

/* local variable declaration */


int a, b;

/* actual initialization */
a = 10;
b = 20;
g = a + b;

printf ("value of a = %d, b = %d and g = %d\n", a, b, g);

return 0;
}
A program can have same name for local and global variables but the value of local variable
inside a function will take preference. Here is an example −
Live Demo
#include <stdio.h>

/* global variable declaration */


int g = 20;

int main () {

/* local variable declaration */


int g = 10;

printf ("value of g = %d\n", g);


return 0;
}
When the above code is compiled and executed, it produces the following result −
value of g = 10

Types of Functions
There are two types of functions in C programming:
1. Library Functions: are the functions which are declared in the C header files such as
scanf(), printf(), gets(), puts(), etc.
2. User-defined functions: are the functions which are created by the C programmer, so
that he/she can use it many times. It reduces the complexity of a big program and
optimizes the code.
Different aspects of function calling
A function may or may not accept any argument. It may or may not return any value. Based on
these facts, There are four different aspects of function calls.
o function without arguments and without return value
o function without arguments and with return value
o function with arguments and without return value
o function with arguments and with return value

1. Function without argument and without return value : When a function has no
arguments, it does not receive any data from the calling function. Similarly, when it does
not return a value, the calling function does not receive any data from the called function.
Syntax :

Function declaration : void function();


Function call : function();
Function definition :
void function()
{
statements;
}

Example1. for Function without argument and without return value

#include<stdio.h>
void printName();
void main ()
{
printf("Hello ");
printName();
}
void printName()
{
printf("World");
}
Output
Hello World

Example2. for Function without argument and without return value

#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}
Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

2.Function without arguments and with returns value : There could be occasions where we
may need to design functions that may not take any arguments but returns a value to the calling
function. An example of this is getchar function it has no parameters but it returns an integer
and integer type data that represents a character.

Syntax :
Function declaration : int function();
Function call : function();
Function definition :
int function()
{
statements;
return x;
}

Example for Function without argument and with return value

#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}
Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34
3.Function with arguments but without return value : When a function has arguments, it
receives any data from the calling function but it returns no values.

Syntax :
Function declaration : void function ( int );
Function call : function( x );
Function definition:
void function( int x )
{
statements;
}

Example1 for Function with argument and without return value

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Example 2: program to calculate the average of five numbers.


#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}
Output
Going to calculate the average of five numbers:
Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

4.Function with arguments and with return value

Syntax :
Function declaration : int function ( int );
Function call : function( x );
Function definition:
int function( int x )
{
statements;
return x;
}

Example for Function with argument and with return value


Example 1
#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}
Output
Going to calculate the sum of two numbers:
Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}
Output
Going to check whether a number is even or odd
Enter the number: 100
The number is even

C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place
called the library. Such functions are used to perform some specific operations. For example,
printf is a library function used to print on the console. The library functions are created by the
designers of compilers. All C standard library functions are defined inside the different header
files saved with the extension .h. We need to include these header files in our program to make
use of the library functions defined in such header files. For example, To use the library
functions such as printf/scanf we need to include stdio.h in our program which is a header file
that contains all the library functions regarding standard input/output.
The list of mostly used header files is given in the following table.

SN Header Description
file

1 stdio.h This is a standard input/output header file. It contains all the library functions
regarding standard input/output.

2 conio.h This is a console input/output header file.

3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(),
calloc(), exit(), etc.

5 math.h This header file contains all the math operations related functions like sqrt(),
pow(), etc.

6 time.h This header file contains all the time-related functions.

7 ctype.h This header file contains all character handling functions.

8 stdarg.h Variable argument functions are defined in this header file.

9 signal.h All the signal handling functions are defined in this header file.

10 setjmp.h This file contains all the jump functions.

11 locale.h This file contains locale functions.

12 errno.h This file contains error handling functions.

13 assert.h This file contains diagnostics functions.

.
Recursive function
A function which calls itself is called recursive function and this technique is known as
recursion.
Recursion is the process of repeating items in a self-similar way. In programming languages, if
a program allows you to call a function inside the same function, then it is called a recursive call
of the function.
void recursion() {
recursion(); /* function calls itself */
}

int main() {
recursion();
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.Recursive functions are very useful to solve many
mathematical problems, such as calculating the factorial of a number, generating Fibonacci
series, etc .
How recursion works?

void recurse()

... .. ...

recurse();

... .. ...

int main()

... .. ...

recurse();

... .. ...

}
The recursion continues until some condition is met to prevent it.

To prevent infinite recursion, if...else statement (or similar approach) can be used where one
branch makes the recursive call, and other doesn't.

Example: Sum of Natural Numbers Using Recursion

#include <stdio.h>
int sum(int n);

int main() {
int number, result;

printf("Enter a positive integer: ");


scanf("%d", &number);

result = sum(number);
printf("sum = %d", result);
return 0;
}

int sum(int n) {
if (n != 0)
// sum() function calls itself
return n + sum(n-1);
else
return n;
}

Output

Enter a positive integer:3


sum = 6

Initially, the sum() is called from the main() function with number passed as an argument.

Suppose, the value of n inside sum() is 3 initially. During the next function call, 2 is passed to
the sum() function. This process continues until n is equal to 0.
When n is equal to 0, the if condition fails and the else part is executed returning the sum of
integers ultimately to the main() function.

You might also like