0% found this document useful (0 votes)
13 views74 pages

4 Function

The document discusses modular programming and functions, detailing the process of breaking complex programs into smaller units. It covers the definition and usage of standard and user-defined functions, function parameters, variable scope, and different parameter passing techniques. Additionally, it provides examples of function definitions, calls, and the handling of arrays in functions.

Uploaded by

kaustubh.kuniyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views74 pages

4 Function

The document discusses modular programming and functions, detailing the process of breaking complex programs into smaller units. It covers the definition and usage of standard and user-defined functions, function parameters, variable scope, and different parameter passing techniques. Additionally, it provides examples of function definitions, calls, and the handling of arrays in functions.

Uploaded by

kaustubh.kuniyal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 74

S t r u c t u r e d

P r o g r a m m i n g - f u n c ti o n s
M o d u l a r p r o g r a m m i n g a n d
F u n c ti o n s

1
Modularization and Function
• Process of splitting the lengthier and complex programs
into a number of smaller units is called Modularization.

• Programming with such an approach is called Modular


programming

• A function is a set of instructions to carryout a particular


task.

• Using functions we can structure our programs in a more


modular way.

2
Functions
Standard functions
(library functions or built in functions)

User-defined functions
Written by the user(programmer)

3
General form of function definition

return_type function_name(parameter_definition)
{
variable declaration;

statement1;
statement2;
.
.
.
return(value_computed);
}
4
Defining a Function
Name (function name)
• You should give functions descriptive names
• Same rules as variable names, generally
Return type
• Data type of the value returned to the part of the program that activated (called)
the function.
Parameter list (parameter_definition)
• A list of variables that hold the values being passed to the function
Body
• Statements enclosed in curly braces that perform the function’s operations(tasks)

5
Understanding of main function

Return type Function


name Parameter
List

int main (void)

}
{
printf(“hello world\n”); Body
return 0;
}
6
Function Definition and Call
// FUNCTION DEFINITION
Return typeFunction Parameter
name
void DisplayMessage(void) List
{
printf(“Hello from function DisplayMessage\n”);
}
int main()
{
printf(“Hello from main \n”);
DisplayMessage(); // FUNCTION CALL
printf(“Back in function main again.\n”);
return 0;
}
7
Multiple Functions- An example
void First (void){ // FUNCTION DEFINITION
printf(“I am now inside function First\n”);
}
void Second (void){ // FUNCTION DEFINITION
printf( “I am now inside function Second\n”);
First(); // FUNCTION CALL
printf(“Back to Second\n”);
}
int main (){
printf( “I am starting in function main\n”);
First ();
printf( “Back//toFUNCTION CALL
main function \n”);
Second ();
printf( “Back //toFUNCTION CALL
main function \n”);
return 0;
}
8
Arguments and parameters
Variables used in the function reference or function
call are called as arguments.
These are written within the parenthesis followed by
the name of the function. They are also called actual
parameters (during call).
Variables used in function definition are called
parameters, They are also referred to as formal
parameters.

9
Functions
Formal
parameters

void dispChar(int n, char c) {


printf(" You have entered %d & %c”,n,c);
}

int main(){ //calling program


int no; char ch;
printf(“Enter a number & a character: \
n“);
scanf(“%d %c”,&no,&ch); Actual
dispChar( no, ch); //Function
parameters
reference 10
return 0;
Scope of Variables
• A scope is a region of the program where a defined
variable can have its existence and beyond that variable
it cannot be accessed.

• There are two types of variables in C


1) local variables
2) global variables

11
Local Variables
• Variables that are declared inside a function are called
local variables.
• They can be used only by statements that are inside that
function.
• In the following example all the variables a, b, and c are
local to main() function.

