BPOPS103 Module3notes New
BPOPS103 Module3notes New
Functions
1. Introduction
C enables programmers to break up a program into segments commonly known as Functions.
Every function in the program to perform a well-defined task. Therefore, the code of one function is
completely insulated from the other functions.
From the figure, we can see that main( ) calls a function named func1( ). Therefore, main( ) is known
as the calling function. The moment the compiler encounters a function call, instead of executing the
next statement in the calling function, the control jumps to the statements that are part of the called
function. After called function is executed, the control is returned back to the calling function.
1.1 Why are Functions Needed?
Dividing a program into separate well-defined functions facilities 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. Definition of Arrays
All the libraries in C contain the set of functions that the programmers are free to use in
their programs
2. Using Functions
While using functions we will use the following terminologies.
A function f( ) that uses another function g is known as the calling function and g is
known as the called function.
When a called function returns some result back to the calling function, it is said to
return that result
The calling function may or may not pass parameters to the called function. If the
called function accepts arguments the calling function will pass the parameters else it
will not do so.
Function declaration is a declaration statement that identifies a function with its name,
a list of arguments that it accepts, and type of data it returns.
Function definition consists of a function header that identifies the functio
n, followed by the body of the function containing the executable code for that
function.
Some compilers make it compulsory to declare the function before its usage while other compilers
make it optional
4. Function Definition
When a function is defined, space is allocated for that function in the memory. A function
definition comprises two parts.
Function Header
Function body
All the above six elements are grouped into two parts. Namely:
Function header (First three elements)
Function body (Second three elements)
Syntax:
function_type function_name(list of parameters)
{
local variable declaration;
executable statement1;
executable statement2;
......
......
return statement;
}
Note: The first line function_type function_name(parameter list) is known as the function header and the
statements within opening and closing braces is known as the function body.
i. Function Header: It consists of three parts: Function type, function name and list of
parameters.The semicolon is not present at the end of header.
Function type:
The function type specifies the type of value that the function is expected to return to the
callingfunction.
If the return type or function type is not specified, then it is assumed as int.
If function is not returning anything, then it is void.
Function name: The function name is any valid C identifier and must follow same rules as of other
variable.
List of Parameters: The parameter list declares the variables that will receive the data sent by the
callingprogram which serves as input and known as Formal Parameter List.
ii. Function Body: The function body contains the declarations and statements necessary
forperforming the required task. The body is enclosed in braces, contains three parts:
5. Function Call
When function is invoked the compiler jumps to the called function to execute the
function
Syntax:
Function_name(Variable1, Variable2);
6. Return Statement
The return statement is used to terminate the execution of a function and returns control to the
calling function
Syntax: return <expression>;
More than one Return statement used in function definition
Refer class notes
When a function is called, the calling function may have to pass some values to the called function
Basically there are two ways in which arguments or parameters are passed to the called function.
Two functions can communicate with each other by two methods:
1. Call by Value (By Passing parameters as values)
2. Call by Reference (By passing parameters as address)
1. Call by Value:
In call-by-value the calling function sends the copy of parameters (Actual Parameters) to the called
function (Formal Parameters). The changes does not affect the actual value.
Example:
#include<stdio.h>
int swap(int, int);
int main( )
{
int a=5, b=10 ;
swap(a, b);
printf(―%d%d:, a, b);
}
int swap(int x, int y)
{
int temp;;
temp = x;
x = y;
y = temp;
}
In the above example even though x and y values get swapped, the a and b values remains unchanged.
So swapping of two values in this method fails.
2. Call by Reference
In call by reference the calling function sends the address of parameters (Actual Parameters) to the
called function (Formal Parameters). The changes affect the actual value.
Example:
#include<stdio.h>
int swap(int *, int *);
int main( )
{
int a=5, b=10 ;
swap(&a, &b);
printf(―%d%d:, a, b);
}
int swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
8. Recursive Functions
Recursive function is function that calls itself to solve a smaller version of its task until a
final call is made which does not require a call to a itself.
Every recursive function has two major cases.
Base case
Recursive case
Base case , in which the problem is simple enough to be solved directly without making any
further calls to the same function
Recursive case, in which first the problem is divided into simpler sub-parts. Second the
function calls itself but with sub-parts of the problem obtained in the first step. Third, the
result is obtained by combining the solutions of simpler sub-parts
Arrays
1. Introduction
We have 20 students in a class and we have been asked to write a program that reads and print the
marks of all these students. In this program we need 20 integer variables with different names as shown
below.
Now to read values for these 20 different variables, we must have 20 read statements. Similarly, to
print the value of these variables, we need 20 write statements. If it is just matter of 20 variables, then it
might be acceptable for the user follow this approach.
1.1 Why do we need Arrays?
To process large amount of data, we need a data structure known as Array.
Arrays are used to represent multiple data items of the same type using single name.
2. Definition of Arrays
An array is a collection of homogeneous/ similar data elements of the same data type.
The elements are stored in consecutive memory locations and are referenced by an index
The array index starts with 0.
Subscript is an ordinal number which is used to identify an element of the array
Arrays are called as subscripted variables because; it is accessed using subscripts/indexes.
Ex: 1. List of employees in an organization.
a. List of products and their cost sold by a store.
b.Test scores of a class of students.
Types of Arrays
I. One-Dimensional Array:
A list of items can be given one variable name using only one subscript and such a variable is
called as one dimensional array.
Points to Remember
C does not allow declaring an array whose number of elements is not known at the time of compile
time. There fore the following code is illegal
int arr[];
int n, arr[n];
Generally it is good programming practice to define the size of an array as a symbolic constant as
shown below.
#include<stdio.h>
#define N 100
main()
{
int arr[N];
…………
}
Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23
2 Bangalore
Introduction to C Programming BESCK104E Module 3
#include<stdio.h>
#define N 100
main()
{
int i=10;
int arr[N+100],my_arr[i-5*10];
…………
}
C never checks the validity of the array index at compile time nor at run time
int arr[N];
int i,marks[10];
for(i=0;i<10;i++)
Marks[i]=-1;
Example-2:
Initialization of One-Dimensional Array: After array is declared, next is storing values in to an array
iscalled initialization. There are two types of array initialization:
i. Compile-time initialization
ii. Run-time initialization
i. Compile time initialization: If we assign values to the array during declaration it is called
compile time initialization. There are 4 different methods:
a) Initialization with size
b) Initialization without size
c) Partial initialization
d) Initializing all values zero
a) Initialization with size: we can initialize values to all the elements of the array.
Syntax: data_type array_name[array_size]={list of values};
Examples: int marks[4]={ 95,35, 67, 87};
float temperature[3]={29.5, 30.7, 35.6};
b) Initialization without size: We needn’t have to specify the size of array provided we are
initializingthe values in beginning itself.
Syntax: data_type array_name[ ]={list of values};
Examples: int marks[ ]={ 95,35, 67, 87};
float temperature[ ]={29.5, 30.7, 35.6, 45.7, 19.5};
c) Partial initialization: If we not specify the all the elements in the array, the unspecified
d) Initializing all the elements zero: If we want to store zero to all the elements in the array we can do.
Examples: int marks[4]={0};
ii. Run-time Initialization: Run time initialization is storing values in an array when program is
running or executing.
Example:
int marks[4],i;
printf(“Enter the marks \n”);
for(i=0; i<4; i++)
{
scanf(“ %d”, &marks[i]);
}
5. Operations on Arrays
There are number of operations that can be performed on arrays.
The operations include the following
1. Traversing the array
2. Inserting an element in an array
3. Deleting an element from an array
4. Merging two arrays
5. Searching an element in an array
6. Sorting an array in ascending or descending order
Example: a) Find the total number and marks of all the students who have secured 80 or more marks
b) Print the roll number and marks of all the students who have got distinction
a) Solution: Step 1: [Initialization] SET COUNT=0, I=Lower_bound
Step 2: Repeat for I=Lower_bound to Upper_bound
IF Marks[I]>=80, then:Set COUNT=COUNT+1
[END OF IF]
SET I=I+1
[END OF LOOP]
Step3: EXIT
b) Solution: Step 1: [Initialization] SET I=Lower_bound
Step 2: Repeat for I=Lower_bound to Upper_bound
IF Marks[I]>=75, Write:I,
Marks[I]
[END OF IF]
SET I=I+1
[END OF LOOP]
Step3: EXIT
Algorithm:
Step 1: [Initialization] SET I=N
Step 2: Repeat steps 3 and 4 while I>=POS
Step 3: SET A[I+1]=A[I]
[END OF LOOP]
Step 4: N=N=1
Step 5: SET A[POS]=VAL
Step 6: EXIT
Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23
11 Bangalore
Introduction to C Programming BESCK104E Module 3
Example:
Example:
Calling DELETE(Data,6,2)
Merging two arrays in third array means first copying the contents of the first array into the third
array and then copying the second array into third array.
Hence merged array contains the contents of first array followed by the contents of second array
Searching means to find whether a particular value is present in the array or not.
If the value is present in an array then the search is said to be successful and search process gives the
location of that value in the array.
Otherwise, if the value is not present in the array, then search is said to be unsuccessfull.
Algorithm:
LINEAR SEARCH(A,N,VAL)
a) A, the array
b) N, the number of elements in the array
c) VAL, the element has to be searched
Step 6: EXIT
Algorithm:
BINARY SEARCH(A,Lower_bound,Upper_bound,VAL)
a) A, the array
b) Lower_bound, the index of the first element of an array
c) Upper_bound, the index of the last element of an array
d) VAL, the element has to be searched
Step 6: EXIT
The term sorting means sorting the elements of the array in some relevant order which
may either by ascending or descending order
If an array A, then elements are arranged in sorted order in such a way that
A[0]< A[1]< A[1]< A[1]< A[2]< A[3]<…….. A[N]
Example:
int A[]={21,34,11,9,1,0,12}; then the sorted list is
int A[]={0,1,9,11,21,22,34};
Types of sorting
Internal Sorting: Sorting the data stored in computer’s memory
External Sorting: Sorting data stored in files
Bubble Sort:
It is a very simple method that sorts the array elements by repeating moving the largest element to
the highest index position of the array.
Bubble_sort(A,N)
Algorithm:
Step 1: Repeat step 2 for I=0 to N-1
Step 2: Repeat For J=0 to N-I-1
Step 3: If A[J]>A[J+1], then
Swap A[J] and A[J+1]
[END of INNER LOOP]
[END of OUTER LOOP]
Step 4: Exit
1. Introduction
We need to store data in the form of matrices or tables. It is specified using two subscripts.
A one subscript denotes row and other denotes column. The following figure shows a two-dimensional
array which can be viewed as an array.
First Dimension
Second Dimension
Two-Dimensional Array
Note: Declaration specifies the data type of array, its name and row_size , column_size
Hence, we see that a 2D array is treated as a collection of 1D array. To understand this, we can also see
the representation of a two-dimensional array as shown in below figure 12.27
Column Major:
The elements of the first column are stored before the elements of the second column and
third column.
The elements of the array area stored column by column. Where the elements of the row
will occupy the first n locations.
Example-1: