Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit Iii

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

PPS UNIT III Mrs.

Amtul Shanaz(CSE Dept,DCET)


Mrs. Sameera Begum(CSE Dept,DCET)

UNIT III

Searching

Searching is a process of finding a particular element among several


given elements.

The search is successful if the required element is found.


Otherwise, the search is unsuccessful.

The searching of an element in the given array may be carried out in


the following two ways-

1. Linear Search (or) Sequential search


2. Binary Search

Linear Search:
 Linear Search is the simplest searching algorithm.
 It traverses the array sequentially to locate the required element.
 It searches for an element by comparing it with each element of
the array one by one.

1
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

 So, it is also called as Sequential Search.

Linear Search Example-

Consider-
 We are given the following linear array.
 Element 15 has to be searched in it using Linear Search
Algorithm. Key=15

Now,
 Linear Search algorithm compares element 15 with all the
elements of the array one by one.
 It continues searching until either the element 15 is found or all
the elements are searched.

Linear Search Algorithm works in the following steps-

Step-01:

 It compares element 15 with the 1st element 92.


 Since 15 ≠ 92, so required element is not found.

2
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

 So, it moves to the next element.

Step-02:

 It compares element 15 with the 2nd element 87.


 Since 15 ≠ 87, so required element is not found.
 So, it moves to the next element.

Step-03:

 It compares element 15 with the 3rd element 53.


 Since 15 ≠ 53, so required element is not found.
 So, it moves to the next element.

Step-04:

 It compares element 15 with the 4th element 10.


 Since 15 ≠ 10, so required element is not found.
 So, it moves to the next element.

Step-05:

 It compares element 15 with the 5th element 15.


 Since 15 = 15, so required element is found.
 Now, it stops the comparison and returns index 4 at which element
15 is present.

3
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Performing Linear search using non-recursive procedure


/* Program to demonstrate Linear search on the list of array
elements */
# include <stdio.h>
void main ( )
{
int a [100];
int key, N, position, i;
int linearsearch (int [ ], int, int);
printf (“Enter the size of array: \n”);
scanf (“%d”, &N);
printf (“Enter elements of array elements\n”);
for (i=0; i< N; i++)
scanf (“%d”, &a [i]);
printf (“Enter the key element: \n”);
scanf (“%d”, &key);
position = linearsearch (a, N, key);
if (position = = -1)
printf (“element not found !!!”);
else
printf (“element found at %d location”, position +1);
}

4
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

int linearsearch(int a [ ], int N, intkey)


{
int i ;
for (i = 0; i< N; i++)
{
if (a [i] = = key)
return (i);
}
return (-1);
}

Binary Search:
 Binary Search is one of the fastest searching algorithms.
 It works on the principle of divide and conquer technique.

To apply binary search on an unsorted array,


 First, sort the array using some sorting technique.
 Then, use binary search algorithm.

Binary Search Example 1-

Consider-
 We are given the following sorted array.
 Element 15 has to be searched in it using Binary Search
Algorithm. Key=15

5
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Binary Search Algorithm works in the following steps-

Step-01:

 To begin with, we take low=0 and high=N-1=7-1=6.


 We compute location of the middle element as-
mid= (low+ high) / 2
= (0 + 6) / 2
=3
 Here, a[mid] = a[3] = 20 ≠ 15 and low < high.
 So, we start next iteration.

Step-02:

 Since a[mid] = 20 > 15, so we take high= mid – 1 = 3 – 1 = 2


whereas low remains unchanged.
 We compute location of the middle element as-
mid= (low + high) / 2
= (0 + 2) / 2
=1

6
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

 Here, a[mid] = a[1] = 10 ≠ 15 and low < high.


 So, we start next iteration.

Step-03:

 Since a[mid] = 10 < 15, so we take low = mid + 1 = 1 + 1 = 2


whereas high remains unchanged.
 We compute location of the middle element as-
mid
= (low + high) / 2
= (2 + 2) / 2
=2
 Here, a[mid] = a[2] = 15 which matches to the element being
searched.
 So, our search terminates in success and index 2 is returned.

7
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Example 2:

It is used to search for a particular element in sorted


Order(Ascending Order).
0 1 2 3 4 5
12 21 45 78 99 100

Suppose key=21
CASE:1
 Find low element, high element and middle element

 low=0
high=N-1 (Here N is the number of elements).
high=
0 1 2 3 4 5
12 21 45 78 99 100
low high

 Find Middle element:


middle=(low+high)/2
middle=0+5/2=2.5

8
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