#include <stdio.h>
int main () {
/* local variable declaration */
int a, b, c;
a = 10; b = 20; c = a + b;
printf ("value of a = %d, b = %d and c =
%d\n", a, b, c);
return 0;
12
}
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.

#include <stdio.h>
int g; /* global variable declaration */
int main () {
int a, b; /* local variable declaration */
a = 10; b = 20; g = a + b;
printf ("value of a = %d, b = %d and g =
%d\n", a, b, g);
return 0;
13
}
Functions- points to note
1. The parameter list must be separated by commas.
dispChar( int n, char c);
2. The parameter names do not need to be the same in the prototype
declaration and the function definition.
3. The types must match the types of parameters in the function
definition, in number and order.
void dispChar(int n, char c); //proto-type
void dispChar(int num, char ch){
printf(" You have entered %d &%c”,
num,ch);
}
4. Use of parameter names in the declaration(prototype) is optional
but parameter type is a must.
void dispChar(int , char); //proto-type
14
Functions- points to note
5. If the function has no formal parameters, the list can be
written as (void) or simply ()
6. The return type is optional, when the function returns
integer type data.
7. The return type must be void if no value is returned.
8. When the declared types do not match with the types
in the function definition, compiler will produce error.

15
Functions- Categories
Categorization based on the arguments and return
values
1. Functions with no arguments and no return
values.
2. Functions with arguments and no return
values.
3. Functions with arguments and one return
value.
4. Functions with no arguments but return a
value. 16
Function with No Arguments/parameters & No return
values

dispPattern(); // prototype

int main(){
printf(“fn to display a line of stars\n”);
dispPattern();
return 0;
}

dispPattern(){
int i;
for (i=1;i<=20 ; i++)
printf( “*”);
}
17
Function with No Arguments but A return value
int readNum(void); // prototype

int main(){
int c;
printf(“Enter a number \n”);
c=readNum();
printf(“The number read is %d“,c);
return 0;
}
int readNum(){
int z;
scanf(“%d”,&z);
return(z);
}
18
Fn with Arguments/parameters & No return values
void dispPattern(char ch); // prototype
int main(){
printf(“fn to display a line of patterns\n”);
dispPattern(‘#’);
dispPattern(‘*’);
dispPattern(‘@’);
return 0;
}
void dispPattern(char ch ){
int i;
for (i=1;i<=20 ; i++)
printf(“%c”,ch);
}

19
Function with Arguments/parameters & One return
value
int fnAdd(int,int);
int main(){
int a,b,c;
printf(“\nEnter numbers to be added\n”);
scanf(“%d %d”,&a,&b);
c=fnAdd(a,b);
printf(“Sum is %d “, c);
return 0;
}
int fnAdd(int x, int y ){
int z;
z=x+y
return(z);
} 20
Extra Problems…
Write appropriate functions to
1. Find the factorial of a number ‘n’.
2. Reverse a number ‘n’.
3. Check whether the number ‘n’ is a palindrome.
4. Generate the Fibonacci series for given limit ‘n’.
5. Check whether the number ‘n’ is prime.
6. Generate the prime series using the function written
for prime check, for a given limit.

21
Parameter passing techniques

22
Functions- Parameter Passing

 Pass by value (call by value)

 Pass by reference (call by reference)

2
3
Pass by value:
void swap(int x, int y )
{
int t=x;
x=y;
y=t;
printf(“In fn: x= %d and y=%d “,x,y);
}
Output:
int main() In fn: x = 7 & y = 5
{ After swap: a = 5 & b = 7
int a=5,b=7;
swap(a, b);
printf(“After swap: a= %d and b= %d“,a,b);
return 0;
2
} 4
Pass by Reference – Using Pointers:
void swap(int *x, int *y )
{ Change is directly on the
int t=*x; variable using the reference
*x=*y; to the address.
*y=t; When function is
called:
}
address of a  x
address of b  y
Output:
int main() After swap: a = 7
{ and b = 5
int a=5,b=7;
swap(&a, &b);
printf(“After swap: a=%d and b= %d”,a,b);
return 0; } 2
5
Pointers as functions arguments:
When we pass addresses to a function, the parameters receiving
the addresses should be pointers.
int change (int *p) #include <stdio.h>
{ int main()
*p = *p + 10 ; {
return 0; int x = 20;
} change(&x); Output :
X after change=30
printf(“x after change==
%d“,x);
return 0;
}
26
Pointers as function arguments
• When the function change() is called, the address of the
variable x, not its value, is passed into the function
change().

• Inside change(), the variable p is declared as a pointer


and therefore p is the address of the variable x. The
statement

• *p=*p +10 adds 10 to the value stored at the address p.


Since p represents the address of x, the value of x is
changed from 20 to 30. therefore it prints 30.
27
Function that return multiple values-Using pointers

Using pass by reference we can write a function that


return multiple values.

void fnOpr(int a, int b, int *sum, int *diff) {


*sum = a + b;
*diff = a -b; }

int main() { Output:


int x, y, s, d; x= 5 & y=
printf(“Enter two numbers: \n“); 3
scanf(“%d %d”,&x, &y); Sum =8 &
fnOpr(x, y, &s, &d); Diff = 2
printf(“Sum = %d & Diff =%d “, s, d);
return 0; }
28
Nesting of functions:
• C language allows nesting of functions by calling one function
inside another function.
• Nesting of function does not mean that we can define an entire
function inside another function. The following examples shows
both valid and invalid function nesting in C language

// Wrong way of function nesting // Right way of function nesting

void fun() void sleep()


{ {
printf(“I am having Fun….”); printf(“I am having sleep”);
}
void sleep()
{ void fun()
printf(“I am having sleep”); {
} printf(“I am having Fun….”);
} sleep();
}
29
Nesting of Functions:
void First (void){ // FUNCTION DEFINITION
printf(“I am now inside function First\n”);
}
void Second (void){ // FUNCTION DEFINITION
printf( “I am now inside function Second\n”);
First(); // FUNCTION CALL
printf(“Back to Second\n”);
}
int main (){
printf( “I am starting in function main\n”);
First ();
// FUNCTION CALL
printf( “Back to main function \n”);
Second ();
printf( “Back //
toFUNCTION CALL
main function \n”);
return 0;
}
30
Nesting of Functions:
void fnOpr(int a, int b, int *sum, int *diff)
{
*sum = a + b; int fnDiff(int p,
if (fnDiff(a,b)) int q){
*diff = a -b; if (p>q)
else return(1);
*diff = b - a; else
} return (0);}
int main() {
int x, y, s, d; Output:
printf(“Enter the values: \n“); x= 3 & y=
scanf(“%d %d”, &x, &y); 5
fnOpr(x, y, &s, &d); s =8 & d =
2
printf(“The results are, Sum =%d and Diff = %d“, s, d);
return 0; }
31
Passing 1D-Array to Function
Rules to pass an array to a function
 The function must be called by passing only the name of
the array.

 In the function definition, the formal parameter must be


an array type; the size of the array does not need to be
specified.

 The function prototype must show that argument is an


array.

32
Passing 1D-Array to Function:
int fnSum( int a[ ], int n) {
int sum=0,i;
for(i=0;i<n;i++)
sum+=a[i];
return (sum); } Output: n=5
1, 2, 3, 4, 5
int main() { Sum of
int n, a[20], x, y,i; elements = 15
printf(“Enter the limit \n“); Array name is passed
scanf(“%d”,&n); along with number of
printf(“Enter the values: \n“); elements
for (i=0; i<n; i++)
scanf(“%d”,&a[i]);
printf(“The sum of array elements is =%d “,fnSum(a, n));//fn call
return 0; }
33
Passing 2D-Array to Function:

Rules to pass a 2D- array to a function


 The function must be called by passing only the array
name.
 In the function definition, we must indicate that the
array has two-dimensions by including two set of
brackets.

 The size of the second dimension must be specified.

 The prototype declaration should be similar to function


header.

34
Passing 2D-Array to Function:
int fn2d(int x[ ][10], int m, int n)
{
int i, j, sum=0; Output: m=2 n=3
for(i=0; i<m; i++) 1 2
for(j=0; j<n; j++) 3 4
sum+=x[i][j]; 5 6
return(sum); Sum of elements = 21
}
int main() {
int i, j, a[10][10], m, n;
printf("Enter dimentions of matrix");
scanf("%d%d", &m, &n);
printf("Enter the elements");
for(i=0;i<m;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
printf ("Sum of elements of 2D array is=%d",fn2d(a, m, n));
return 0;
}
35
Extra problems:
• Write a c program to add all the even elements of an array
using a function Add().

• Write a C program to replace all odd numbers of an array with


the largest number in the array using a function Replace().

• Write a C program to replace all the zeros in the matrix by the


trace of the matrix using a function Trace().

• Write a C program using pass-by-pointer method to compute


the compound interest using a function Compound().

36
Write a c program to add all the even elements of an array using a function Add()

#include <stdio.h> int main()


int Add( int a[ ], int {
n) int n, a[20], x, y,i;
{ printf("Enter the limit \n");
int sum=0,i; scanf("%d",&n);
for(i=0;i<n;i++) printf("Enter the values: \n");
{ for (i=0; i<n; i++)
if((a[i]%2) == 0) scanf("%d",&a[i]);
sum+=a[i]; printf("The sum of even array
} elements is =%d
return (sum); ",Add(a,n));
} Return 0;
}

37
Write a C program to replace all odd numbers of an array with the largest number in the array using a function Replace()

#include <stdio.h>
void Replace( int arr[ ], int main()
int n) {
{ int n, a[20], x, y,i;
// To find the largest printf("Enter the limit \n");
int i, max = arr[0]; scanf("%d",&n);
for (i = 1; i < n; i++) printf("Enter the values: \n");
if (arr[i] > max) for (i=0; i<n; i++)
max = arr[i]; scanf("%d",&a[i]);
Replace(a,n);
// To replace printf("The array after replacement is\n");
for(i=0;i<n;i++) for (i=0; i<n; i++)
{ printf("%d \n",a[i]);
if(arr[i]%2 != 0)
arr[i]=max; return 0;
} }
}
38
Write a C program to replace all the zeros in the matrix by the trace of the matrix using a function Trace()

int main() {
#include <stdio.h> int i, j, m, n;
#include <math.h>
float a[10][10];
void Trace(float a[ ][10], int m, int n)
printf("Enter dimentions of matrix");
{ scanf("%d %d", &m, &n);
int i, j, norm, sum=0; printf("Enter the elements");
for(i=0;i<m;i++)
// Finding Trace for(j=0;j<n;j++)
for(i=0;i<m;i++) scanf("%f",&a[i][j]);
{ Trace(a, m, n);
for(j=0;j<n;j++) printf("Matrix after replacement \n");
sum=sum+a[ i ][ j]*a[ i ][ j ]; for(i=0;i<m;i++)
} {
norm=sqrt(sum); for(j=0;j<n;j++)
//Replacing zeros {
for(i=0;i<m;i++) printf("%f",a[i][j]);
for(j=0;j<n;j++) }
if(a[i][j]==0) printf("\n");
a[i][j]=sum; }
return 0;
} 39
}
Write a C program using pass-by-pointer method to compute the simple interest and compound interest using a function SI_CI()

#include <stdio.h>
#include <math.h>
int main() {
float p,q,r,SI,CI;
int n;
printf("Enter the value of Principal p = ");
scanf("%f",&p);
printf("Enter the value of Rate r = ");
scanf("%f",&r);
printf("Enter the value of Period in year n = ");
scanf("%d",&n);

SI_CI(&p,&r,&n,&SI,&CI);

printf("Simple Interest SI=%f \n",SI);


printf("Compound Interest CI=%f \n",CI);

return 0;
} 40
Write a C program using pass-by-pointer method to compute the simple interest and compound interest using a function SI_CI()

void SI_CI(float *pr, float *ra, int *yr, float *smp, float
*cmp)
{
int amount;

// Simple interest
*smp = ((*pr)*(*ra)*(*yr)/100);

// Compound interest
amount= (*pr)*pow((1 +(*ra)/100),(*yr));
*cmp= amount-(*pr);
}

41
RECURSION
What is Recursion ?
• Sometimes, the best way to solve a problem is by solving a
smaller version of the exact same problem first.

• Recursion is a technique that solves a problem by solving a


smaller problem of the same type.

• A recursive function is a function that invokes / calls itself


directly or indirectly.

43
Let us consider the code …
int main() {
int i, n, sum=0;
printf("Enter the limit“);
scanf(“%d”,n);
printf("The sum is %d“,fnSum(n));
return 0;
}
int fnSum(int n){
int sum=0;
for(i=1;i<=n;i++)
sum=sum+i;
return (sum);
} 44
Steps to Design a Recursive Algorithm
 Base case:
 It prevents the recursive algorithm from running forever.

 Recursive steps:
 Identify the base case for the algorithm.
 Call the same function recursively with the parameter
having slightly modified value during each call.
 This makes the algorithm move towards the base case and
finally stop the recursion.

45
Let us consider same code again …
int main() {
int i, n, sum=0; int fnSum(int x) {
printf("Enter the limit“); if (x == 1) //base case
scanf(“%d”, n);
return 1;
printf(“The sum is %d“,fnSum(n));
return 0; else
} return x + fnSum(x-1) ;

int fnSum(int n){ //recursive


int sum=0; case
for(i=1;i<=n;i++) }
sum=sum+i;
return (sum);
}
46
Factorial of a natural number–
a classical recursive
example

So factorial(5)
= 5* factorial(4)
= 4* factorial(3)
= 3*factorial(2)
= 2* factorial(1)
=
1*factorial(0)
47
Factorial- recursive procedure
#include <stdio.h>
long factorial (long a) {
if (a ==0) //base case
return (1);
return (a * factorial (a-1));
}
int main () {
long number;
printf("Please type a number: “);
scanf(“%d”, number);
printf(“number ! = %d”, factorial (number));
return 0;
}

48
Recursion - How is it doing!
rFact(5) 120

x =2 = 120
5 rFact(4)
4
Notice that the
recursion isn’t x
finished at the 4 rFact(3) = = 24
6
bottom --
It must unwind all x =
3 rFact(2) = 6
the way back to the
2
top in order to be
factorial(0) = 1
done.
factorial(n) = n * 2
x
rFact(1) = = 2
factorial(n-1) [for n>0] 1

long rFact (long a) {


if (a ==0) 1
x
rFact(0) = =1
return (1); 1
return (a * rFact (a-1));
}
49
Fibonacci Numbers: Recursion
fibonacci(0) = 0
fibonacci(1) = 1
fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) [for n>1]

So fibonacci(4)
= fibonacci(3) + fibonacci(2)
= (fibonacci(2) + fibonacci(1)) + (fibonacci(1) + fibonacci(0))
= ((fibonacci(1) + fibonacci(0)) + 1) + (1 + 0)
= ( 1 + 0 ) + 1) + (1 + 0)
=3

50
Fibonacci Numbers: Recursion
Fibonacci series is 0,1, 1, 2, 3, 5, 8 …
int rfibo(int n)
{
if (n <= 1)
return n;
else
return (rfibo(n-1) + rfibo(n-2));
}
Output:
n=4
fib = 3

51
Recursive Calls initiated by Fib(4)

52
Fibonacci Series using Recursion
int rfibo(int);

int main(void){
int n,i, a[20], fibo;
printf("enter any num to n\n“);
scanf(“%d”, n);
printf(“Fibonacci series “);
for (i=1; i<=n; i++)
{
fibo = rfibo(i);
printf(“%d”, fibo);
}
return 0;
}
53
GCD: Recursion

int gcd(int x, int y)


{ gcd(24,9)  Control In gcd fn on call
if (x == 0) gcd(9,24%9) gcd(9, 6)
return (y); gcd(6,9%6) gcd(6, 3)
if (y==0) gcd(3,6%3) gcd(3, 0)
return (x); return values return 3
return 3
return gcd(y, x % y); return 3
} return 3

Output:
x= 24 , y = 9
gcd = 3
54
Recursion - Should I or Shouldn’t I?

• Pros • Cons
– Recursion is a – Recursive programs
natural fit for typically use a large
recursive problems amount of computer
memory and the greater
the recursion, the more
memory used
– Recursive programs can
be confusing to develop
and extremely
complicated to debug

55
Recursion vs Iteration

RECURSION ITERATION

Uses more storage space Less storage space


requirement requirement

Overhead during runtime Less Overhead during


runtime

Runs slower Runs faster


A better choice, a more
elegant solution for Less elegant solution for
recursive problems recursive problems

56
Recursion – Do’s
• You must include a termination condition or Base
Condition in recursive function; Otherwise your
recursive function will run “forever” or infinite.
• Each successive call to the recursive function must be
nearer to the base condition.

57
Extra Problem- Finding product of two numbers
#include <stdio.h> int product(int a, int b)
{
int product(int, int); if (a < b)
int main() {
return product(b, a);
{
}
int a, b, result; else if (b != 0)
printf("Enter two numbers to find their product: "); {
return (a + product(a, b - 1));
scanf("%d%d", &a, &b); }
result = product(a, b); else
{
printf("%d * %d = %d\n", a, b, result); return 0;
return 0; }
}
}
Output:
Enter two numbers to find their product: 10
20
10*20=200
58
Extra Problem- Dividing two numbers
#include <stdio.h> int divide(int a, int b)
int divide(int a, int b); {
if(a - b <= 0)
{
int main() return 1;
{ }
else
int a,b; {
return divide(a - b, b) + 1;
printf("Enter two numbers for division"); }
}
scanf("%d%d", &a,&b);
printf("%d/%d=%d",a,b,divide(a,b));
return 0;
} Output:
Enter two numbers for division: 20 10
20/10=2

59
Extra Problem- Calculating power of a number
#include <stdio.h> int power(int base, int powerRaised)
int power(int n1, int n2); {
if (powerRaised != 0)
return (base*power(base, powerRaised-1));
int main()
else
{ return 1;
int base, powerRaised, result; }

printf("Enter base number: ");


scanf("%d",&base);

printf("Enter power number);


scanf("%d",&powerRaised);
Output:
result = power(base, powerRaised); Enter base number:3
Enter power number: 4
printf("%d^%d = %d", base, powerRaised, result); 3^4=81

return 0;
}
60
Extra Problem- Sum of natural numbers
#include <stdio.h> int sum(int num)
int sum(int n); {
if (num!=0)
return num + sum(num-1);
int main()
else
{ return num;
int number, result; }

printf("Enter a positive integer: ");


scanf("%d", &number);
Output:
result = sum(number); Enter a positive integer: 10
Sum= 55

printf("sum=%d", result);
}
61
Extra Problem- To count number of digits
#include <stdio.h>
int countDigits(int num)
int countDigits(int);
{
int main() static int count=0;
{
int number; if(num>0)
int count=0; {
count++;
printf("Enter a positive integer number: "); countDigits(num/10);
}
scanf("%d",&number);
else
{
count=countDigits(number); return count;
}
printf(“Number of digits is: %d\n",count); }
Output:
return 0; Enter a positive integer number: 123
Number of digits is: 3
}
62
Extra Problem- To find sum of all digits
#include <stdio.h>
int sumDigits(int num)
int sumDigits(int num); {
int main() static int sum=0;
{ if(num>0)
int number,sum; {
sum+=(num%10);
sumDigits(num/10);
printf("Enter a positive integer number: ");
}
scanf("%d",&number); else
{
sum=sumDigits(number); return sum;
}
printf("Sum of all digits are: %d\n",sum); }
Output:
return 0; Enter a positive integer number: 123
} Number of digits is: 3
63
Extra Problem-Reversing a Number

#include <stdio.h> int rev(int num){


int rev(int); static int n = 0;
int main() { if(num > 0)
int num; n = (n* 10) + (num%10) ;
printf(“enter else
number)”;
return n;
scanf(“%d”,num);
printf(“%d”, return rev(num/10);
rev(num)); } Output:
return 0; num = 234
} rev = 432

64
Extra Problem- To find length of a string

#include <stdio.h>
int length(char [], int); int length(char str[], int index)
{
int main()
if (str[index] == '\0')
{
char str[20]; {
int count; return 0;
}
printf("Enter any string :: "); return (1 + length(str, index + 1));
scanf("%s", str); }
count = length(str, 0);
printf("The length of string=%d.\n",count);
return 0;
Output:
}
Enter any string :: Manipal
The length of string= 7
65
Extra Problem-Binary Search
#include<stdio.h>
int binarySearch(int x[],int element,int start,int end);
int main(){
int x[20],n,i,index,start=0,end,element;
printf("Enter number of elements: ");
scanf("%d",&n);
end = n;
printf("Enter array elements: ");
for(i=0;i<n;i++){
scanf("%d",&x[i]);
}
printf("Enter the element to search: ");
scanf("%d",&element);
index = binarySearch(x,element,start,end-1);
if(index == -1)
printf("Element Not Found.\n");
else
printf("Element found at index : %d\n",index);
return 0;
66
}
Extra Problem-Binary Search
int binarySearch(int x[],int element,int start,int end){
int mid,noOfElements,i;
mid = (int)(start+end)/2;
if(start > end)
return -1;
if(x[mid] == element)
return mid;
else if(x[mid] < element){
start = mid+1;
binarySearch(x,element,start,end);
}
else{
start = 0;
end = mid-1; Output:
binarySearch(x,element,start,end); Enter number of
} elements: 5
Enter array elements: 1
2345
} Enter the element to
search: 3
67
Element found at
Extra Problem- Recursive Sorting
Base Case:
if length of the list (n) = 1
No sorting, return

Recursive Call:
1. Find the smallest element in the list and
place it in the 0th position
2. Sort the unsorted array from 1.. n-1
sortR(&list[1], n-1)

For eg: list [ ] = {33,-2,0,2,4} n=5

68
Extra problem-Sorting

list[] function calls


{33,-2,0,2,4} sort(list,5) Main()

{-2,33,0,2,4} sort(&list[1],4)

{-2,0,33,2,4} sort(&list[1],3)

{-2,0,2,33,4} sort(&list[1],2)

{-2,0,2,4,33} sort(&list[1],1)

Base case reached .... Return


69
Extra problem - Sorting
sortR(list, n);// call of fn & display of sorted array in
main()
int sortR(int list[], /* move smallest element
to 0-th element */
int ln){
tmp = list[0];
int i, tmp, min;
list[0] = list[min];
if (ln == 1)
list[min] = tmp;
return 0;
/* recursive call */
/* find index of smallest no
*/ return
min = 0; sortR(&list[1], ln-
for(i = 1; i < ln; i++) 1);
Output:
if (list[i] < }
Orign. array-: 33 -2
0 2 4
list[min]) Sorted array -: -2 0
2 4 33
min = i; 70
Factorial of a given number ‘n’
long factFn(int); //prototype long factFn(int num) {
//function definition
int main() { int i;
int n, f; long fact=1;

printf("Enter a number :“); //factorial computation


scanf(“%d”,&n); for (i=1; i<=num; i++)
f =factFn(n); fact=fact * i;
printf(“Fact= %d“,f);
// return the result
return 0; return (fact);
} }

71
Reversing a given number ‘n’
int Reverse(int); //prototype int Reverse(int num)
{
int main() int rev=0;
{ int digit;
int n,r;
printf("Enter a number : \n“); while(num!=0)
scanf(“%d”, &n); {
digit = num % 10;
r= Reverse(n); rev = (10 * rev) + digit;
printf(“ reversed no=%d“,r) num = num/10;
}
return 0; return (rev);
} }

72
Check whether given number is prime or not
int IsPrime(int); //prototype int IsPrime(int num) //prime
check
int main() { {
int n; int p=1;
for(int j=2;j<=num/2;j++)
printf(“Enter a number : “); {
scanf(“%d”,&n); if(num%j==0)
if (IsPrime(n)) {
Printf(“%d is a prime no”,n); p=0;
else break;
Printf(“%d is not a prime no”,n); }
return 0; }
} return p;
}

73
First n Fibonacci number generation
void fibFn(int); //prototype void fibFn(int lim) { //fib generation
int i, first, sec, next;
int main() { if (lim<=0)
printf("limit should be +ve.\n“);
int n;
else
printf("Enter the limit ”); {
scanf(“%d”,&n); printf("\nFibonacci nos\n“);
fibFn(n); //function call first = 0, sec = 1;
return 0; for (i=1; i<=lim; i++) {
} printf(“%d”, first)
next = first + sec;
first = sec;
sec = next;
}
}
}

74

You might also like