0% found this document useful (0 votes)
3 views35 pages

POP Module 3

The document provides an overview of functions in C programming, detailing their advantages, definitions, and types such as user-defined functions. It explains the elements of functions including prototypes, definitions, and calls, along with examples of function usage and parameter passing methods (call by value and call by reference). Additionally, it covers variable scope and storage classes in C, emphasizing their importance in memory management and program structure.

Uploaded by

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

POP Module 3

The document provides an overview of functions in C programming, detailing their advantages, definitions, and types such as user-defined functions. It explains the elements of functions including prototypes, definitions, and calls, along with examples of function usage and parameter passing methods (call by value and call by reference). Additionally, it covers variable scope and storage classes in C, emphasizing their importance in memory management and program structure.

Uploaded by

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

Principles of Programming using C BCSESC103/203

MODULE 3

FUNCTIONS

Function (Subroutine or subprogram)

✔ “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.

Fig shows: function calling another function

User-Defined/ Programmer Defined Functions


✔ The functions written by the programmer/user to do the specific tasks is called User-Defined/
Programmer Defined Functions.
✔ main( ) is the user defined function.

Elements of User-Defined Functions


✔ The three elements of user-defined functions are shown below:
i. Function Prototype/Declaration
ii. Function Definition
iii. Function Call

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.

Ex: int add(int a,int b);


✔ The function prototype contains the following information in a single line terminated by semicolon:
● The type of the value returned by the function.
● The name of the function.
● The number of parameters passed to that function.
● The type of each parameter.

BIET, DVG 2
Principles of Programming using C BCSESC103/203

Table shows: Valid function declaration.

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

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


{
--------;
statements;
return (variable);
}

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

Ex: int add ( int a, int b);

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.

✔ Syntax: function_name( variable1,variable2,….);

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;

printf("\n Enter first number: ");


scanf("%d", &num1);

printf("\n Enter second number: ");


scanf("%d", &num2);

total = sum(num1, num2); // Function Call


printf("Total= %d\n", total); // Displaying the result
return 0;
}

int sum (int a, int b) // Function Header


{
int result;
result = a+b; // Function Body // Function Definition
return result ;
}

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.

✔ The ‘main()’ is always the “Calling Function”.

✔ The ‘sum()’ function is called “Called Function”.

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.

2. return <expression>; // Returns control by sending 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>

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”);
retutn 0;
}
int check_relation(int a, int b);
{
if(a==b)
return 0;
else

BIET, DVG 6
Principles of Programming using C BCSESC103/203
if (a>b)
return 1;
else
return -1
}

Output:
a is less than b

Passing Parameter to Functions


✔ There are mainly two parameter passing mechanisms in ‘C’ functions. They are:
i. Call by Value or Pass by Value
ii. Call by Address or Pass by Address

i. Call by Value or Pass by Value


✔ Calling (Invoking) a function by passing values or variables to the function is called as call by
value.
✔ The values of actual parameters are copied into formal parameters.
✔ Formal parameters contain only the copy of actual parameters. So, even if the values of the formal
parameters changes in the called function, the values of the actual parameters are not changed.

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.

ii. Call by Address or Pass by Address

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

printf(" In main(), a = %d and b = %d\n", a, b);


swap_call_by_value(a, b);
printf(" In main(), a = %d and b = %d\n", a, b);

printf(" In main(), c = %d, d = %d\n", c, d);


swap_call_by_reference(&c, &d);
printf(" In main(), c = %d, d = %d\n", c, d);
return 0;
}

// Function to swap values using call by value


void swap_call_by_val(int a, int b)
{
int temp = a;
a = b;
b = temp;
printf("\n In function (call by value method) a=%d and b=%d”,a,b);
}

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:

1. Block Scope (or Local Scope)


2. Function Scope
3. Program Scope
4. File Scope (or Global Scope)

1. Block Scope (Local Scope)

 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() {

int x = 10; // x is local to example()

if (x > 5) {

int y = 20; // y is local to this if-block

} // y is no longer accessible here

2. Function Scope

 Definition: Labels (used with goto statements) have function scope.


 Access: Labels are accessible throughout the function where they are defined, regardless of the
block.

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.

Ex: void function() {

auto int x = 10; // 'x' is an auto variable

int y = 20; // 'y' is also auto by default

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

int globalVar = 100; // Defined in file1.c

// In file2.c

extern int globalVar; // Declared in file2.c

void function() {

globalVar += 10; // Accessing the variable defined in file1.c

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

Static Global Variables:

 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

static int fileVar = 20; // Only accessible within file1.c

Static Local Variables:

 Scope: Limited to the block or function in which it is declared.


 Lifetime: Retains its value across function calls, as it persists for the entire program duration
but is only accessible within the defining function.

Ex:

void function() {

static int counter = 0; // Retains value between function calls

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() {

register int fastVar = 5; // Suggest to store in CPU register

Table shows: comparison of storage classes

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 ( );

} }

Example: Program to calculate factorial of a given number.


#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
void main()
Output:
{
Enter a number=5
int n,fact;
Factorial of given number =120
printf(“Enter a number=”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“\nFactorial of given number=%d”,fact);
}

Example: Program to calculate nCr value using recursion function.


#include<stdio.h>
int factorial(int n)
{
if(n==1) Output:
return 1; Enter a value for n and r
else 6
return (n*fact(n-1)); 2
} nCr Value =15
void main()
{
int n,fact;

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

Example: C Program to find the Fibonacci series using recursive function.


#include<stdio.h>
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 a value for n
5
void main() The Fibonacci series is:
{ 0
int n, i, result; 1
printf(“Enter a value for n ”); 1
scanf(“%d”, &n); 2
printf(“ The Fibonacci series is: \n”); 3
for ( i =0; i < n ; i ++)
{
res = fibonacci (i);
printf(“%d\n”, res);
}
}

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’

▪ An ‘Index’ is also called as Subscript ([ ]). It is used to indicate the position of an


element in the Array.
Basic Properties of the Arrays

✔ All the elements in an array should be of the same data type.


✔ The elements are stored continuously in the memory. (For example, in the array char
B[5], if the first address is 1000 then the data is stored contiguously in the addresses
1000, 1001, 1002 and so on).
✔ The Subscript (index) of first item is always zero.
✔ Each element of an array is accessed using the name of the Array, but with different
subscript.
✔ The Index of the Array is always an Integer number can’t be float.
Ex: a [1] or a [5].
a [1.5] is an Error.

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.

Ex: int Marks[5];

Declares Marks as an array consisting of 5 elements of integer data type.

Accessing the elements of an array:

 To access an array element, refer to its index number.

 Array indexes start with 0: [0] is the first element. [1] is the second element, etc.

Ex: int myNumbers[] = {25, 50, 75, 100};


printf("%d", myNumbers[0]);

// Output is 25
Calculating the address of array elements:

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

marks [0] [1] [2] [3] [4] [5] [6] [7]


1000 1002 1004 1006 1008 1010 1012 1014

WKT, storing an integer value requires 2 bytes,therefore, word size is 2 bytes.


Address(marks[4]) = 1000+2(4-0)
= 1000+2(4)
= 1008

Calculating the Length of an array:

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.

Storing Values in Arrays

BIET, DVG 18
Principles of Programming using C BCSESC103/203

1. Initializing arrays during declaration

 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”.

Syntax data_type array_name[size]={list of values};

 data_type: it can be int, float, char etc.


 array_name: it is the name of the array.
 size: it is the number of elements in the array.

BIET, DVG 19
Principles of Programming using C BCSESC103/203

2. Inputting Values from the keyboard

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:

//Input values of each element of the array

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

3. Assigning Values to individual elements

 Assign values to specific array elements by using array [index] = value;.


 You can assign values to individual elements through loops and user input.
 Arrays can be initialized directly at the time of declaration if all values are known.
Ex: #include <stdio.h>
int main()
{
int marks[5]; // Declare an array of size 5

// Assign values to each element


marks[0] = 90; // First element
marks[1] = 85; // Second element
marks[2] = 88; // Third element
marks[3] = 76; // Fourth element
marks[4] = 92; // Fifth element

// Print the values of the array


printf("Marks:\n");
for (int i = 0; i < 5; i++) {
printf("marks[%d] = %d\n", i, marks[i]);
}
return 0;
}

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

Fig, shows: Algorithms for array traversal

Ex: #include <stdio.h>

int main() {
int n;

// Prompt the user to enter the number of elements


printf("Enter the number of elements: ");
scanf("%d", &n);

// Declare an array to store n elements


int numbers[n];

// Read n numbers from the user


printf("Enter %d numbers:\n", n);
for (int i = 0; i < n; i++) {
printf("Number %d: ", i + 1);
scanf("%d", &numbers[i]); // Read each number and store in the array
}

// Display the numbers


printf("\nThe numbers you entered are:\n");
for (int i = 0; i < n; i++) {
printf("numbers[%d] = %d\n", i, numbers[i]); // Display each number
}

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

2. Searching for a value in a array.

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.

Algorithm and Program for Linear Search:

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.

Algorithm and Program for Binary Search:

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.

The fig. Shows one dimensional arrays for inter-function communication.

1. Passing individual elements

 All array elements can be passed as individual elements to a function like any other variable

The fig. Shows Passing value of individual array elements to a function.


2. Passing address
 Like ordinary variables, we can pass the address of an individual array element by preceding the
indexed array element with the address operator(&).

The fig. Shows Passing address of individual array elements to a function.

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.

The fig. Shows Passing entire array to a function.

Two- Dimensional Arrays

✔ 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

Declaration of Two-dimensional arrays


✔ As we declare the variables before they are used in a program, an array must also be
declaredbefore it is used using the following syntax.
Syntax:
data_type array_name [row_size][col_size];

data_type: It can be int, float, char etc.


array_name: It is the name of the array.
row_size: It is the number of rows in the array.
col_size: It is the number of columns in the array.
Semicolon is must at the end.

BIET, DVG 25
Principles of Programming using C BCSESC103/203

BIET, DVG 26
Principles of Programming using C BCSESC103/203

Accessing the elements of Two-Dimensional Arrays


✔ To read the 2-dimensional array, we have to use two for loops along with scanf(),
where the outer for loop indicates the number of rows to be read and the inner for loop
indicates the number of columns to be read.
✔ To read the ‘n’ array elements of Two dimensional array:
for(i=0;i<m;i++)
{ for(j=0;j<n;j++) {
scanf(“%d”,&a[i][j]);
}
}
✔ To write/print the 2-dimensional array elements, we have to use two for loops along
with printf(), where the outer for loop indicates the number of rows to be printed and
the inner for loop indicates the number of columns to be printed.
✔ To print the ‘n’ array elements of Two dimensional array:
for(i=0;i<m;i++)
{ for(j=0;j<n;j++) {
printf(“%d\t”,a[i][j]);
}
printf(“\n”); }

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

printf(“Entered array elements are:\n”); 2


for(i=0;i<m;i++) 3
{ 4
for(j=0;j<n;j++)
Entered array elements are:
{
1 2
printf(“%d\t”,a[i][j]);
3 4
}
}
printf(“\n”);
}
}
Operations on Two- Dimensional Arrays

· Addition: Adding two matrices involves summing corresponding elements in the matrices. This
operation is possible only if the matrices are of the same dimensions.

C[i][j] = A[i][j] + B[i][j];

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.

C[i][j] = A[i][j] - B[i][j];

· Multiplication: The matrix multiplication operation requires the number of columns in the first
matrix to match the number of rows in the second matrix.

C[i][j] = A[i][j] * B[i][j];

· Transpose: Swapping rows with columns results in the transpose of the matrix.

A[i][j]=A[j][i]

Ex: Write a program to read and display 3 * 3matrix.


#include <stdio.h>

int main() {
int matrix[3][3];

// Input elements for the 3x3 matrix


printf("Enter elements of a 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]); OUTPUT
} Enter elements of a 3x3 matrix:
} Enter element [0][0]: 1
Enter element [0][1]: 2
// Display the 3x3 matrix Enter element [0][2]: 3
printf("\nThe 3x3 matrix is:\n"); Enter element [1][0]: 4
for (int i = 0; i < 3; i++) { Enter element [1][1]: 5
for (int j = 0; j < 3; j++) { Enter element [1][2]: 6
printf("%d ", matrix[i][j]); Enter element [2][0]: 7
} Enter element [2][1]: 8
printf("\n"); Enter element [2][2]: 9
}
The 3x3 matrix is:
return 0; 123
} 456
789

BIET, DVG 29
Principles of Programming using C BCSESC103/203

Ex: Write a program to transpose a 3 * 3matrix

#include <stdio.h>

int main() {
int matrix[3][3], transpose[3][3];

// Input elements for the 3x3 matrix


printf("Enter elements of a 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}

// Compute the transpose of the matrix OUTPUT


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) { The original matrix is:
transpose[j][i] = matrix[i][j];
123
}
} 456
// Display the original matrix 789
printf("\nThe original matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]); The transpose of the matrix is:
}
printf("\n"); 147
}
258
// Display the transpose of the matrix
printf("\nThe transpose of the matrix is:\n"); 369
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}

return 0;
}

BIET, DVG 30
Principles of Programming using C BCSESC103/203

Passing Two- Dimensional Arrays to functions.


 There are three ways of passing two-dimensional arrays to functions. First, we can
pass individual elements of the array. This is exactly same as passing elements of a one-
dimensional array. Second, we can pass a single row of the two-dimensional array. This is
equivalent to passing the entire one-dimensional array to a function. This has already been
discussed in the previous section.. Third, we can pass the entire two-dimensional array to
the function.

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.

Figure shows passing a single row of a two-dimensional array.

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.

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

You might also like