Module 3
Module 3
MODULE-III
ARRAYS
3.1 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
m
A[1] 20
A[2] 30
A[3] 40
A[4] 50
co
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’.
e.
2. char B[5]; //Array of 5 Characters
B[0] ‘A’
dg
B[1] ‘r’
B[2] ‘r’
B[3] ‘a’
B[4] ‘y’
3. float C[5]; //Array of 5 floats
ue
C[0] 12.56
C[1] 234.20
C[2] 215.60
C[3] 322.50
vt
C[4] 123.45
m
contiguously in memory locations one after the other.
Or
An array with one index is called as Single dimensional array (One-dimensional
array)
co
Declaration of Single dimensional 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
e.
data_type array_name[size];
Where,
data_type: data type can be int, float, char etc.
dg
1000 35 Marks[0]
data type array_name 1002 45 Marks[1]
vt
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.
m
Ex: 1. int a[5] = {10, 20, 30, 40, 50};
The compiler allocates 5 memory locations and these locations are initialized with the integer
values in the order specified.
co
a[0] 10
a[1] 20
a[2] 30
a[3]
40
a[4]
50
2. int a[5] = {10, 20};
e.
10 20 0 0 0
dg
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’.
ue
A r r a y \0
a[0] a[1] a[2] a[3] a[4] a[5]
m
C code or C instruction to display/write ‘n’ elements of an array is shown below:
for(i=0;i<n;i++)
{
co
printf(“%d\n”,a[i]);
}
m
printf(“Enter the array elements:\n”); Enter the array elements:
for(i=0;i<n;i++) 10
{ 20
scanf(“%d”,&a[i]); 30
co
} 40
for(i=0;i<n;i++) 50
{ The largest number in the
if(a[i]>large) array is= 50
{
large=a[i];
e.
}
}
printf(“The largest number in the array is=%d\n”,large);
}
dg
scanf(“%d”,&n); 5
printf(“Enter the array elements:\n”); Enter the array elements:
for(i=0;i<n;i++) 10
{ 20
scanf(“%d”,&a[i]); 30
}
vt
40
for(i=0;i<n;i++) 50
if(a[i]<small) The largest number in the
{ array is= 10
small=a[i];
}
printf(“The smallest number in the array is=%d”,small);
}
3.2.2 Two dimensional arrays (Multi-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).
m
col_size: It is the number of columns in the array.
Semicolon is must at the end.
The size used during declaration of the array is useful to reserve the specified memory
co
locations.
data_type array_name[row_size][col_size]={
{a1,a2, ---- ,an},
vt
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}
m
};
The array has 4 rows and 3 columns.
Columns
co
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
e.
Reading/Writing Two dimensional arrays
To read the 2-dimensional array, we have to use two for loops along with scanf(), where the
dg
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++)
ue
{
for(j=0;j<n;j++)
{
scanf(“%d”,&a[i][j]);
}
}
vt
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”);
}
m
{ Enter the number of Rows and
scanf(“%d”,&a[i][j]); Columns of the Array:
2 2
}
Enter the Array elements:
} 1
co
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
e. 3 4
printf(“%d\t”,a[i][j]);
}
}
dg
printf(“\n”);
}
}
ue
vt
m
} 2 2
printf(“Enter the elements of Matrix B:\n”); Enter the elements of Matrix A:
for(i=0;i<m;i++) 1 2
{ 3 4
co
for(j=0;j<n;j++) Enter the elements of Matrix B:
{ 5 6
scanf(“%d”,&b[i][j]); 7 8
} The Resultant Matrix C is:
} 6 8
for(i=0;i<m;i++)
e. 10 12
{
for(j=0;j<n;j++)
{
c[i][j]=a[i][j]+b[i][j];
dg
}
}
printf(“The Resultant Matrix C is:\n”);
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
ue
{
printf(“%d\t”,c[i][j]);
}
printf(“\n”);
}
vt
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]);
m
4. Write a C program to find the smallest of ‘n’ array elements in a 2-Dimensional array.
#include<stdio.h>
void main( )
co
{
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”);
e.
for(i=0;i<m;i++)
{
for(j=0;j<n;j++) Output:
dg
{ 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
{
ue
for(j=0;j<n;j++)
{
if(a[i][j]<small)
{
vt
small=a[i][j];
}
}
}
printf(“The smallest element is:%d\n”,small);
}
m
co
e.
dg
ue
vt
m
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
co
once but it can be used any number of times.
v. Easy to do the modifications.
Types of Functions
i. Library Functions/Pre-Defined/ Built-in Functions
e.
✔ C Library of C Compiler has a collection of various functions which perform some standard
and pre-defined tasks.
✔ These functions written by designers of C Compilers are called as Library
functions/Pre-Defined/Built-in functions.
dg
Example: in the above program main() function invokes sqrt() function, the function main() is
calling function and function sqrt() is called function.
m
✔ main( ) is the user defined function.
co
i. Function Prototype/Declaration
ii. Function Definition
iii. Function Call
e.
Function Prototype/Declaration
✔ As we normally declare the variables before they are used, the functions also should be
declared before they are used.
✔ The process of declaring the functions before they are used (or called) in the program is
dg
Where,
return_type: This is the data type of the value that the function is expected to return (int, float,
double, char).
vt
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_type function_name (parameter list)
{
declaration part;
executable part;
return statement;
m
}
return_type:
✔ This is the data type of the value that the function is expected to return (int, float, double,
char).
co
✔ 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:
e.
✔ The parameters are the list of variables enclosed within parenthesis. Variables are separated
by comma.
Data type of parameters
dg
Parameter name
return type Function name
Function Body
ue
✔ Declaration part: All the variables used in the function body should be declared in this part.
✔ Executable par: This part contains the statements or instructions that perform the specified
activity.
✔ return statement: It is a keyword used to return the control to the calling function (main)
with/without a value.
vt
Syntax:
1.
// Returns control without sending any value to main program
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.
m
Example: add(m,n);
Example Program: Write a C program to perform the addition of two numbers using function
co
#include<stdio.h>
int add(int a,int b); /*Function Prototype*/
int add(int a,int b)
{
int sum;
sum=a+b;
e.
return sum;
}
void main()
dg
{
int result;
result=add(10,20);
printf(“sum=%d\n”,result);
getch();
ue
variables a and b.
3. The result is computed by adding 10 and 20.
4. The result is returned to the main() and will be copied into the variable result.
5. The result is displayed on the screen.
Function Parameters
✔ “The list of variables defined in the function header within the parenthesis are called
Function parameters”.
✔ There are 2 types of parameters in ‘C’ functions.
i. Actual parameters
ii. Formal parameters
m
receive them and use the same values.
✔ Actual parameters can be constants, variables or expressions.
Ex: res = add (m, n);
co
ii. Formal or Dummy Parameters
✔ The variables defined in the function header or function definition are called formal
parameters.
✔ All the variables should be separately declared and each declaration must be separated by
commas.
e.
✔ The formal parameters receive values form the actual parameters.
✔ If the formal parameters receive the address from the actual parameters, then they should be
declared as pointers.
dg
✔ The formal parameters should be only variables. Expressions and constants are not allowed.
Ex: int add(int a,int b);
return sum;
}
void main()
{
int m,n,res;
printf(“Enter the values for m,n\n”);
scanf(“%d%d”,&m,&n);
res=add(m,n); // Actual parameters m,n
printf(“Sum=%d\n”,res);
}
Location of Functions
✔ The placement of the function definition in relation to the main program is very important.
✔ There are a number of ways to arrange the main program and a function.
m
Syntax file method1.c
co
e.
✔ File method1.c contains a function followed by a main program.
Example Program
dg
#include<stdio.h>
#include<conio.h>
int add(int a,int b);
{
int sum;
sum=a+b;
return sum;
}
vt
void main()
{
int m,n,res;
printf(“Enter the values for m,n:\n”);
scanf(“%d%d”,&m,&n);
res=add(m,n);
printf(“add(%d,%d)=%d\n”,m,n,res);
getch();
}
m
✔ File method2.c contains a main program followed by a function.
co
Example Program
#include<stdio.h>
int add(int a,int b);
e.
void main()
{
int m,n,res;
dg
int sum;
sum=a+b;
return sum;
}
iii. Functions in Separate files (Separate Compilation)
✔ In this method, immediately after #includes and #defines we write all function prototypes.
✔ Next, we write the main function.
✔ All user function definitions will be in separate files.
✔ It puts the function in one file and the main program in another and compiles them separately.
separate file
✔ Here the file method3.c contains a main program and also a separate file.
✔ The file method4.c is a separate file containing a function and it performs some specific tasks
m
and returns the value or result to the main program in a file ‘method3.c’. i.e., a separate file.
Example Program
co
#include<stdio.h> main.c int add(int a,int b) add.c
#include<conio.h> {
int add(int a,int b); int sum;
sum=a+b;
void main() return sum;
e.
{ }
int m,n,res;
printf(“Enter the values for m,n:\n”);
dg
scanf(“%d%d”,&m,&n);
res=add(m,n);
printf(“add(%d,%d)=%d\n”,m,n,res);
}
ue
Categories of Functions
✔ Based on the parameters and return value, the functions have been classified into four categories.
vt
1. void and parameter less functions (Functions with no parameters and no return values)
2. non void and parameter less functions(Functions with no parameters and return values)
3. void with parameters functions (Functions with parameters and no return values)
4. non void with parameters functions (Functions with parameters and return values)
m
sum=a+b;
} printf(“Sum=%d”,sum);
/*No return value*/
}
co
2. non void and parameter less functions (Functions with no parameters and return values)
✔ In this category there is no data transfer from the calling function and the called function.
✔ But, there is data transfer from the called function to the calling function.
e.
✔ When the function returns a value, the calling function receives one value from the called
function.
dg
✔ We can write a function that has no parameters but returns an answer to the main program as
shown in the syntax.
Example: Program showing function call without parameters, with return value.
#include<stdio.h>
ue
int add()
void main() {
{ int res; int a=10, b= 20,sum;
res= add();
printf(“Sum=%d”,res); sum=a+b;
vt
} return sum;
}
3. void with parameters functions (Functions with parameters and no return values)
✔ In this category, there is a data transfer from the calling function to the called function using
parameters.
✔ But, there is no data transfer from the called function to the calling function
m
4. non void with parameters functions (Functions with parameters and return values)
✔ In this category, there is data transfer between the calling function and the called function.
✔ When parameters are passed, the called function can receive values from the calling function.
co
✔ When the function returns a value, the calling function can receive a value from the called
function.
Example: Program showing a function call with parameters and with returns value.
e.
#include<stdio.h>
void add(int m, int n)
void main() {
dg
{
int a=10, b=20, res; int sum;
res=add(a,b);
printf(“Sum=%d”, res); sum= m + n;
} return sum;
ue
m
printf(“result = %d \n”, res);
}
co
✔ 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
e.
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.
dg
✔ 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>
ue
void add (int *a, int *b) // Formal parameters *a = 10, *b =20
{
int sum;
sum = *a + *b;
return sum;
vt
}
void main()
{
int m=10,n=20, res;
res = add(&m, &n); // Actual parameter m=10, n =20
printf(“result = %d \n”, res);
}
m
swap(&m,&n);
printf(“m=%d\n n=%d\n”,m,n);
}
co
Using Arrays with Functions
The arrays can be passed to functions using two methods:
i. Passing individual elements of the array
ii. Passing the whole array
e.
1. Passing individual elements of the array
✔ All array elements can be passed as individual elements to a function like any other variable.
Example program: Write a C program to print square of given array elements.
#include<stdio.h>
dg
void print_square(int x)
{
printf(“%d”, x*x);
}
void main()
ue
{
int n,a[10],i;
printf(“Enter the number of elements:”);
scanf(“%d”,&n);
printf(“\nEnter the array elements:\n”);
vt
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
printf(“Squares of array elements are:\n);
for(i=0;i<n;i++)
{
print_square(a[i]); //Passing each individual element of the array to the function
}
}
Example Program: Write a C program to read the array elements using functions.
#include<stdio.h>
m
void read_array(int a[ ], int n) // no need to specify the size of the array
{
int i;
co
for(i=0;i<n;i++)
{
scanf(“%d”,&a[i]);
}
e.
}
void main()
{
dg
int n,b[10],i;
printf(“Enter the number of elements:”);
scanf(“%d”,&n);
printf(“\nEnter the array elements:\n”);
ue
read_array (b, n); // function must be called by passing only the name of the array
printf(“The array elements are:\n);
for(i=0; i<n; i++)
{
vt
printf(“%d”, b[i]);
}
}
{ {
m
recursion ( ); recursion ( );
} }
co
#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
e.
else
return (n*fact(n-1));
}
dg
void main()
{
int n,fact;
printf(“Enter a number=”);
scanf(“%d”,&n);
ue
fact=factorial(n);
printf(“\nFactorial of given number=%d”,fact);
}
#include<stdio.h>
int factorial(int n)
{
if(n==1)
return 1;
else
return (n*fact(n-1));
}
void main()
{
int n,fact;
printf(“Enter a value for n and r”);
scanf(“%d”,&n);
Dept.of CS&E-BIET, DVG 14
Principles of Programming using C 22POP13
fact=factorial(n) / (factorial(n-r) * factorial(n));
printf(“\n nCr value =%d”,fact);
}
m
else
return ( fibonacci (n-1) * fibonacci (n-2));
}
co
void main()
{
int n, i, result;
printf(“Enter a value for n ”);
scanf(“%d”, &n);
e.
printf(“ The Fibonacci series is: \n”);
for ( i =0; i < n ; i ++)
{
res = fibonacci (i);
dg
printf(“%d\n”, res);
}
}
ue
vt
ASSIGNMENT QUESTIONS
m
6. Define recursion? Explain the recursion with example.
7. Write a program to calculate nCr value using recursion.
co
8. Write a program to print the Fibonacci series using recursion.