0 1 2 3 4 5
12 21 45 78 99 100
low middle high

 Compare middle and key


if(a[middle]==key)
i.e 45==21(false)

 If it is false then we will compare whether


key<middle – If this condition is true then search in the
left side.

 If key>middle then search in the right side.

if(key<a[middle])
21<45(true)
0 1 2 3 4 5
12 21 45 78 99 100
low middle high

9
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

CASE:2
 Find low element, high element and middle element
low=0
high=middle-1
high= 2-1=1

0 1
12 21
low high

middle=(low+high)/2
middle=0+1/2=0.5=0(truncate the decimal)
0 1
12 21
low high
middle

 Compare middle and key


if(a[middle]==key)
12==21 (false)

10
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

 If(key<a[middle])
21<12(false) then search in the right side.

21
low
high
middle

 if(a[middle]==key)
21==21 (true)
Element Found.

Performing Binary search using non-recursive procedure


/* Program to perform binary search on the list of array elements */
# include <stdio.h>
void main ( )
{
int binarysearch (int [ ], int, int);
int a [100];
int N, key, position, i;
printf (“Enter the size of array: \n”);
scanf (“%d”, &N);
printf (“Enter %d elements in ASCENDING ORDER:”, N);
11
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

for (i=0; i< N; i++)


scanf (“%d”, &a[i]);
printf (“Enter the key element: \n”);
scanf (“%d”, &key);
position = binarysearch (a, N, key);
if (position = = -1)
printf (“element not found !!!”);
else
printf (“element found at %d location”, position +1);
}
int binarysearch (int a [ ], int N, int key)
{
int low = 0, high = N-1, middle;
while (low < = high)
{
middle = (low + high) / 2;
if (a [middle] = = key)
return (middle);
else if (key < a [middle])
high = middle – 1;
else
low = middle +1;
}

12
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

return (-1);
}

Sorting
Sorting is a process of arranging individual elements of a list
according to their proper rank, either in ascending or descending
order.

Bubble sort:
Bubble Sort is based on the idea of repeatedly comparing pairs of
adjacent elements and then swapping their positions if they exist in
the wrong order.

Steps on how it works:

1. In an unsorted array of 5 elements, start with the first two


elements and sort them in ascending order. (Compare the
element to check which one is greater).

2. Compare the second and third element to check which one is


greater, and sort them in ascending order.

3. Compare the third and fourth element to check which one is


greater, and sort them in ascending order.

13
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

4. Compare the fourth and fifth element to check which one is


greater, and sort them in ascending order.

5. Repeat steps 1–5 until no more swaps are required.

Example:
An Array with n elements is taken
 Here it compare the first 2 elements in the list that is
a[0] and a[1].

 If a[1] is smaller than a[0] Interchange or swap their


values.

 Again it compares next two elements in the list that is


a[1] and a[2] .

 If a[2] is smaller than a[1] Interchange or swap their


values.This will repeat till we get the sorted list

14
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Trip-1
25 25 25
46
25 46 35 35

35 35 46 2
2 2 2 46

Note: After end of 1st trip last element is sorted

Trip-2

25 25 25
35 35 2
2 2 35
46 46 46

Note: After end of 2nd trip last two elements are sorted

15
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Trip-3

25 2
2 25
35 35

46 46

In n-1 trips we got our sorted list

Performing Bubble sort on the given list of array elements


/* Program to perform Bubble sort on list of array elements */
# include <stdio.h>
void main ( )
{
int a [100];
int trip, N, i, temp;
printf (“Enter the size of array: \n”);
scanf (“%d”, &N);
printf (“Enter %d elements: \n”, N);
for (i=0; i< N; i++)
{
scanf (“%d”, &a [i]);
}
16
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

for (trip = 1; trip < N; trip++)


{
for (i=0; i<N-trip; i+ +)
{
if(a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[ i + 1];
a[i + 1] = temp;
}
}
}
printf (“\n the sorted array list is: \n”);
for (i=0; i< N; i + +)
printf("%d\t",a[i]);
}

17
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Selection sort:
How Selection Sort Works?

Consider the following elements are to be sorted in ascending order


using selection sort-
6, 2, 11, 7, 5

Selection sort works as-


 It finds the first smallest element (2).
 It swaps it with the first element of the unordered list.
 It finds the second smallest element (5).
 It swaps it with the second element of the unordered list.
 Similarly, it continues to sort the given elements.

As a result, sorted elements in ascending order are-


2, 5, 6, 7, 11

Selection Sort Example-1

Consider the following elements are to be sorted in ascending order-


6, 2, 11, 7, 5

The above selection sort algorithm works as illustrated below-

18
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Step-01: For i = 0

Step-02: For i = 1

Step-03: For i = 2

19
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Step-04: For i = 3

Step-05: For i = 4

Loop gets terminated as „i‟ becomes 4.

The state of array after the loops are finished is as shown-

20
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

With each loop cycle,


 The minimum element in unsorted sub-array is selected.
 It is then placed at the correct location in the sorted sub-array
until array A is completely sorted.

Example-2

 Find the smallest element in the unsorted array.


 Place the smallest element in the first position.

Ex: N=8
20 35 18 8 14 41 3 39

i=0
3 35 18 8 14 41 20 39

21
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

i=1
3 8 18 35 14 41 20 39

i=2
3 8 14 35 18 41 20 39

i=3
3 8 14 18 35 41 20 39

i=4
3 8 14 18 20 41 35 39

i=5
3 8 14 18 20 35 41 39

i=6
3 8 14 18 20 35 39 41

22
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

From i=0 to i=6(7 times)


The Unsorted part is gone through (N-1) times. i.e 8-1=7

Performing Selection sort on the given list of array elements *


/* Program to perform Selection sort on the given list of numbers */
# include <stdio.h>
void main ( )
{
int A [100];
int small, N, i, j, temp;
printf (“Enter the size of array: \n”);
scanf (“%d”, &N);
printf (“\n Enter array elements: \n”, N);
for (i=0; i< N; i++)
scanf (“%d”, &A [i]);
for (i=0; i<N; i + +)
{
small = i;
for (j =i + 1; j < N; j + +)
{
if (A [j] < A[small])
{
small = j;
23
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

}
}
temp = A [i];
A [i] = A [small];
A [small] = temp;
}
printf (“\n the sorted array list is: \n”);
for (i = 0; i< N; i + +)
printf (“ %d \t”, A [i]);
}

24
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Functions

A function is a block of code that performs a specific task.

Dividing complex problem into small components makes program easy to understand and use.

Types of functions

Depending on whether a function is defined by the user or already included in C compilers, there
are two types of functions in C programming

 Standard library functions


 User defined functions

Standard library functions

The standard library functions are built-in functions in C programming to handle tasks such as
mathematical computations, I/O processing, string handling etc.

These functions are defined in the header file. When you include the header file, these functions
are available for use. For example:

The printf() is a standard library function to send formatted output to the screen (display output
on the screen). This function is defined in "stdio.h" header file.

There are other numerous library functions defined under "stdio.h", such
as scanf(), fprintf(), getchar() etc. Once you include "stdio.h" in your program, all these functions
are available for use.

Note : see the table given in unit one

25
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

User-defined functions

As mentioned earlier, C allow programmers to define functions. Such functions created by the
user are called user-defined functions.

Depending upon the complexity and requirement of the program, you can create as many user-
defined functions as you want.

How user-defined function works

#include <stdio.h>

voidfunctionName()

... .. ...

... .. ...

int main()

... .. ..

.. .. ...

functionName();

26
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

... .. ...

... .. ...

The execution of a C program begins from the main() function.

When the compiler encounters functionName(); inside the main function, control of the program
jumps to

void functionName()

And, the compiler starts executing the codes inside the user-defined function.

The control of the program jumps to statement next to functionName(); once all the codes inside
the function definition are executed.

Remember, function name is an identifier and should be unique.

Need for user defined functions (or)Advantages of user-defined function

1. The program will be easier to understand, maintain and debug.


2. Reusable codes that can be used in other programs
3. A large program can be divided into smaller modules. Hence, a large project can be
divided among many programmers.

27
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Elements of user defined functions

1.function definition

2. function call

3. function declaration or prototype

#include<stdio.h>

int addNumbers(int a, int b); // function prototype

int main()

int n1,n2,sum;

printf("Enters two numbers: ");

scanf("%d %d",&n1,&n2);

sum = addNumbers(n1, n2); // function call

printf("sum = %d",sum);

return 0;

28
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

int addNumbers(inta,int b) // function definition

int result;

result = a+b;

return result; // return statement

Function definition

Function definition contains the block of code to perform a specific task i.e. in this case, adding
two numbers and returning it.

It is divided into two parts namely function head, function body.

When a function is called, the control of the program is transferred to the function definition.
And, the compiler starts executing the codes inside the body of a function.

Note: We should not use semicolon ; in function definition() head same like main() function.

The general syntax of a functiondefinition is as follows:

