POP Module 3
POP Module 3
MODULE 3
FUNCTIONS
✔ “Function is a small program or program segment that carryout some specific well-defined
tasks”.
Advantages of Functions/Why are function Needed?
i. Reduces the Complexity.
✔ When a program contains more number of instructions (complex program), then such large program
can be divided into number of sub programs called as functions.
ii. Improves the Readability.
iii. Easy to debug the errors.
iv. Reusability: The set of instructions specifying the task performed by the function is written just once but
it can be used any number of times.
v. Easy to do the modifications.
Function Prototype/Declaration
✔ As we normally declare the variables before they are used, the functions also should be declared
before they are used.
BIET, DVG 1
Principles of Programming using C BCSESC103/203
✔ The process of declaring the functions before they are used (or called) in the program is called
Function Prototype.
✔ The function prototype is also called as Function declaration.
✔ It is same as the Function Header but terminated with semicolon.
✔ It does not contain the body of the function.
Syntax
return_data_type function_name(data_type variable1,data_type variable2,….);
Where,
return_data_type: This is the data type of the value that the function is expected to return (int, float,
double, char).
function_name: It is the name of the function. It can be any valid Identifier.
data_type variable1,data_type variable2,..: a list of variables enclosed within parenthesis. Variables
are separated by comma.
BIET, DVG 2
Principles of Programming using C BCSESC103/203
Function Definition
✔ The program module that is written to achieve a specific task is called function definition.
✔ Each function definition consists of two parts:
⮚ Function Header
⮚ Function Body
BIET, DVG 3
Principles of Programming using C BCSESC103/203
return_type:
✔ This is the data type of the value that the function is expected to return (int, float, double, char).
✔ If the function is not returning any value, then we need to specify the return type as ‘void’.
✔ The default return value of any function is integer.
function_name:
✔ It is the name of the function. It can be any valid Identifier.
Parameters:
✔ The parameters are the list of variables enclosed within parenthesis. Variables are separated by
comma.
Data type of parameters
Parameter name
Return_data_type Function name
Function Body may includes:
✔ Declaration part: All the variables used in the function body should be declared in this part.
✔ Executable statements: This part contains the statements or instructions that perform the specified
activity.
✔ return (variable) : It is a keyword used to return the control to the calling function (main)
with/without a value.
Ex: int add(int a,int b)
{
int sum; //variable declaration
sum=a+b; //executable statement
return sum; //return statement
}
Function Call
✔ Once the function is defined, it has to be called so as to achieve the task. This method of calling
a function to achieve a specified task is called Function Call.
✔ The function can be called by writing the name of the function and passing the appropriate number of
arguments.
✔ The number of arguments in the function call and number of parameters in the function definition
must match.
✔ Also the order of arguments in the function call and parameters in the function definition must match.
Example: add(m,n);
BIET, DVG 4
Principles of Programming using C BCSESC103/203
Example: Write a C program to perform the addition of two numbers using function.
#include <stdio.h>
int sum(int a, int b) ; // Function declaration
int main()
{
int num1, num2, total=0;
Output:
Enter first number:
20
Enter second number:
30
Total= 50
1. The function sum() is called with two arguments a and b.
2. The control is transferred to the function sum() and the entered values 20 and 30 are received using
variables a and b.
3. The result is computed by adding 20 and 30.
4. The result is returned to the main() and will be copied into the variable result.
5. The result is displayed on the screen.
BIET, DVG 5
Principles of Programming using C BCSESC103/203
return Statement:
✔ C return statement ends the execution of a function and returns the control to the function from where
it was called. The return statement may or may not return a value depending upon the return type of
the function.
For example, int returns an integer value, void returns nothing, etc.
Syntax:
1.
return; // Returns control without sending any value to main program.
hear expression is placed in between angular brackets because specifying an expression is optional. The value of
expression is present, is returned to the calling function. However in case expression is omitted, the return value
of the function is undefined.
It is an error to use a return statement in a function that has void as its return type.
The programmer may or may not place the expression in a return statement within a parentheses, by
default the return type is int.
An error is generated when the function does not return data of the specified type.
A function that does not return any value cannot be placed on the right side of the assignment
operator.
A function may have more than one return statement, For example.
#include <stdio.h>
BIET, DVG 6
Principles of Programming using C BCSESC103/203
if (a>b)
return 1;
else
return -1
}
Output:
a is less than b
Example Program: Write a C program to add two numbers using call by value.
#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:
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
BIET, DVG 7
Principles of Programming using C BCSESC103/203
Pros and Cons:
The biggest advantage of using the call by value techniques to pass the arguments to the called function
is that arguments can be variables, literals or expression.
The disadvantages is that copying data consumes additional storage space.
✔ Call by address is done indirectly by passing the address of the variables in the function call
and changing the value of the variable through its address.
✔ In the called function, the formal parameters should be declared as pointers with the same type as the
actual parameters.
✔ The addresses of actual parameters are copied into formal parameters. Using these addresses the
values of the actual parameters can be changed.
✔ In call by reference if any change in formal parameters imply then there is a change in actual
parameters.
Example Program: Write a C program to add two numbers using call by reference.
#include <stdio.h>
void swap_call_by_val(int , int);
void swap_cal_by_reference(int *, int *);
int main()
{
int a = 1, b = 2,c = 3, d = 4;
BIET, DVG 8
Principles of Programming using C BCSESC103/203
// Function to swap values using call by reference
void swap_cal_by_reference(int *c, int *d) {
int temp = *c;
*c = *d;
*d = temp;
printf("\n In function (call by reference method) c=%d and d=%d”,*c,*d);
}
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 = 3 and d = 4
Pros:
Memory Efficiency: Call by reference doesn’t create a new copy of the arguments, so it saves
memory, especially for large data structures like arrays or structs.
Direct Modifications: Functions can directly modify the original variables, making it useful when
changes are required in the caller’s scope, such as updating multiple return values or applying
transformations.
Cons:
The side effect of using this technique is that when an argument is passed using cal by address, it
becomes difficult to tell whether that argument is meant for input, output or both.
Scope of Variables
In C, the scope of a variable refers to the region of the code where the variable is accessible.
Understanding variable scope is crucial for effective memory management, reducing errors, and
writing efficient code. The main types of scopes in C are:
Definition: Variables declared within a block (e.g., within {}) have block scope. A block can be
inside functions, if, while, for loops, etc.
Access: These variables are accessible only within the block they are defined.
Lifetime: They are created when the block is entered and destroyed upon exiting.
BIET, DVG 9
Principles of Programming using C BCSESC103/203
Example:
void example() {
if (x > 5) {
2. Function Scope
Example:
void example() {
goto label; // Can access label even though it's declared below
label:
printf("This is a label.");
3. Program Scope
In C, the program scope of a variable (also known as global scope ) means that a variable is
accessible throughout the entire program or file, depending on whether it’s defined with extern
linkage or static linkage. Program scope variables are typically declared outside any function,
making them global variables that can be shared across different functions or even multiple files.
Definition: Variables defined outside any function (usually at the top of a file) have program
scope, meaning they are accessible by any function within that file.
Access: All functions in the same file can access and modify these variables.
Lifetime: They exist for the entire runtime of the program.
4. File Scope
Definition: Variables declared outside of any function have file scope, meaning they are
accessible throughout the file.
Access: These variables are accessible by all functions within the same file after their
declaration. They are often called global variables.
Lifetime: They persist for the entire duration of the program's execution.
BIET, DVG 10
Principles of Programming using C BCSESC103/203
Storage Classes
In C, storage classes define the scope, lifetime, and visibility of variables or functions within a
program. Each storage class specifies different rules for how and where a variable or function can be
accessed, as well as the duration of its existence in memory. There are four main storage classes in
C:
1. Automatic (auto)
2. External (extern)
3. Static (static)
4. Register (register)
1. Automatic (auto)
Usage: This is the default storage class for local variables (variables declared inside a
function or block). Although auto can be explicitly declared, it is rarely used because it’s the
default for local variables.
Scope: Local to the block in which it’s defined.
Lifetime: Created when the block or function is entered and destroyed when it exits.
Storage: Stored in the stack.
2. External (extern)
Usage: Used to declare global variables or functions. The extern keyword tells the compiler
that a variable or function exists, but is defined elsewhere (possibly in another file).
Scope: Global, meaning it can be accessed from any file in a multi-file program if properly
declared.
Lifetime: Exists for the entire duration of the program.
Ex: // In file1.c
// In file2.c
void function() {
}
BIET, DVG 11
Principles of Programming using C BCSESC103/203
3. Static (static)
The static keyword has different effects based on whether it is used with a global variable, a local
variable, or a function.
Scope: Restricted to the file in which they are defined (file scope with internal linkage). This
prevents other files from accessing the variable, even if it’s global.
Lifetime: Exists for the entire program duration.
Ex:
// In file1.c
Ex:
void function() {
counter++;
printf("%d\n", counter);
4. Register (register)
Usage: Suggests that the variable be stored in a CPU register instead of regular memory,
allowing for faster access. This is only a suggestion, as the compiler may ignore it based on
system constraints and optimization settings.
Scope: Local to the block in which it’s defined.
Lifetime: Only exists within the function or block, like auto.
Storage: Stored in a register (if available and appropriate).
Restrictions: Cannot take the address of a register variable, as it may not have a memory
address.
BIET, DVG 12
Principles of Programming using C BCSESC103/203
Ex:
void function() {
BIET, DVG 13
Principles of Programming using C BCSESC103/203
Recursion
✔ “The process in which a function calls itself again and again is called as Recursion”.
✔ A function which calls itself again and again is called as Recursive function.
✔ While using recursion, user need to be careful to define exit condition from function; otherwise it will go
in infinite loop.
✔ Recursive functions are very useful to solve many mathematical problems like to calculate factorial of a
number, generating Fibonacci series, etc.
Syntax:
void main() int recursion ()
{ {
recursion ( ); recursion ( );
} }
BIET, DVG 14
Principles of Programming using C BCSESC103/203
printf(“Enter a value for n and r”);
scanf(“%d”,&n);
fact=factorial(n) / (factorial(n-r) * factorial(n));
printf(“\n nCr value =%d”,fact);
}
BIET, DVG 15
Principles of Programming using C BCSESC103/203
ARRAYS
An Array is a special and powerful data structure and it is used to store, process and print large
amounts of data.
“An array is a collection of similar type of items (elements) stored sequentially (continuously)
one after the other in memory”.
Ex: 1. int A[5] ; // Array of 5 Integers
A[0] 10
A[1] 20
A[2] 30
A[3] 40
50
A[4]
▪ The Elements in the Array A can be accessed using the common name A, but with
different index.
▪ The Element ‘10’ is called 0th Element and it can be accessed using the Subscript 0
(called Index ‘0’) along with name of the array ‘A’.
Ex: 2. char B[5]; //Array of 5 Characters
B[0] ‘A’
B[1] ‘r’
B[2] ‘r’
B[3] ‘a’
B[4] ‘y’
BIET, DVG 16
Principles of Programming using C BCSESC103/203
Declaration of arrays:
✔ As we declare the variables before they are used in a program, an array must also be
declared and defined before it is used using following syntax.
● Syntax
data_type array_name[size];
Where,
✔ data_type: data type can be int, float, char etc.
✔ array_name: name of the array which is a valid C variable.
✔ size: it is the number of elements in the array.
✔ Complete declaration ends with Semicolon.
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
// Output is 25
Calculating the address of array elements:
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 first element in the array.
BIET, DVG 17
Principles of Programming using C BCSESC103/203
Ex: Given an array int marks[]= {99,67,78,56,88,90,34,85}, calculating the address of marks[4]
elements with example if base address =1000
Soln:
99 67 78 56 88 90 34 85
Length=upper_bound - lower_bound+1
Where upper_bound is the index of the last element and lower_bound is the index of the first
element in the array.
BIET, DVG 18
Principles of Programming using C BCSESC103/203
Once an array is declared it must be initialized with some values using Initialization.
“Process of assigning the values to the individual elements of an array is called as
Initialization of an array”.
BIET, DVG 19
Principles of Programming using C BCSESC103/203
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 value for each element of the array.
Ex:
int i,marks[10];
for(i=0; i<10; i++)
scanf(“%d”, &marks[i]);
Operations on Arrays:
1. Traversing an array.
2. Searching for a value in a array.
BIET, DVG 20
Principles of Programming using C BCSESC103/203
1.Traversing an array.
“Traversing an array means accessing each and every element of the array for a specific
purpose”.
Step 1: [INTIALIZATION] 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]
Srep 5: EXIT
int main() {
int n;
return 0;
}
Output:Enter the number of elements: 5
Enter 5 numbers:
Number 1: 10
Number 2: 20
Number 3: 30
Number 4: 40
Number 5: 50
BIET, DVG 21
Principles of Programming using C BCSESC103/203
The numbers you entered are:
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
In C, searching for a value in an array typically involves checking each element in the array until the
desired value is found. There are two common methods for searching in an array:
1. Linear Search: This is the simplest search algorithm where each element of the array is
checked one by one.
2. Binary Search: This method works only on sorted arrays, where you repeatedly divide the
search interval in half. This approach is much faster than linear search for large arrays.
Linear Search:
Linear search is a basic search method where we start from the first element and check each element
sequentially until the desired value is found or the end of the array is reached.
BIET, DVG 22
Principles of Programming using C BCSESC103/203
Binary Search:
Binary search is much more efficient than linear search, but it only works on sorted arrays. The
basic idea is to repeatedly divide the search interval in half. If the target value is smaller than
the middle element, it is on the left side; otherwise, it is on the right side.
BIET, DVG 23
Principles of Programming using C BCSESC103/203
Passing Arrays to Functions:
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 situation you
may want to pass the entire array.
All array elements can be passed as individual elements to a function like any other variable
BIET, DVG 24
Principles of Programming using C BCSESC103/203
3. Passing the entire array
Suppose, we want to pass whole array to a function. In such situation, we must follow
the two rules:
1. The function must be called by passing only the name of the array.
2. In the function definition, the parameter must be declared as an array of the same
type as that of actual parameter. There is no need to specify the size of the array.
✔ Arrays which are specified with 2 subscripts (2 set of square brackets [ ][ ]) are
called 2-dimensional arrays.
✔ Arrays with two or more dimensions are called Multi-dimensional arrays.
✔ In 2-Dimensional Array, the first index indicates the ‘row size’( the number of
rows)and second index indicates the ‘column size’( the number of columns).
Ex: int a[10][10]; //Two dimensional array
BIET, DVG 25
Principles of Programming using C BCSESC103/203
BIET, DVG 26
Principles of Programming using C BCSESC103/203
BIET, DVG 27
Principles of Programming using C BCSESC103/203
Example Programs:
Write a C Program to read and print 2-dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n;
printf(“Enter the number of Rows and Columns of the Array:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the Array elements:\n”);
for(i=0;i<m;i++)
{
Output:
for(j=0;j<n;j++)
Enter the number of Rows and
{ Columns of the Array:
scanf(“%d”,&a[i][j]); 2 2
} Enter the Array elements:
} 1
· Addition: Adding two matrices involves summing corresponding elements in the matrices. This
operation is possible only if the matrices are of the same dimensions.
BIET, DVG 28
Principles of Programming using C BCSESC103/203
· Subtraction: Similar to addition, each element in the first matrix is subtracted by the
corresponding element in the second matrix.
· Multiplication: The matrix multiplication operation requires the number of columns in the first
matrix to match the number of rows in the second matrix.
· Transpose: Swapping rows with columns results in the transpose of the matrix.
A[i][j]=A[j][i]
int main() {
int matrix[3][3];
BIET, DVG 29
Principles of Programming using C BCSESC103/203
#include <stdio.h>
int main() {
int matrix[3][3], transpose[3][3];
return 0;
}
BIET, DVG 30
Principles of Programming using C BCSESC103/203
Figure shows the three ways of using two-dimensional arrays for inter-function communication.
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.
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.
BIET, DVG 31
Principles of Programming using C BCSESC103/203
Write a menu-driven program to read and display an m × n matrix. Also find the sum,
transpose, and product of two m x n matrices.
#include <stdio.h>
#include <conio.h>
void read_matrix (int mat [2] [2], int, int);
void sum matrix (int mat1 [2] [2], int mat2 [2] [2], int, int);
void mul matrix (int mat1 [2] [2], int mat2 [2] [2], int, int);
void transpose_matrix (int mat2 [2] [2], int, int);
void display_matrix (int mat [2] [2], int r, int c);
int main()
{
int mat1 [2] [2], mat2 [2] [2];
clrscr();
do
{
printf("\n ******* MAIN MENU ********") ;
printf("\n 1. Read the two matrices");
printf("\n 2. Add the matrices");
printf("\n 3. Multiply the matrices");
printf("\n 4. Transpose the matrix");
printf("\n 5. EXIT");
printf("\n\n Enter your option: ");
scanf("%d", &option);
switch (option)
{
case 1: printf("\n Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &row, &col);
printf("\n Enter the first matrix: ");
read_matrix (matl, row, col);
printf("\n Enter the second matrix: ");
read matrix (mat2, row, col);
break;
case 2: sum matrix (mat1, mat2, row, col);
break;
case 3: if (col = = row)
mul_matrix (mat1, mat2, row, col);
BIET, DVG 32
Principles of Programming using C BCSESC103/203
else
printf("\n To multiply two matrices, number of columns in the first matrix must be equal to number
of rows in the second matrix");
break;
case 4: transpose_matrix (mat1, row, col);
break;
}
} while (option != 5);
getch();
return 0;
}
void read matrix (int mat [2] [2], int r, int c)
{
int i, j;
for (i = 0; i < r;i++)
{ printf("\n");
for(j = 0; j < C;j++)
{
printf("\t mat [%d] [%d] = ",i,j);
scanf("%d", &mat [i] [j]);
}
}
}
void sum matrix (int mat1 [2] [2], int mat2 [2] [2], int r, int c)
{
int i, j, sum [2] [2];
for (i=0;i<r;i++)
{
for(j=0;j<c;j++)
sum [i][j] = mat1 [i][j] + mat2 [i][j];
}
display_matrix (sum, r, c);
}
void mul_matrix (int mat1 [2] [2], int mat2 [2] [2], int r, int c)
{
int i, j, k, prod [2] [2];
BIET, DVG 33
Principles of Programming using C BCSESC103/203
for (i=0; i<r; i++)
{
for(j=0;j<c;j++)
{
prod[i][j] = 0;
for (k=0;k<c;k++)
prod [i][j] += mat1 [i] [k] * mat2 [k] [j]; Output
} ******* MAIN MENU ********
} 1. Read the two matrices
display_matrix (prod, r, c); 2. Add the matrices
} 3. Multiply the matrices
void transpose_matrix (int mat [2] [2], int r,int c) 4. Transpose the matrix
{ 5. EXIT
int i, j, tp_mat [2] [2]; Enter your option: 1
for (i=0;i<r;i++) Enter the number of rows and columns of the
{ matrix: 2 2
for(j=0;j<c;j++) Enter the first matrix:
tp_mat [j] [i] = mat [i][j]; mat [0] [0] = 1 mat [0] [1] = 2
} mat [1] [0] = 3 mat [1] [1] = 4
display_matrix (tp_mat, r, c); Enter the second matrix :
} mat [0] [0] = 2 mat [0] [1] = 3
void display_matrix (int mat [2] [2], int r,int c) mat [1] [0] = 4 mat [1] [1] = 5
{ ******* MAIN MENU ********
int i, j; 1. Read the two matrices
for (i=0;i<r;i++) 2. Add the matrices
{ 3. Multiply the matrices
printf("\n"); 4. Transpose the matrix
for(j=0;j<c;j++) 5. EXIT
printf("\t mat [%d] [%d] = %d", i, j, mat [i] [j]); Enter your option: 2
} mat [0] [0] = 3 mat [0] [1] = 5
} mat [1] [0] = 7 mat [1] [1] = 9
BIET, DVG 34
Principles of Programming using C BCSESC103/203
APPLICATIONS OF ARRAYS
Arrays are widely used to implement mathematical vectors, matrices, and other kinds of
rectangular tables.
Many databases include one-dimensional arrays whose elements are records.
Arrays are also used to implement other data structures such as strings, stacks, queues, heaps,
and hash tables. We will read about few of these data structures in the subsequent chapters.
Arrays can be used for sorting elements in ascending or descending order.
BIET, DVG 35