Functions
Functions
CHAPTER - 4
FUNCTIONS
INTRODUCTION
• C enables its programmers to break up a program into segments commonly known as functions, each of
which can be written more or less independently of the others.
• Every function in the program is supposed to perform a well defined task. Therefore, the program code
of one function is completely insulated from that of other functions.
• Every function has a name which acts as an interface to the outside world in terms of how information is
transferred to it and how results generated by the function are transmitted back from it.
• In the fig, main() calls another function, func1() to perform a well defined task.
• main() is known as the calling function and func1() is known as the called function.
• When the compiler encounters a function call, instead of executing the next statement in the calling
function, the control jumps to the statements that are a part of the called function.
• After the called function is executed, the control is returned back to the calling program.
main()
{ func1()
………….. {
………….. Statement Block;
func1(); }
…………
………..
return 0;
}
INTRODUCTION CONTD….
• It is not necessary that the main() can call only one function, it can call as many functions as it
wants and as many times as it wants. For example, a function call placed within a for loop,
while loop or do-while loop may call the same function multiple times until the condition holds
true.
• It is not that only the main() can call another functions. Any function can call any other
function. In the fig. one function calls another, and the other function in turn calls some other
function.
• There are two ways in which arguments or parameters can be passed to the called function.
• Call by value in which values of the variables are passed by the calling function to the called function.
• Call by reference in which address of the variables are passed by the calling function to the called
function.
Example round():
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("round of %f is %f\n", i, round(i));
printf("round of %f is %f\n", j, round(j));
return 0;
}
Output:
Round of 5.4 is 5.000
Round of 5.6 is 6.000
Build-in Functions (math Functions)
ceil():
This function returns nearest integer value which is greater than or
equal to the argument passed to this function.
Example:
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("ceil of %f is %f\n", i, ceil(i));
printf("ceil of %f is %f\n", j, ceil(j));
return 0;
}
Output:
ceil of 5.400000 is 6.000000
ceil of 5.600000 is 6.000000
Build-in Functions (math Functions)
log():
This function is used to calculates natural logarithm.
Example:
#include <stdio.h>
int main()
{
float k=50;
printf("RESULT:%f", log(k));
return 0;
}
Output:
RESULT: 3.912
Build-in Functions (math Functions)
sqrt():
This function is used to find square root of the argument passed to
this function.
Example:
#include <stdio.h>
int main()
{
float k=49;
printf("RESULT:%f", sqrt(k));
return 0;
}
Output:
RESULT: 7
Build-in Functions (math Functions)
trunc():
This function truncates the decimal value from floating point value
and returns integer value.
Example:
#include <stdio.h>
int main()
{
float k=5.67898;
printf("RESULT:%f", trunc(k));
return 0;
}
Output:
RESULT: 5
Build-in Functions (math Functions)
pow():
This is used to find the power of the given number.
Example:
#include <stdio.h>
int main()
{
float a=2, b=3;
printf("RESULT:%f", pow(a,b));
return 0;
}
Output:
RESULT: 8.000
Build-in Functions (string Functions)
Function Description
strlen() calculates the length of string
strcat() Appends one string at the end of another
strncat() Appends first n characters of a string at the end of another
strcpy() Copies a string into another
strncpy() Copies first n characters of one string into another
strcmp() Compares two strings
strncmp() Compares first n characters of two strings
strchr() Finds the first occurrence of a given character in a string
strrchr() Finds the last occurrence of a given character in a string
strstr() Finds the first occurrence of a given string in another string
strlwr() Converts string to lowercase
strupr() Converts string to uppercase
strrev() Reverses the given string
Build-in Functions (string Functions)
Example:
Refer examples for strlen(), strcpy(), strcat() and strcmp() from unit 2.
strchr():
1. Pass the given string in the strchr() function and mention the character we need
to point.
2. The function return the first occurrence of a given character in a string.
#include <stdio.h>
#include <string.h>
int main ()
{
const char str[] = "C Programming";
const char ch = ‘m';
char *ret;
ret = strchr(str, ch);
printf("Index Location:%d", ret-str); OUTPUT:
return(0); Index Location: 8
}
Build-in Functions (string Functions)
strrchr():
1.The function returns the last location of character in the string
EXAMPLE:
#include <stdio.h>
#include <string.h>
int main ()
{
const char str[] = "C Programming";
const char ch = ‘m';
char *ret;
ret = strchr(str, ch); OUTPUT:
printf("Index Location:%d", ret-str); Index Location: 9
return(0);
}
Build-in Functions (string Functions)
strlwr():
1.The function converts the given string into lowercase.
EXAMPLE:
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “C PROGRAMMING";
// converting the given string into lowercase.
printf("%s\n",strlwr (str));
return 0;
}
OUTPUT:
c programming
Build-in Functions (string Functions)
strupr():
1.The function converts the given string into uppercase.
EXAMPLE:
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “c programming";
// converting the given string into lowercase.
printf("%s\n",strupr (str));
return 0;
}
OUTPUT:
C PROGRAMMING
Build-in Functions (string Functions)
strrev():
1.The function converts the given string into uppercase.
EXAMPLE:
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = “c programming";
// converting the given string into lowercase.
printf("%s\n",strrev(str));
return 0;
}
VARIABLES SCOPE
• In C, all constants and variables have a defined scope.
• By scope we mean the accessibility and visibility of the variables at different points in the program.
• A variable or a constant in C has four types of scope: block, function, file and program scope.
Variable Scope
PROGRAM SCOPE
• If you want that functions should be able to access some variables which are not passed to
them as arguments, then declare those variables outside any function blocks. Such
variables are commonly known as global variables. Hence, global variables are those
variables that can be accessed from any point in the program.
#include<stdio.h>
int x = 10;
void print();
int main()
{ printf("\n The value of x in the main() = %d", x);
int x = 2;
printf("\n The value of local variable x in the main() = %d", x);
print();
}
void print()
{ printf("\n The value of x in the print() = %d", x);
}
FILE SCOPE
• When a global variable is accessible until the end of the file, the variable is said to have file
scope.
• To allow a variable to have file scope, declare that variable with the static keyword before
specifying its data type, like this:
static int x = 10;
• A global static variable can be used any where from the file in which it is declared but it is not
accessible by any other files.
• Such variables are useful when the programmer writes his own header files.
RECURSIVE FUNCTIONS
• A recursive function is a function that calls itself to solve a smaller version of its task
until a final call is made which does not require a call to itself.
• Every recursive solution has two major cases, they are
base case, in which the problem is simple enough to be solved directly without
making any further calls to the same function
recursive case, in which first the problem at hand is divided into simpler sub parts.
Second the function calls itself but with sub parts of the problem obtained in the
first step. Third, the result is obtained by combining the solutions of simpler
sub-parts.
• Therefore, recursion is defining large and complex problems in terms of a smaller
and more easily solvable problem. In recursive function, complicated problem is
defined in terms of simpler problems and the simplest problem is given explicitly.
FINDING FACTORIAL OF A NUMBER USING RECURSION
PROBLEM SOLUTION
5! 5 X 4 X 3 X 2 X 1!
= 5 X 4! = 5 X 4 X 3 X 2 X 1
= 5 X 4 X 3! = 5 X 4 X 3 X 2
= 5 X 4 X 3 X 2! = 5 X 4 X 6
= 5 X 4 X 3 X 2 X 1! = 5 X 24
= 120
Recursion
DIRECT RECURSION
A function is said to be directly recursive if it explicitly calls itself. For example, consider the function
given below.
int Func( int n)
{
if(n==0)
retrun n;
return (Func(n-1));
}
INDIRECT RECURSION
A function is said to be indirectly recursive if it contains a call to another function which ultimately calls
it. Look at the functions given below. These two functions are indirectly recursive as they both call each
other.
TAIL RECURSION
• A recursive function is said to be tail recursive if no operations are pending to be performed when
the recursive function returns to its caller.
• That is, when the called function returns, the returned value is immediately returned from the callin
function.
• Tail recursive functions are highly desirable because they are much more efficient to use as in the
case, the amount of information that has to be stored on the system stack is independent of the
number of recursive calls.
int Fact(n) int Fact1(int n, int res)
{ {
return Fact1(n, 1); if (n==1)
} return res;
return Fact1(n-1, n*res);
}
LINEAR AND TREE RECURSION
• Recursive functions can also be characterized depending on the way in which the recursion grows- in a
linear fashion or forming a tree structure.
• In simple words, a recursive function is said to be linearly recursive when no pending operation involves
another recursive call to the function. For example, the factorial function is linearly recursive as the
pending operation involves only multiplication to be performed and does not involve another call to
Fact.
• On the contrary, a recursive function is said to be tree recursive (or non-linearly recursive) if the pending
operation makes another recursive call to the function. For example, the Fibonacci function Fib in which
the pending operations recursively calls the Fib function.
A B C
A B C
If there is only one ring, then simply move the ring from source to the destination
A B C
A B C A B C
If there are two rings, then first move ring 1 to the spare pole
and then move ring 2 from source to the destination. Finally
move ring 1 from the source to the destination
A B C
• Consider the working with three rings.
A B C
A B C
A B C
A B C A B C
A B C
A B C A B C