MODULE 3
(FUNCTIONS & ARRAYS)
Introduction
◦ C enables programmers to break up a program into segments commonly known as functions.
◦ Every function is supposed to perform a specific task with proper termination.
◦ Calling function, called function.
◦ Any times, any number of functions can be called( within a for loop, while etc)
Why are functions needed? (reasons for segmenting the program into functions)
◦ Facilitates each function to be written and tested separately.
◦ Understanding, coding, and testing multiple separate functions is far easier than doing it for one big function.
◦ Maintaining the program is easier. ( avoids many lines in the main function)
◦ C contains set of functions that are well tested and can be readily used.
◦ In actual implementation the workload can be decided by writing different functions by different programmers.
◦ Like C libraries, programmer can use their functions at different points in the main function .
Function declaration/function prototype.
◦ Before using a function, the compiler must know about the number of parameters and the type of
parameters that the function expects to receive and the data type of the value that it will return to the
calling functions.
◦ Placing the function declaration statement prior to its use, enables the compiler to make a check on the
arguments used while calling that function.
Declaring a function syntax:
Syntax: return_data_type function_name(data_type var1, data_type var2);
Example: int sum(int a, int b);
Things to be remembered about function declaration
◦ after the declaration of every function, there should be a semicolon.
◦ The function declaration is global. Therefore, declared function can be called from any point in the program
◦ Using argument names in the function declaration statement is optional.
int func (int, char, float);
or
int func(int i, char ch, float f);
◦ Function cannot be declared within the body of another function.
◦ a function having void as its return type cannot return any value.
◦ a function having void as its parameter list cannot accept any value.
◦ If the function declaration does not specify any return type, then by default it returns an integer value.
Function definition and Function call
◦ A function definition comprises of 2 parts: function header, function body.
◦ When a function is invoked, the compiler jumps to the called function to execute the statements that are part of that
function.
◦ Function call has the following syntax:
function_name(variable1, variable 2);
sum(num1, num2);
◦ The parameters passed to a function are more than what it is specified to accept then extra arguments will be discarded.
◦ If the parameters passed to a function are less than what it is specified to accept then the unmatched arguments will be
initialise it to some garbage value.
◦ The variable result is called as automatic local
variable
◦ it is called as automatic local variable for the
following 2 reasons
1. they are local to the function so their effect is
limited to the function any changes made to these
variables is visible only in that function.
2. They are automatically created whenever the
function is called and ceases to exist after control
exits the function.
Function cannot be used on the left side of an
argument statement.
return statement:
◦ The return statement terminates the execution of the called function and return control to calling function.
return <expression>
◦ A function that has void as it is return written type cannot return any value to the calling function
◦ so in the function that has been declared with return type void, return statement containing an expression generates a
warning.
◦ Function with more than one return
statement
Using variable number of arguments:
◦ Some functions have a variable number of arguments and data types that cannot be known at the compile time.
◦ Typical examples of such functions include the printf(), scanf().
◦ ANSI C offers a symbol called ellipsis ( … )
int func (char ch, …); // during function declaration
◦ However one must ensure that both the function declaration and function definition should use the ... symbol
Passing parameters to function:
There are 2 ways in which arguments or parameters can be passed to the called function
1. call by value - values of variables are passed by the calling function to the called function
2. call by reference - address of variables are passed by the calling function to the called function
Call by Value:
◦ In this method the called function creates new variables to store the value of the arguments passed to it.
◦ The called function uses a copy of the actual argument to perform its intended task.
◦ If the called function is supposed to modify the value of the parameter passed to it then change will be like reflected only
in the called function.
Summary of call by value:
◦ When arguments are passed by value the called function creates new variables of the same data type.
◦ the value of the arguments passed by the functions are copied into newly created variables.
◦ arguments are called by the values when the called function does not need to modify the values of the
original variables in the calling function.
◦ values of the variables in the calling function remains unaffected when the arguments are passed using call
by value technique
Pros and cons:
◦ Advantage: arguments can be variables literals or expressions.
◦ Disadvantage: copying data consumes additional storage space.
Call by reference:
◦ when a function wants to modify the value of the argument is to pass arguments using call by reference
◦ in call by reference, we declare function parameters as references rather than the normal variables.
◦ When this is done any changes made by the function to the arguments it receives are visible in the
calling function also.
◦ Reference of the variable is given through address of he variable(&)
◦ To indicate that an argument is passed using call by reference an asterisk (*) is placed after the type in the
parameter list in the function declaration, function definition function body.
◦ Hence in call by reference method a function receives an implicit reference to the argument rather than a copy
of its value.
Assignment:
1. Write a program to calculate area of a circle using function
2. write a program to convert time to minutes using function
3. Write a program to find biggest of 3 integers using functions.
Scope of variables:
◦ Scope means the accessibility and visibility of the variables at different points in the program.
◦ A variable or a constant in C has 4 types of scope
1. block scope
2. function scope
3. program scope
4. file scope
Block Scope:
◦ Statement block is a group of statements enclosed within opening and closing curly brackets {}.
◦ If a variable within a statement block is present then as soon as the control exits the block the variable will
cease to exist.
◦ Such variable also known as the local variable is set to have a block scope.
◦ Tips: it is an error to use the name of a function argument as the name of the local variable
Conclusions:
◦ Variables declared with same names as those in outer block, mask the outer block variables while executing the inner
block.
◦ In nested blocks, variables declared outside the inner blocks are accessible to the nested blocks provided these variables
are not re-declared within the inner block.
◦ Function Scope:
◦ Function scope indicates that a variable is active and visible from the beginning to the end of a function.
◦ In c, only the goto label has function scope.
◦ We cannot jump to label in another function
◦ Function scope is applicable only with go to label names.
Program Scope:
◦ If function want to access some variables which are not passed to it as arguments then declare those variables outside any
function blocks. Search variables are commonly known as global variables.
◦ Global variables are created at the beginning of the program execution and remain in existence throughout the period of
execution of the program.
◦ These variables are known to all the functions in the program and accessible to them for usage.
◦ These variables retain their value so that they can be used from every function in the program.
◦ If a global variable is not initialized during its declaration, then by default it will be set to 0.
Place of Declaration: The global variables are declared outside the functions including main().
Name Conflict: if we have a variable declared in a function that has same name as that of the global variable, then the
function will use the local variable declared within it and ignore the global variable
File scope:
◦ If a variable or a function has to be used across the files.
◦ By using extern keyword.
◦ By default, value will be zero.
Storage Class: Auto, register, extern, static
◦ Storage class defines the scope and lifetime of variables or functions declared within a C program.
The storage class gives the following information about the variable or the function:
1. The storage class of a function or variable determines the part of memory where storage space will be
allotted for the variable or function.
2. It's specify how long the storage allocation will continue to exist for that function or variable.
3. It specifies the scope of the variable or function.
4. It's specify whether the variable or function has internal external or no linkage
5. it specify whether the variable will be automatically initialised to zero or to any indeterminant value.
auto storage:
◦ It is the default storage class for variables declared inside a block.
auto int x; or int x;
◦ then x is an integer that has automatic storage it is deleted when the block in which x is declared is exited.
◦ All local variables declared within a function belong to automatic storage class by default
◦ they should be declared at the start of the program block right after the opening curly bracket {
◦ memory for the variable is automatically allotted upon entry to a block and freed automatically upon
exit from that block.
◦ The auto variables are stored in the primary memory (RAM)of the computer.
◦ Initial value will be garbage.
register Storage class.
◦ When variable is declared using register as its storage class it is stored
in a CPU register instead of RAM.
◦ register storage class is a type specifier that hints to the compiler that the
variable will be heavily used and therefore should be stored in a CPU
register if possible, for faster access.
◦ Since the variable is stored in register, the maximum size of the variable is
equal to register size.
register int x;
◦ Register variables are used when quick access to a variable is needed.
◦ If the register cannot be allotted , by default storage class will be auto.
◦ Initial value will be garbage.
extern Storage class
◦ A large program can be broken down into smaller programs.
◦ The smaller programs may need to share certain variables for processing.
◦ For such situations, C provides, and external storage class specified through extern. Default value is 0.
static storage Class
◦ While auto is default storage class for local variables, static is the default storage class for all global
variables
◦ static variables have a lifetime over the entire program.
static int x; // Default value will be zero
◦ Static variable when defined within a function is not reinitialised when the function is called again and
again.
Recursive Functions:
◦ Recursive function is defined as a function that calls itself to solve a smaller version of its task until final call is
made which does not require a call to itself.
◦ Every recursive solution has 2 major cases:
1. base case, the problem is simple enough to be solved directly without making any further calls to the same function.
2. recursive case, in which first the problem at hand is divided into simpler sub parts(itself).
◦ The base case of a recursive function acts as the terminating condition so, in the absence of an explicitly defined base
case recursive function would call itself indefinitely.
Arrays:
◦ An array is a collection of similar data elements. These data elements have the same data type. (one
dimensional)
◦ The elements of the array are stored in consecutive memory locations and are referenced by an index
(subscript).
◦ Subscript is the ordinal number which is used to identify an element of the array.
◦ Examples: employees in company, products sold, customers, marks of student etc.
Declaration of arrays:
data_type name[size];
◦ data type -what kind of values it can store (int, float, char, double)
◦ name -to identify the array
◦ Size- the maximum number of values that they can hold.
int marks[10];
Some of the points to remember:
◦ in an array of size n, the index ranges from 0 to n-1.
◦ int arr[] – illegal
◦ int n, arr[n] – illegal.
◦ Number of elements should be known at the compile time.
Accessing the elements of the array:
◦ By subscript.
◦ To access all the elements of the array we must use a loop.
◦ There is no single function that can operate on all the elements of the array.
Assignment:
Write a code snippet initialize each element of the array to -1.
Write a code snippet initialize array with even elements. arr[10]
Some of the legal statements in C:
◦ int marks[5]= {90,60,66,88,35};
◦ int marks[]= {98,66,38};
◦ int marks[5]= {68,98}; // rest of the elements are filled with zero
Assigning values to individual values:
◦ marks[3]= 100 // 4th element is assigned the value 100.
◦ We cannot assign one array to another array even if they are of same data type. Individual array elements should
be copied.
Operations on Array:
◦ Traversing an array
◦ inserting an element in an array
◦ deleting an element from an array
◦ merging to arrays
◦ searching and array element
◦ sorting an array in ascending or descending order
Traversing an array:
◦ Traversing an array means accessing each and every element of an array for a specific purpose.
◦ If A is an array of homogeneous data elements, then traversing the data elements can include printing every
element ,counting the total number of elements performing any process on these elements.
Inserting an element at the end of array:
◦ Adding the new data element to an already existing array
◦ if the element has to be inserted at the end of the existing array then the task of instruction is quite simple, we
just add one to the upper bound and assign the value.
Inserting an element in the middle of the array:
◦ Insert( A, N,POS, VAL)
◦ A, The array in which the element has to be inserted
◦ N, the number of elements in the array
◦ POS, the position at which the element has to be inserted
◦ VAL, the value that has to be inserted
Deleting the array element:
◦ SET upper_bound = upper_bound -1
◦ Exit
◦ Similar program to Inserting a specified location.
Searching an array element:
1.Linear Search
2. Binary search
Linear search:
◦ Also called as sequential search.
◦ It works by comparing every elements to of the array
with the key to be searched.
◦ Can work on unsorted array.
Binary search:
◦ Works only on sorted array.
Passing arrays to function:
◦ We can pass an array to a function. Either we may want to pass individual element of the array or entire array.
Passing the entire array:
int arr[5]={1,2,3,4,5}
func(arr) // in called function void func( int arr[]).
Passing individual values by data values:
int arr[5]={1,2,3,4,5}
func(arr[3]);
Passing individual values by address
int arr[5]={1,2,3,4,5}
func(&arr[3])
Passing entire array by its address:
Two-dimensional Array:
◦ 2-dimensional array is specified using 2 subscripts where one subscript denote the row and other denotes the
column.
Declaring two dimensional Arrays:
◦ Similar to one dimensional array:
int marks[3][5] //to store marks obtained by 3 students in 5 different subjects.
3 rows, 5 columns.
First element is denoted by marks[0][0], second as marks[0][1]
Usually, the variable i for rows and j for columns.
Initializing two -dimensional Array:
int marks[2][3] ={ 90,87,78,68,62,71};
The above statement can also be written as int marks[2][3]= {{90,87,78},{68,62,71}};
◦ Only the size of first dimension can be omitted. int marks[][3] ={ 90,87,78,68,62,71};
◦ int marks[2][3]= {0}; // assign entire array to Zero
◦ marks[1][1]= 79;
◦ marks[1][2]= marks[1][1]+10;
Accessing elements in the 2-D array.
(Refer programs in 12.7.3 section)
Operations on 2-D arrays:
◦ Transpose
◦ Sum ( Ci,j = Ai,j +Bi,j )
◦ Difference ( Ci,j = Ai,j +Bi,j )
◦ Product (Ci,j = ⅀ Ai,j Bi ,j for k=1 to k<n)
Assignment:
1. Program to multiply two matrices
2. Program to calculate sum of two m*n matrices
3. Program to calculate difference of two m*n matrices
Passing 2-D arrays to functions:
◦ There are three ways to pass 2-D arrays:
1. Pass individual elements of the array. //func(a[0][1])
2. Pass single row of the 2-D array ( equivalent to passing entire 1-D array to function)
3. Pass entire 2-D array to the function.
Passing a row:
◦ Row of 2-D array can be passed by indexing the array name with the row number.
◦ When we send a single row of a 2-D array, then called function receives one dimensional array.
Passing an entire 2-D array:
Function declaration should have the complete dimensions.
int func(arr[2][3]); // function declaration
func(arr); // function call
int func(int arr[2][3]) // function header in the definition
Multidimensional Arrays:
◦ Array of arrays.
◦ n indices is n-dimensional arrays.
◦ A 3-dimensional array consists of pages. Each page internal contains m rows and columns.