PRINCIPLES OF PROGRAMMING USING C
– 22POPS23
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING
ARRAYS AND FUNCTIONS
UNIT-3
CONTENTS
Arrays Functions
• A brief overview
• Defining an array
• Defining a function
• Processing an array
• Accessing a function
• Multidimensional arrays
• Function prototypes
• Bubble sort
• Passing arguments to a function
• Binary search • Call by value passing array to function
• Recursion
ARRAYS
• An array is a collection of elements of the same data type stored in
contiguous memory locations.
• Arrays allow you to store multiple values under a single variable name,
making it easier to manage and access data.
• It can be used to store the collection of elements of primitive data types
such as int, char, float, etc., and also derived and user-defined data types
such as pointers, structures, etc.
ARRAYS
ARRAY DECLARATION
• An array should be declared like any other variable before using it. It can be declared by specifying
its name, the type of its elements, and the size of its dimensions.
• When an array is declared, the compiler allocates the memory block of the specified size to the array
name.
Syntax : data_type array_name[size];
Example: int a[5];
• data_type: This is the data type of the elements that the array will hold. It could be int, float, char, or
any other valid C data type.
• array_name: This is the name given to array variable.
• size: This is the number of elements the array will be able to hold. It should be a positive integer value.
ARRAY DECLARATION
ARRAY DECLARATION
• The C arrays are static in nature, i.e., memory is allocated to them during
compile time.
Example of array declaration:
#include <stdio.h>
int main()
{
int array[5]; //declaring array of integers
char array[5]; //declaring array of characters
return 0;
}
ARRAY INITIALIZATION
• An array can also be initialized along with its declaration.
• An initializer list is used to initialize multiple elements of the array.
• An initializer list is the list of values enclosed within braces { } separated by a
comma.
Syntax : data_type array_name[size] = {value1, value 2, …., value n}
Where ‘n’ represents number of elements
Example: int a[5]= {2, 4, 8, 12,16} size(n)=5
ARRAY INITIALIZATION
ACCESSING ARRAY ELEMENT
• Any element of an array can
be accessed using the array
subscript operator [ ] and the
index value i of the element as,
array_name [index];
• It is important to note that the
indexing in the array always
starts with 0, i.e., the first
element is at index 0 and
the last element is at N –
1 where N is the number of
elements in the array.
ACCESSING ARRAY ELEMENT
Output:
Example of illustrate accessing array element:
Element at 3rd position is: 30
#include <stdio.h>
Element at 4th position is: 40
int main()
Element at 1st position is: 10
{
int a[5] = {10, 20, 30, 40, 50}; //array declaration and initialization
printf(“Element at 3rd position is: %d\n”, a[2]); //accessing element at index 2 i.e., 3rd element
printf(“Element at 4th position is: %d\n”, a[3]); //accessing element at index 3 i.e., 4th element
printf(“Element at 1st position is: %d\n”, a[0]); //accessing element at index 2 i.e., 1st element
return 0;
}
UPDATE ARRAY ELEMENT
• An array element’s value at the given index i can be updated to a new value by using the array
subscript operator [ ] and assignment operator =.
Syntax : data_type array_name[i] = new_value;
Example to illustrate updation of an array element:
#include <stdio.h>
int main()
{
int a[5] = {10, 20, 30, 40, 50}; //array declaration and initialization
a[2]=200; //updating/modifying element at index 2
printf(“Element at 3rd position is: %d\n”, a[2]); //accessing element at index 2
Output:
i.e., 3rd element
return 0;
Element at 3rd position is: 200
}
ARRAY TRAVERSAL
• Array traversal is the process in which
every element of the array is visited
• Traversal is carried out using loops to
iterate through each element of the
array as,
for (int i = 0; i < N; i++)
{
array_name[i];
}
ARRAY TRAVERSAL
Example to demonstrate the traversal of array:
#include <stdio.h>
int main()
{
int a[5] = {10, 20, 30, 40, 50}; //array declaration and initialization
a[2]=200; //updating/modifying element at index 2
printf(“The elements in the array are:\n”);
for(i=0;i<5;i++) //traversing array elements using loop Output:
printf(“%d”, a[i]); Elements in the array are :
return 0; 10, 20, 200, 40, 50
}
LINEAR SEARCH
A Linear Search also known as sequential search, is a process for
finding a particular element from the list of elements.
This searching algorithm checks each and every element of the array
list one by one until a particular match is found.
Each element in the array is compared with the key/search element
(the one we are looking for) until it is found or until all the elements
in the array are traversed and searched.
WORKING OF LINEAR SEARCH ALGORITHM
The algorithm starts the search by comparing the key(search) element
with the first element of the array.
If the first element does not match with the key element, it moves to the
next element to compare, and so on until the match is discovered or till
the array ends.
If a match is discovered, then the index is returned; otherwise, it reaches
the end of the array, indicating that the key element is not available in
the array list.
Example: Consider the array, arr[ ] = {10, 50, 30, 70, 80, 20, 90, 40} and key = 30
LINEAR SEARCH LOGIC /ALGORITHM
for (i = 0; i < n; i++)
{
if (key == arr[i] )
{
flag= 1;
break;
}
} Note: For implementation, to use for
if (flag== 1) loop to traverse all the elements of the
printf(“Element found at index %d",i+1);
array.
else
printf(“Element not found\n"); for (i = 0; i < n ; i++)
}
Linear Search Program in C
#include <stdio.h>
printf("\n Enter the key element to be searched: ");
void main()
scanf("%d", &key);
{
/* Linear search starts */
int n; for (i = 0; i < n ; i++)
{
int i, key, flag= 0;
if (key == arr[i] )
printf("Enter the number of elements: "); {
flag= 1;
scanf("%d", &n);
break;
int arr[n]; }
}
printf("\n Enter the elements :");
if (flag== 1)
for (i = 0; i < n; i++) printf(“Element found at index %d",i); or
printf(“Element found at position %d”, i+1);
{
else
scanf("%d", &arr[i]); printf(“Element not found\n");
}
}
ADVANTAGES AND DISADVANTAGES OF LINEAR SEARCH
Advantages of Linear Search Algorithm:
• Linear search can be used irrespective of whether the array is sorted or not. It can be used
on arrays of any data type.
• Does not require any additional memory.
• It is a well-suited algorithm for small datasets.
Disadvantages of Linear Search Algorithm:
• Linear search has a time consuming which in turn makes it slow for large datasets.
• Not suitable for large arrays.
TYPES OF ARRAY
There are two types of arrays based on the number of dimensions it has, namely
[Link] Dimensional Arrays (1D Array)
[Link] Arrays - Two dimensional (2D Array), Three dimensional (3D Array)
One dimensional Array
The One-dimensional arrays are those
arrays that have only one dimension. They
are known as 1-D arrays
Syntax of 1D array
array_name[size];
ONE DIMENSIONAL ARRAY (1D ARRAY)
Example: Program to illustrate the use of 1D array
#include <stdio.h>
int main()
{
int a[5] = {10, 20, 30, 40, 50}; //array declaration and initialization
for(int i=0;i<5;i++) //1D array initialization using for loop
{
a[i]= i * i – 2 * i +1;
}
printf(“Elements of the array are:\n”); //printing 1D array by traversing using for loop
for(int i=0;i<5;i++)
printf(“%d”, a[i]); Output:
return 0;
Elements of the array are :
}
1 0 1 4 9
TWO DIMENSIONAL ARRAY (2D ARRAY)
Multi-dimensional Arrays are those arrays that have more than one dimension. Some of the
popular multidimensional arrays are 2D arrays and 3D arrays.
Two dimensional Array
A Two-Dimensional array or 2D array an array
that has exactly two dimensions. They can be
visualized in the form of rows and columns
organized in a two-dimensional plane.
Syntax of 2D array
array_name[size 1] [size 2];
[size 1]- size of the first dimension (rows)
[size 2]- size of the second dimension (columns)
TWO DIMENSIONAL ARRAY (2D ARRAY)
Example: Program to illustrate the use of 2D array Output:
#include <stdio.h>
int main()
2D Array
{ 10 20 30
int a[2] [3] = {10, 20, 30, 40, 50, 60}; //declaring and initializing 2D array 40 50 60
printf(“2D array:\n”); //printing 2D array
for(int i=0;i<2;i++)
{
for(int j=0;j<3;j++)
{
printf(“%d”, a[i][j]);
}
printf(“\n”)
return 0;
}
THREE DIMENSIONAL ARRAY (3D ARRAY)
Three dimensional Array
A 3D array has exactly three dimensions. It can be visualized as a
collection of 2D arrays stacked on top of each other to create the
third dimension.
Syntax of 3D array
array_name[size 1] [size 2] [size 3];
[size 1]- size of the first dimension (No. of 2D blocks/2D pages)
[size 2]- size of the second dimension (No. of rows in each 2D
block)
[size 3]- size of the third dimension (No. of columns in each 2D
block)
THREE-DIMENSIONAL ARRAY (3D ARRAY)
Example: Program to illustrate the use of 3D array
#include <stdio.h>
int main()
{
int a[2] [2][2] = { {10, 20}, {30, 40}, {50, 60} }; //declaring and initializing 3D array
Output:
printf(“3D array:\n”); //printing 3D array 3D Array
for(int i=0;i<2;i++) {
for(int j=0;j<2;j++) { 10 20
for(int k=0;k<2;k++) { 30 40
printf(“%d”, a[i][j][k]);
}
printf(“\n”)
} 50 60
printf(“\n”) 0 0
}
return 0;
}
THREE DIMENSIONAL ARRAY (3D ARRAY)
a[k] = a[2] => k=2(0,1)
k=0 k=1
BUBBLE SORT
Bubble sort is a basic algorithm for arranging a string of numbers or
other elements in the correct order.
The method works by examining each set of adjacent elements in the
string, from left to right, switching their positions if they are not in the
desired (required) order.
Eg.: Assume an array
Assume that these elements to be arranged in ascending order.
BUBBLE SORT
How does bubble sort works?
[Link] at the beginning of the list.
[Link] the first value in the list with the next one up. If the first value is bigger, swap the
positions of the two values.
[Link] to the second value in the list. Again, compare this value with the next and swap if
the value is bigger.
[Link] going until there are no more items to compare.
[Link] back to the start of the list.
Each run through the list, from start to finish, is known as a pass. The bubble sort continues
until a pass is made where no values have been swapped. At this point, the list is sorted.
BUBBLE SORT
The example array contains five elements.
That means four comparisons (passes) are required to bubble up the most significant
(greatest) element to the top of the array.
Why there are four comparisons?
• N = The number of elements in an array
• N-1 = The number of time comparisons that occur
Therefore: 5 - 1 = 4
BUBBLE SORT
First Pass
BUBBLE SORT
Second Pass
BUBBLE SORT
Third Pass
Fourth Pass
BUBBLE SORT ALGORITHM AND WORKING CODE
BINARY SEARCH
• Binary Search is a searching algorithm used to search/ find an
element's position in a sorted array.
• In this approach, the element is always searched in the middle of a
portion of an array.
• Note: Binary search can be implemented only on a sorted list of items.
If the elements are not sorted already, we need to sort them first.
• Eg.: Assume a sorted array
BINARY SEARCH
The general steps to perform binary search:
1. Consider the array
Assume an element to be searched in the given array, say x=4
2. Set two pointers low and high at the lowest and the highest positions respectively
BINARY SEARCH
3. Find the middle element mid of the array i.e. mid=[(low + high)/2] = 6
[Link] x == mid, then return mid. Else, compare the element to
be searched with mid
5. If x > mid, compare x with the middle element of the
elements on the right side of mid. This is done by
setting low to low = mid + 1.
6. Else, i.e, x < mid, compare x with the middle element of the
elements on the left side of mid. This is done by
setting high to high = mid - 1.
BINARY SEARCH
7. Repeat steps 3 to 6 until low meets high
8. x=4 is found
BUBBLE SORT ALGORITHM AND WORKING CODE
FUNCTIONS
UNIT-3
FUNCTIONS
A function is a set of statements that performs some specific actions
only when it is invoked/called .
In simple words, a function is a block of code which will be executed
only when it is called.
The programming statements of a function are enclosed within { }
braces.
FUNCTION DECLARATION
A function declaration tells the compiler that there is a function with the given
name defined somewhere in the program.
It contains the function name, its return type and number of parameters with their
return types. The parameter list is optional, that is, a function may or may not
contain parameters.
The actual body of the function can be defined separately.
Syntax:
• return_type function_name(parameter list);
FUNCTION DECLARATION
Example:
int function(); //function without parameters
int sum(int a, int b); //function with parameters
Figure: Function Declaration
DEFINING A FUNCTION
The general form of a function definition in C programming language is as follows –
return_type function_name(parameter list)
{
//body of the function
}
The parts of a function are discussed below:
Return Type − A function may return a value. The return_type is the data type of the
value that the function returns. Some functions perform the desired operations without
returning a value. Such cases, the return_type is void.
DEFINING A FUNCTION
Function Name − This is the actual name of the function.
Parameters/Arguments − A parameter is like a placeholder. When a function is
invoked(called), a value is passed to the parameter. This value is referred to as
argument. The parameter list is optional, that is, a function may or may not
contain parameters.
Function Body − The function body contains the actual statements that are
executed when the function is called.
CALLING/ACCESSING A FUNCTION
Declared functions are not executed immediately. They will be
executed upon a function call (when they are called).
A function call is a statement that instructs the compiler to execute
the function.
To call a function, write the function's name followed by two
parentheses ( ) and a semicolon ;
CALLING/ACCESSING A FUNCTION
Example: To create a function and call that function inside main
//create a function
In the code myFunction() is a
void myFunction()
function that is used to print a text
{
(the action), when it is called.
printf(“Welcome to C Programming course”);
}
int main()
{
Output:
myFunction(); //call the function
Welcome to C programming
return 0;
course
}
CALLING/ACCESSING A FUNCTION
CALLING/ACCESSING A FUNCTION
Example: A function can also be called multiple times
void myFunction()
{
printf("Function is executed!");
}
Output:
int main() Function is executed!
Function is executed!
{ Function is executed!
myFunction();
myFunction();
myFunction();
return 0;
}
FUNCTION PROTOTYPE
A function prototype is used to declare the signature of a function, which includes its name,
return type, and parameters.
Function prototypes are important because they inform the compiler about function'
before it is called, allowing for proper type checking and error handling.
Syntax of function prototype:
return_type function_name(parameter_list);
The return_type is the data type that the function returns, such as int, float, or char.
The function_name is the name of the function, and
The parameter_list is a comma-separated list of parameters that the function takes. Each
parameter in the parameter_list consists of a data type followed by the parameter name.
FUNCTION PROTOTYPE
Example: The following is a function prototype for a function that takes
two integers as arguments and returns their sum
int add(int num1, int num2);
In this example, the return type is int, the function name is add, and the
parameter list consists of two integers named num1 and num2.
FUNCTION PROTOTYPE
Uses of Function prototype
They allow the compiler to check for errors before the program is actually
executed.
If a function is called with the wrong number or type of arguments, the compiler
will generate an error message, preventing the program from crashing or
behaving unexpectedly at runtime.
Function prototypes also make it easier to read and understand the code.
FUNCTION DECLARATION VERSUS FUNCTION PROTOTYPE
Function Declaration Function Prototype
The function prototype tells the compiler
Function Declaration is used to tell the
about the existence and signature of the
existence of a function.
function.
A function prototype is a function declaration
A function declaration is valid even with only that provides the function’s name, return type,
function name and return type. and parameter list without including the
function body.
Typically used in header files to declare Used to declare functions before their actual
functions. definitions.
Syntax: Syntax:
return_type function_name(); return_type function_name(parameter_list);
PASSING ARGUMENTS TO A FUNCTION
The data passed when the function is being
called/invoked is known as the actual
parameters or arguments. The variable and
the data type as mentioned in the function
declaration are referred to as formal
Parameters or arguments.
Example: In the below program, a and b are
known as formal parameters and the values
10 and 30 are actual parameters.
PASSING ARGUMENTS TO A FUNCTION
Arguments can be passed to the C function in two ways:
1. Pass by value/Call by Value
• This method copies the actual value of an argument into the formal argument of the function. In
this case, changes made to the parameter inside the function have no effect on the argument.
2. Pass by Reference/Call by Reference
• This method copies the address of an argument into the formal argument. Inside the function,
the address is used to access the actual argument used in the call. This means that changes
made to the parameter affect the argument.
PASSING ARGUMENTS TO A FUNCTION
Example: C program to swap two numbers using call by value/pass by value
#include <stdio.h>
void swap(int var1, int var2) Output:
{ Before swapping value of var1 and var2 is: 3, 2
int temp = var1; After swapping value of var1 and var2 is: 2, 3
var1 = var2;
var2 = temp;
}
int main()
{
int var1 = 3, var2 = 2;
printf("Before swapping var1 and var2 is: %d, %d\n",
var1, var2);
swap(var1, var2);
printf("After swapping var1 and var2 is: %d, %d",
var1, var2);
return 0;
}
PASSING ARGUMENTS TO A FUNCTION
Example: C program to swap two numbers using call by reference
#include <stdio.h>
void swap(int *var1, int *var2)
{
Output:
int temp = *var1; Before swapping value of var1 and var2 is:
*var1 = *var2; 3, 2
*var2 = temp; After swapping value of var1 and var2 is: 2,
} 3
int main()
{
int var1 = 3, var2 = 2;
printf("Before swapping value of var1 and var2 is: %d, %d\n",
var1, var2);
swap(&var1, &var2);
printf("After swapping value of var1 and var2 is: %d, %d",
var1, var2);
return 0;
}
PASSING ARRAY TO A FUNCTION
In C programming, an entire array can be passed to functions. To understand this,
initially need to understand how to pass individual elements of an array to
functions.
1. Pass individual array elements to functions
Passing array elements to a function is similar to passing variables to a function.
PASSING ARRAY TO A FUNCTION
Example 1: Pass individual array elements
Output:
8
4
PASSING ARRAY TO A FUNCTION
2. Passing array to a function (one dimensional array)
• To pass an entire array to a function, only the name of the array is passed as an
argument.
3. Pass arrays to a function (multidimensional arrays)
• To pass multidimensional arrays to a function, only the name of the array is passed
to the function (similar to one-dimensional arrays).
Example 2: To pass one dimensional array
Output:
Result = 162.50
Here, only the name of the array ‘num’ is passed
as an argument as
result = calculateSum(num);
It is very important to notice the use of [] in the
function definition.
This means that a one-dimensional array is
passed to the function.
Example 3: To pass two dimensional array
Output:
Enter 4 numbers: Displaying:
2 2
3 3
4 4
5 5
Notice the parameter int num[2][2] in the
function prototype and function definition:
This signifies that the function takes a two-
dimensional array as an argument.
RECURSION
• Recursion is the process of calling a function itself repeatedly until a particular
condition is met. A function that calls itself directly or indirectly is called a
recursive function and such kind of function calls are called recursive calls.
The basic syntax structure of the recursive functions is:
type function_name (args) {
// function statements
// base condition
// recursion case (recursive call)
}
RECURSION
Example: C Program to calculate the factorial of a number
#include <stdio.h>
int fact (int);
int main()
{
int n, f;
printf("Enter the number whose factorial you want to calculate? :");
scanf("%d",&n);
f = fact(n);
printf(“Factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1; Output:
}
else Enter the number whose factorial you want
{ to calculate ? : 5
return n*fact(n-1);
} Factorial= 120
}
RECURSION
Example: C Program to find the nth term of the Fibonacci series.
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
} Output:
else
{ Enter the value of n? : 5
return fibonacci(n-1)+fibonacci(n-2); 144
}
}
TYPES OF FUNCTION
There are two types of functions in C:
• Library functions also referred to as a built-in functions - have the
advantage of being directly usable without being defined.
• User defined functions - must be declared and defined before being
used.
TYPES OF FUNCTION
Library Functions
• A library function is a compiler package that already exists which contains these
functions, each of which has a specific meaning and is included in the package.
Advantages of C library functions
C Library functions are easy to use and optimized for better performance.
C library functions save a lot of time i.e, function development time.
C library functions are convenient as they always work.
TYPES OF FUNCTION
User Defined Functions
• Functions that the programmer creates are known as User-Defined functions or “tailor-
made functions”. User-defined functions can be improved and modified according to the
need of the programmer.
Advantages of User-Defined Functions
Changeable functions can be modified as per need.
The code of these functions is reusable in other programs.
These functions are easy to understand, debug and maintain.
ADVANTAGES OF FUNCTION
• The function can reduce the repetition of the same statements in the program.
• The function makes code readable by providing modularity to our program.
• There is no fixed number of calling functions it can be called as many times as you
want.
• The function reduces the size of the program.
• Once the function is declared you can just use it without thinking about the internal
working of the function.