0% found this document useful (0 votes)
104 views58 pages

BPOPS103 Module3notes New

Uploaded by

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

BPOPS103 Module3notes New

Uploaded by

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

Introduction to C Programming BESCK104E Module 3

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

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


1 Bangalore
Introduction to C Programming BESCK104E Module 3

1.2 Advantages of Using Functions

1. Managing huge programs and software packages is easier by dividing them


intofunctions/modules—Maintenance is easier
2. Error detection is easier—Debugging is easier
3. Functions once written can be re-used in any other applications – Reusability is enhanced
4. We can protect our data from illegal users—Data protection becomes easier

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.

3. Function Declaration/ Function Prototype


Syntax:
return_data_type function_name(data_type variable1, data-type variable2,……);

where function name is a valid function name


return_data_type specifies the data type of the value that will be returned to the calling
function
data_type variable1, data_type variable2 … is list of variables of specified data types
Ex: int sum(int a, int b);
int isprime(int n);

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


2 Bangalore
Introduction to C Programming BESCK104E Module 3

Points to Remember while declaration of functions


 After declaration of every function, there should be a semicolon.
 The function declaration is global.
 Use of argument names in the function declaration statement is optional
So both declarations of statements are valid in c
Example: int func(int, char, float);
int func(int num, char ch, float fnum);
 Function cannot be declared within body of the 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. So the function declared as
void func(void); OR void print();
 If the function declaration does not specify any return type, then by default, the function returns an
integer value to the caller. Sum
Example: Sum(int a, int b)

 Some compilers make it compulsory to declare the function before its usage while other compilers
make it optional

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


3 Bangalore
Introduction to C Programming BESCK104E Module 3

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

A function definition, also known as function implementation will include:


i. Function type/ Return type
ii. Function name
iii. List of parameters/ Arguments
iv. Local variable declaration
v. Function statements/ Executable statements
vi. A return statement

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:

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


4 Bangalore
Introduction to C Programming BESCK104E Module 3

1. Local declarations that specify the variables needed by the function.


2. Function statements that perform the task of the function.
3. A return statement that returns the value evaluated by the function.

5. Function Call

 A function call invokes the function.

 When function is invoked the compiler jumps to the called function to execute the

statements that are part of that function.


 Once the called function is executed, the program control passes back to the calling

function
Syntax:
Function_name(Variable1, Variable2);

Points to Remember while calling a Functions


 Function name and the number and type of arguments in the function call must be same as that given in
the function declaration and header of the function definition
 If by mistake , the parameters passed to a function are more than what it is specified to accept, then the
extra arguments will be discarded
 If by mistake , the parameters passed to a function are less than what it is specified to accept, then the
un matched arguments will be initialized to some garbage value
 Names of Variables in function declaration, function call and header of the function definition may
vary
 Arguments may be passed in the form of expressions to he called function
 The parameters must be separated with comma operator
 If the return type of the function is not void, then the value returned by the called function may be
assigned to some variable as shown in the following statement
Syntax: Variable_nam=Function_name(Variablea1, Variable2,….);

Write a program to add two integers using Functions

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


5 Bangalore
Introduction to C Programming BESCK104E Module 3

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

7. Passing parameters to the Function

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.

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


6 Bangalore
Introduction to C Programming BESCK104E Module 3

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;
}

In this method the values a and b have been changed or swapped.


Advantages:
 Since the arguments are not copied into new variables, it provides greater time and space-efficiency
 The function can change the value of the argument and the change is reflected in the caller
 A function can return only one value.
Disadvange:
 When argument is passed using call by address, it becomes difficult to tell whether that
argument is meant for input, output or both

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


7 Bangalore
Introduction to C Programming BESCK104E Module 3

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

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


8 Bangalore
Introduction to C Programming BESCK104E Module 3

 To understand recursive functions, let us take an example of calculating the factorial of a


number.
 To calculate the n! we multiply the number with factorial of the number that is 1 less than
that number. In other words n!=n*(n-1)!
Example:
5!=5*4*3*2*1=120

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


9 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


10 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


11 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


12 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


13 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


14 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


15 Bangalore
Introduction to C Programming BESCK104E Module 3

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.

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


1 Bangalore
Introduction to C Programming BESCK104E Module 3

 Here marks[0]=10, marks[1]=20, marks[2]=30 and marks[3]=40. This subscript/index notation


isborrowed from Mathematics where we have the practice of writing: marks4, marks3, marks2 and so on.

Types of Arrays

I. One dimensional array/ Single-Subscripted Variable


II. Two dimensional array/ Double-Subscripted Variable
III. Multidimensional array

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.

Ex: int marks[4];


 Here marks is the name of the array which is capable of storing 4 integer values. The first value
will be stored in marks[0], the second value will be stored in marks[1] and so on and the last
value will be in marks[3].
Declaration of One-Dimensional Array:
Here is general syntax for array declaration along with examples.

Syntax: data_type array_name[array_size];


Examples: int marks[10];
float temperature[5];
Note: Declaration specifies the data type of array, its name and size.

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

 The size of an array can be specified using an expression.

#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];

3. Accessing Array Elements


 To accessing array individual element of the array, subscript must be used.

int i,marks[10];
for(i=0;i<10;i++)
Marks[i]=-1;

3.1 Calculating the Address of Array Elements

Address of an element A[k]=BA(A)+w(k-lower_bound)

Where A is an array, k is an index


BA is the Base Address of an array
W is the word size of the one element in memory
Example-1:

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


3 Bangalore
Introduction to C Programming BESCK104E Module 3

Example-2:

3.2 Calculating the Length of an Array

Length of an array= Upper_bound-Lower_bound+1

Where Upper_bound is the index of the last element


Lower_bound is the index of the first element
Example-1:

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


4 Bangalore
Introduction to C Programming BESCK104E Module 3

4. Storing values in Arrays


 When declaring an array, we are just allocating a space for the elements. No values are stored in
array.
 There are three ways of storing values in an array
1. Initialize the elements during declaration
2. Input the values for the elements from the keyboard
3. Assign values to individual elements

4.1 Initializing the Arrays during declaration


 Elements of the array can also be initialized at the time of declaration as other variables.
 When we initialize, we need to provide a value for every element in the array
Syntax:
data_type array_name[size]={list of values};

Example: int marks[5]={90,82,78,95,88};

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


5 Bangalore
Introduction to C Programming BESCK104E Module 3

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

elementswill be initialized to zero.


Example: int marks[5]={10,12,20};
Here, marks[3] and marks[4] will be initialized to zero.

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};

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


6 Bangalore
Introduction to C Programming BESCK104E Module 3

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]);
}

4.2 Inputting values from the keyboard

 An array can be filled by inputting the values from the keyboard

Example: int marks[10],i;


printf(“Enter the marks \n”);
for(i=0; i<10; i++)
{
scanf(“ %d”, &marks[i]);
}

4.3 Assigning values to Individual Elements


The third way to assign values to individual elements of the array by using the assignment operator
Example: int Marks[3]=100;
Here the value 100 is assigned to the fourth element of an array

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


7 Bangalore
Introduction to C Programming BESCK104E Module 3

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

5.1 Traversing an Array:


Traversing an array means accessing each and every element of the array for specific purpose
Algorithm:
Step 1: [Initialization] SET I=Lower_bound
Step 2: Repeat steps 3 to 4 while I<=Upper_bound
Step 3: Apply process to A[I]
Step 4: SET I=I+1
[END OF LOOP]
Step 5: EXIT

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

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


8 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


9 Bangalore
Introduction to C Programming BESCK104E Module 3

5.2 Inserting an Element into an Array:


Inserting an element into an array means adding a new data element to an already existing array.
Algorithm to insert an element at the last position of an array:
Step 1: SET Upper_bound= Upper_bound+1
Step 2: SET Upper_bound =VAL
Step 3: EXIT

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


10 Bangalore
Introduction to C Programming BESCK104E Module 3

Algorithm to insert an element at the middle of an array:


The algorithm INSERT will declared as INSERT(A,N, POS,VAL)
The arguments are.
a) A, the array in which the element has to be inserted
b) N, the number of elements in the array
c) POS, the position in which the element has to be inserted and
d) VAL, the value that has to be inserted

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:

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


12 Bangalore
Introduction to C Programming BESCK104E Module 3

5.3 Deleting an Element from an Array:


Deleting an element from an array means removing an element from an already existing array.

Algorithm to delete an element from the End of the Array:


Step 1: SET Upper_bound= Upper_bound-1
Step2: EXIT

Algorithm to delete an element from the middle of an Array:


The algorithm DELETE will declared as DELETE (A, N, POS)
The arguments are.
a) A, the array in which the element has to be deleted
b) N, the number of elements in the array
c) POS, the position in which the element has to be deleted

Step 1: [Initialization] SET I=POS


Step 2: Repeat steps 3 and 4 while I<=N-1
Step 3: SET A[I]=A[I+1]
Step 4: I=I+1
[END OF LOOP]
Step 5: N=N=1
Step 6: EXIT

Example:
Calling DELETE(Data,6,2)

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


13 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


14 Bangalore
Introduction to C Programming BESCK104E Module 3

5.4 Merging Two Arrays:

 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

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


15 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


16 Bangalore
Introduction to C Programming BESCK104E Module 3

Write a program to merge two sorted arrays


Refer Class notes:

5.5 Searching for a Value in an 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.

There are two methods for searching an array elements


1. Linear Search
2. Binary Search

5.5.1 Linear Search:


 Linear search is also called as Sequential search
 It works by comparing every element of the array one by one in sequential until a match is found
 It is mostly used to search an unsorted list of elements
