Module-3
Module-3
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.
• 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.
• 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.
• A function f that uses another function g is known as the calling function and g is
known as 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 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,….);
• 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.
• When a function is defined, space is allocated for that function in the memory.
• Function header
• Function body
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.
#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;
}
// Function Definition
int sum (int a, int b)
{
int result;
result = a+b;
return result;
}
Output:
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>;
#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;
}
Output:
a is less than b
Some functions have a variable number of arguments and data types that cannot be
known at the compile time.
ANSI C offers a symbol called ellipsis to handle such functions. The ellipsis consists
of three periods (…). It can be used as;
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.
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.
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.
#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);
}
Output:
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.
#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;
}
Output:
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.
#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;
}
Output:
#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;
}
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.
#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++;
}
Output:
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.
#include<stdio.h>
int x = 10;
void print();
int main()
{
printf(" \n The value of x in the main() = %d", x);
int x = 2;
Output:
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.
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.
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.
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.
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.
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.
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.
#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.
#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.
// 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;
}
//FILE2.c
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.
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;
#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;
}
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
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.
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.
n! = n * (n-1)!
¨ 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!
#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
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.
The greatest common divisor (GCD) of two numbers (integers) is the largest integer
that divides both the numbers.
Euclid’s algorithm:
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
#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
¨ 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.
#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;
}
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
Recursion is a technique that breaks a problem into one or more sub-problems that are
similar to the original problem.
¨ Here, Func() calls itself for all positive values of n, so it is said to be a directly
recursive function.
¨ 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 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.
¨ 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.
¨ 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).
¨ The final step is to move the n-1 rings from B to C using A as the spare pole.
¨ 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:
¨ 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.,
¨ Size: The maximum number of values that the array can hold.
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];
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.
¨ 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.
¨ 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:
¨ Where the upper_bound is the index of the last element and lower_bound is the
index of the first element in the array.
¨ 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.
¨ 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.
¨ 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]);
¨ 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
¨ 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
¨ Traversing an array means accessing each and every element of the array for a
specific purpose.
¨ 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
#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;
}
#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
Output:
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};
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
¨ 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.
#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
¨ 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.
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.
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]
#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
¨ 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]);
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
¨ 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
#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)
{
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.
#include<stdio.h>
int main()
{
int a[10],i,n,low,high,mid,key,flag=0;
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;
¨ 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.
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.
#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
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
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.
int marks[3][5];
A two-dimensional array called marks is declared that has m(3) rows and n(5)
columns.
¨ 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.
¨ 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.
¨ The initialization of a two dimensional array is done row by row. The above
statement can also be written as:
¨ 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 order to initialize the entire two-dimensional array to zero, simply specify the
first value as zero.
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]);
¨ 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.
#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;
}
#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];
if(n!=p)
{
printf("multiplication not possible\n");
exit(0);
} Dr. Vikhyath K B, Dept of CSE, Dr. HNNCE, Bengaluru 18/12/24
137
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
¨ 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.
¨ Differences: Two matrices that are compatible with each other can be subtracted
thereby storing the result in the third matrix.
¨ 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.
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);
}
¨ 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.
¨ 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.
#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:");
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;
Output:
Enter the elements of the matrix
12345678
¨ Arrays are widely used to implement mathematical vectors, matrices, and other
kind of rectangular tables.
¨ Arrays are also used to implement other data structures such as strings, stacks,
queues, heaps, and hash tables.