0% found this document useful (0 votes)
2 views

Module-3

This document is a module on functions in the C programming language, detailing their importance, usage, and syntax. It explains how functions allow for program segmentation, making coding and testing easier, and covers concepts such as function declaration, definition, and parameter passing methods (call by value and call by reference). Additionally, it provides examples to illustrate these concepts, including a program that adds two integers using functions.

Uploaded by

naxibew907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Module-3

This document is a module on functions in the C programming language, detailing their importance, usage, and syntax. It explains how functions allow for program segmentation, making coding and testing easier, and covers concepts such as function declaration, definition, and parameter passing methods (call by value and call by reference). Additionally, it provides examples to illustrate these concepts, including a program that adds two integers using functions.

Uploaded by

naxibew907
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 150

1

Dr. H N National College of Engineering, Bengaluru


Department of Artificial Intelligence and Data Science
Principles of Programming Using C
Module-3
By,
Dr. Vikhyath K B

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Module-3: Functions
2

11.1 Introduction
• C enables programmers to break up a program into segments commonly known as
functions, each of which can be written more or less independently of the others.

• Every function is supposed to perform a well-defined task. Therefore, the code of one
function is completely insulated from the other functions.

• Every function interfaces to the outside world in terms of how information is transferred
to it and how results generated by it are transmitted back.

main()
{ func1()
……
{
…… Statement Block;
func1();
}
…….
…….
return 0;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
3

• In the previous figure main() function call the function named func1(). Therefore,
main() is known as the calling function and func1() is known as the called 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 the
part of the called function. After the called function is executed, the control is
returned back to the calling function.

• The main() function can call many functions as it wants and as many times as it
wants.

• Example: A function call placed within a for loop, while loop, or do-while loop can
call the same function multiple times until the condition holds true.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


4

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.1.1 Why are Functions Needed?
5

Reasons for segmenting a program into functions:

• Dividing a program into separate well-defined functions facilitates each function to


be written and tested separately. This simplifies the process of getting the total
program to work.

• Understanding, coding, and testing multiple separate functions is far easier than
doing it for one big function.

• If a big program has to be developed without the use of any function other than
main() function, then there will be countless lines in the main() function and
maintaining this program will be very difficult.

• When a big program is broken into comparatively smaller functions, then different
programmers working on that project can divide the workload by writing different
functions.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


6

• Like C libraries, programmers can also write their functions and use them at
different points in the main program or in any program that needs its
functionalities.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.2 Using Functions
7
Some of the important terminologies of functions:

• A function f that uses another function g is known as the calling function and g is
known as called function.

• The inputs that a function takes are known as arguments/parameters.

• 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 the arguments, the calling function will pass parameters.
Else it will not do so.

• Function declaration is declaration statement that identifies with its name, a list of
arguments that it accepts, and the type of data it returns.
• Function definition consists of a function header that identifies the function,
followed by the body of the function containg the executable code for that function.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.3 Function Declaration/ Function
Prototype
8

• 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 type of the
value that it will return to the calling function.

• Placing the function declaration statement prior to its use enables the compiler to
make a check on the arguments used while calling that function.

Syntax:
return_data_type function_name(data_type variable1, data_type variable2,….);

• Here, function_name is a valid name for the function.

• return_data_type specifies the data type of the value that will be returned to the
calling function as a result of the processing performed by the called function.

• data_type variable1, data_type variable2, …. Is a list of variables of specified data


types.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
9

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.4 Function Definition
10

• When a function is defined, space is allocated for that function in the memory.

A function definition comprises two parts:

• Function header
• Function body

The syntax of a function definition can be given as:

return_data_type function_name(data_type variable1, data_type variable2,….)


{
statements
………….
return(variable);
}
The number of arguments and the order of arguments in the function header must be
same as that given in the function declaration statement.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.5 Function Call
11

The function call statement invokes the function. When a function is invoked the
compiler jumps to the called function to execute the statements that are part of that
function.

Syntax:

function_name(variable1, variable2,……..);

Function definitions are often placed in separate header files which can be included in
other C source files that wish to use these functions.

Example: The header file stdio.h contains the definition of scanf and printf functions.
We simply include this header file and call these functions without worrying about the
code to implement their functionality.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to add two integers
using functions.
12

#include <stdio.h>
int sum(int a, int b);
int main()
{
int num1, num2, total = 0;
printf("Enter the first number:");
scanf("%d", &num1);
printf("\n Enter the second number:");
scanf("%d", &num2);
total = sum(num1, num2);
printf("\n Total = %d", total);
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


13

// Function Definition
int sum (int a, int b)
{
int result;
result = a+b;
return result;
}

Output:

Enter the first number: 20


Enter the second number: 30
Total = 50

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.6 return Statement
14

The return statement terminates the execution of the called function and returns
control to the calling function. When the return statement is encountered, the program
execution resumes in the calling function at the point immediately following the
function call.

Syntax:

return <expression>;

Here, expression placed between the angular brackets because specifying an


expression is optional. The value of the expression, if present, is returned to the calling
function. However, in case expression is omitted, the return value of the function is
undefined.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


15

#include <stdio.h>
int check_relation(int a, int b);
int main()
{
int a=3, b=5, res;
res = check_relation(a, b);
if(res==0)
printf("\n Equal");
if(res==1)
printf("\n a is greater than b");
if(res==-1)
printf("\n a is less than b");
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


16

int check_relation(int a, int b)


{
if(a==b)
return 0;
else if(a>b)
return 1;
else
return -1;
}

Output:

a is less than b

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.6.1 Using Variable Number of
Arguments
17

Some functions have a variable number of arguments and data types that cannot be
known at the compile time.

Example: printf() and scanf() functions.

ANSI C offers a symbol called ellipsis to handle such functions. The ellipsis consists
of three periods (…). It can be used as;

int func(char ch, …);

The function declaration statement given above states that func is a function that has
an arbitrary number and type of arguments. However, one must ensure that both the
function declaration and function definition should use ellipsis symbol.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.7 Passing Parameters to Functions
18

When a function is called, the calling function may have to pass some values to the
called function.

There are two ways in which arguments can be passed to the called function. They
include:

Call by value: In which values of variables are passed by the calling function to the
called function.

Call by reference: In which address of variables are passed by the calling function to
the called function.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.7.1 Call by Value
19

In the call-by-value method, the called function creates new variables to store the
value of the arguments passed to it. Therefore, the called function uses a copy of the
actual arguments to perform its intended task.

If the called function is supposed to modify the value of the parameters passes to it,
then the change will be reflected only in the called function. In the calling function no
changes will be made to the value of the variables. This is because all the changes
were made to the copy of the variables and not to the actual variables.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


20

#include <stdio.h>
void add(int n);
int main()
{
int num=2;
printf(" \n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}

void add(int n)
{
n = n + 10;
printf(" \n The value of num in the called function = %d", n);
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


21

Output:

The value of num before calling the function = 2

The value of num in the called function = 12

The value of num after calling the function = 2

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.7.2 Call by Reference
22

In call by reference, we declare the function parameters as references rather than


normal variables. When this is done any changes made by the function to the
arguments it receives are visible in the calling functions.

To indicate that an argument is passed using call by reference, an asterik (*) is placed
after the type in the parameter list. This way changes made to the parameter in the
called function will then be reflected in the calling function.

Hence, in call-by-reference method, a function receives an implicit reference to the


argument, rather than a copy of its value. Therefore, the function can modify the value
of the variable and that change will be reflected in the calling function as well.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Example:
23

#include <stdio.h>
void add(int *n);
int main()
{
int num=2;
printf(" \n The value of num before calling the function = %d", num);
add(&num);
printf("\n The value of num after calling the function = %d", num);
return 0;
}

void add(int *n)


{
*n = *n + 10;
printf(" \n The value of num in the called function = %d", *n);
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


24

Output:

The value of num before calling the function = 2

The value of num in the called function = 12

The value of num after calling the function = 12

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Advantages and Disadvantages
25

Advantages:

Since arguments are not copied into new variable, it provides greater time and space
efficiency.

The called function can change the value of the argument and the change is reflected
in the calling function.

A return statement can return only one value. In case we need to return multiple
values, pass those arguments by reference.

Disadvantages:

The side effect of using this technique is that when an argument is passed using call by
address, it becomes difficult to tell whether that argument is meant for input, output, or
both.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a function to swap the value of
two variables.
26

#include <stdio.h>
void swap_call_by_val(int, int);
void swap_call_by_ref(int *, int *);
int main()
{
int a=1,b=2,c=3,d=4;
printf("\n In main(), a=%d and b=%d", a, b);
swap_call_by_val(a,b);
printf("\n In main(), a=%d and b=%d", a,b);
printf("\n\n In main(), c=%d and d=%d",c,d);
swap_call_by_ref(&c, &d);
printf("\n In main(), c=%d and d=%d", c, d);
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


27

void swap_call_by_val(int a, int b)


{
int temp;
temp=a;
a=b;
b=temp;
printf("\n In function (call by value method) a =%d and b=%d", a, b);
}
void swap_call_by_ref(int *c, int *d)
{
int temp;
temp=*c;
*c=*d;
*d=temp;
printf("\n In function (Call by reference method) c=%d and d=%d", *c, *d);
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


28

Output:

In main(), a=1 and b=2

In function (call by value method) a =2 and b=1

In main(), a=1 and b=2

In main(), c=3 and d=4

In function (Call by reference method) c=4 and d=3

In main(), c=4 and d=3

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to convert time to
minutes.
29

#include<stdio.h>
int convert_time_in_mins(int hrs, int minutes);
int main() Output:
{ Enter hours and minutes:
int hrs, minutes, total_mins; 4
printf("\n Enter hours and minutes:"); 30
scanf("%d%d", &hrs, &minutes); Total minutes=270
total_mins = convert_time_in_mins(hrs,minutes);
printf("\n Total minutes=%d",total_mins);
return 0;
}

int convert_time_in_mins(int hrs, int mins)


{
mins=hrs*60+mins;
return mins;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.8 Scope of Variables
30

In C all constant and variables have a defined scope. A variable or a constant in C has
four types of scope: block, function, program, and file.

11.8.1 Block Scope: A statement block is a group of statements enclosed


within opening and closing curly brackets { }. If a variable is declared within a
statement block then as soon as the control exits that block, the variable will cease to
exit. Such a variable is known as local variable and is said to have a block scope.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Example:
31

#include<stdio.h>
int main()
{
int x=10;
int i=0;
printf(" \n The value of x outside the while loop is %d", x);
while(i<3)
{
int x=i;
printf(" \n The value of x inside the while loop is %d", x);
i++;
}

printf(" \n The value of x outside the while loop is %d", x);


return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


32

Output:

¨ The value of x outside the while loop is 10

¨ The value of x inside the while loop is 0

¨ The value of x inside the while loop is 1

¨ The value of x inside the while loop is 2

¨ The value of x outside the while loop is 10

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.8.2 Function Scope
33

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. In other words function scope is
applicable only with goto label names. This means that the programmer cannot have
the same label names inside a function.

Example:
int main() In this example, the label loop is visible from the beginning to
{
..
the end of the main() function. Therefore, there should not be
.. more than one label having the same name within the main()
loop: function.
..
..
goto loop;
..
..
return 0; Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
}
11.8.3 Program Scope
34

If we want a function to access some variable which are not passed to it as arguments,
then declare those variables outside any function blocks. Such variables are commonly
known as global variables and can be accessed from any point in the program.

Lifetime: 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 program and are accessible to them for usage.

Place of Declaration: The global variables are declared outside all 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.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Example:
35

#include<stdio.h>
int x = 10;
void print();
int main()
{
printf(" \n The value of x in the main() = %d", x);
int x = 2;

printf(" \n The value of local variable x in the main() = %d", x);


print();
return 0;
}
void print()
{
printf(" \n The value of x in the print() = %d", x);
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru
18/12/24
36

Output:

¨ The value of x in the main() = 10

¨ The value of local variable x in the main() = 2

¨ The value of x in the print() = 10

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.8.4 File Scope
37

When a global variable is accessible until the end of the file, the variable is said to
have file scope.

To allow a variable to have file scope, declare that variable with the static keyword
before specifying its data type.

Example: static int x =10;

A global static variable can be used anywhere from the file in which it is declared but
it is not accessible by any other file.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.9 Storage Classes
38

Storage class defines the scope (visibility) and lifetime of variables and/or functions
declared within a C program.

The storage class of a function or a variable determines the part of memory where
storage space will be allocated for that variable or function (whether the
variable/function will be stored in a register or in RAM).

It specifies how long the storage allocation will continue to exists for that function or
variable.

It specifies the scope of the variable or function, i.e., the storage class indicates the
part of the C program in which the variable name is visible or the part in which it is
accessible.

It specifies whether the variable or function has internal, external or no linkage. It


specifies whether the variable will be automatically initialized to zero or to any
indeterminate value.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.9.1 auto Storage Class
39

The auto storage class specifier is used to explicitly declare a variable with automatic
storage. It is the default storage clas for variables declared inside a block.

Example: auto int x;

Then x is an integer that has automatic storage. It is deleted when the block in which x
is declared is exited.

The auto storage class can be used to declare variables in a block or the names of
function parameters. However, since the variable names of function parameters by
default have automatic storage, the auto storage class specifier is therefore treated as
redundant while declaring data.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


40

Variables declared with auto storage class are as follows:

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 allocated upon entry to a block and freed
automatically upon exit from that block.

The scope of the variable is local to the block in which it is declared.

Every time the block is entered, the variable is initialized with the values declared.

The auto variables are stored in the primary memory of the computer.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


41

#include<stdio.h>
void func1() Output:
{ int a=10;
printf("\n a=%d",a); a=10
} a=20
void func2() a=30
{
int a=20;
printf("\n a=%d",a);
}
int main()
{
int a=30;
func1();
func2();
printf("\n a=%d",a);
return 0;
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.9.2 register Storage Class
42

When a variable is declared using register as its storage class, it is stored in a CPU
register instead of RAM. Since, the variable is stored in a register, the maximum size
of the variable is equal to the register size.

One drawback of using a register variable is that they cannot be operated using the
unary ‘&’ because it does not have a memory location associated with it. A register
variable is declared in the following manner:

register int x;

Register variables are used when quick access to the variable is needed.

Like auto variables, register variables also have automatic storage duration. That is,
each time a block is entered, the register variables defined in that block are accessible
and the moment that block is excited, the variables become no longer accessible for
use.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


43

#include<stdio.h>
int exp(int a, int b);
int main()
{
int a=3, b=5, res;
res=exp(a,b);
printf("\n %d To the power of %d =%d", a, b, res);
return 0;
}
int exp(int a, int b) Output:
{ 3 To the power of 5 =243
register int res=1;
int i;
for(i=1;i<=b;i++)
res=res*a;
return res;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.9.3 extern Storage Class
44

A large C program can be broken down into smaller programs. When these smaller
programs are compiled, they are joined together to form a large program. However,
these smaller programs may need to share certain variables for processing. For such
situations C language provides an external storage class that is specified using the
keyword extern.

The extern storage class is used to give a reference of a global variable that is visible
to all the program files.

Syntax: extern int x;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


45

// FILE1.c

#include<stdio.h>
#include<FILE2.c>

int x;
void print(void);
int main()
{
x=10;
printf("\n x in FILE1 = %d", x);
print();
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


46

//FILE2.c

#include <stdio.h> Output:


extern int x;
void print() x in FILE1 = 10
{ x in FILE2 = 10
printf("\n x in FILE2=%d", x);
}
int main()
{
//statements
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.9.4 static Storage Class
47

While auto is the default storage class for all local variables, static is the default
storage class for all global variables. Static variables have a lifetime over the entire
program.

To declare an integer x as static:

static int x = 10;

Here x is a local static variable. Static local variables when defined within a function
are initialized at the runtime.

Static storage class can be specified for auto as well as extern variables.

Example:
static extern int x;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


48

#include <stdio.h>
void print(void);

int main()
{
printf(" \n First call of print()");
print();
printf("\n \n Second call of print()");
print();
printf("\n\n Third call of print()");
print();
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


49

void print()
{
static int x;
int y=0;
printf("\n Static integer variable, x=%d",x);
printf("\n Integer variable, y=%d",y);
x++;
y++;
}
Output: Third call of print()
First call of print() Static integer variable, x=2
Static integer variable, x=0 Integer variable, y=0
Integer variable, y=0

Second call of print()


Static integer variable, x=1
Integer variable, y=0
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.9.5 Comparison of Storage Classes
50

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.10 Recursive Functions
51

A recursive function is defined as a 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 itself.

Every recursive solution has two major cases:

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 the problem at hand 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.

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


number.

n! = n * (n-1)!

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


52

¨ The value of 5!

¨ 5! = 5*4*3*2*1
¨ = 120
¨ This can be written as:
¨ 5! = 5*4!, where 4!=4*3!
¨ Therefore,
¨ 5!=5*4*3!
¨ Similarly, we can also write
¨ 5! = 5*4*3*2!
¨ Expanding further
¨ 5! = 5*4*3*2*1!

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


53

#include<stdio.h>
int Fact(int);
int main()
{
int num, factorial;
printf("\n Enter the number");
scanf("%d",&num);
factorial= Fact(num);
printf("\n Factorial of %d = %d", num, factorial);
return 0;
} Output:
int Fact(int n)
{ Enter the number 5
if(n==1) Factorial of 5 = 120
return 1;
else
return(n*Fact(n-1));
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
54

Analysis of the basic steps of the recursive program:

Step1: Specify the base case which will stop the function from making a call to itself.

Step2: Check to see whether the current value being processed matches with the value
of the base case. If yes, process and return the value.

Step3: Divide the problem into smaller or simpler sub-problems.

Step4: Call the function from the sub-problem.

Step5: Combine the results of the sub-problem.

Step6: Return the result of the entire problem.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.10.1 Greatest Common Divisor
55

The greatest common divisor (GCD) of two numbers (integers) is the largest integer
that divides both the numbers.

Euclid’s algorithm:

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


56

Working:
Assume a=62 and b=8
GCD(62,8)
rem=62%8=6
GCD(8,6)
rem=8%6=2
GCD(6,2)
rem=6%2=0
return 2
return 2
return 2

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


57

#include<stdio.h>
int GCD(int, int);
int main(){
int num1, num2, res;
printf("\n Enter the two numbers:");
scanf("%d%d", &num1, &num2);
res=GCD(num1, num2);
printf("\n GCD of %d and %d = %d", num1, num2, res);
return 0; }
int GCD(int x, int y)
{ Output:
int rem;
rem = x%y; Enter the two numbers:10 34
if(rem==0) GCD of 10 and 34 = 2
return y;
else
return (GCD(y,rem));
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.10.2 Finding Exponent
58

#include<stdio.h>
int exp_rec(int, int);
int main()
{
int num1, num2, res; Output:
printf("\n Enter the two numbers:");
scanf("%d%d",&num1,&num2); Enter the two numbers: 2 4
res=exp_rec(num1,num2); RESULT =16
printf("\n RESULT =%d", res);
return 0;
}
int exp_rec(int x, int y)
{
if(y==0)
return 1;
else
return(x*exp_rec(x, y-1));
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
11.10.3 Fibonacci Series
59

¨ The Fibonacci series can be given as:

¨ 0 1 1 2 3 5 8 13 21 34 55 ………

¨ That the term term of the series is the sum of the first and second terms.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


60

#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i=0, res;
printf("\n Enter the number of terms \n");
scanf("%d",&n);
printf("Fibonacci series \n");
for(i=0;i<n;i++)
{
res = Fibonacci(i);
printf("%d \t",res);
}
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


61

int Fibonacci(int n)
{
if(n==0)
return 0;
else if(n==1)
return 1;
else
return (Fibonacci(n-1) + Fibonacci(n-2));
}

Output:
Enter the number of terms
5
Fibonacci series
0 1 1 2 3

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.11 Types of Recursion
62

Recursion is a technique that breaks a problem into one or more sub-problems that are
similar to the original problem.

Any recursive function can be characterized based on:

¨ Whether the function calls itself directly or indirectly.

¨ Whether any operation is pending at each recursive call, and

¨ The structure of the calling pattern.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.11.1 Direct Recursion
63

¨ A function is said to be directly recursive if it explicitly calls itself.

¨ Here, Func() calls itself for all positive values of n, so it is said to be a directly
recursive function.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.11.2 Indirect Recursion
64

¨ A function is said to be indirectly recursive if it contains a call to another function


which ultimately calls it.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.11.3 Tail Recursion
65

¨ A recursive function is said to be tail recursive if no operations are pending to be


performed when the recursive function returns to its caller.

¨ Tail recursive function are highly desirable because they are much more efficient to
use as the amount of information that has to be stored on the system stack is
independent of the number of recursive calls.

¨ The factorial function that we have written is a non-tail-recursive function, because


there is a pending operation of multiplication to be performed on return from each
recursive call.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


66

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.11.4 Linear and Tree Recursion
67

¨ Recursive function can also be characterized depending on the way in which


recursion grows, i.e., in a linear fashion or forming a tree structure.

¨ A recursive function is said to be linearly recursive when the pending operation


does not make another recursive call to the function.

¨ A recursive function is said to be tree recursive if the pending operation makes


another recursive call to the function.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


11.12 Tower of Hanoi
68

¨ The tower of Hanoi is one of the main applications of recursion. It says, if you can
solve n-1 cases, then you can easily solve the nth case.

¨ As represented in the below figure, shows three rings mounted on a pole A. The
problem is to move all these rings from pole A to pole C while maintaining the
same order. The main issue is that the smaller disk must always come above the
larger disk.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


69

¨ We will be doing this using a spare pole. In our case, A is the source pole, C is the
destination pole, and B is the spare pole. To transfer all the three rings from A to C,
we will first shift the upper two rings (n-1 rings) from the source pole to the spare
pole. We move the first two rings from pole A to b using C as the spare pole as
shown below.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


70

¨ Now that n-1 rings have been removed from pole A, the nth ring can be easily
moved from the source pole(A) to the destination pole(C).

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


71

¨ The final step is to move the n-1 rings from B to C using A as the spare pole.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


72

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12. Arrays
73

¨ An array is a collection of similar data elements. These data elements have the
same data type.

¨ The elements of the array are stored in consecutive memory locations and are
referenced by an index.

Examples:

¨ Temperatures recorded on every day of the month


¨ Employees in a company
¨ Students in a class
¨ Products sold
¨ Customers
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
12.2 Declaration of Arrays
74

¨ An array must be declared before being used. Declaring an array means specifying
three things:

¨ Data type: What kind of values it can store, for example int, char, float.,

¨ Name: To identify the array

¨ Size: The maximum number of values that the array can hold.

Syntax: type name[size];

Here the type can be either int, float, double or any other valid data type. The number
within the brackets indicates the size of the array, i.e., the maximum number of
elements that can be stored in the array.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
75

¨ The size of the array is a constant and must have a value at compilation time.

int marks[10];

¨ The above statement declares, marks to be an array containing 10 elements. In C


array index (also known as subscript) starts from zero. This means that the array
marks will contain 10 elements in all.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


76

Points to be Remembered:
¨ C does not allows declaring an array whose number of elements is not known at
the compile time. Therefore, the following array declaration are illegal in C.
int arr[];
int n, arr[n];
¨ Generally it is a 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];
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
77

¨ The size of the array can be specified using an expression. However, the
components of the expression must be available for evaluation of the expression
when the program is compiled.
#include<stdio.h>
#define N 100
main() {
int i=10;
int arr[N+10], my_arra[i-5*10];
}
C never checks the validity of the array index-neither at compile time nor at run time.
So even if we declare an array as:
int arr[N];
The C compiler will not raise any error but the result of running such code is totally
unpredictable.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
12.3 Accessing the Elements of an
Array
78

¨ For accessing an individual elements of the array, the array subscription must be
used. For example, to access the fourth element of the array, we must write arr[3].

¨ We can access all the elements of the array by varying the value of the subscription
into the array.

¨ To process all the elements of the array, we will use a loop as shown below:

int i, marks[10];
for(i=0;i<10;i++)
marks[i]=-1
¨ The code accesses every individual elements of the array and sets to -1, then the
value of the index (i) is incremented and the next value, i.e., marks[i] is set to -1.
The procedure is continued until all the 10 elements of the array are set to -1.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
12.3.1 Calculating the Address of
Array Elements
79

¨ We are wondered that how C knows where an individual elements of the array is
located in the array. The array name is a symbolic reference to the address of the
first byte of the array.

¨ The index represents the offset from the beginning of the array to the elements
being referenced. With just the array name and index, C can calculate the address
of any element in the array.

¨ Since an array stores all its data elements in consecutive memory locations, storing
just the base address, i.e., the address of the first element in the array is sufficient.

¨ The address of other data element can simply be calculated using the base address.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


80

¨ The formula for doing this calculation is:

¨ Address of data element, A[k] = BA(A) +W(k-lower_bound)

¨ Here, A is the array, k is the index of the element for which we have to calculate
the address, BA is the base address of the array A, W is the word size of one
element in memory, and lower_bound is the index of the element in the array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


81

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.3.2 Calculating the Length of an
Array
82

¨ The length of the array is given by the number of elements stored in it. The general
formula to calculate the length of the array is:

¨ Length = upper_bound – lower_bound + 1;

¨ Where the upper_bound is the index of the last element and lower_bound is the
index of the first element in the array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


83

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.4 Storing Values in Arrays
84

¨ When we declare an array, we are just allocating space for the element; no values
are stored in the array.

¨ There are three ways to store the values in an array – first, to initialize the array
element at the time of declaration; second, to input value for every individual
element at the run time; third to assign values to the individual elements.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.4.1 Initializing Array during
Declaration
85

¨ Elements of the array can also be initialized at the time of declaration as other
variables. When an array is initialized, we need to provide a value for every
element in the array.

¨ type array_name[size] = {list of values};

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

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.4.2 Inputting Values from the
Keyboard
86

¨ An array can be filled by inputting values from the keyboard. In this method, a
while/do-while or a for loop is executed to input the values for each element of the
array.

int i, marks[10];
for(i=0;i<10;i++)
scanf(“%d”, &marks[i]);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.4.3 Assigning Values to individual
Elements
87

¨ The third way is to assign values to individual elements of the array by using the
assignment operator. Any value that evaluates to the data type of the array can be
assigned to the individual array elements. Assignment statement can be written as:

¨ marks[3] = 100;
¨ Here, 100 is assigned to the fourth element of the array which is specified as
marks[3].

¨ We cannot assign one array to another array, even if the two arrays have the same
type and size. To copy an array, you must copy the value of every element of the
first array into the element of the second array.
¨ int i, arr1[10];
¨ for(i=0;i<10;i++)
¨ arr[i]=i*2;
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
12.5 Operations on Arrays
88

The operations includes the following:

¨ Traversing an array
¨ Inserting an element in an array
¨ Deleting an element from an array
¨ Merging two arrays
¨ Searching an element in an array
¨ Sorting an array in ascending or descending order

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.5.1 Traversing an Array
89

¨ Traversing an array means accessing each and every element of the 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, or
performing any process on these elements.

¨ Since an array is a linear data structure traversing its elements is very simple and
straightforward.
¨ 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:Dr.
Exit
Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
Write a program to read and display
n numbers using an array.
90

#include<stdio.h>
int main()
{
int i=0, n, arr[20];
printf(" \n Enter the number of elements:");
scanf("%d", &n);
printf("\n Enter the elements");
for(i=0;i<n;i++)
{
printf("\n Arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\n The array elements are \n");
for(i=0;i<n;i++)
printf("Arr[%d] = %d\t", i, arr[i]);
return 0;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
91

Output:
Enter the number of elements:5
Enter the elements

Arr[0] = 1

Arr[1] = 2

Arr[2] = 3

Arr[3] = 4

Arr[4] = 5

The array elements are

Arr[0] = 1 Arr[1] = 2 Arr[2] = 3 Arr[3] = 4 Arr[4]


=5 Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
Write a program to read and display
n random numbers using an array.
92

#include<stdio.h>
#define MAX 10 Output:
int main() The contents of the array are:
{
int arr[MAX], i, RandNo; 3 6 7 5 3
for(i=0;i<MAX;i++) 5 6 2 9 1
{
RandNo = rand() % MAX;
arr[i] = RandNo;
}
printf("\n The contents of the array are: \n");
for(i=0;i<MAX;i++)
printf("\t %d", arr[i]);
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to print the position of
the smallest of n numbers using arrays.
93

#include<stdio.h>
int main()
{
int i, n, arr[20], small, pos;
printf(" \n Enter the number of elements in the array:");
scanf("%d", &n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
small=arr[0];
pos=0;
for(i=1;i<n;i++)
{
if(arr[i]<small)
{
small = arr[i];
pos = i;
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
}
94

printf("\n The smallest element is %d", small);


printf("\n The position of the smallest element in the array is %d", pos);
return 0;
}

Output:

Enter the number of elements in the array:5

Enter the elements:1 2 3 4 5

The smallest element is 1

The position of the smallest element in the array is 0

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.5.2 Inserting an Element in an
Array
95

¨ Inserting an element in an array means adding a 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 insertion is quit simple. We just add 1 to the upper_bound and assign the
value.

¨ Algorithm to insert a new element to the end of the array.

¨ Step 1: Set upper_bound = upper_bound+1


¨ Step 2: Set A[upper_bound] = VAL
¨ Step 3: EXIT

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Example:
96

Data[] is an array that is declared as int Data[20]; and contains the following values:

Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};

¨ a) Calculate the length of the array


¨ b) Find the upper bound and lower bound
¨ c) Show the memory representation of the array
¨ d) If a new data element with value 75 has to be inserted, find the position.
¨ e) Insert the new data element and then show the memory representation of the
array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Solution:
97

a) Length of the array = number of elements


Therefore, length of the array = 10
b) By default, lower_bound = 0 and upper_bound = 9
c) 12 23 34 45 56 67 78 89 90 100
Data[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]
d) Since the elements of the array are stored in ascending order, the new data element
will be stored after 67, i.e., at the 6th location. So, all the array elements from the 6th
position will be moved one location towards the right to accommodate the new value.
e) 12 23 34 45 56 67 75 78 89 90 100
Data[0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10]

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Algorithm to Insert an Element in
the Middle of an Array
98

The algorithm INSERT will be 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 at which the element has to be inserted and
d) VAL, the value that has to be inserted.

In the algorithm given below, we first initialize I with the total number of elements in
the array.
¨ 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]
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
99

Step 4: SET N=N+1


Step 5: SET A[POS]=VAL
Step 6: EXIT

¨ In Step2, a while loop is executed which will move all the elements that have
greater than POS one position towards right to create space for the new element.

¨ In step4, we increment the total number of elements in the array by 1and finally in
step5, the new value is inserted at the desired position.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to insert a number
at a given location in an array
100

#include<stdio.h>

int main() {
int i, n, num,pos,arr[10];
printf("\n Enter the number of elements in the array:");
scanf("%d",&n);
printf("\n Enter the values:");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\n Enter the number to be inserted:");
scanf("%d",&num);
printf("\n Enter the position at which the number has to be added:");
scanf("%d",&pos);
for(i=n-1;i>=pos;i--)
arr[i+1]=arr[i];
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
101

arr[pos]=num;
n++;
printf("\n The array after insertion of %d is:",num);
for(i=0;i<n;i++)
printf("\t %d",arr[i]);
return 0;
}

Output:
Enter the number of elements in the array: 5
Enter the values: 1 2 3 4 5
Enter the number to be inserted: 7
Enter the position at which the number has to be added: 3
The array after insertion of 7 is: 1 2 3 7 4 5

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.5.3 Deleting an Element from an
Array
102

¨ Deleting an element from the array means removing a data element from an
already existing array. If the element has to be deleted from the end of the existing
array, then the task of deletion is quite simple. We just have to subtract 1 from the
upper_bound.

¨ Step 1: SET upper_bound = upper_bound – 1


¨ Step 2: EXIT

Example:
Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};
¨ a) If a data element with value 56 has to be deleted, find its position.
¨ b) Delete the data element and give the memory representation of the array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


103

Solution:

¨ a) Since the element of the array are stored in ascending order, we will compare the
value that has to be deleted with the value of every element in the array. As soon as
VAL = Data[I], where I is the index or subscript of the array, we will get the
position from which the element has to be deleted.

¨ Example: If we see this array, here VAL = 56. data[0] = 12 which is not equal to
56. Like this, we will compare and finally get the value of POS = 4.

¨ b) 12 23 34 45 67 78 89 90 100
¨ Data[0] [1] 2] [3] [4] [5] [6] [7] [8]

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Algorithm to Delete an Element from
the Middle of an Array
104

¨ The algorithm DELETE will be 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 at which the element has to be deleted.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


105

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to delete a number
from a given location in an array.
106

#include <stdio.h>
int main() {
int i, n,pos,arr[10];
printf("\n Enter the size of the array:");
scanf("%d",&n);
printf("\n Enter the elements of the array:");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
printf("\n Enter the position from which the number has to be deleted:");
scanf("%d", &pos);
for(i=pos;i<n-1;i++)
arr[i]=arr[i+1];
n--;
printf("\n The array after deletion is:");
for(i=0;i<n;i++)
printf("\n Arr[%d]=%d",i,arr[i]);
return 0;
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
107

Output:
¨ Enter the size of the array:5
¨ Enter the elements of the array:1 2 3 4 5
¨ Enter the position from which the number has to be deleted:3
¨ The array after deletion is:

¨ Arr[0]=1
¨ Arr[1]=2
¨ Arr[2]=3
¨ Arr[3]=5

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.5.4 Merging Two Arrays
108

¨ Merging two arrays in a third array means first copying the contents of the first
array into the third array and then copying the contents of the second array into the
third array. Hence, the merged array contains contents of the first array followed by
the contents of the second array.

¨ If the arrays are unsorted then merging the arrays is very simple as one just needs
to copy the contents of one array into another. But merging is not a trivial task
when the two arrays are sorted and the merged array also needs to be sorted.

¨ Array 1 90 56 89 77 69

¨ Array 2 45 88 76 99 12 58 81

¨ Array 3 90 56 89 77 69 45 88 76 99 12 58 81
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
Write a program to merge two
unsorted arrays.
109

#include <stdio.h>

int main() {
int arr1[10], arr2[10],arr3[20];
int i, n1, n2, m, index=0;
printf("\n Enter the number of elements in array1:");
scanf("%d", &n1);
printf("\n Enter the elements of the first array");
for(i=0;i<n1;i++)
scanf("%d", &arr1[i]);
printf("\n Enter the number of elements in array2:");
scanf("%d", &n2);
printf("\n Enter the elements of the second array");
for(i=0;i<n2;i++)
scanf("%d", &arr2[i]);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


110

m=n1+n2;
for(i=0;i<n1;i++)
{
arr3[index] = arr1[i];
index++;
}
for(i=0;i<n2;i++)
{
arr3[index]=arr2[i];
index++;
}
printf("\n The merged array is");
for(i=0;i<m;i++)
printf("\t Arr[%d]=%d", i, arr3[i]);
return 0;

}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
111

Output:
¨ Enter the number of elements in array1:3
¨ Enter the elements of the first array
¨ 10 20 30
¨ Enter the number of elements in array2:3
¨ Enter the elements of the second array
¨ 15 25 35

¨ The merged array is:


Arr[0]=10 Arr[1]=20 Arr[2]=30 Arr[3]=15 Arr[4]=25 Arr[5]=35

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.5.5 Searching for a value in an
Array
112

¨ Searching means to find whether a particular value is present in the array or not. If
the value is present in the array then search is said to be successful and the search
process gives the location of that value in the array. Otherwise, if the value is not
present in the array, the search process displays the appropriate message and in this
case search is said to be unsuccessful.

¨ Linear Search: Is also called sequential search. Is a very simple method used for
searching an array for a particular value. It works by comparing every element of
the array one by one in sequence until a match is found. Linear search is mostly
used to search an unordered list of elements.

¨ Example:
¨ int A[] = { 10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
¨ The value to searched is VAL = 7, then searching means to find whether the value
7 is present in the array or not. If yes, then search is successful and it returns the
position of occurrence of VAL.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
113

¨ The best case of linear search is when


VAL is equal to the first element of the
array. In this case only one comparison
will be made.

¨ Likewise, the worst case will happen


when either VAL is not present in the
array or it is equal to the last element of
the array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


114

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to implement
linear search.
115

#include <stdio.h>

int main() {
int arr[10], num, i, n, found=0, pos=-1;
printf("\n Enter the number of elements in the array:");
scanf("%d", &n);
printf("\n Enter the elements:");
for(i=0;i<n;i++)
scanf("%d", &arr[i]);
printf("\n Enter the number that has to be searched:");
scanf("%d", &num);

for(i=0;i<n;i++)
{
if(arr[i] == num)
{

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


116

found=1;
pos=i;
printf("\n %d is found in the array at position = %d", num, i);
break;
}

}
if(found==0)
printf("\n %d does not exist in the array", num);
return 0; }

Output:
Enter the number of elements in the array:5
Enter the elements:1 2 3 4 5
Enter the number that has to be searched:7
7 does not exist in the array
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
Binary search
117

¨ Binary search algorithm works efficiently with a sorted list. The algorithm finds
the position of a particular element in the array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


118

#include<stdio.h>
int main()

{
int a[10],i,n,low,high,mid,key,flag=0;

printf("enter the number of elements\n");


scanf("%d",&n);

printf("enter array elements\n");


for(i=0;i<n;i++)
scanf("%d",&a[i]);

printf("enter the key element to be searched\n");


scanf("%d",&key);

low=0;
high=n-1; Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
119

while(low<=high)
{
mid = (low+high)/2;

if(key==a[mid])
{
flag=1;
break;
}

else if(key<a[mid])
high=mid-1;

else
low= mid+1;
}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
120

if(flag)
printf("element found %d position",mid+1);

else
printf("element not found \n");
return 0;

Output: Enter the number of elements: 5


Enter array elements
10 24 43 57 89
Enter the key element to be searched
57
Element found 4 position

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.6 Passing Arrays to Functions
121

¨ Like variables of other data types, we can also pass an array to a function. While in
some situations, you may want to pass individual elements of the array, and in
other situations you may want to pass the entire array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Passing individual elements
122

¨ The individual elements of an array can be passed to a function by passing either


their data values or their addresses.

Passing Data Values: The individual elements can be passed in the same manner as
we pass variables of any other data type. The condition is just that the data type of the
array element must match with the type of the function parameter.
main()
{
In the example, only one element of
int arr[5] = { 1, 2, 3, 4, 5}; the array is passed to the called
func(arr[3]); function. This is done by using the
index expression.
}
void func(int arr[3])
{
printf(“%d”, arr[3]);
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
}
Passing Address
123

¨ 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].

¨ In the called function the value of the array element must be accessed using the
indirection (*) operator.
main()
{
int arr[5] = { 1, 2, 3, 4, 5};
func(*arr[3]);
}
void func(int *num)
{ printf(“%d”, *num);
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
Passing the Entire Array
124

¨ When we need to pass an entire array to a function, we can simply pass the name
of the array.

¨ In case where we do not want the called function to make any changes to the array,
the array must be received as a constant array by the called function. This prevents
any type of unintentional modifications of the array elements.

¨ To declare the array as a constant array, simply add the keyword const before the
data type of the array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to read and print
an array of n numbers.
125

#include <stdio.h>
void read_array(int arr[], int);
void display_array(int arr[], int);

int main()
{
int num[10], n;
printf("\n Enter the size of the array:");
scanf("%d",&n);
read_array(num, n);
display_array(num, n);
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


126

void read_array(int arr[10], int n)


{
int i; Output:
printf("\n Enter the elements of the array:"); Enter the size of the array:5
for(i=0;i<n;i++)
{ Enter the elements of the array:
scanf("%d",&arr[i]); 12345
}
} The elements of the array are:
1 2 3 4 5
void display_array(int arr[10], int n)
{
printf("\n The elements of the array are:");
for(int i=0;i<n;i++)
printf("\t %d", arr[i]);

}
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
Two Dimensional Arrays
127

¨ A two dimensional array is specified using two subscripts where one subscript
denotes row and other denotes column.

First
Dimension

Second Dimension

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.7.1 Declaring Two-Dimensional
Arrays
128

Synatx:

data_type array_name[row_size][column_size];
Therefore, a two-dimensional m * n array is an array that contains m * n data elements
and each element is accessed using two subscripts , i and j where i<=m and j<=n.

Example: If we want to store the marks obtained by 3cstudents in 5 different subjects,


then we can declare a two-dimensional array as:

int marks[3][5];
A two-dimensional array called marks is declared that has m(3) rows and n(5)
columns.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


129

The pictorial form of a two-dimensional array is given as below.

We see that a 2D array is treated as a collection of 1D arrays. Representation is shown


below:

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


130

¨ The above picture shows a rectangular picture of a two-dimensional array, these


elements will be actually stored sequentially in memory. Since computer memory
is basically one-dimensional, a multidimensional array cannot be stored in memory
as a grid.
¨ There are two ways of storing a two-dimensional array in memory.

¨ i) Row major order: The elements of the first row are stored before the elements of
the second and third row.

¨ ii) Column major order: The elements of the first column are stored before the
elements of the second and third column.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12. 7.2 Initializing Two-dimensional
Arrays
131

¨ Declaring a two dimensional array only reserves space for the array in the memory.
No values are stored in it. A two dimensional array I initialized in the same way as
a one-dimensional array.

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

¨ The initialization of a two dimensional array is done row by row. The above
statement can also be written as:

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

¨ The given two-dimensional array has 2 rows and 3 columns. The elements in the
first row are initialized first and then the elements of the second row are initialized.
¨ marks[0][0] = 90 marks[0][1] = 87 marks[0][2] = 78
¨ marks[1][0] = 68 marks[1][1] = 62 marks[1][2] = 71
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
132

¨ In case of one-dimensional arrays, if the arrays is completely initialized, we may


omit the size of the array. Same concept can be applied to a two-dimensional array,
except that only the size of the first dimension can be omitted. Therefore, the
declaration statement given below is valid.

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

¨ In order to initialize the entire two-dimensional array to zero, simply specify the
first value as zero.

int marks[2][3] = {0};


¨ If some values are missing in the initialization then it is automatically set to zero.
For example, the statement given below will initialize the values in the first row
but the elements of the second row will be initialized to zero.
int marks [2][3] = { { 50, 60, 70} };
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
133

¨ Individual elements of a two-dimensional array can be initialized using the


assignment operator as shown below.

marks[1][2] = 79;
marks[1][2] = marks[1][1] + 10;

In order to input the values from the keyboard, use the below code:

for(i=0;i<2;i++)
for(j=0;j<2;j++)
scanf(“%d”, &arr[i][j]);

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.7.3 Accessing the Elements of
Two-dimensional Array
134

¨ The elements of a 2D array are stored in contiguous memory locations. While


accessing the elements, remember that the last subscript varies most rapidly
whereas the first varies least rapidly.

¨ Since the two-dimensional array contains two subscripts, we will use two for loops
to scan the elements. The first for loop will scan each row in the 2D array and the
second for loop will scan individual columns for every row in the array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to print the
elements of a 2D array.
135

#include <stdio.h>

int main()
{
int arr[2][2] = {12, 34, 56, 32}; Output:
int i, j; 12 34
for(i=0;i<2;i++)
{ 56 32
printf("\n");
for(j=0;j<2;j++)
printf("%d\t", arr[i][j]);
}
return 0;
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Implement matrix multiplication and
validate the rules of multiplication
136

#include <stdio.h>
#include<stdlib.h>

int main()
{
int m, n, p, q, i, j, k ;
int a[10][10], b[10][10], c[10][10];

printf("Enter number of rows and columns of first matrix\n");


scanf("%d%d", &m, &n);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &p, &q);

if(n!=p)
{
printf("multiplication not possible\n");
exit(0);
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
137

printf("Enter elements of first matrix\n");


for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
scanf("%d", &a[I][j]);

printf("Enter elements of second matrix\n");


for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
scanf("%d", &b[i][j]);

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


{
for (j = 0; j < q; j++)
{
c[i][j] =0;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


138

for (k = 0; k < p; k++)


c[i][j] = c[i][j] + a[i][k]*b[k][j];
}
}

printf("Product of the matrices is:\n");

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


{
for (j = 0;j < q; j++)
printf("%d\t", c[i][j]);
printf("\n");
}

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


139

Output:
¨ Enter number of rows and columns of first matrix 2 3
¨ Enter number of rows and columns of second matrix 3 2
¨ Enter elements of first matrix
123
456
¨ Enter elements of second matrix
12
34
56
¨ Product of the matrices is:
22 28
49 64
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
12.8 Operations on Two-Dimensional
Arrays
140

¨ Two-dimensional arrays can be used to implement the mathematical concept of


matrices. In mathematics, a matrix is a grid of numbers, arranged in rows and
columns. Thus using 2D arrays, we can perform the following operations on an
m * n matrix.

¨ Transpose: Transpose of a m * n matrix A is given as a n * m matrix B where:


Bi,j = Aj,i

¨ Sum: Two matrices that are compatible with each other can be added together
thereby storing the result in the third matrix. Two matrices are said to be
compatible when they have the same number of rows and columns.

Ci,j = Ai,j + Bi,j

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


141

¨ Differences: Two matrices that are compatible with each other can be subtracted
thereby storing the result in the third matrix.

Ci,j = Ai,j - Bi,j


¨ Product: Two matrices can be multiplied with each other if the number of column
in the first matrix is equal to the number of rows in the second matrix.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


12.9 Passing Two-dimensional Arrays
to Functions
142

¨ There are three ways of passing two-dimensional arrays to functions:

i) We can pass individual elements of the array.

ii) We pass a single row of the two-dimensional array.

iii) We can pass the entire two-dimensional array to the function.

12.9.1 Passing a Row

¨ A row of a two-dimensional array can be passed by indexing the array name with
the row number. When we send a single row of a two-dimensional array, then the
called function receives a one-dimensional array.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


143

main()
{
int arr[2][3] = { { 1, 2, 3 }, { 4, 5, 6 } };
func(arr[1]);
}
void func(int arr[])
{
int i;
for(i=0;i<3;i++)
printf(“%d”, arr[i] * 10);
}

12.9.2 Passing an Entire 2D Array


¨ To pass a two-dimensional array to a function, we use the array name as the actual
parameter. However, the parameter in the called function must indicate that the
array has two dimensions.
Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
12.10 Multidimensional Arrays
144

¨ A multidimensional array in simple terms is an array of arrays. Like we have one


index in a one-dimensional array, two indices in a two-dimensional array, in the
same way we have n indices in an n-dimensional array or multidimensional array.

¨ Conversely, an n-dimensional array is specified using n indices. An n-dimensional


m1*m2*m3* …. mn array is a collection of m1 * m2 * m3 * …. * mn elements. In a
multidimensional array, a particular elements is specified by using n subscripts as
a[I1][I2][I3]…[In], where,

¨ I1 <=M1 I2 <=M2 I3 <=M3 ………… In <= Mn

¨ Multidimensional array can contain as many indices as needed and the requirement
of the memory increases with the number of indices used. However, practically
speaking we will hardly use more than three indices in any program.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


145

¨ The below diagram shows the three-dimensional array. The array has three pages,
four rows, and two columns.
¨ A multidimensional array is declared and initialized similar to one-and two-
dimensional arrays.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Write a program to read and display a
2 * 2 * 2 array
146

#include <stdio.h>
int main()
{
int array[2][2][2], i, j, k;
printf("\n Enter the elements of the matrix");
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for(k=0;k<2;k++)
{
scanf("%d",&array[i][j][k]);
}
}
}
printf("\n The matrix is:");

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


147

for(i=0;i<2;i++)
{
printf("\n\n");
for(j=0;j<2;j++)
{
printf("\n");
for(k=0;k<2;k++)
printf("\t arr[%d][%d][%d] = %d", i, j, k, array[i][j][k]);
}
}
return 0;

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


148

Output:
Enter the elements of the matrix

12345678

The matrix is:


arr[0][0][0] = 1 arr[0][0][1] = 2
arr[0][1][0] = 3 arr[0][1][1] = 4
arr[1][0][0] = 5 arr[1][0][1] = 6
arr[1][1][0] = 7 arr[1][1][1] = 8

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


Applications of Arrays
149

¨ Arrays are widely used to implement mathematical vectors, matrices, and other
kind of rectangular tables.

¨ Many databases includes one-dimensional arrays whose elements are recorded.

¨ Arrays are also used to implement other data structures such as strings, stacks,
queues, heaps, and hash tables.

¨ Arrays can be used for sorting elements in ascending or descending order.

Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24


150 Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24

You might also like