C Programming Functions Overview
C Programming Functions Overview
ON
PROBLEM SOLVING
&
PROGRAMMING
I [Link] I SEMESTER
Regulation: R20
(2021 – 2022)
Problem Solving & Programming
UNIT – III
Learning Outcomes:
Functions
Introduction:
Function:
Definition: A function is defined as a block of code that performs a specific task when it is
called. In other words, a function is defined as a sub program.
Finally, a function is a group of statements that together perform a task.
We can divide up your code into separate functions. How you divide up your code among
different functions is up to you, but logically the division is such that each function performs a
specific task.
Advantages of Functions:
● C functions are used to avoid rewriting same logic/code again and again in a program.
● There is no limit in calling C functions to make use of same functionality wherever
required.
● We can call functions any number of times in a program and from any place in a
program.
● A large C program can easily be tracked when it is divided into functions.
● The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.
There are many library functions available in C programming to write a good and efficient
program.
Below are the 4 most important advantages of using standard C library functions.
1. They work
One of the most important reasons we should use library functions is simply because they
work.
These functions help you in that they do the same thing on every computer. This saves time,
effort and makes your program portable.
ctype.h:
The ctype.h header file of the C Standard Library declares several functions that are useful for
testing and mapping characters.
All the functions return non-zero (true) if the argument c satisfies the condition described,
and zero (false) if not.
Following are some of the functions defined in the header ctype.h −
[Link]. Function & Description
int isalnum(int c)
1
This function checks whether the passed character is alphanumeric.
int isalpha(int c)
2
This function checks whether the passed character is alphabetic.
int iscntrl(int c)
3
This function checks whether the passed character is control character.
int isdigit(int c)
4
This function checks whether the passed character is decimal digit.
int isgraph(int c)
5 This function checks whether the passed character has graphical
representation using locale.
int islower(int c)
6
This function checks whether the passed character is lowercase letter.
int isprint(int c)
7
This function checks whether the passed character is printable.
int ispunct(int c)
8
This function checks whether the passed character is a punctuation character.
int isspace(int c)
9
This function checks whether the passed character is white-space.
int isupper(int c)
10
This function checks whether the passed character is an uppercase letter.
int isxdigit(int c)
11
This function checks whether the passed character is a hexadecimal digit.
math.h:
The math.h header file defines various mathematical functions. All the functions available in
this library take double as an argument and return double as the result.
Library Functions
double acos(double x)
1
Returns the arc cosine of x in radians.
double asin(double x)
2
Returns the arc sine of x in radians.
double atan(double x)
3
Returns the arc tangent of x in radians.
double cos(double x)
4
Returns the cosine of a radian angle x.
double cosh(double x)
5
Returns the hyperbolic cosine of x.
double sin(double x)
6
Returns the sine of a radian angle x.
double sinh(double x)
7
Returns the hyperbolic sine of x.
double tanh(double x)
8
Returns the hyperbolic tangent of x.
double exp(double x)
9
Returns the value of e raised to the xth power.
double log(double x)
10
Returns the natural logarithm (base-e logarithm) of x.
double log10(double x)
11
Returns the common logarithm (base-10 logarithm) of x.
double sqrt(double x)
13
Returns the square root of x.
double ceil(double x)
14
Returns the smallest integer value greater than or equal to x.
double fabs(double x)
15
Returns the absolute value of x.
double floor(double x)
16
Returns the largest integer value less than or equal to x.
string.h
The string.h header defines various functions for manipulating arrays of characters called
strings.
Library Functions
Following are some of the functions defined in the header file string.h −
The implementation of functions in C programming is done with the following three elements-
Function Declaration:
A function should be declared before defining it. It can be identified with a function name, a
list of parameters and the type of data return by it as a result.
Syntax:
return_datatype function_name(parameter_types);
Examples:
add( ) is a function which takes two integers as parameters and returns one integer as
a result.
add( ) is a function which takes two integers as parameters and does not return
anything.
add( ) is a function which takes one integer array and one integer as parameters and
returns an integer array as a result.
join is a function which takes two character pointers and returns a character pointer as
a result.
Note:
1. Every function must be declared before its usage in the program.
2. If any function need not to return anything then its return type must be void.
Function Definition:
Implementing the function as per the task done by a function as a sequence of
statements is known as function definition.
Syntax:
return_datatype function_name(datatype1 variable1, datatype2 variable2, ....................)
{
}
Example:
Function Call:
Function call is a statement used to do the following –
1. To invoke the execution of a function, it means any function gets executed only when it
is called by another function.
2. To establish the communication between two functions.
3. To pass the arguments (input data) as values or references to a function.
Syntax:
function_name(arguments_list);
Example:
Program:
Write a C program to implement four functions add, sub, mult, div and perform operations on
two integers.
Source Code:
#include<stdio.h>
void main()
{
int add(int,int); /* Function Declaration */
int sub(int,int); /* Function Declaration */
int mult(int,int); /* Function Declaration */
int div(int,int); /* Function Declaration */
int a,b,sum, diff, prod, quo;
printf("\n Enter any two integers:");
scanf("%d %d",&a,&b);
sum=add(a,b); /* Function Call */
diff=sub(a,b); /* Function Call */
prod=mult(a,b); /* Function Call */
quo=div(a,b); /* Function Call */
printf("\n Sum of two numbers:%d",sum);
printf("\n Difference of two numbers:%d",diff);
printf("\n Product of two numbers:%d",prod);
printf("\n Quotient of two numbers:%d",quo);
}
Output:
Here,
main( ) is a calling function, since it calls fun( ).
fun( ) is a called function, since it has been called by main( ).
Actual Arguments:
The data values that are passed from calling function to called function through a
function call are called actual arguments. Simply, these are the arguments that appear in
function call.
Formal Parameters:
These are the parameters that appear in function declaration or function header is
called formal parameters.
Working of a function:
The above figure shows that how a function works, when a function is called the
program control transfers from calling function to called function now the execution of calling
function is suspended temporarily and the execution of called function is initiated and returns
to the calling function then the execution of calling function is resumed.
Examples:
return; /* returns control from function */
function declaration:
void function ( int );
function call: function( a );
With arguments and
function definition:
without
void function( int a )
return values
{
statements;
}
function declaration:
void function();
function call: function();
Without arguments and
function definition:
without
void function()
return values
{
statements;
}
function declaration:
int function ( );
function call: function ( );
Without arguments and function definition:
with int function( )
return values {
statements;
return a;
}
NOTE:
● If the return data type of a function is “void”, then, it can’t return any values to the
calling function.
● If the return data type of the function is other than void such as “int, float, double etc”,
then, it can return values to the calling function.
Sample Programs:
1. Function with arguments and return values
Program: Write a C program to find factorial of a given number using functions.
Source Code:
#include<stdio.h>
void main()
{
long factorial(int); /* Function Declaration */
int num;
long fact;
printf("Enter a number to find factorial:");
scanf("%d", &num);
fact = factorial(num); /* Function Call */
printf("\n Factorial of %d is: %ld", num, fact);
}
long factorial(int n) /* Function Definition */
{
long f=1;
int i;
for(i=1; i<=n; i++)
f = f * i;
return f;
}
Output:
Enter a number to find factorial: 8
Factorial of 8 is: 40320
#include<stdio.h>
void main()
{
void factorial(int); /* Function Declaration */
int num;
printf("Enter a number to find factorial:");
scanf("%d", &num);
factorial(num); /* Function Call */
}
void factorial(int n) /* Function Definition */
{
long f=1;
int i;
for(i=1; i<=n; i++)
f = f * i;
printf("\n Factorial of %d is: %ld",n,f);
}
Output:
Enter a number to find factorial: 8
Factorial of 8 is: 40320
#include<stdio.h>
void main()
{
long factorial();
long fact;
fact = factorial();
printf("\n Factorial is: %ld", fact);
}
long factorial()
{
long f=1;
int num, i;
printf("Enter a number to find factorial:");
scanf("%d", &num);
for(i=1;i<=num; i++)
f=f*i;
return f;
}
Output:
Enter a number to find factorial: 8
Factorial of 8 is: 40320
#include<stdio.h>
void main()
{
void factorial();
factorial();
}
void factorial()
{
long f=1;
int num, i;
printf("Enter a number to find factorial:");
scanf("%d", &num);
for(i=1;i<=num; i++)
f=f*i;
printf("\n Factorial of %d is: %ld", num, f);
}
Output:
Enter a number to find factorial: 8
Factorial of 8 is: 40320
Output:
value of a = 10, b = 20 and c = 30
Global Variables:
● The variables that are declared outside of all functions including main( ) are known as
Global Variables.
● It is available for use throughout the entire program after its declaration. No two global
variables should have same name.
● These variables must be declared at Global declaration section before main( ).
Example:
Srinivasa Ramanujan Institute of Technology, [Link] 19
Problem Solving & Programming
Source Code:
#include <stdio.h>
/* global variable declaration */
int g;
void main ( )
{
/* local variable declaration */
int a, b;
/* local variable initialization */
a = 10;
b = 20;
g = a + b; /* here g is a global variable */
printf ("value of a = %d, b = %d and g = %d\n", a, b, g);
}
Output:
value of a = 10, b = 20 and c = 30
If the local and global variables have same name then the local variable hides the global
variable and gives preference to local variable.
Example:
Source Code:
#include <stdio.h>
/* global variable declaration */
int g = 20;
void main ()
{
/* local variable declaration */
int g = 10;
printf ("value of g = %d\n", g);
}
Output:
value of g = 10
There are different ways in which parameter data can be passed into and out of
functions. Let us assume that a function B() is called from another function A(). In this
case A is called the “calling function” and B is called the “called function”. Also, the
arguments which A sends to B are called actual arguments and the parameters of B are
called formal parameters.
Following are the two ways that are used to pass parameters to a function:
1. Call-by-value (or) Pass-by-value
2. Call-by-reference (or) Pass-by-reference
1. Call-by-value:
The call by value method of passing arguments to a function copies the actual
value of an actual argument into the formal parameter of the function. In this case, changes
made to the formal parameter inside the function have no effect on the actual argument, since
the formal parameter is the duplicate of actual argument.
Program:
Write a C program to exchange two numbers using call-by-value parameter passing method.
Source Code:
#include <stdio.h>
void swap(int, int); /* Function Declaration */
void main ( )
{
/* local variable definition */
int a,b;
printf(“Enter any two numbers:”);
scanf(“%d%d”,&a, &b);
printf("Before swap:\n value of a : %d\n value of b : %d ", a, b);
swap(a, b); /* calling a function as call-by-value */
printf("After swap:\n value of a : %d\n value of b : %d ", a, b);
}
void swap(int x, int y) /* Function Definition */
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put temp into y */
Srinivasa Ramanujan Institute of Technology, [Link] 21
Problem Solving & Programming
}
Output:
Enter any two numbers: 48 62
Before swap:
value of a: 48
value of b: 62
After swap:
value of a: 48
value of b: 62
2. Call-by-reference:
The call by reference method of passing arguments to a function 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. It means the changes made to the parameter affect
the passed argument.
To pass a value by reference, argument pointers are passed to the functions just
like any other value. So accordingly we need to declare the function parameters as pointer
types which exchanges the values of the two integer variables pointed to, by their arguments.
Program:
Write a C program to exchange two numbers using call-by-reference parameter passing
method.
Source Code:
#include <stdio.h>
void swap(int*, int*); /* Function Declaration with pointers as parameters*/
void main ( )
{
/* local variable definition */
int a, b;
printf(“Enter any two numbers:”);
scanf(“%d %d”, &a, &b);
printf("Before swap:\n value of a : %d\n value of b : %d ", a, b);
swap(&a, &b); /* calling a function as call-by-reference */
printf("After swap:\n value of a : %d\n value of b : %d ", a, b);
}
void swap(int *x, int *y) /* Function Definition */
Srinivasa Ramanujan Institute of Technology, [Link] 22
Problem Solving & Programming
{
int temp;
temp = *x; /* save the value of x */
*x = *y; /* put y into x */
*y = temp; /* put temp into y */
}
Output:
Enter any two numbers: 48 62
Before swap:
value of a: 48
value of b: 62
After swap:
value of a: 62
value of b: 48
Storage Classes:
In C language, each variable has a storage class which decides the following things:
● scope i.e the value of the variable would be available upto which extent.
● default initial value i.e if we do not explicitly initialize that variable, what will be its
default initial value.
● lifetime of that variable i.e for how long will that variable exist.
The following storage classes are most oftenly used in C programming,
1. Automatic variables
2. External variables
3. Static variables
4. Register variables
Automatic variables
A variable declared inside a function without any storage class specification, is by
default an automatic variable. They are created when a function is called and are
destroyed automaticallywhen the function exits. Automatic variables can also be called local
variables because they are local to a function. By default they are assigned garbage value by
the compiler.
extern keyword
The extern keyword is used before a variable to inform the compiler that this variable is
declared somewhere else. The extern declaration does not allocate storage for variables.
Static variables
A static variable tells the compiler to persist the variable until the end of program.
Instead of creating and destroying a variable every time when it comes into and goes out of
scope, static is initialized only once and remains into existence till the end of program. A static
variable can either be internal or external depending upon the place of declaration. Scope
of internal static variable remains inside the function in which it is defined. External
static variables remain restricted to scope of file in which they are declared.
Program:
Write a C program to illustrate static keyword.
Source Code:
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global static variable */
void main() {
while(count--) {
func();
}
}
/* function definition */
void func( void ) {
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
Output:
i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
Register variables:
The register keyword is used to declare register variables. Register variables were
supposed to be faster than local variables. However, modern compilers are very good at code
optimization and there is a rare chance that using register variables will make your program
faster. Unless you are working on embedded system where you know how to optimize code for
the given application, there is no use of register variables.
Keyword Used: register
Syntax: register datataype variable_name;
Example: register int num;
Scope: Local to the block in which the variable is defined
Default initial value: Garbage value.
Lifetime: Till the whole program doesn't finish its execution.
Storage area: Processor Registers.
Recursion: