PPS unit-III PDF

You might also like

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

UNIT-3: Arrays &Functions

Objectives
• Demonstrate the use of arrays.
• Understand initialization, declaration of arrays.
• Applications of 1-D and 2-D arrays.
• To understand the software engineering principles of Structured
programming and modularity (top-down development).
• To understand the function declaration, function call, and function
definition.
• To understand inter- function communication through parameters
• To understand the four basic function designs.
• To understand how function communicate through parameters.
• To understand Standard functions.
• To understand the differences between global and local scope.
1
Derived data types

• Limited number of problems can be solved by using primary


data types
• Derived data types are needed to solve complex problems.
• Complex data types are derived from primary data types
• Derived data types available in C language are given below:

2
Unit No:3

Arrays: Concepts Lecture No:L35

Link to Session

Planner (SP):S.No….of SP

• An array is one of the derived data types. Date Conducted:

Page No:
• Arrays are useful to process large amounts of data

• For example, suppose we have a temperature reading for each day of the
year and need to manipulate their values several times within a program

• With simple variables,

•We would need to declare 365 variables.


•We would not be able to loop over these variables
• The above problem can be solved by using an array: Temp [365]

• The elements in an array share the same name and are distinguished from one
another by their numbers or subscripts: 0,1,2….. Size-1

• An array must be declared before it can be used.


• Array declaration and definition provides information to the compiler - the
name of the array, type of array and the size.
3
Characteristics of an Array

• An array represents a group of related data.

• An array has two distinct characteristics:

An array is ordered: data is grouped sequentially: element 0, element 1,…


n-1

An array is homogenous: every value within the array must share the same
data type. In other words, an int array can only hold integers, but not other
data types.

4
How to Create an Array

• Before we create an array, we need to decide on two properties:

Element type: what kind of data will the array hold? int, double, char?
Remember, we can only choose one type.

Array size: how many elements will the array contain?

5
Types of Arrays

• Arrays can be classified based on how the data items will be arranged.

• Arrays are broadly classified into three categories.

1. One dimensional arrays

2. Two dimensional arrays

3. Multi dimensional arrays

16
One Dimensional Array & Declaration
• One dimensional array is a linear list consisting of related and similar data
items.

• In memory, all the data items are stored in contiguous memory locations.

Declaring a one dimensional array


• To declare ordinary variables, we use the following notation:
int number;

• To declare an array, the following syntax can be used:

Syntax: type arrayname[size];

For example:
int number[5];
• Creates an array of 5 integer elements.

7
Unit No:3

Initialization of one Dimensional Array (1 of 5) Lecture No:L36

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:
1. Initializing
• There are four options to initialize one dimensional arrays.

Option A: Basic Initialization


• If the values of all the data elements are known, the values must be
specified within the braces.

int temp [5] = {75, 79, 82, 70, 68};

Memory
Layout temp[0] temp[1] temp[2] temp[3] temp [4]

75 79 82 70 68
1000 1002 1004 1006 1008
8
Memory Representation of an Integer Array

9
Operations on one Dimensional Array (2 of 5)
Option B: Initialization without size
int temp [] = {75, 79, 82, 70, 68};
• The compiler allocates memory for an array of 5 elements. The array temp is
initialized as shown below:
temp[0] temp[1] temp[2] temp[3] temp[4]

75 79 82 70 68
1000 1002 1004 1006 1008 Address

OptionC: Partial Array Initialization


int temp [5] = {75, 79, 82}; // All values are not specified

temp[0]temp[1] temp[2]temp[3]temp[4]

75 79 82 0 0
1000 1002 1004 1006 1008 Address

• Values for first three elements have been specified


• The elements for which values are not specified, are initialized to zero’s.
10
Operations on one Dimensional Array (3 of 5)
Option D: Initialization to all zero’s
• If values of data elements are not known well in advance, then all elements
can be initialized to zero’s.

For example:

int temp [5] = {0};

temp[0] temp[1] temp[2] temp[3] temp [4]

0 0 0 0 0
1000 1002 1004 1006 1008 Address

11
Operations on one Dimensional Array (4 of 5)
2. Inputting values
• Another way to fill the array is to read the values from the keyboard or a file.
• This could be done by using a loop.
Ex:
for(i=0; i<9; i++)
scanf(“%d”,&scores[i]);
3. Accessing elements of an array
• Index is used to access individual elements of an array.
Ex: scores[0];
4. Printing/Output values
• Another common application is printing the contents of an array.
• This can be easily done by using a loop.
Ex.
for(i=0; i<9; i++)
printf(“%d”,scores[i]);

12
Operations on one Dimensional Array (5 of 5)
5. Assigning values to an array
• Suppose we have an array temperature, the readings of the temperature for
the year is represented in the below example .
• The subscripts would be 0, 1, …, 364.
Temperature array

75 79 82 70 68 65 58 63 67 61
temperature[4]

• We can loop through the elements of an array by varying the subscript. To


set all the elements of any array to 0:
for(i=0;i<365;i++)
temperature[i] = 0;

• We cant use assignment statement directly with arrays.



if a[], b[] are two arrays then the assignment a=b is invalid

Example37 shows 1D array declaration & accessing 13


Unit No:3

Two Dimensional Array Lecture No:L37

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:

• An array of arrays is called multi-dimensional array.


• A multidimensional array can have two dimensions, three dimensions, four
dimensions, etc.
• A Multi-dimensional array which has only two dimensions is called as a two
dimensional array.
• Two-dimensional array can be regarded as a table with rows and columns:
Example:
'J' 'o' 'h' 'J' 'o' 'h'
'n' is a 3 × 4 'n'
array:
'M' 'a' 'r' 'M' 'a' 'r'
3 rows, 4
'y' 'y'
columns
'I' 'v' 'a' 'I' 'v' 'a'
'n' 'n'

• This is a two dimensional array having 3 rows and 4 columns


14
Two Dimensional Array
DECLARATION
Syntax:

• Type arrayName [rows][cols];

Example

• char names[3][4];

In the above declaration

• Char (elementType) 🡪 specifies type of element in each slot

• Names (arrayName) 🡪 specifies name of the array

• [3] (rows) 🡪 specifies number of rows

• [4] (cols) 🡪 specifies number of columns


15
Unit No:3

Initialization & Accessing of 2-D arrays Lecture No:L38

Link to Session

Planner (SP):S.No….of SP

Date Conducted:
Initializatio Page No:
n
• A two dimensional array can be initialized at the time of declaration:
char names [3][4] = {
{‘J’, 'o', 'h', 'n'},
{‘M’, 'a', 'r', 'y'},
{‘I’, 'v', 'a', 'n'}
};
• An integer array can be initialized to all zeros by using the following
statement:
int nums[3][4] = {0};
• The declaration of a two dimensional array should have the column size
so that ,the elements can be in the form of rows and columns.

• To access an element of a 2D array, requires both the row and the


column.

2Dexmpl 38 , 2Dexmp 39.c demonstrate 2d array declaration and initialization through turbo c.
16
Multi Dimensional Array

• C allows arrays of multiple dimensions.

• The general form of a multidimensional array is

type arrayName[s1][s2][s3]….[sm];

• For example
int a[10][3][2];
• It is represented as “an array of ten arrays of three rows of two
columns”

17
Multi Dimensional Array
3-D Array example.

Example 40.c will demonstrate 3D array….


18
Representation of a Multi Dimensional
Array
A Three-dimensional Array (3 x 5 x
4)

19
Applications of Arrays
1. Matrix Operations
Addition, multiplication, trace, transpose…etc

2. Sorting: One of the most common applications in computer science is


sorting—the process through which data is arranged according to their
values.
• Sorting techniques
• Selection Sort

• Bubble Sort

• Insertion Sort

• Merge Sort

• etc 20
Unit No:3

Basic Algorithms: Searching Lecture No:L39

Link to Session

Planner (SP):S.No….of SP

Date Conducted:
• Another common operation in computer science is searching, which is the process
Page No:
used to find the location of a target among a list of objects.

• In the case of an array searching means that given a value , we want to find the
location of the first element in the array that contains that value .

• There are two basic searches for arrays:


1. The sequential search
2.The binary search

• The sequential search can be used to locate an item in any array.

• The binary search , on other hand, requires the list to be sorted.


Linear/ Sequential search (1 of 9)
• Sequential search is used whenever the list is not ordered.

• Generally we use the technique only for small lists or lists that are not

searched often.

• In the sequential search , we start searching for the target from the

beginning of the list, and we continue until the we find the target or

until we are sure that it is not in the list.

• This gives us two possibilities:

either we find it or

we reach the end of the list


Linear search Example (2 of 9)

Locating data in unordered list


Linear search Example (3 of 9)

Locating data in unordered list


Linear search Example (4 of 9)

Unsuccessful search in unordered list


Linear search Example (5 of 9)

Unsuccessful search in unordered list


Linear search Example (6 of 9)

Unsuccessful search in unordered list


Linear search Algorithm (7 of 9)
1.start
2.read n
3.read elements of list (a[])
4.read element to be searched(item)
5.initialize found=0
6. for(i=0;i<n;i++)
7. {
If(a[i]==item)
{
found=1
Break
}
}
8.if (found==1)
then print element a[i] is found i th location
else
print element not found
9.stop
Linear search Flowchart (8 of 9)
Linear search (9 of 9)
Advantages :

1.Easy to understand
2.The list need not be in sorted order
3.If item is at beginning not many comparisons are needed

Disadvantages:

1.Slow if list is large


2.when item at end of list which takes more time to execute
3.which needs more time and space complexity.

Complexity:
Best case: O(1)
Average case: O(n)
Worst case: O(n)

C program u7_ex6.c
Binary search (1 of 5)
• Sequential search algorithm is very slow if list contains more number of
elements.
• If the array is not sorted ,linear search is the only solution.
• If the list is sorted , we can use a more efficient algorithm called
the binary search.
• We should use a binary search whenever the list starts to become large.
• The binary search starts by testing the data in the element at the middle of the list.
• This determines if the target is in first half or second half of the list.
• If it is in first half , we do not need to check the second half.
• If it is in second half , we do not need to check the first half.
• In other words ,either way we eliminate half the list from further
consideration.
• We repeat this process until we find the target or satisfy ourselves
that it is not in the list.
• To find the middle of the list we three variables,
one to identify the beginning of the list(first)
one to identify the beginning of the list(mid)
one to identify the beginning of the list(last)
mid=( first + last )/2
Binary search Example (2 of 5)

Binary search example if target is present in the list


Binary search Example (3 of 5)

Binary search example if target is not present in the list


Binary search Example (4 of 5)

Binary search example if target is not present in the list


Binary search Algorithm (5 of 5)
Iterative Algorithm
int binarysearch (int a[], int target, int n)
// pre: list is sorted in ascending order
//post: ITERATIVE binary search will return the index of the target element, else -1
{
int mid;
int first = 0;
int last = n-1
while ( first <= last )
{
mid = (first + last) / 2;
if ( a[mid] == target )
return mid;
if ( a[mid] > target )
last = mid - 1; Complexity of quick sort:
else Best case: O(logn)
first = mid + 1; Average case: O(logn)
} Worst case: O(log n)
return -1;
}

C program u7_ex7.c
Linear Vs Binary Search
Analysis Linear Search Binary Search

Best Case O(1) O(1)

Average Case O(n) O(log n)

Worst Case O(n) O(log n)

Unsuccessful Search O(n) O(log n)

List Unordered List Ordered List

Usage Small list Large List

Time & Space More Less

Search Starts at beginning Starts at middle

36
Unit No:3

Lecture No:L40

Basic Sorting Algorithms Link to Session

Planner (SP):S.No….of SP

Date Conducted:

• Sorting is the process through which data are arranged according


Page No:to their

values.

• Three sorting algorithms:

• Selection Sort
• Bubble Sort
• Insertion Sort

37
Selection Sort (1 of 4)

• The list is divide into two sub lists as sorted and unsorted.

• The sub lists are divided by an imaginary wall.

• Find the smallest element from the unsorted sub list and swap it with the
element at the beginning of unsorted sub list.

• After each selection and swapping, the wall between the two sub lists
moves one element ahead, increasing the number of sorted elements and
decreasing the number of unsorted sub lists.

• Move one element from the unsorted sub list to the sorted sub list
completes a sort pass.

• Thus a list of n elements need n-1 passes to completely rearrange the


data.
Selection Sort (2 of 4)

Example

39
Selection Sort (3 of 4)

Flowchar
t

40
Selection Sort (4 of 4)

• Code:

selection_sort ( int A[ ] , int n )


{
int i , j , small , temp ;
for ( i = 0 ; i < n ; i++ )
{
small = i ;
for ( j = i + 1 ; j <= n ; j ++ )
{
if ( A [ j ] < A [ small ] )
small = j ;
}
temp = A [ i ] ;
A [ i ] = A [ small ] ;
Complexity of Selection Sort
A [ small ] = temp ;
Best Case : O ( n2 )
} Average Case : O ( n2 )
} Worst Case : O ( n2 )
41 C program u7_ex1.c
Bubble Sort (1 of 4)

• The list is divide into two sub lists as sorted and unsorted.
• The smaller element is bubbled from the unsorted sub list and
moved to the sorted sub list.
• After moving the smallest element to the sorted list, the wall
moves one element ahead, increasing the number of sorted
elements and decreasing the number of unsorted ones.
• Move one element from the unsorted sub list to the sorted sub list
completes one sort pass.
• Thus a list of n elements, the bubble sort requires up to n-1
passes to sort the data.

42
Bubble Sort (2 of 4)

• Example:

43
Bubble Sort (3 of 4)
• Flowchart:

44
Bubble Sort (4 of 4)
Complexity of Bubble_Sort
The complexity of sorting algorithm is
• Code: depends upon the number of comparisons
that are made.
bubblesort ( int A[ ] , int n )
Total comparisons in Bubble sort is
{ n ( n – 1) / 2 ≈ n 2 – n
int i , j, temp ; Complexity = O ( n 2 )
for ( i = 0 ; i < n ; i++ )
{
for ( j = n; j > i ; j - - )
{
if ( A [ j ] < A [ j-1 ] )
{
temp = A [ j ] ;
A[j]=A[j-1];
A [j -1] = temp ;
}
}
}

45 C program u7_ex2.c
Insertion Sort (1 of 4)

• Insertion sort is one of the most common sorting techniques used by card

players.

• The list is divide into two sub lists as sorted and unsorted.

• In each pass, the first element of the unsorted sub list is picked up and

transformed into the sorted sub list by inserting at the appropriate place.

• A list of n elements, the insertion sort requires at most n-1 passes to sort

the data.

46
Insertion Sort (2 of 4)

Example:

47
Insertion Sort (3 of 4)

Flowchart

48
Insertion Sort (4 of 4)

• Code: Complexity of Insertion Sort


insertion_sort ( int A[ ] , int n ) Best Case : O ( n )
{ Average Case : O ( n2 )
int i , j, temp ; Worst Case : O ( n2 )
for ( i = 1 ; i <= n ; i++ )
{
flag = false;
temp = A[i];
for ( j = i-1; j > 0 && !flag )

if ( A temp < A [ j ] )
{
A[j+1] = A[j];
j - -;
}//if
else
flag = true;
A[j+1] = temp;
}
}
49 C program u7_ex3.c
Designing Structured Programs

• Simple programs studied so far can be solved and understood without too
much effort.

• Large programs need to be reduced into elementary parts for better


understanding.

• The principles of top-down design and structured programming dictate that a


program should have a main module and its related modules.

• Each module can be further divided in to sub modules.

• Breaking a complex problem into smaller parts is known as factoring.

50
Hierarchy of modularization

• Module 1,2,3 are sub modules of main module


• Module 1a,1b,1c are sub modules of module1
• Module 2a is sub module of module 2
• Module 3a,3b are sub modules of module 3

51
Modularization
Example:
PRINCIPAL
(main module)

CULTURAL SPORTS ACADEMIC


( module 1) (module 2) (module 3)

SINGING DANCE VOLLEY


CRICKET
(module 1a) (module 1b) BALL
(module 2a)
(module 2b)

PRESENTATI
TECH QUIZ
ON
(module 3a)
(module 3b) 52
Modular Programming - Manageable
Same book
published in
Huge Book of several volumes.
3000 pages Easily
manageable
Unit No:3

Functions in C Lecture No:L41

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:

• Top-down design is implemented by using Functions in C

• A Program in C is made up of one or more functions, one and only one of

which must be named as main.

• The execution of the program always starts and ends with main, but it can

call other functions to do specific task.

• main ( ) is called by the OS and control returns to the OS after completion of

main function.

54
Structure Chart for a C Program

55
Functions in C
• A function is a section of a program that performs a specific task

• Solving a problem using different functions makes programming much simpler


with fewer defects

• A function receives zero or more pieces of data, operate on them and return at
most one piece of data

56
Advantages of Functions (1 of 2)
• Problems can be factored in to understandable and manageable
steps(easy to code and debug).

• Functions can be developed by different people and can be combined


together as one application.

• Functions support reusability. That is, once a function is written, it can


be called from any other module without having to rewrite the same.
This saves time in rewriting the same code.

57
Advantages of Functions (2 of 2)

Work Allotment

Application Development
58
Function Definition (1 of 4)
• A function is always associated with following three steps

• Function definition

• Function declaration

• Function call

• Function definition contains the code for a function

• Function definition is made up two parts

• Function Header

• Function body (Compound statement within opening and closing


braces)

59
Function Definition (2 of 4)
Function Header
• A function header consist of 3 parts
return type
function name
formal parameter list
• A semicolon is not used at end of function definition header

Function Body
• The function body contains local declarations and function statements in
between braces.
• Local declarations specify the variables needed by the function.
• The function statement terminated by a return statement
• If the function return type is void, a return statement is optional.

60
Function Definition (3 of 4)
Parameters
• Formal parameters are variables that are declared in the header of the function
definition

• Actual parameters are used in the calling statement or sometimes they may be
an expression

• Formal and actual parameters must match exactly in type, order, and number.
Their names, however, no need to match.

61
Function Definition (4 of 4)
Parameters
Formal and actual parameters must match exactly in type, order, and number.
Their names, however, need not match.
double average(int x,int y);
void main() actual
{ parameters
double sum1;
sum1=average(10,20);// calling function
} x,y formal
parameters Execute

turbo C program examples 2 & 3, also show error simulation 62


Function Declaration (1 of 2)
• Function declaration consists only of a function header (no code)

• Function declaration header consists of three parts: the return type, the
function name and formal parameters

• Function declarations are terminated with a semicolon

• Declarations are placed in global declaration section before

the main function

• Function declaration is also known as function prototype

63
Function Declaration (2 of 2)
The general form of a function Prototype or
Declaration

64
Function Call (1 of 4)
• Function call is a postfix expression

• The operand in a function call is the function name; the operator is the
parentheses set (…), which contains actual parameters.

• Actual parameters identify the values that are to be sent to called function and
must match the formal parameters in type and order

• Multiple actual parameters are separated by comma

• Function call transfers the control to the function definition (called function)

• After execution of the function, it returns the result to the calling function

• Function having a return type void can be used only as a stand-alone statement

65
Function Call (2 of 4)
General form

Actual parameters

return type function-name(name1,name2,name3,……….,namen);

Return type of function


Each parameter is separated by
comma and function call ends with
semicolon

66
Function Call (3 of 4)

turbo c example 1 also show error simulation


67
Function Call (4 of 4)
Examples of Function
Calls

68
How Functions Work?
main()

User defined
function
Function
call

69
Sample Program with function

70
Sample Program with function

71
Sample Program with function

turbo c example 2 also show error simulation

72
Unit No:3

Lecture No:L42

User Defined Functions Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:
• Functions must be both declared and defined.
• Function declaration gives the whole picture of the function .
• Function declaration must be placed before the function call.

• Function declaration consists of:

• name of the function,


• return type,
• type and order of parameters

• Function definition contains the code that needs to complete the task

73
Declaring, Calling and Defining Functions

74
Basic Function designs (1 of 5)
• Basic function design is based on their return value and parameter list

• There are four basic designs

1. Void Functions without Parameter.

• Function with no arguments and no return value.

2. Void Functions with Parameter.

• Functions with arguments and no return values.

3. Non Void Functions without Parameters

• Functions with no argument and return values.

4. Non Void Functions with Parameters

• Functions with argument and return values.

75
Basic Function designs (1 of 5)
Do not pass argument Do pass arguments
void main(void) void main(void)
{ {
TestFunct(); TestFunct(123);
... ...
} }

void TestFunct( void) void TestFunct( int i)


No return
{ {
// receive nothing // receive something and
// and nothing to be // the received/passed
// returned // value just
} // used here. Nothing
// to be returned.
}
void main(void) void main(void)
{ {
x = TestFunct(); x = TestFunct(123);
... ...
} }

With a return int TestFunct( void) int TestFunct( int x)


{ {
// received/passed // received/passed something
// nothing but need to // and need to return something
// return something return (x + x);
return 123; }
}
76
Basic Function designs (2 of 5)
1. Void Functions without Parameters
• Void functions without parameters does not receive any parameters
and also does not return any value .
• This can be used only as a statement because a Void function does
not return a value
• This cannot be used in an expression
Example : result=greeting(); //error

turbo c example 4 also show error simulation


77
Basic Function designs (3 of 5)
2. Void Functions with Parameter
• The function that receives parameter but does not return any value
• This function takes arguments(parameter list)
• It can be used only as statement
• It cannot be used in an expression
Example: result=greeting(); //error

Void Function with Parameters C program example5.c


78
Basic Function designs (4 of 5)
3. Non Void Functions without Parameters
• The function returns a value but does not receive parameters

• It cannot be used as statement

• It can be used in an expression

Example: result=greeting(); //correct

Non-void Function without Parameters c program example6.c


79
Basic Function designs (5 of 5)
4. Non Void Function with Parameters
• The function receives parameters and return values
• It cannot be used as a statement
• It can be used in an expression
Example : result=greeting(); //correct

Calling a Function That Returns a Value c program example7.c 80


Assignment

Write a C program to implement GCD of 2


numbers by using 4 types of user defined
functions

81
Unit No:3

Standard Functions (1 of 15) Lecture No:L43

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:

• A Function whose definitions have been written and are available, which
can be used in a program.

• Declare the standard function that is to be used in the function declaration.

• Function declaration for these functions are grouped together and collected
in several header files

• Instead of using function declarations, standard functions can be included in


the header files at top portion of the program
• Ex: printf(),scanf()

82
Standard Functions (2 of 15 )
Library Functions and the Linker

83
Standard Functions (3 of 15 )
Math functions
• Many important library functions are available for mathematical calculations
• Most of these function declarations are in math header file (math.h) or standard
library header file (stdlib.h )
• Integer functions can be found in stdlib.h

Absolute value functions


• Absolute value function returns absolute value of a number
• Absolute value is the positive rendering of the value regardless of its sign
• In this function, there are 3 integer and 3 real functions
• Three integer functions are abs, labs and llabs
int abs (int number); //stdlib.h
long int labs(long int number); //stdlib.h
long long int llabs(long long int number); //stdlib.h
84
Standard Functions (4 of 15 )
Absolute value functions
• Three real functions are fabs(), fabsf() and fabsl()

double fabs(double number); //math.h


float fabsf(float number) //math.h
long double fabsl(long double number); //math.h

Example

abs(3)=3
abs(-3)=3
fabs(-3.4)=3.4
fabs(1.1)=1.1
abs(-1.9)=1

C example program12.c 85
Standard Functions (5 of 15)
Ceiling Functions
• A ceiling is the smallest integral value greater than or equal to a
number
• If all numbers are considered as a continuous range from minus
infinity to plus infinity, this function moves the number right to an
integral value
• Syntax
double ceil(double number); //math.h
float ceilf(float number); //math.h
long double ceill(long double number); //math.h
• Example
ceil(-1.9) =-1.0 ceil(1.9) =2.0
ceil(1.1) =2.0 ceil(-1.1) =-1.0

Note: ceilf() and ceill() are not supported in the current version
c example program program13.c 53
Standard Functions (6 of 15)
Floor Functions
• A floor is the largest integral value that is less than or equal to a
number
• If all numbers are considered as a continuous range from minus
infinity to plus infinity, this function moves the number left to an
integral value
• Syntax
double floor(double number); //math.h
float floorf(float number); //math.h
long double floorl(long double number); //math.h
• Example
floor(-1.9) =-2.0 floor(1.9) =1.0
floor(1.1) =1.0 floor(-1.1) =-2.0

Note: floorf() and floorl() are not supported in the current version
c example program program14.c 54
Standard Functions (7 of 15)
Truncate Functions
• A Truncate functions return the integral in the direction of zero
• This functions same as floor function for positive numbers and the same as
ceiling for negative numbers
• Syntax
double trunc(double number); //math.h
float truncf(float number); //math.h
long double truncl(long double number); //math.h
• Example
trunc(-1.1) =-1.0
trunc(1.9) =1.0
trunc(2.1) =2.0
trunc(-1.1) =-1.0
Note: trunc() function not supported in the current version 55
Standard Functions (8 of 15)
Round function
• Round function returns nearest integer value
• Syntax:
double round(double number); //math.h
float roundf(float number) //math.h
long double roundl(long double number); //math.h
long int lround(double number); //math.h
long int lroundf(float number) //math.h
long int lroundl(long double number); //math.h
long long int llround(double number); //math.h
long long int llroundf(float number) //math.h
long long int llroundl(long double number); //math.h
• Examples:
round(-1.1)=-1.0 round(1.9)=2.0
round(-1.5)=-2.0 round(1.5)=2.0

56
Standard Functions (9 of 15 )
Power function

• The power(x,y) function returns the value of the x raised to the power of y i.e., x y

• Syntax:

double pow(double n1,double n2) //math.h


float powf(float n1,float n2) //math.h
long double powlf(long double n1,lobg double n2)//math.h

• Example:

pow(3.0,4.0)=81.0
pow(3.4,2.3)=16.687893

90
Standard Functions (10 of 15)
Sqrt function
Sqrt () returns non-negative square root of a number. Error occurs if the number is
negative

Syntax:

double sqrt(double number); //math.h


float sqrtf(float number) //math.h
long double sqrtlf(long double number); //math.h

Examples:
sqrt(25)=5.0
sqrt(256)=16.0

91
Standard Functions (11 of 15 )
Random numbers
• A random number is a number selected from a set in which all members have
same probability of being selected
• Random numbers are useful in many areas of computer science
• Applications are testing and gaming
Random number Generation:
• Most languages provides functions to generate random numbers
• Each time a function is called, it generates another number
• To generate next number, the function uses its previous number
Random number generation methods
1. Seed provided by the user
2.we can use default seed provided by system

92
Standard Functions (12 of 15 )
Random Number
Generation

93
Standard Functions (13 of 15 )

Generating a Random Number Series

94
Standard Functions (14 of 15)

Random numbers in C
• Two Random functions are provided in ‘C’ to build a random number series
seed random (srand)
random (rand)
• These function declarations are available in stdlib.h

Seed Random Number function(srand)


• This function creates the starting seed from a number series

Syntax
void srand(unsigned int seed);
• To generate same series in each run we can provide a constant seed,
preferably prime number such as 997 Ex: srand(997);
• To generate a different series in each run ,we use time of day as seed
as time will change every second , for this we need time.h
Ex: srand(time(NULL));

C program example15.c example17.c 62


Standard Functions (15 of 15)
Random number function
• The random number function - rand() returns pseudo random integer between 0
and RAND_MAX
• RAND_MAX is defined in standard library as largest number that rand() can
generate
• Each call generates next number in a random number series
• The random number function declaration is
int rand(void);
• C specifies the range between 0 to 32767
• When we need a random number in a different range we must map the standard
range to specified range
• Two common ranges are
real number series 0.0 to 1.0
integer series 0 to 25 or 11 to 20
• Generalized formula: rand()%range + minimum
range=(maximum-minimum)+1
63
Unit No:3

Storage Classes Lecture No:L44

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

• Each and every variable is stored in computer memory. Page No:

• Every variable and function in C has two attributes:

1. datatype (Eg: int, float, char, etc..)

2. Storage Class

• Storage Class specifies the scope, extent and linkage.

64
SCOPE (1 of 4)
• Scope determines the region of the program in which a defined object is
visible.

• Scope pertains to any object that can be declared, such as a variable or a


function declaration.

• An object can have three levels of scope

1. Block scope

2. Function scope

3. File scope

65
Scope (2 of 4)
Block Scope
• Variables defined within a block have a local scope. They are visible in
that block only. Outside the block they are not visible. Eg:
• { //outer block starts
{//inner block starts

}//inner block ends


• } //outer block ends
• Variables are in scope from their point of declaration until the end of the
block. Block scope is also referred as local scope.

• Variables that are declared in a block are known as local variables.

Demo C Program Ex No. 18 and also show error simulation.


66
Scope (3 of 4)
Function Scope
• Variables defined within a function (including main) are local to this function
and no other function has direct access to them.
• Eg: int add(int a, int b) //add() is a function
{ //function scope starts

}//function scope ends

Demo C Program Ex No. 19 and also show error simulation.


67
Scope (4 of 4)
File Scope
• File scope includes the entire source file for a program, including any files that
are part of it.

• An object with file scope has visibility through the whole source file in which it is
declared.

• Objects within block scope are excluded from file scope unless specifically
declared to have file scope; in other words, by default, block scope hides
objects from file scope.

• An object with file scope sometimes referred to as a global object and the
variables declared inside this scope are referred to as Global Variables.

Demo C Program Ex No. 20 and also show error simulation.


68
Extent

• Defines the duration for which the computer allocates memory for the
variable.

• It is also known as storage duration.

• Extents are of two types:

1. Automatic Extent: object is created each time when it is declared and it


is destroyed each time when the block is exited.

2. Static Extent : object is created when the program is loaded for


execution and it is destroyed when the execution stops.

69
Linkage

⚫ A large application program may be broken into several modules, with each
module potentially written by a different programmer. Each module is a
separate source file with its own objects.
⚫ We can define two types of linkages:
-internal
-external
⚫ Internal Linkage: An object with an internal linkage is declared and visible in
one module. Other modules cannot refer to this object.

⚫ External Linkage: An object with an external linkage is declared in one


module but is visible in all other modules with a special keyword, extern.

70
Storage Class Specifiers

⚫ There are four storage classes

1. Automatic (auto variable)

2. Register (register variable)

3. Static (static variable)

4. External (extern variable)

71
Automatic Variables (1 of 2)

• The default and the most commonly used storage class is automatic.

• Memory for automatic variables is allocated when a block or function is


created. They are defined and are “local” to the block.

• When the block is exited, the system releases the memory that was allocated
to the automatic variables, and their values are lost.

• These variables are also referred as local variables.

72
Automatic Variables (2 of 2)

• Characteristics:
• Scope: block
• Extent: automatic
• Linkage: internal
• Declaration:
auto type variable_name;
• Initialization:
An auto variable can be initialized where it is defined or left uninitialized.
When auto variables are not initialized, its value is a garbage value.

Demo C Program Ex No. 21 and also show error simulation.


73
Register Variables (1 of 2)

• Register variables specify to the compiler that the variables should be stored
in high-speed memory registers if possible. This is done for efficiency.

• If no register space is free, variables become auto instead.

• Keep register variables in small local blocks which are reallocated quickly.

• The address of a register variable is unavailable to the user. The user


program can’t use both the address operator and the indirection operator
(pointer) with a register.

74
Register Variables (2 of 2)

• Characteristics:

• Scope: block

• Extent: automatic/register

• Linkage: internal

• Declaration:

register type variable name;

• Initialization:

A register variable can be initialized where it is defined or left uninitialized.

Demo C Program Ex No. 22 and also show error simulation.


75
Static Variables (1 of 3)
• The value of static variables persists until the end of the program.

• It is declared using the keyword static :


static int x;
static float y;

• By default, Static variables are initialized with zero.

• The static specifier has two different usages depending on its scope.
1. static variable with block scope
2. static variable with file scope.

76
Static Variables (2 of 3)
Static variable with block scope
• When a static variable is declared in a block scope, static defines the extent of the
variable
• Static variables with Block Scope are also known as Static Local Variables

Scope: Block
Extent: Static
Linkage: Internal

• Declaration:
static type variable_name
• Initialization:
• A static variable name can be initialized where it is defined, or it can be left
uninitialized. If it is initialized, it is initialized only once. If not initialized, its
value will be initialized to zero

Demo C Program Ex No. 23 and also show error simulation. 77


Static Variable (3 of 3)

Static variable with file scope


• When the static specifier is used with a variable that has a file scope (global
scope) and its linkage is internal.

Scope: File
Extent: Static
Linkage: Internal

Declaration:
Static type variable name;

Demo C Program Ex No. 24 and also show error simulation. 78


External Variables (1 of 2)
• Extern is used for global variables that are shared across code in several
files.

• External variables are used with separate compilations.

• Large projects are decomposed in to many source files.

• Decomposed source files are compiled separately and linked together to form
a unit.

• Storage is permanently assigned to Global variables (defined outside


functions) and all functions of the storage class extern.

79
External Variables (2 of 2)

• Characteristics:

• Scope: file

• Extent: static

• Linkage: external

• Declaration:

extern type variable_name;

Demo C Program Ex No. 25 80


Summary of Storage Classes

Class Scope Extent Linkage Keyword

auto block automatic internal auto or none

register block automatic internal register

static(extent) block static internal static

static(linkage) file static internal static

extern file static internal extern or none

81
C - Scope Rules

A scope in any programming is a region of the


program where a defined variable can have its
existence and beyond that variable it cannot be
accessed.
There are three places where variables can be declared
in C programming language −
•Inside a function or a block which is
called local variables.
•Outside of all functions which is
called global variables.
•In the definition of function parameters which are
called formal parameters.

81
Unit No:3

Parameter Passing in functions Lecture No:L45

Link to Session

Call by Value & call by Reference(1 of 5) Planner (SP):S.No….of SP

Date Conducted:

Page No:

• The calling and called functions need to communicate to exchange data.


• The data flow between the calling and called functions can be divided into
three strategies:
1. a downward flow,
2. an upward flow, and
3. a bi-directional flow.
• A downward flow from calling function to called function
• An upward flow from called function to calling function
• A bi-directional flow in both directions

116
Unit No:3

Call by Value & call by Reference(2 of 5)


Lecture No:L46

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:
Data Flow
Strategies

117
Call by Value & call by Reference(3 of 5)
Downward flow
• Calling function sends data to called function (one way communication)
• Copy of data items are passed from calling function to called function
• Called function may change the values passed, but the original values in the
calling function remains unchanged
• Use call by value mechanism to implement downward flow
• Rules:
a. Use values in function call to pass the data
b. Use appropriate data types in function parameter list to receive data
values
c. Use parameter identifiers in the called function to access the local
copies of the data

118
Call by Value & call by Reference(4 of 5)
Upward flow
• Called function sends data back to the calling function (one way
communication)
• Data items are returned to the calling function from the called function
• Calling function may use the values passed from called function
• Original values of called function remains unchanged
• Use call by reference or return mechanism to implement upward
communication
• Rules:
a. Use &variable name in function call to pass a reference to the variable
b. Use types * in the function parameter list to receive the variable’s address
c. Use *parameter name in the function to reference the original variable

119
Call by Value & call by Reference(5 of 5)
Bi-directional flow

• Calling function sends data down to called function


• Called function sends data up to calling function during or at the end of the
process.
• Use call by reference or return mechanism to implement
bi-directional communication

• Rules:
a. Use &variable name in function call to pass a reference to the variable
b. Use types * in the function parameter list to receive the variable’s
address
c. Use *parameter name in the function to reference the original variable

120
Call by Value & call by Reference
‘C’
implementation
• Most programming languages have three strategies for Inter-function
communication: Pass by value, pass by reference and return

• C Language uses two mechanisms for Inter function communication:

1. Pass by values

2. return

121
Call by Value & call by Reference
Downward Communication in
C
• Pass-by-Value is a perfect solution for communication in downward direction

• Two data items are passed from main to the down function.

• Called function does not return any data item

122
Call by Value & call by Reference
An example for Downward
Communication

turbo c example8.c also show error simulation 123


Call by Value & call by Reference
Upward Communication
• Return statement provides a mechanism for the return of data items in upward
direction flow
• This mechanism allows only one data item to be returned to the calling function.
• Called function needs to access variables in the calling function for passing
multiple data items. But C does not allow direct reference to a variable in the
calling function.
• The solution to this problem is as follows.
• Calling function pass the address of a variable:
Ex: upfun (&x, &y)
• Called function declares a pointer variable to receive the address:
Ex: void upfun (int * ax, int * ay).
• Called function can then put the data in the address of the variable given
by the calling function.
124
Call by Value & call by Reference
Upward Communication in
C

125
Call by Value & call by Reference
An example for Upward Communication

turbo c example9.c also show error simulation 126


Call by Value & call by Reference
Bi-directional Communication
• Strategy used for upward direction can be applied for communication in both
directions with a little difference.
• Use indirect reference in both sides of the assignment statement
• The variable in the called function is first accessed for retrieving the address
variable in the right hand side
• Access the same parameter again to store a value in the left hand side

127
Call by Value & call by Reference
An example for Bi-directional Communication

128
turbo c example10.c also show error simulation
Call by Value & call by Reference
An Exchange
Function

129
turbo c example11.c also show error simulation
Call by Value & call by Reference
An example for Bi-directional Communication

Calculate Quotient and Remainder C program example16.c 130


Arrays to functions
• To process arrays in a large program, arrays are required to be passed to
functions.

• Arrays can be passed to functions in two ways:

• Passing Individual Elements

• Individual elements can be passed to a function either by passing the


data values or by passing the addresses

• Passing the whole Array

• By using this, an Array name can be passed to the called function

131
Arrays to functions
Passing Array
Elements

132
Arrays to functions

Passing the Address of an Array


Element

133
Arrays to functions
Passing the Whole Array

134
Unit No:3

Recursion Lecture No:L47

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:
• There are two approaches to write repetitive algorithms: one approach uses
loops and the other one uses recursion

• Recursion is a repetitive process, in which a function can call itself.

• Recursive functions are useful in evaluating certain types of mathematical


functions.

• Recursion is also a useful way of creating and accessing dynamic data


structures such as linked lists or binary trees.

86
Designing recursive function

• Recursive functions have two steps:


• each call either solves one part of the problem
• it reduces the size of the problem

• Every recursive function must have a base case. The statement that solves
the problem is known as the base case.

• The rest of the function is known as the general case.

• The recursion will be done until the problem converges to the simplest
case.

• This simplest case will be solved by the function which will then return a
value.

• Each recursive call reduces the size of the problem


87
Rules for designing recursive function

• First, determine the base case

• Then, determine the general case

• Finally, combine the base case and general case into a function.

88
Unit No:3

Example: Factorial of a given number Lecture No:L48

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:
Iterative Definition
•Factorial(n)= 1 if n=0
n*(n-1)*(n-2)…3*2*1 if n>0

Recursive Definition
Base Case
Factorial(n) = 1 if n=0
n*Fcatorial(n-1) if n>0
General Case

89
Recursive representation of Factorial(3) (1 of 2)

90
Recursive representation of Factorial(3) (2 of 2)
factorial(0) = 1;
factorial(n) =
n*factorial(n-1);
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * ( 2 * (1 * factorial(0)))
= 3 * ( 2 * ( 1 * 1)))
= 3 * ( 2 * 1)
=3*2
=6

91
Recursive representation of Factorial(4) (5 of 11)

Executes factorial(0)

96
The Fibonacci Series

• Set of recursive calls to function fibonacci

f( 3 )

return f( 2 ) + f( 1 )

return f( 1 ) + f( 0 ) return 1

return 1 return 0
Unit No:3

Lecture No:L49

Ackermann’s function
Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:

Ackermann’s function:

143
Unit No:3

Lecture No:L50
Divide and Conquer sorting methods (1 of 4) Link to Session

Planner (SP):S.No….of SP

Date Conducted:
• We have described 3 sorting techniques – Page No:

selection ,bubble , insertion sorts,


which are useful for sorting very small lists.

• To sort large lists we use quick sort and merge sort.

• Divide and conquer is an important algorithm design paradigm in solving all


kinds computational problems.

• Quick sort ,merge sort and binary search are based on divide and conquer
strategy.

• Divide and conquer is essentially a special case of recursion in which a given


problem is divided into two or more sub problems of exactly the same type
and solution to the problem is expressed in terms of solutions to the sub
problems.

144
Divide and Conquer sorting methods (2 of 4)

• Example: Cutting a circle out of a sheet of paper is a tedious task which takes a

lot of time .

• But there is a way by which we can reduce the time and effort required and cut

perfect circles every time ----divide and conquer.

• Divide and conquer strategy helps in simplification of complex problems

(a) (b) (c) (d)

145
Divide and Conquer sorting methods (3 of 4)
• Divide and conquer algorithms are quite efficient as the average number of steps in this
methods is less as compared to other procedures.

• Divide and conquer algorithms are more efficient with regard to use of memory caches
Internal and external sorts:
Sorting algorithms are generally classified into 2 types:
1.Internal sorting
2.External sorting
• Internal sort uses only primary memory during entire sorting process.

• All data items are held in the main memory and no secondary memory is required.

• Selection, bubble and insertion sorts are internal sorting techniques.

• Internal sorting procedures can only process relatively small lists due to memory
constraints
Divide and Conquer sorting methods (4 of 4)
Sorts

Internal Sorts
∙Natural
∙Balanced
Insertion Selection Exchange
∙Polyphase
∙Insertion • selection ∙Bubble

∙shell •heap ∙Quick

•Sorting large chunks of data requires the use of external or secondary memory.

•An external sort uses a secondary memory such as hard disk, to store data that does not fit
into the main memory

•All external sorts are based on process of merging, different portions of data are sorted
separately and then merged together.

•Depending on the complexity of the list to be sorted, different types of merging procedures
are used in external sorting.
Quick sort (1 of 8)
• Quick sort algorithm was developed by C.A.R Hoare in 1962.
• Like bubble sort quick sort is an exchange sort ,i.e. , items swap positions till the entire
array is sorted.
• The quick sort is more efficient because it requires fewer exchanges to correctly
position an element.
• The basic principle underlying the quick sort algorithm is to pick one element in the array
and rearrange the remaining elements around it.
• The chosen element is called the pivot(usually first element of list).
• Once the pivot is chosen , all the elements lesser than the pivot are moved to the left of
the pivot, and all elements equal to or greater than the pivot are moved to the right of the
pivot.
• The pivot acts as a partition dividing the original lists into two sub lists, and after the
partitioning, the pivot is in its correct position in the sorted list.
• This procedure of choosing the pivot and partitioning the list is recursively applied to the
sub lists till the subsequent sub lists consists of only one element and entire list is
sorted.

148
Quick sort (2 of 8)
Quick sort Algorithm (3 of 8)
1.Start

2.Read the no of elements to sort(n).

3.Read elements to be sorted in array a


a[0]………a[n-1]

4.Call quick sort function


quicksort(a,0,n-1)

5.Print the sorted array a[0]…..a[n-1]

6.Stop
Quick sort (4 of 8)
Algorithm quicksort(int a[10],int first,int last)
{
i=first; j=last; pivot=first;
if(first<last)
{
while(i<j)
{
while(x[i]<=x[pivot]&&i<last)
Complexity of quick sort: i++;
while(x[j]>x[pivot])
Best case: O(n logn) j--;
if(i<j)
{
Average case:O(n logn) t=x[i]; x[i]=x[j]; x[j]=t;
}
2
Worst case: O(n ) }
t=x[pivot]; x[pivot]=x[j]; x[j]=t;
}
qsort(x,first,j-1);
qsort(x,j+1,last);
}
Quick sort example (5 of 8)
Quick sort (6 of 8)
Quick sort (7 of 8)
Quick sort (8 of 8)

C program u7_ex4.c
Merge sort (1 of 6)
• Merge sort is a divide and conquer external sorting algorithm.

• It was invented by John von Neumann in 1942.

• The basic procedure of merge sort is to divide the list to be sorted into two
smaller sub lists (roughly equal in size) and recursively repeat this
procedure till only one element is left in the sub list.

• After this the various sorted sub lists are merged back to from the parent list

• The merging process also goes on recursively till the sorted original list is
arrived at.

Complexity of quick sort:


Best case: O(n logn)
Average case: O(n logn)
Worst case: O(n log n)
Merge sort Example (2 of 6)
99 6 86 15 58 35 86 4 0

99 6 86 15 58 35 86 4 0

99 6 86 15 58 35 86 4 0

99 6 86 15 58 35 86 4 0

Divide 4 0
Merge sort Example (3 of 6)
0 4 6 15 35 58 86 86 99

6 15 86 99 0 4 35 58 86

6 99 15 86 58 35 0 4 86

99 6 86 15 58 35 86 0 4

Merge 4 0
Merge sort Algorithm (4 of 6)

1.Start

2.Read the no of elements to sort(n).

3.Read elements to be sorted in array a


a[0]………a[n-1]

4.Call merge sort function


mergesort(a,0,n-1)

5.Print the sorted array a[0]…..a[n-1]

6.Stop
Merge sort Algorithm (5 of 6)
mergesort (a, low, high)
if left >= right return
else
mid ← b(low+high)/2⎦
mergesort(A, low, mid)
mergesort(A, mid+1, high)
merge(a, low, mid, high)
Merge sort Algorithm (6 of 6)
merge(A, low, mid, high)
1. n1 ← mid – low + 1
2. n2 ← high – mid
3. create array L[n1], R[n2]
4. for i ← 0 to n1-1 do L[i] ← A[low +i]
5. for j ← 0 to n2-1 do R[j] ← A[mid+j]
6. k←i←j←0
7. while i < n1 & j < n2
8. if L[i] < R[j]
9. A[k++] ← L[i++]
10. else
11. A[k++] ← R[j++]
12. while i < n1
13. A[k++] ← L[i++]
14. while j < n2
15. A[k++] ← R[j++]

C program u7_ex5.c

You might also like