return_type function_name(parameter list) /*……..function head…….*/

{
local_variables declaration; /*…..function body…..*/
executable statement(s);
return_value;
}

29
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Example:

int add( int a, int b )


{
int sum;
sum = a + b;
return sum; }

In function head:

Return Type

 The "return type" indicates what kind of data this function will return. In the example
above,the function returns an int.

 If the function returns nothinguse the return type "void".


 If no return type is given, the compiler will normally assume the function returns an int.

Function Name

 The function name is an identifier by which this function will be known, and obeys the
same naming rules as applied to variable names

 It can be anything, however it is advised to have a meaningful name for the functions so
that it would be easy to understand the purpose of function just by seeing it’s name.

30
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Formal Parameter List

 Following the function name are a pair of parentheses containing a list of the formal
parameters, ( arguments ) which receive the data passed to the function.Argument list
contains variables names along with their data types. These arguments are kind of inputs
for the function.
 If a function takes no parameters, the parameters may be left empty. The compiler will
not perform any type checking on function calls in this case. A better approach is to
include the keyword "void" within the parentheses, to explicitly state that the function
takes no parameters.

In Function Body:

 The body of the function is enclosed within curly {} braces, just as the "main" function
with which we have been dealing so far, and contains the instructions that will be
executed when this function is called.
 The function body starts by declaring all local variables, prior to any executable
statements.

Return Statement

 The return statement exits the called function and returns control back to the calling
function.
o Once a return statement is executed, no further instructions within the function are
executed.
 A single return value ( of the appropriate type ) may be returned.
o Parentheses are allowed but not required around the return value.

31
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

o A function with a void return type will not have a return value after the return
statement.
 More than one return statement may appear in a function, but only one will ever be
executed by any given function call.

In the example, the value of variable result is returned to the variable sum in the main() function.

Syntax of return statement

return (expression);

For example,

32
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

return a;

return (a+b);

The type of value returned from the function and the return type specified in function prototype
and function definition must match.

Function Call

Control of the program is transferred to the user-defined function by calling it.

Syntax of function call

functionName(argument1, argument2, ...);

In the above example, function call is made using addNumbers(n1,n2); statement inside
the main().

Passing arguments to a function

In programming, argument refers to the variable passed to the function. In the above example,
two variables n1 and n2 are passed during function call. These are called actual parameters.

The parameters a and b accepts the passed arguments in the function definition. These arguments
are called formal parameters of the function.

33
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

The type of arguments passed to a function and the formal parameters must match, otherwise the
compiler throws error.

If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be
of float type.

A function can also be called without passing an argument.

Function prototype

A function prototype is simply the declaration of a function that specifies function's name,
parameters and return type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later be used in the
program.

34
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2,...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides
following information to the compiler:

1. name of the function is addNumbers()


2. return type of the function is int
3. two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before
the main() function.

35
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Category of functions:

A function depending an whether the arguments are present or not and whether a value is
returned or not, may belong to one of following categories

1. Function with no argument and no Return value


2. Function with no argument and with Return value
3. Function with argument and No Return value
4. Function with argument and Return value

NOTE:

 From the above, 1 and 3 types does not return any value when the function is called so, We
use void return type while defining the function.
 When we call the function 2 and 4 types will return some value so, We have to use the
appropriate data type (int, float, double etc) as return type while defining the function. We
use return keyword inside the function to return some value when the function is called
from the main() function or any sub functions.

1. Function with No argument and No Return value

In this category, the function has no arguments. It does not receive any data from the calling
function. Similarly, it doesn’t return any value. The calling function doesn’t receive any data
from the called function. So, there is no communication between calling and called functions.

In this program, We are going to calculate the Sum of 2 integer values and print the output from
the user defined function itself.

#include<stdio.h>

36
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

// Function Declaration
void sum();

void main()
{

sum();
}

void sum()
{
int a = 10, b = 20,c ;
c= a + b;

printf("\n Sum of a and b is %d", c);


}

2. Function with no argument and with Return value

In this category, the functions has no arguments and it doesn’t receive any data from the calling
function, but it returns a value to the calling function. The calling function receives data from the
called function. So, it is one way data communication between calling and called functions.

In this program, We are going to calculate the sum of 2 integer values using the user defined
function without arguments and return keyword.

#include<stdio.h>

37
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

int sum();

void main()
{
int c;

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

int sum()
{
int a = 20, b = 40 ,c;

c= a + b;

return c;
}

3. Function with argument and No Return value

If you observe the above 2 methods, No matter how many times you executive, it will give the
same output. We don’t have any control over the values of the variables a and b because they are
fixed values. In real time, we mostly deal with dynamic data means we have to allow the user to
enter his own values rather than fixed ones.

This method allows us to pass the arguments to the function while calling the function. But, This
type of functions will not return any value when we call the function from main () or any sub
function.

38
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

If we want to allow our user to pass his own data to the function arguments but we are not
expecting any return value then, this type of functions are very useful.

Function with argument and No Return value Example

This program allows the user to enter 2 integer values and then, We are going to pass those
values to the user defined function to calculate the sum.

#include<stdio.h>

void sum(int, int);

void main()
{
int a, b;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


sum(a, b);
}

void sum(int a, int b)


{
int c;

c= a + b;

printf("\n sum of a and b is %d \n", c);


}

39
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

4. Function with argument and Return value

This method allows us to pass the arguments to the function while calling the function. This type
of functions will return some value when we call the function from main () or any sub function.
Data Type of the return value will depend upon the return type of function declaration. For
instance, if the return type is int then return value will be int.

This type of user defined functions are called as fully dynamic function means, it provide
maximum control to the end user.

Function with arguments and Return value Example

This program allows the user to enter 2 integer values and then, We are going to pass those
values to the user defined function to Addthose values and return the value using return keyword.

#include<stdio.h>

int sum(int, int);

void main()
{
int a, b,c;

printf("\n Please Enter two integer values \n");


scanf("%d %d",&a, &b);

//Calling the function with dynamic values


c = sum(a, b);

40
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

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

int sum(int a, int b)


{
Int c;

c= a + b;

return c;
}

Passing array to the functions:

Like the value of the simple variables, it is also possible to pass the array to the function. To pass
an array to a clledfuction,it is sufficient to list the name of the array,without any subscripts, and
the size of the array as arguments .

largest(a,n);

Will pass all the elements of the array a of size n. the largest function header look like:

float largest(float a[], int n)

Example

void main( )

int getsum(int a[], int n)

int a[5]={1,2,3,4,5};

41
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

int sum;

sum=getsum(a,5);

printf(“sum of elements is %d”,sum);

int getsum(inta[],int n)

int i,sum=0;

for(i=0;I,n;i++)

sum+=a[i];

return sum;

Parameter passing in functions:

There are different ways in which parameter data can be passed into and out

42
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

of methods and functions.


First some important terminology:

Formal Parameter

A variable and its type as they appear in the prototype of the function or method.

Actual Parameter

The variable or expression corresponding to a formal parameter that appears in the function or
method call in the calling environment.

Call by value or Pass by Value

Using "pass by value", the data associated with the actual parameter is copied into a separate
storage location assigned to the formal parameter. Any modifications to the formal parameter
variable inside the called function or method affect only this separate storage location and will
therefore not be reflected in the actual parameter in the calling environment.

Example:

#include<stdio.h>

/* function declaration */

void swap(int x,int y);

void main ()

/* local variable definition */

int a =100, b =200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values */

swap(a, b);

43
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

/* function definition to swap the values */

void swap(int x,int y)

int temp;

temp= x;/* save the value of x */

x = y;/* put y into x */

y = temp;/* put temp into y */

return;

Output:

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200

It shows that there are no changes in the values, though they had been changed inside the
function.

Call by Reference or Pass by Reference

44
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

Using "pass by reference", the formal parameter receives a reference (or pointer) to the actual
data in the calling environment, hence any changes to the formal parameter arereflected in the
actual parameter in the calling environment.

Example:

#include<stdio.h>

/* function declaration */

void swap(int*x,int*y);

void main ()

/* local variable definition */

int a =100;

int b =200;

printf("Before swap, value of a : %d\n", a );

printf("Before swap, value of b : %d\n", b );

/* calling a function to swap the values.

* &a indicates pointer to aie. address of variable a and

* &b indicates pointer to b ie. address of variable b. */

swap(&a,&b);

printf("After swap, value of a : %d\n", a );

printf("After swap, value of b : %d\n", b );

/* function definition to swap the values */

void swap(int*x,int*y)

45
PPS UNIT III Mrs. Amtul Shanaz(CSE Dept,DCET)
Mrs. Sameera Begum(CSE Dept,DCET)

int temp;

temp=*x;/* save the value at address x */

*x =*y;/* put y into x */

*y = temp;/* put temp into y */

return;

Output:

Before swap, value of a :100


Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

It shows that the change has reflected outside the function as well, unlike call by value where
the changes do not reflect outside the function.

46

You might also like