Professional Documents
Culture Documents
c03 PSCP PDF
c03 PSCP PDF
Why Functions?
• Generally, a difficult problem is divided into sub problems and then solved. This divide and
conquer technique is implemented in C through functions. A program can be divided into
functions, each of which performs some specific task. So, the use of C functions modularizes and
divides the work of a program.
• When some specific code is to be used more than once and at different places in the program the use
of functions avoids repetition of that code.
• The program becomes easily understandable, modifiable and easy to deluge and test. It became
simple to write the program and understand what work is done by each part of the program.
• Functions can be stored in a library and reusability can be achieved.
Introduction:
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. We can divide up
code into separate functions. Logically 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, function strcat() to concatenate two strings, function memcpy() to copy one memory location to
another location and many more functions.
A function is known with various names like a method or a sub-routine or a procedure etc.
Definition of Function:
The general form of a function definition in C programming language is as follows:
A function definition in C programming language 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:
Following is the source code for a function called max(). This function takes two parameters num1
and num2 and returns the maximum 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;
}
Declaration of Function
A function declaration tells the compiler about a function name and how to call the function. The
actual body of the function can be defined separately.
A function declaration has the following parts:
Function Call:
While creating a C function, you give a definition of what the function has to do. To use a function,
you will have to call that function to perform the defined task.
When a program calls a function, program control is transferred to the called function. A called
function performs defined task and when its return statement is executed or when its function-ending closing
brace is reached, it returns program control back to the main program.
To call a function you simply need to pass the required parameters along with function name and if
function returns a value then you can store returned value. For example:
#include <stdio.h>
/* function declaration */
int max(int num1, int num2);
void main ()
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a, b);
printf( "Max value is : %d\n", ret );
}
/* 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;
}
We kept max() function along with main() function and complied the source code. While running final
executable, it would produce following result:
Max value is : 200
Categories of functions:
There are mainly four categories of functions are there they
are:
1)functions without argument and without return type
2)functions with argument and without return type
3)functions without argument and with return type
4)functions with argument and with return type.
void main()
{
area();
}
We have just called a function , we can see that there is no variable or anything specified between the pair of
round brackets.
1
#include<stdio.h>
void add(); //function prototype
void main()
{
add(); //function call
}
3
Functions without argument and with return type
In this category of functions, functions can be called without arguments but it returns a value
Program:
#include <stdio.h>
int add();
void main()
{
int c;
c = add();
printf(“%d”,c);
}
int add()
{
int a=10, b=20;
return a+b;
}
4
Functions with argument and with return type
In this example we are going to learn function which can accept an argument and return a value.
Function accepts argument and it return a value back to the calling Program thus it can be termed as Two-
way Communication between calling function and called function.
#include<stdio.h>
int add(int,int);
void main()
{
int a=10,b=20,c;
c=add(a,b);
printf(“%d”,c):
}
int add(int x,int y)
{
return x+y;
}
Practice Programs:
1. What is the output when the flowing program segment is executed?
int a=1,b=2;
int f1(int a,int b);
main()
{
int i=1,c,d;
c=5*(i+1);
d=10*(i-1);
printf(“% d, %d “,f1(a,c),f1(b,d));
}
int f1(int x,int y)
{
return(x*y);
}
2. What will be the output when the flowing program segment is executed?
#include<stdio.h>
int i;
void increment(int i)
{
i++;
}
int main()
{
for(i=0;i<10;increment(i))
{}
printf(“i=%d\t “,i)
}
To find the given numbe is Armstrong number or not using user defined function.
#include<stdio.h>
#include<conio.h>
int armstrong(int);
void main()
{
int temp,n;
clrscr();
printf("\n Enter the number to check for armstron no:");
scanf("%d",&n);
temp = n;
if (temp == armstrong(n))
printf("\n The given number %d is an armstrong number",temp);
else
printf("\n The given number %d is not an armstrong number",temp);
getch();
}
int armstrong(int m)
{
int sum=0,re;
while(m>0)
{
re=m%10;
sum=sum+(re*re*re);
m=m/10;
}
return(sum);
}
To find the maximum of given numbers using parameter passing in functions.
#include<stdio.h>
#include<conio.h>
int maximum(int,int,int);
void main()
{
int max,a,b,c;
clrscr();
void draw_line()
{
int i;
for(i=0;i<45;i++)
printf("-");
}
int square(int n)
{
return(n*n);
}
int cube(int n)
{
return(n*n*n);
}
int sum_of_natural_number(int);
void main()
{
int sum,n;
clrscr();
printf("\n Enter the number n :");
scanf("%d",&n);
sum=sum_of_natural_number(n);
printf("\nThe sum of %d Natural numberis %d",n,sum);
getch();
}
int sum_of_natural_number(int n)
{
int sum=0,i=1;
while(i<=n)
{
sum=sum+i;
i++;
}
return(sum);
}
In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple
example that shows declaration and function call using function pointer.
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
// fun_ptr is a pointer to function fun()
void (*fun_ptr)(int) = &fun;
Here foo is a function that returns int and takes one argument of int type. So as a logical guy will think, by
putting a * operator between int and foo(int) should create a pointer to a function i.e.
int * foo(int);
But in C, operator precedence also plays role here. So, in this case, operator () will take priority over operator *.
And the above declaration will mean – a function foo with one argument of int type and return value of int * i.e.
integer pointer. So, it did something that we didn’t want to do.
So, as a next logical step, we must bind operator * with foo somehow. And for this, we would change the default
precedence of C operators using () operator.
int (*foo)(int);
That’s it. Here * operator is with foo which is a function name. And it did the same that we wanted to do.
1) Unlike normal pointers, a function pointer points to code, not data. Typically a function pointer stores the
start of executable code.
2) Unlike normal pointers, we do not allocate de-allocate memory using function pointers.
3) A function’s name can also be used to get functions’ address. For example, in the below program, we have
removed address operator ‘&’ in assignment. We have also changed function call by removing *, the program
still works.
#include <stdio.h>
// A normal function with an int parameter
// and void return type
void fun(int a)
{
printf("Value of a is %d\n", a);
}
int main()
{
void (*fun_ptr)(int) = fun; // & removed
fun_ptr(10); // * removed
return 0;
}
Output:
Value of a is 10
4) Like normal pointers, we can have an array of function pointers. Below example in point 5 shows syntax for
array of pointers.
5) Function pointer can be used in place of switch case. For example, in below program, user is asked for a
choice between 0 and 2 to do different tasks.
#include <stdio.h>
void add(int a, int b)
{
printf("Addition is %d\n", a+b);
}
void subtract(int a, int b)
{
printf("Subtraction is %d\n", a-b);
}
void multiply(int a, int b)
{
printf("Multiplication is %d\n", a*b);
}
int main()
{
// fun_ptr_arr is an array of function pointers
void (*fun_ptr_arr[])(int, int) = {add, subtract, multiply};
unsigned int ch, a = 15, b = 10;
(*fun_ptr_arr[ch])(a, b);
return 0;
}
6) Like normal data pointers, a function pointer can be passed as an argument and can also be returned from a
function.
For example, consider the following C program where wrapper() receives a void fun() as parameter and calls the
passed function.
int main()
{
wrapper(fun1);
wrapper(fun2);
return 0;
}
This point is very useful in C. In C, we can use function pointers to avoid code redundancy.
Passing Pointer to Function in C Programming
In C programming, we can pass the address of the variable to the formal arguments of a function. This method
of calling a function by passing pointer arguments is known as call by reference. Any change in the value of
formal parameters inside function will effect the value of actual argument. To pass a pointer to a function, we
have to declare the function argument of pointer type.
C program to show how to pass pointer to a function
#include<stdio.h>
#include<conio.h>
void getDoubleValue(int *F)
{
*F = *F + 2;
printf("F(Formal Parameter) = %d\n", *F);
}
int main(){
int A;
printf("Enter a numbers\n");
scanf("%d", &A);
/* Calling function using call by reference */
getDoubleValue(&A);
/* Any change in the value of formal parameter(F)
will effect the value of actual parameter(A) */
printf("A(Actual Parameter) = %d\n", A);
getch();
return 0;
}
Output
Enter a numbers
7
F(Formal Parameter) = 9
A(Actual Parameter) = 9
Call by value and call by reference:
Data can be passed from calling function to the called function in two ways
1. Call by value
2. Call by reference
In call by value a copy of the values of actual arguments from calling function are passed to the formal
parameters of the called function
Output:
values of x and y before swap
x=20 y=30
values of x and y after swap
x=20 y=30
Note:It is noticed that there is no change in the values of x and y of the function main after the call of the
function swap. Because, the function swap interchanged the values of a and b in the copy and this change is not
reflected in the original arguments x and y.
In call by reference the addresses of actual arguments are passed to the formal parameters. Since the formal
parameters hold addresses, they must be declared as pointers.
Smaller problems are solved and their solutions are applied to get the final
solution of the original problem.
Example:
void fun1()
{
--------
fun1();
--------
}
The function call fun1() is in the body of the function fun1().Thus fun1() calls itself. This feature is called
recursion.
Example:
void main()
{
printf(“\nKLU”);
main();
}
In this example main() calls itself indefinitely.
Since recursion process simulates repetitive process, it is required to check a condition for stopping the
repetitions.
Writing a Recursive Function
Recursion is a way of thinking about a problem, so before writing recursive function for a problem we should be
able to define the solution of problem in terms of a similar type of a smaller problem.
The two main steps in writing a recursion function are-
• Identification of base case and its solution, i.e., the case where solution can be achieved
without recursion.
• Identification of the general case or the recursive case i.e., the case in which recursion call
will be made.
Identification of base case is very important because without it the function will keep on calling
itself resulting in infinite recursion.
We must ensure that each recursive call takes us closer to the base case i.e., the size of the problem should be
diminished at each recursive call.
*The recursive calls must be made in such a way that finally we arrive at the base case. If we don’t do so, we
will have infinite loop.
*So merely defining a base case will not help us avoid infinite recursion, we should implement the function such
the base case finally reached.
When any function is called from main(), the memory is allocated to it on stack. A recursive function calls itself,
the memory for called function is allocated on top of memory allocated to calling function and different copy of
local variables is created for each function call. When the base case is reached, the function returns its value to
the function by whom it is called and memory is de-allocated and the process continues.
Let us take the example how recursion works by taking a simple function.
int main()
{
int test = 3;
printFun(test);
}
Output :
321123
When printFun(3) is called from main(), memory is allocated to printFun(3) and a local variable test is
initialized to 3 and statement 1 to 4 are pushed on the stack as shown in below diagram. It first prints ‘3’. In
statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to
2 and statement 1 to 4 are pushed in the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls
printFun(0). printFun(0) goes to if statement and it return to printFun(1). Remaining statements of printFun(1)
are executed and it returns to printFun(2) and so on. In the output, value from 3 to 1 are printed and then 1 to 3
are printed. The memory stack has been shown in below diagram.
Examples of Recursion:
Recursive function to find factorial of an integer
For example (Factorial of 5) is: !5 = 5*4*3*2*1 = 120
Factorial program using recursion
#include <stdio.h>
//function for factorial
long int factorial(int n)
{
if(n==0) return 1;
return n*factorial(n-1);
}
int main()
{
int num;
long int fact=0;
fact=factorial(num);
printf("Factorial of %d is = %ld",num,fact);
printf("\n");
return 0;
}
Program:
#include<stdio.h>
int add(int n);
int main()
{
int num;
printf(“enter a positive number”);
scanf(“%d”,&num);
Printf(“sum of n numbers is: %d\n”,add(n));
}
Int add(int x)
{
If(n!=0)
return( n+add(n-1) );
else
return n;
}
For example GCD of 20 and 28 is 4 and GCD of 98 and 56 is 14.GCD of 36,60 is 12.
Finding GCD of two numbers
This program takes two positive integers as input from the user and calculates GCD using recursion.
#include <stdio.h>
int hcf(int n1, int n2);
int main()
{
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, hcf(n1,n2));
return 0;
}
Fibonacci Series
Following is another example which generates fibonacci series for a given number using a recursive function:
#include <stdio.h>
int fibonaci(int i)
{
if(i= =0)
return 0;
else if (i= =1)
return 1;
else return (fibonaci(i-1) + fibonaci(i-2));
}
void main()
{
int i;
for (i = 0; i < 10; i++)
printf("%d\t%n", fibonaci(i));
}
When the above code is compiled and executed, it produces the following result:
0 1 1 2 3 5 8 13 21 34
B. Scope of Variable
Scope of Variable tells compile about the visibility of Variable in the block.
Variable may have (a)Block Scope , (b)Local Scope and (c)External Scope.
D. Lifetime of variable
Lifetime of the = Time Of - Time of Variable
variable Declaration Destruction
Suppose we have declared variable inside main function then variable will be destroyed only when the control
comes out of the main .i.e end of the program.
Global Declaration:
#include<stdio.h>
void Check();
int a=5; // "a” is global variable because it is outside every function
void main()
{
a+=4;
printf("a=%d\n",a);
Check(); // Variable “a” is not declared in this function but, works in any
function as they are global variable
}
void Check()
{
++a;
printf("a=%d\n",a);
}
void main( )
{
int i;
for(i=1; i<5; i++)
printf(“%d\n”, fun1( ));
}
int fun1(void )
{
static int x=10;
return(++x);
}
Output: count is 5
//Default value of extern is Zero
Session 26 Arrays
Content:
Arrays:
1. Program to print the position of given element from the list of values (To print the location of
given employee id in an array)
void main( )
{
int a[10],i,n,pos,ele;
printf(“enter n value”);
scanf(“%d”,&n);
printf(“enter values for the array”);
for(i=0;i<n;i++)
{
scanf(“%d”,&n);
}
printf(“enter the value to find position”);
scanf(“%d”,&ele);
for(i=0;i<n;i++)
{
if(a[i]==ele)
{
pos=i+1;
}
}
2. program to find the average of given N positive integers and then find out the number of elements
less than the average and greater than the average.
void main( )
{
int a[10],i,n,lcount=0,scount=0,avg,sum=0;
printf(“ enter n value”);
scanf(“%d”,&n);
printf(“enter values for the array”);
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
for(i=0;i<n;i++)
{
sum=sum+a[i]);
}
avg=sum/n;
for(i=0;i<n;i++)
{
if(a[i]>=avg)
Gcount++;
else
scount++;
}
printf(“number of values less than average =%d”,scount);
printf(“number of values grater than average=%d”,lcount);
}
#include <stdio.h>
int main(){
int n, i;
float num[100], sum=0.0, average;
printf("Enter the numbers of data: ");
scanf("%d",&n);
while (n>100 || n<=0)
{
printf("Error! number should in range of (1 to 100).\n");
printf("Enter the number again: ");
scanf("%d",&n);
}
for(i=0; i<n; ++i)
{
printf("%d. Enter number: ",i+1);
scanf("%f",&num[i]);
sum+=num[i];
}
average=sum/n;
printf("Average = %.2f",average);
return 0;
}
void main()
{
int array[MAXSIZE];
int i, num, negative_sum = 0, positive_sum = 0;
float total = 0.0, average;
𝑎[0] 𝑎[1]𝑎[2]𝑎[3]𝑎[4]
10 20 30 40 50
2000 2002 2004 2006 2006
a (array name)
&a[0]
Array name ‘a’ represent the base address i.e 2000. Thus both a and &a[0] represent the address of the first
element i.e 2000.
In general &a[i] is represented as a+i to get the i th elements address of the array.
Array Of Pointers
We can declare an array that contains pointers as its elements. Every element of this array is a pointer variable
that can hold address of any variable of appropriate type.
The syntax of declaring an array of pointers is similar to that of declaring arrays except that an asterisk is
placed before the array name.
datatype *arrayname[size];
For example to declare an array of size 10 that contains integer pointers we can write
int *arrp[10];
/*Program for understanding the concept of array of pointers*/
#include<stdio.h>
main ( )
{
int *pa[3];
int i,a=5,b=10,c=15;
pa[0]=&a;
pa[1]=&b;
pa[2]=&c;
for(i=O;i<3;i++)
{
printf ("pa [%d] = %u \t",i,pa[i]);
printf("*pa[%d] = %d\n",i,*pa[i]);
}
}
Output:
pa[O] = 2012 *pa[O] = 5
pa[l] = 2560 *pa[l] = 10
pa[2] = 3020 *pa[2] = 15
Here pa is declared as an array of pointers. Every element of this array is a pointer to an integer. pa[i] gives the
value of the ith element of 'pa' which is an address of any int variable and *pa[i] gives the value of that int
variable.
The array of pointers can also contain addresses of elements of another array.
/*Program for understanding array of pointers* /
#include<sidio.h>
main( )
{
int i,arr[4]={5,lO,15,20};
int *pa[4];
for(i=O;i<4;i++)
pa[i] = &arr[i];
for(i=O;i<4;i++)
{
printf ("pa [%d] = %u \t",i,pa[i]);
printf (" *pa[%d] = %d\n",i,*pa[i]);
}
}
Output:
pa[O] = 1000 *pa[O] = 5
pa[l] = 1002 *pa[l] = 10
pa[2] = 1004 *pa[2] = 15
pa[3] = 1006 *pa[3] = 20
Here 'pa' is declared as array of pointers. Each element of this array contains the address of each element of
array 'arr'.
******************************************************************************
Now we'll take a 2-D array arr with 3 rows and 4 columns. An array of pointers of size 3 is declared and each
pointer in this array is assigned the address of Oth element of each row of the 2-D array, i.e., ith element of pa is
a pointer to Oth element of ith row of a 2-D array. This can be done as-
Now let us see how we can access the elements of the 2-D array' arr using the array of pointers pa.
pa[0] is a pointer to the 0th element of 0th I-D array of the array arr, similarly pa will be a pointer to 0th element
of ith I-D array of arr.
Since base type of pointer pa[i] is int, so if we want the address of jth element of ith I-D array then we can add j
to the expression pa[i]. Hence the expression pa[i]+j will give the address of jth element of ith I-D array. So the
expression *( pa[i]+j ) will give the value of the jth element of ith I-D array.
We know that pa[i] is equivalent to *(pa+i). So the above expression can be written as *(*(pa+i) +j), and we
know that this expression is equivalent to pa[i][j]. So finally we can access the jth element of ith I-D array by
writing pa[i][j].
/"program for understanding array of pointers*/
#include<stdio.h>
main( )
{
int i, j , arr [3] [4] = { { 10, 11, 12, 13}, {2 0,21,22, 23 }, {3 0, 31,32,33 } } ;
int *pa[3];
for(i=O;i<3;i++)
pa [i] =arr [i] ;,
for(i=O;i<3;i++)
{ for(j=O;j<4;j++)
printf("%d ",pa[i] [j]);
printf("\n");
}
}
Output:
10 11 12 13
20 21 22 23
30 31 32 33
Pointer to an Array
We can also declare a pointer that can point to the whole array. This pointer is useful
when talking about multidimensional arrays.
Declaring a pointer to an array.
int (*Ptr)[10] ;
Here ptr is pointer that can point to an array of 10 integers. Note that it is necessary to enclose the pointer name
inside parentheses. Here the type of ptr is 'pointer to an array of 10 integers' Note that the pointer that points to
the 0th element of array and the pointer that points to the whole array are totally different. The following
program shows this'::
/*P9.11 Program to understand difference between pointer to an integer and pointer to an array of
integers*/
#include<stdio.h>
int main(void)
{
int *p; /*Can point to an integer*/
int (*ptr)[5]; /*Can point to an array of 5 integers*/
int arr[5];
p=arr; /*Points to 0th element of arr*/
ptr=&arr; /*Points to the whole array arr*/
printf("p=%p,ptr=%u\n",p,ptr);
p++;
ptr++;
printf("p=%p,ptr=%u\n",p,ptr);
return 0;
}
Output:
p = 3000, ptr = 3000
p = 3004, ptr = 3010
Here p is pointer that points to 0th element of array arr, while ptr is a pointer that points to the whole array arr.
The base type of p is 'int' while base type of ptr is an array of 5 integers.' We Know that the pointer arithmetic is
performed relative to the base size, so if we write ptr++, then the pointer ptr will be shifted forward by 10 bytes.
The following figure shows the pointers p and ptr, in this chapter we'll use darker arrow to denote pointer to an
array
On dereferencing a pointer expression we get a value pointed to by that pointer expression. Pointer to an array
points to an array, so on dereferencing it we should get the array, and the name of array denotes the base
address. So whenever a pointer to an array is dereferenced, we get the base address of the array to which it
points.
/*Program to dereference a pointer to an array*/
#include<stdio.h>
main ( )
{
int arr [5J = {3, 5,6,7,9} ;
int *p=arr;
int (*ptr) [5]=arr;
printf("p = %u, ptr = %u\n",p,ptr);
printf("*p = %d, *ptr = %u\n",*p,*ptr);
printf("sizeof(p) = %u, sizeof(*p) = %u\n",sizeof(p),sizeof(*p));
printf("sizeof(ptr) = %u, sizeof(*ptr) = %u\n",sizeof(ptr),sizeof(*ptr));
}
p = 3000, ptr = 3000
*p = 3, *ptr = 3000
sizeof(p) = 2, sizeof(*p) = 2
sizeof(ptr) = 2, sizeof(*ptr) = 10
Initilizing a 2D Array
Multidimensional arrays may be initialized by specifying bracketed values for each row. Following is an array
with 3 rows and each row has 4 columns.
int a[3][4] = {
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to
the previous example −
For processing 2-D arrays, we use two nested for loops. The outer for loop corresponds to the row
and the inner for loop corresponds to the column.
/* function declaration */
double getAverage(int arr[], int size);
int main () {
return 0;
}
double getAverage(int arr[], int size)
{
int i;
double avg;
double sum = 0;
return avg;
}
When the above code is compiled together and executed, it produces the following result −
Average value is: 214.400000
As you can see, the length of the array doesn't matter as far as the function is concerned because C performs no
bounds checking for formal parameters.
• Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
• If x matches with an element, return the index.
• If x doesn’t match with any of elements, return -1.
// Linearly search x in arr[]. If x is present then return its
// location, otherwise return -1
int search(int arr[], int n, int x)
{
int i;
for (i=0; i<n; i++)
if (arr[i] == x)
return i;
return -1;
}
The idea of binary search is to use the information that the array is sorted and reduce the time complexity to
O(Logn).
We basically ignore half of the elements just after one comparison.
1. Compare x with the middle element.
2. If x matches with middle element, we return the mid index.
3. Else If x is greater than the mid element, then x can only lie in right half subarray after the mid
element. So we recur for right half.
4. Else (x is smaller) recur for the left half.
Recursive implementation of Binary Search
#include <stdio.h>
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Run on IDE
Output:
Element is present at index 3
Iterative implementation of Binary Search
C/C++PythonJava
#include <stdio.h>
int main(void)
{
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr)/ sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n-1, x);
(result == -1)? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
Output:
Element is present at index 3
Time Complexity:
The time complexity of Binary Search can be written as
T(n) = T(n/2) + c
The above recurrence can be solved either using Recurrence T ree method or Master method. It falls in case II of
Master Method and solution of the recurrence is \Theta(Logn).
Session 31 Bubble Sort
Content:
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they
are in wrong order.
Example:
First Pass:
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap
them.
Second Pass:
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one
whole pass without any swap to know it is sorted.
Third Pass:
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Fourth Pass
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )