Professional Documents
Culture Documents
Pop Module 3
Pop Module 3
MODULE-III
Functions
Introduction
• A program is broken up into segments called “functions”. These functions can be
written more or less independently of the others.
• Every function in the program is supposed to perform a well-defined task.
• 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.
• This interface is specified by the function name.
• Below figure explains how the main() function calss another function to perform a
well-defined task.
main() func1()
main()
{ {
{
………………… Statement Block;
………………… }
func1();
…………………
…………………
return 0;
}
Main function
Function B1 Function B2
main() func1()
{ {
…………. ……………….
…………. ……………….
func1(); ………………….
…………. …………………
………… ……………..
func1(); return;
……….. }
………..
return 0;
}
Function func1() called twice from main()
Using Functions
• A function “f” that uses another function “g” is known as the “calling function” and “g”
is known as the “called function”.
• The inputs that a function takes are known as “arguments/parameters”.
• When a called function returns some result back to the calling function, it is said to
“return” that result.
• The calling function may or may not pass “parameters” to the called function. If the
called function accepts arguments, the calling function will pass parameters, else it will
not do so.
• “Function declaration” is a declaration statement that identifies a function 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 containing the executable code for that function.
Function Definition
• When a function is defined, space is allocated for that function in the memory.
• A function definition comprises two parts:
➢ Function header
➢ Function body
Principles of Programming using C BPOPS203
Function Call
• 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.
• Once the called function is executed, the program control passes back to the calling
function.
• Function call statement has the following syntax:
function_name(variable1, variable2,…);
• When the function declaration is present before the function call, the compiler can
check if the correct number and type of arguments are used in the function call and the
returned value, if any, is being used reasonably.
• 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
Write a program to add two integers using functions.
#include<stdio.h>
// FUNCTION DECLARATION
int sum(int a, int b);
int main()
{
int num1,num2,total=0;
printf(“\nEnter the first number:”);
scanf(“%d”,&num1);
printf(“\nEnter the second number:”);
scanf(“%d”,&num2);
total-sum(num1,num2);
Principles of Programming using C BPOPS203
//FUNCTION CALL
printf(“\nTotal=%d”,total);
return 0;
}
//FUNCTION DEFINITION
int sum(int a,int b) //FUNCTION HEADER
{
int result; //FUNCTION BODY
result=a+b;
return result;
}
Output
Enter the first number:20
Enter the second number:30
Total=50
return Statement
• 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.
• A “return” statement may or may not return a value to the calling function.
• The syntax of “return” statement can be given as
return <expression>;
Here “expression” is placed in between angular brackets because specifying an
expression is optional.
• The value of expression, if present, is returned to the calling function.
• In case “expression” is omitted, the return value of the function is undefined.
• The expression, if present, is converted to the type returned by the function.
• A function that has “void” as its return type cannot return any value to the calling
function.
• For functions that have no “return” statement, the control automatically returns to the
calling function after the last statement of the called function is executed.
• A function may have more than one “return” statement.
Principles of Programming using C BPOPS203
Example
#include<stdio.h>
#include<conio.h>
int check_relation(int a,int b);
int main()
{
int a=3,b=5,res;
clrscr();
res=check_relation(a,b);
if(res==0) //Test the returned value
printf(“\nEQUAL”);
if(res==1)
printf(“\n a is greater than b”);
if(res== -1)
printf(“\n a is less than b”);
getch();
return 0;
}
int check_relation(int a,int b)
{
if(a==b)
return 0;
else if(a>b)
return 1;
else
return -1;
}
Output
a is less than b
• There are two ways in which argu,ments or parameters 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.
Call by Value
• 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 passed to it,
then the change will be reflected only in the called function.
• In the calling function no change will be made to the value of the variables.
• This is because all the changes were made to the copy of the variables.
Example
#include<stdio.h>
void add(int n);
int main()
{
int num=2;
printf(“\nThe value of num before calling the function=%d”,num);
add(num);
printf(“\nThe value of num after calling the function =%d”,num);
return 0;
}
void add(int n)
{
n=n+10;
printf(“\nThe 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
• Since the called function uses a copy of “num”, the value of “num” in the calling function
remains unchanged. This concept can be more clearly understood from below figure.
Principles of Programming using C BPOPS203
2 2
“num” in the calling function “num” in the calling function is known as in the called function
2 12
“num” in the calling function remains unchanged “num” is modified in the called function
Call by Reference
• When the calling function passes arguments to the called function using call-by-
reference technique, function parameters are declared as references.
• Any changes made by the function to the arguments are visible in the calling function.
• To indicate that an argument is passed using call by reference, an asterisk(*) is placed
after the type in the parameter list.
• Changes made to the parameter in the called function will then be reflected in the
calling function.
• In call-by-reference method, a function receives an implicit reference to the argument.
Therefore, the function can modify the value of the variable and that change will be
reflected in the calling function as well.
Example
#include<stdio.h>
void add(int *n);
int main()
{
int num=2;
printf(“\nThe value of num before calling calling the function=%d”,num);
add(&num);
printf(“\nThe value of num after calling the function=%d”,num);
return 0;
}
Advantages
• Since arguments are not copied into new variables, 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
When an argument is passed using call by address, it becomes difficult to tell whether that
argument is meant for input, output, or both.
Scope of Variables
• In C, all constants and variables have a defined scope.
• By scope we mean the accessibility and visibility of the variables at different points in
the program.
• A variable or constant in C has four types of scope: block, function, program, and file.
Block Scope
• A statement block is a group of statements enclosed within opening and closing curly
brackets { }.
• If a variable is declared within a statement block then as soon as the control exits that
block, the variable will cease to exist.
• Such a variable also known as a local variable is said to have a “block scope”.
• Blocks of statements may be placed one after the other in a program. Such blocks that
are placed at the same level are known as “parallel blocks”.
Example
#include<stdio.h>
int main()
{
int x=10;
int i=0;
printf(“\nThe value of x outside the while loop is %d”,x);
while(i<3)
{
int x=i;
}
printf(“\nThe value of x outside the while loop is %d”,x);
return 0;
}
Output
The value of x outside the while loop is 10
The value of x inside the while loop is 0
The value of x inside the while loop is 1
The value of x inside the while loop is 2
The value of x outside the while loop is 10
Function Scope
• “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.
Example
int main()
{
.
.
loop: /* A goto label has function
scope */
.
.
goto loop; /* the goto statement */
.
.
return 0;
}
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() function.
Program Scope
• The variables are declared outside any function blocks and the function accesses these
variables which are not passed as arguments.
• 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 program execution and remain in
existence throughout the period of execution of the program.
Principles of Programming using C BPOPS203
These variables are known to all the functions in the program and are accessible to
them for usage.
Global variables exist even when a function calls another function.
These variables retain their value so that they can be used from every function in the
program.
• Place of Declaration
The gloabal variables are declared outside all the functions including main().
It is always recommended to declare these variables on top of the program code.
• 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.
The programmer must not use names of global variables as the names of local
variables, as this may lead to confusion and erroneous result.
Example
#include<stdio.h>
int x=10;
void print();
int main()
{
printf(“\nThe value of x in the main()=%d”,x);
int x=2;
printf(“\nThe value of local variable x in the main()=%d”,x);
print();
return 0;
}
void print()
{
printf(“\nThe value of x in the print()=%d”,x);
}
Output
The value of x in the main()=10
The value of local variable x in the main()=2
The value of x in the print()=10
File Scope
• 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:
static int x=10;
• A global static variable can be used anywhere from the file in which it is declared
but it is not accessible by any other file.
• Such variables are useful when the programmer writes his own header files.
Principles of Programming using C BPOPS203
Storage Classes
• “Storage class” defines the scope (visibility) and lifetime of variables and/or functions
declared within a C program.
• Additional information regarding storage class of a variable or a function:
➢ 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.
➢ It specifies how long the storage allocation will continue to exist for that function or
variable.
➢ It specifies the scope of the variable or function, that is, the storage class indicates
the part of the C program in which the variable name is visible or the part in which
it accessible.
➢ It specifies whether the variable or function has internal, external, or no linkage,
➢ It specifies whether the variable will be automatically initialized to zero or to any
indeterminate value.
• C supports four storage classes: automatic, register, external and static.
• The general syntax for specifying the storage class of a variable can be given as:
<storage_class_specifier> <data type>
<variable name>
auto Storage Class
• The auto storage class specifier is used to explicitly declare a variable with “automatic
storage”.
• It is the default storage class for variables declared inside a block. For example, if we
write
auto int x
then “x” is an integer that has automatic storage. It is deleted when the block in which
x is declared is exited.
Example
#include<stdio.h>
void func1()
{
int a=10;
printf(“\na=%d”,a);
// auto integer local to func1()
}
void func2()
{
int a=20;
printf(“\na=%d”,a);
//auto integer local to func2()
}
void main()
{
int a=30; // auto integer local to main()
func1();
func2();
Principles of Programming using C BPOPS203
printf(“\na=%d”,a);
}
Output
a=10
a=20
a=30
variables is allocated when the program begins running and is freed when the program
terminates.
• To declare an integer x as “static”,
static int x=10;
Here x is a local static variable.
• Static local variables when defined within a function are initialized at the runtime.
• Static storage class can be specified for “auto” as well as “extern” variables. For
example,
static extern int x;
When a variable is declared as “extern static” variable, then that variable is accessible
from all the functions in this source file.
Example
#include<stdio.h>
void print(void);
int main()
{
printf(“\nFirst call of printf()”);
print();
printf(“\nSecond call of printf()”);
print();
printf(“\nThird call of printf()”);
print();
return 0;
}
void print()
{
static int x;
int y=0;
printf(“\nStatic integer variable, x=%d”,x);
printf(“\nInteger variable, y=%d”,y);
x++;
y++;
}
Output
First call of print()
Static integer variable, x=0
Integer variable, y=0
Recursive Functions
• A “recursive function” is defined as a function that calls itself to solve a smaller version
of its task until a final call is made which does not require a call to itself.
• Every recursive solution has two major cases:
➢ Base case
Problem is simple enough to be solved directly without making any further calls to
the same function
➢ Recursive case
First 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.
Example
Calculate factorial of a number
To calculate n!, multiply the number with factorial of the number that is 1 less than that
number. In other words, n! =n*(n-1)!
To find 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!
Principles of Programming using C BPOPS203
We know, 1! =1
Therefore, the series of problems and solutions can be given as shown below
Problem Solution
5! 5*4*3*2*1!
=5*4! =5*4*3*2*1
=5*4*3! =5*4*3*2
=5*4*3*2! =5*4*6
=5*4*3*2*1! =5*24
=120
Recursive factorial function
ARRAYS
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”.
A[0] 10
A[1] 20
A[2] 30
A[3] 40
A[4] 50
✓ 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’.
B[0] ‘A’
B[1] ‘r’
B[2] ‘r’
B[3] ‘a’
B[4] ‘y’
3. float C[5]; //Array of 5 floats
C[0] 12.56
C[1] 234.20
C[2] 215.60
C[3] 322.50
C[4] 123.45
1
Principles of Programming using C BPOPS203
5. 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.
Classification of Arrays
1. Single Dimensional Array
2. Multi-Dimensional Array
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.
1000 35 Marks[0]
data type array_name 1002 45 Marks[1]
1004 65 Marks[2]
1006 55 Marks[3]
char name[5]; 1008 75 Marks[4]
✓ 5 memory locations are reserved. sizeof(int) is 2 bytes, 2*5=10 bytes are reserved.
✓ 5 memory locations are reserved. sizeof(char) is 1 bytes 1*5=5 bytes are reserved.
2
Principles of Programming using C BPOPS203
Principles of Programming using C
Initialization of Single dimensional arrays
✓ 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”.
a[0] 10
a[1] 20
a[2] 30
a[3]
a[4] 40
50
2. int a[5] = {10, 20};
10 20 0 0 0
a[0] a[1] a[2] a[3] a[4]
✓ When the numbers of initial values are lesser than declared array size then those many
elements will be initialized and other memory locations are automatically initialized to 0’s, in
case of numeric arrays.
✓ It is ‘partial array initialization’.
A r r a y \0
a[0] a[1] a[2] a[3] a[4] a[5]
3
Principles of Programming using C BPOPS203
Accessing the Elements of an Array
• For accessing an individual element of the array, the array subscript must be used.
• To access all the elements of the array, use a loop.
• Access all the elements of the array by varying the value of the subscript into the array.
• As shown in below figure, the first element of the array “marks[0]” can be accessed by writing,
marks[0]. Now to process all the elements of the array, use a loop.
// Set each element of the array to -1
int i, marks[10];
for(i=0;i<10;i++)
marks[i]= -1;
Code to initialize each element of the array to -1
• The code accesses every individual element of the array and sets its value to -1.
• In the “for” loop, first the value of marks[0] is set to -1, then the value of the index (i) is
incremented and the next value , that is marks[1] is set to -1.
• The procedure is continued until all the 10 elements of the array are set to -1.
• The subscript or the index represents the offset from the beginning of the array to the element
being referenced.
• With just the array name and the 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, that is, the address of the first element in the array is sufficient.
• The address of other data elements can simply be calculated using the base address.
• The formula for doing this calculation is:
Address of data element, A[k]=BA(A)+w(k-lower_bound)
Here,
A is the array
k is the index of the element to calculate the address
BA is the base address of the array A
w is the word size of one element in memory
lower_bound is the index of the first element in the array
Example
Given an array int marks[ ] = {99,67,78,56,88,90,34,85}. Calculate the address of marks[4] if base
address = 1000.
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
4
Principles of Programming using C BPOPS203
lower_bound is the index of the first element in the array
• Usually, “lower_bound” is zero.
Example
Show the memory representation of the array and calculate its length.
Memory representation of the array Age is as given
2 5 3 1 7
Age[0] Age[1] Age[2] Age[3] Age[4]
• When an array is declared, allocate space for the elements but no values are stored in the array.
• There are three ways to store 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.
Initialize the elements
during declaration
Assign values to
individual elements
marks[0] is assigned with the value 90. Similarly, the second element of the array, that is, marks[1] is
assigned 82, and so on.
5
Principles of Programming using C BPOPS203
• While initializing the array at the time of declaration, the size of the array may be omitted. For
example,
int marks[] = {98,97,90};
The compiler will allocate enough space for all initialized elements.
• If the number of values provided is less than the number of elements in the array, the un-assigned
elements are filled with zeros.
• Below figure illustrates initialization of arrays.
int marks[5] = {90,45,67,85,78};
90 45 67 85 78
[0] [1] [2] [3] [4]
int marks[]={90,45,72,81,63,54};
90 45 72 81 63 54
[0] [1] [2] [3] [4] [5]
Operations on Arrays
• 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
• Traversing an array means accessing each and every element of the array for a specific purpose.
Example
Write a program to read and display n numbers using an array.
#include<stdio.h>
#include<conio.h>
int main()
{
int i=0,n,arr[20];
clrscr();
printf(“\nEnter the number of elements:”);
scanf(“%d”,&n);
printf(“\nEnter the elements”);
for(i=0;i<n;i++)
{
printf(“\nArr[%d]=”,i);
scanf(“%d”,&arr[i]);
}
printf(“\nThe array elements are\n”);
for(i=0;i<n;i++)
printf(“Arr[%d]=%d\t”,i,arr[i]);
return 0;
}
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
7
Principles of Programming using C BPOPS203
Example
#include<stdio.h>
#include<conio.h>
int main()
{
int i,n,num,pos,arr[10];
clrscr();
printf(“\nEnter the number of elements in the array:”);
scanf(“%d”,&n);
printf(“\nEnter the values:”);
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
printf(“\nEnter the number to be inserted:”);
scanf(“%d”,&num);
printf(“\nEnter 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];
arr[pos]=num;
n++;
printf(“\nThe array after insertion of %d is:”,num);
for(i=0;i<n;i++)
printf(“\t%d”,arr[i]);
getch();
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
8
Principles of Programming using C BPOPS203
Example
#include<stdio.h>
#include<conio.h>
int main()
{
int i,n,pos,arr[10];
clrscr();
printf(“\nEnter the size of the array:”);
scanf(“%d”,&n);
printf(“\nEnter the elements of the array:”);
for(i=0;i<n;i++)
scanf(“%d”,&arr[i]);
printf(“\nEnter 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(“\nThe array after deletion is:”);
for(i=0;i<n;i++)
printf(“\nArr[%d]=%d”,i,arr[i]);
getch();
return 0;
}
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]=4
Arr[4]=5
#include<stdio.h>
#include<conio.h>
int main()
{
int arr1[10],arr2[10],arr3[20];
int i,n1,n2,m,index=0;
9
Principles of Programming using C BPOPS203
clrscr();
printf(“\nEnter the number of elements in array 1:”);
scanf(“%d”,&n1);
printf(“\nEnter the elements of the first array”);
for(i=0;i<n1;i++)
scanf(“%d”,&arr1[i]);
printf(“\nEnter the number of elements in array 2:”);
scanf(“%d”,&n2);
printf(“\nEnter 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\nThe merged array is”);
for(i=0;i<m;i++)
printf(“\tArr[%d]=%d”,I,arr3[i]);
getch();
return 0;
}
Output
Enter the number of elements in array 1:3
Enter the elements of the first array
10 20 30
Enter the number of elements in array 2:3
Enter the elements of the second array
15 25 35
The merged array is
Arr[0]=10 Arr[1]=20 Arr[2]=30
Arr[3]=15 Arr[4]=25 Arr[5]=35
• There are two popular methods for searching the array elements: Linear Search and Binary Search.
Linear Search
• It is also called sequential search.
• It 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.
Example
Binary Search
• Binary search is a searching algorithm that works efficiently with a sorted list.
11
Principles of Programming using C BPOPS203
#include<stdio.h>
#include<conio.h>
int main()
{
int arr[10],num,I,n,pos=-1,beg,end,mid,found=0;
clrscr();
printf(“\nEnter the number of elements in the array:”);
scanf(“%d”,&n);
printf(“\nEnter the elements:”);
for(i=0;i<n;i++)
{
scanf(“%d”,&arr[i]);
}
printf(“\nEnter the number that has to be searched:”);
scanf(“%d”,&num);
beg=0,end=n-1;
while(beg<end)
{
mid=(beg+end)/2;
if(arr[mid]==num)
{
printf(“\n%d is present in the array at position=%d”,num,mid);
found=1;
break;
}
else if(arr[mid]>num)
end=mid-1;
else
beg=mid+1;
}
if(beg>end && found==0)
printf(“\n%d does not exist in the array”,num);
getch();
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
12
Principles of Programming using C BPOPS203
One-dimensional arrays
for inter-function
communication
Passing individual
elements Passing an entire array
Passing Addresses
• Pass the address of an individual array element by preceding the indexed array element with the
address operator(&).
• To pass the address of the fourth element of the array “arr” to the called function, it is denoted
&arr[3].
13
Principles of Programming using C BPOPS203
Example
main() //Calling function
{
int arr[5]={1,2,3,4,5};
func(arr[3]);
}
void func(int *num) //Called function
{
printf(“%d”,*num);
}
Passing address of individual array elements to function
14
Principles of Programming using C BPOPS203
for(i=0;i<n;i++)
{
printf(“%d\n”,a[i]);
}
15
Principles of Programming using C BPOPS203
16
Principles of Programming using C BPOPS203
Ex: int a[10][10]; //Two-dimensional array
int b[3][4][5]; //Three-dimensional array
✓ The size used during declaration of the array is useful to reserve the specified memory
locations.
✓ The array ‘a’ is a 2-dimensional array with 2 rows and 4 columns. This declaration informs
the compiler to reserve 8 locations (2*4=8 locations, 2*8=16 bytes in total) continuously one
after the other.
data_type array_name[row_size][col_size]={
{a1,a2, ---- ,an},
{b1,b2, ---- ,bn},
..…………...,
{z1,z2, ---- ,zn}
};
17
Principles of Programming using C BPOPS203
Columns
0 1 2
0 11 22 33
1
44 55 66
Rows 2
3 77 88 99
10 20 30
2. int a[4][3]= {
{11,22},
{33,4},
{55,66},
{77,88}
};
The array has 4 rows and 3 columns.
Columns
0 1 2
0 11 22 0
1 //This is a partial array initialization
33 44 0
Rows 2
3 55 66 0
77 88 0
✓ 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”);
}
18
Principles of Programming using C BPOPS203
Example Programs:
1. 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++)
{
for(j=0;j<n;j++) Output:
{ Enter the number of Rows and
scanf(“%d”,&a[i][j]); Columns of the Array:
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”);
}
}
2. Write a C program to add 2 matrices A and B and store sum in C.
#include<stdio.h>
void main( )
{
int a[10][10],b[10][10],c[10][10],i,j,m,n;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”); Output:
for(i=0;i<m;i++) Enter the size of matrix:
{ 2 2
for(j=0;j<n;j++) Enter the elements of Matrix A:
{ 1 2
scanf(“%d”,&a[i][j]); 3 4
} Enter the elements of Matrix B:
} 5 6
printf(“Enter the elements of Matrix B:\n”); 7 8
for(i=0;i<m;i++) The Resultant Matrix C is:
{
6 8
for(j=0;j<n;j++)
{ 10 12
scanf(“%d”,&b[i][j]);
}
}
19
Principles of Programming using C BPOPS203
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
}
}
printf(“The Resultant Matrix C is:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
}
3. Write a C program to find the largest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n,big=-1;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
Output:
}
Enter the size of matrix:
for(i=0;i<m;i++)
2 2
{
Enter the elements of Matrix A:
for(j=0;j<n;j++)
10 20
{
30 40
if(a[i][j]>big)
{ The largest element is: 40
big=a[i][j];
}
}
}
printf(“The largest element is:%d\n”,big);
}
20
Principles of Programming using C BPOPS203
4. Write a C program to find the smallest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
{
int a[10][10],i,j,m,n,small=9999;
printf(“Enter the size of matrix:\n”);
scanf(“%d%d”,&m,&n);
printf(“Enter the elements of Matrix A:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:
{ Enter the size of matrix:
2 2
scanf(“%d”,&a[i][j]);
Enter the elements of Matrix A:
} 10 20
} 30 40
for(i=0;i<m;i++) The largest element is: 10
{
for(j=0;j<n;j++)
{
if(a[i][j]<small)
{
small=a[i][j];
}
}
}
printf(“The smallest element is:%d\n”,small);
}
Example
147
258
789
Passing a Row
• A row of a two-dimensional array can be passed by indexing the array name with the row number.
• When a single row of a two-dimensional array is sent, then the called function receives a one-
dimensional array.
• Below figure how a single row of a two-dimensional array is passed to the called function.
main() //Calling function
{
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);
}
Passing a single row of a 2D array
Example
Multidimensional Arrays
Three-dimensional array
24
Principles of Programming using C BPOPS203
• The array has three pages, four rows, and two columns.
• A multidimensional array is declared and initialized similar to one- and two-dimensional arrays.
Example
Write a program to read and display a 2 X 2 X 2 array.
#include<stdio.h>
#include<conio.h>
int main()
{
int array[2][2][2], i, j, k;
clrscr();
printf(“\nEnter 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(“\nThe 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(“\tarr[%d][%d][%d]=%d”,i,j,k,array[i][j][k]);
}
}
getch();
return 0;
}
Output
Enter the elements of the matrix
12345678
The matrix is:
arr[0][0][0] = 1 arr[0][0][1] = 2
arr[0][1][0] = 3 arr[0][1][1] = 4
arr[1][0][0] = 5 arr[1][0][1] = 6
arr[1][1][0] = 7 arr[1][1][1] = 8
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.
• Arrays can be used for sorting elements in ascending or descending order.
25