Example;
int A[]={10,8,2,7,3,4,9,1,6,5};
Value to be searched is 7
The value is present at the position of 3, successful search

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


17 Bangalore
Introduction to C Programming BESCK104E Module 3

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 1: [Initialize] SET POS=-1


Step 2: [Initialize] SET I=1
Step 3: Repeat steps 4 while I<=N
Step 4: IF A[I]=VAL
SET POS=I
PRINT POS
Goto Step6
[END OF IF]
[END OF LOOP]
Step 5: IF POS=-1
PRINT “VALUE is not present in the Array”
[END OF IF]

Step 6: EXIT

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


18 Bangalore
Introduction to C Programming BESCK104E Module 3

 Write a program to implement Linear Search

5.5.2 Binary Search:


 Binary search is searching algorithm that efficiently with a sorted list.
 The algorithm finds the position of particular element in the array.

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 1: [Initialize] SET BEG= Lower_bound , END=Upper-bound,POS=-1


Step 2: Repeat steps 3 and 4 while BEG<=END
Step 3: SET MID=(BEG+END)/2
Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23
19 Bangalore
Introduction to C Programming BESCK104E Module 3

Step 4: IF A[MID]=VAL, then


POS=MID
PRINT POS
Goto Step6
ELSE IF A[MID]>VAL, then
SET END=MID-1
ELSE
SET BEG=MID+1
[END OF IF]
[END OF LOOP]
Step 5: IF POS=-1
PRINT “VALUE is not present in the Array”
[END OF IF]

Step 6: EXIT

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


20 Bangalore
Introduction to C Programming BESCK104E Module 3

5.6 Sorting Array Elements:

 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

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


21 Bangalore
Introduction to C Programming BESCK104E Module 3

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

Program: Refer Class Notes

6. Passing Arrays to Functions


Like variables of other data types, we can also pass an array to a function.

6.1 Passing Individual Elements


The individual elements of an array can be passed to a function by passing either their data values
or their addresses.

i. Passing Data Values


The individual elements can be passed in the same manner as we pass variables of any other data
types. The condition is that the data type of the array element must match the type of the function.

ii. Passing Addresses


Like ordinary variables, we can pass the address of an individual array element by preceding the
indexed array element with the address operator (&). Therefore, to pass the address of the fourth
element of the array to the called function. We will write &arr[3].

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


22 Bangalore
Introduction to C Programming BESCK104E Module 3

6.2 Passing the Entire Arrays

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


23 Bangalore
Introduction to C Programming BESCK104E Module 3

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


24 Bangalore
Introduction to C Programming BESCK104E Module 4

Two Dimensional Arrays

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

1.1 Declaration of Two-Dimensional Array:


Here is general syntax for array declaration along with examples.

Syntax: data_type array_name[row_size] [column_size];


Example: int marks[3][5];

Note: Declaration specifies the data type of array, its name and row_size , column_size

Pictorial Representation of Two dimensional array is shown below.

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

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


1 Bangalore
Introduction to C Programming BESCK104E Module 4

 There are two ways of storing 2D array in memory.


1. Row Major order
2. Column Major order
Row Major:
 The elements of the first row are stored before the elements of the second row and third
row.
 The elements of the array area stored row by row. Where the elements of the row will
occupy the first n locations.

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.

Calculating the Address of Array Elements:


Find the Address of an Element Using Column Major Method
If an index start with 1
Address of an element (A[i][j])=BA+W{M(J-1)+(I-1)}

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


2 Bangalore
Introduction to C Programming BESCK104E Module 4

Where A is an array, I and J are the subscripts of the array element


BA is the Base Address of an array
W is the word size of the one element in memory
M is the No of Rows

Find the Address of an Element Using Row Major Method


If an index start with 1
Address of an element (A[i][j])=BA+W{M(J-1)+(I-1)}

Where A is an array, I and J are the subscripts of the array element


BA is the Base Address of an array
W is the word size of the one element in memory
N is the No of Columns

Example-1:

1.2 Initializing Two-Dimensional Arrays


 Two-dimensional array is initialized in the same way as a one-dimensional array..
 When we initialize, we need to provide a value for every element in the array
Syntax:
data_type array_name[rowsize][columnsize]={list of values};

Example: int marks[2][3]={90,87,78,68,62,71};


The above initialization of two-dimensional array is done by row major method. The above statement can
also be written as
int marks[2][3]={{90,87,78},{68,62,71}};
In order to initialize the entire two-dimensional array to zero
int marks[2][3]={0};
Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23
3 Bangalore
Introduction to C Programming BESCK104E Module 4

Program to print the elements of 2D array

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


4 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


5 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


6 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


7 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


8 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


9 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


10 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


11 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


12 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


13 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


14 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


15 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


16 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


17 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


18 Bangalore
Introduction to C Programming BESCK104E Module 4

Subrahmanya H M, Asst. Professor, Dept. of CSE, GCEM, 2022-23


19 Bangalore

You might also like