SlideShare una empresa de Scribd logo
1 de 35
Editor: DEBASIS DWIBEDY
ARRAYS in C
Debasis Dwibedy
Assistant Professor*
Dept. CSE, VSSUT, Burla
*Personal Web Site: www.sites.google.com/view/debasis-dwibedy
Editor: DEBASIS DWIBEDY
What is an Array
An array is a fixed-size sequenced collection of related data items
of same type sharing a common name.
An array is a derived data type that holds a list of items of same
type.
Unlike the fundamental data types int, char, float, that holds only
one value, an array holds a list of values in contiguous memory
locations.
Example 1: int arr [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* Array of first 10 natural numbers */
Example 2: float r [5] = {10.8, 9.6, 8.4, 11.5, 12.6}; /* Array of rate of interest of 5 banks */
Example 3: char name [8] = {‘D’, ‘E’, ‘B’, ‘A’, ‘S’, ‘I’, ‘S’, ‘0’} ; /* Array of characters*/
Editor: DEBASIS DWIBEDY
Types of Arrays
We can use arrays to represent not only simple lists of values but
also tables of data in two or three or more dimensions.
Accordingly, we have following types of arrays.
One –dimensional arrays
Two –dimensional arrays
Multi –dimensional arrays
A list of same type items can be given one variable name
using only one subscript, also known as the row-wise
representation of data. Eg: int arr [10] ;
A table of items can be given one variable name using two
subscripts, also known as the row and column wise
representation of data. Eg: int arr [3][3] ;
C allows arrays of three or more dimensions. The exact
limit is determined by the compiler. Eg: int arr [3][5][12] ;
Editor: DEBASIS DWIBEDY
One-Dimensional Arrays
Editor: DEBASIS DWIBEDY
Variable vs. Array
Variable Array
Declaration
data_type variable_name;
Eg. int mark ;
Memory Representation
mark
Declaration
data_type array_name [size] ;
Eg. int mark [5] ;
Memory Representation (column-measure order)
0
1
2
3
4
mark
mark[0]
mark[1]
mark[2]
mark[3]
mark[4]
1000
1002
1004
1006
1008
Real Memory Addresses
Base Address
Values at
Addresses
Array Name
Editor: DEBASIS DWIBEDY
Why to use an Array Type
Let’s consider that we need to store and print
a list of 1000 students' marks of an integer
type.
int main(void)
{
/* How long is the declaration and how many variables
used */
int studMark1, studMark2, studMark3, studMark4, …,
…, studMark998, stuMark999, studMark1000;
…
…
return 0;
}
We have to use 1000 variables of integer type to store and
print the marks. (that many variables are hard to remember)
Editor: DEBASIS DWIBEDY
Initialization of an Array
Method 1
/* Declaration*/
int mark[5];
/*Initialization*/
mark[0]=40;
mark[1]=45;
mark[2]=50;
mark[3]=35;
mark[4]=42;
Method 2
/* Declaration and
initialization*/
int mark[5]={40,45,50,35,42};
Method 3
/* Declaration and
initialization*/
int mark []={40,45,50,35,42} ;
Method 4
/* Declaration */
int mark [5], i ;
/* Initialization */
printf (“Enter 5 marks”) ;
for (i = 0 ; i < 5 ; i++)
{
scanf(“%d”, &mark[i]) ;
}
Not recommendable to omit
the size of the array, while
declaration and initialization
take place at the same time.
Editor: DEBASIS DWIBEDY
Character Array and String
/* Declaration and initialization*/
char name[9]={‘w’, ‘E’, ‘L’, ‘ ’, ‘C’, ‘O’, ‘M’, ‘E’, ‘0’};
‘W’
‘E’
‘L’
‘ ’
‘C’
‘O’
‘M’
‘E’
‘0’
0
1
2
3
4
5
6
7
8
/* Declaration and initialization*/
char name[9]={“WEL COME”};
Rule: The size of a character
array must be one more than
the number of characters to
be stored in memory or to be
displayed on the console. The
extra space is required to
store the “o” character to tell
the compiler explicitly about
the end of the array.
Editor: DEBASIS DWIBEDY
Array Initialization Tips
Error 1
/* Initializers are more than the
declared size*/
int mark[3]={40,45,50,35,42};
If we have more initializers, than the
declared size of the array, then the
compiler generates an error.
No Error
/* Initializers are less than the
declared size*/
int mark[5]={40,45,50};
If we have less initializers, than the
declared size of the array, then the
compiler does not generate an error
and allocates 0s to the vacant
locations of the integer array and ‘0’
to the character array.
No Error
/* Any reference to the array
outside the declared limit*/
int mark[5]={40,45,50, 35, 42};
printf(“%d”, mark[6]);
It would not cause an error, it outputs
a garbage value.
Editor: DEBASIS DWIBEDY
Run-Time Initialization of Array
Any array can also be initialized at run time explicitly. This
approach is useful for large arrays.
Example
/* Declaration */
int mark[100], i ;
/* Initialization */
for(i=0; i<100; i++)
{
if (i < 50)
mark[i]=45;
else
mark[i]=90;
}
Editor: DEBASIS DWIBEDY
Skeleton of a Program
Basic structure of a program that uses arrays.
#include<stdio.h>
void main()
{
/* Declaration of array and variables */
Declaration statements;
/* Initialization of array and variables */
Initialization statements;
/* Program Logic */
Logic statements;
/* Print the result */
Using for loops to print the array elements;
}
Editor: DEBASIS DWIBEDY
Program-1
W.A.P to display the sum of squares of any 10 real numbers.
#include<stdio.h>
void main()
{
/* Declaration */
int i ;
float arr[10], value, total=0.0 ;
/* Initialization of the Array*/
printf(“Enter values to the array”);
for(i = 0; i < 10; i++)
{
scanf(“%f”, &value);
arr[i] = value;
}
/* Print the Result*/
printf(“n total = %f”, total);
}
/* Computation of Total*/
for(i = 0; i < 10; i++)
{
total = total + arr[i] * arr[i];
}
Editor: DEBASIS DWIBEDY
Program-2
W.A.P that interchanges the odd and even positioned elements of an
array.
#include<stdio.h>
void main()
{
/* Logic*/
for (i = 0 ; i < n ; i = i+2)
{
t = num [i] ;
num [i] = num [i+1] ;
num [i+1] = t ;
}
/ * Print the Resultant Array * /
for ( i = 0 ; i < n ; i++ )
{
printf( “ %d”, num [i] ) ;
}
return 0 ;
}
/* Declaration */
int num[], i, n, t ;
/* Initialization of the Array*/
printf (“Enter size of the arrayn”) ;
scanf(“%d”, &n) ;
printf(“Enter elementsn”);
for(i = 0 ; i < n ; i++)
{
scanf(“%d”, &num[i]) ;
}
Editor: DEBASIS DWIBEDY
Program-3
Enter 5 students marks and display the percentage obtained by
each student as output.
#include<stdio.h>
void main()
{
/* Declaration */
int std[5], m1, m2, m3, m4, m5, i ;
/* Logic */
for(i=0; i<5; i++)
{
printf(“Enter marks of 5 subjects
of student %d”, i);
scanf(“%d%d%d%d%d”, &m1,
&m2, &m3, &m4, &m5);
std[i]=(m1+m2+m3+m4+m5)/5;
}
/* Print Results*/
for(i=0; i<5; i++)
{
printf(“%d”, std[i]);
}
}
Editor: DEBASIS DWIBEDY
Program-4
Enter 5 students marks into an array and sort the marks in an
ascending order.
Logic Execution of Iteration 1
for(i = 0 ; i < 5 ; i++)
{
j = i ;
for (k = i+1 ; k < 5 ; k++)
{
if (std [k] < std [i])
{
j = k ;
/* Swap the values of std [i] and std [j] */
temp = std [i] ;
std [i] = std [j] ;
std [j] = temp;
}
}
40 35 50 20 10
i, j k
40 35 50 20 10
k, j
i
35 40 50 20 10
i j k
35 40 50 20 10
i j k
35 40 50 20 10
k, j
i
Editor: DEBASIS DWIBEDY
Execution Continues
20 40 50 35 10
i j k
20 40 50 35 10
k, j
i
10 40 50 35 20
i j k
10 40 50 35 20
i j k
Termination of Iteration- 1 of outer For loop
Execution of Iteration 2
10 40 50 35 20
i, j k
Editor: DEBASIS DWIBEDY
Program-4 (Code)
Enter 5 students marks into an array and sort the marks in an
ascending order.
#include<stdio.h>
void main()
{
/* Declaration */
int std [5] = {40, 35, 50, 20, 10} ;
int i, j, k, temp ;
/* Logic */
for(i = 0 ; i < 5 ; i++)
{
j = i ;
for (k = i+1 ; k < 5 ; k++)
{
if (std [k] < std [i])
{
j = k ;
temp = std [i] ;
std [i] = std [j] ;
std [j] = temp;
}
}
/* Print the sorted Array*/
for(i = 0 ; i < 5 ; i++)
{
printf(“%dn”, std[i]);
}
}
Editor: DEBASIS DWIBEDY
Program-5
Given an array of n integers. W.A.P to find whether a number is
present in the array, if present, then print its position in the array.
#include<stdio.h>
int main()
{
/* Declaration */
int arr [], n, i, key ;
/* To know size of the Array */
printf(“Enter the number of
elements in the arrayn”) ;
scanf(“%d”, &n);
/* Initialization of the Array */
printf(“Enter %d numbersn”, n) ;
for (i = 0 ; i < n ; i++)
scanf(“%d”, &arr[i]);
/* Search Logic */
printf(“Enter the number to searchn”);
scanf(“%d”, &key);
for (i = 0 ; i < n ; i++ )
{
if (arr [i] = = key)
{
printf(“%d is present at position
%d n”, key, i+1);
break; } }
if (i = = n) {
printf (“%d is not present in the array”,
key);
return 0;
}
Editor: DEBASIS DWIBEDY
Program-6
W.A.P to copy the contents of one array of size 5 into another in the
reverse order.
#include<stdio.h>
void main()
{
/* Logic*/
for (i = 0, j = 4 ; i < 5 ; i++, j--)
{
arr2 [j] = arr1 [i] ;
}
/ * Print the Resultant Array * /
for ( i = 0 ; i < 5 ; i++ )
{
printf( “ n%d”, arr2 [i] ) ;
}
return 0 ;
}
/* Declaration */
int arr1[5], arr2 [5], i, j ;
/* Initialization of the Array 1*/
printf(“Enter 5 elements into array
n”);
for(i = 0 ; i < 5 ; i++)
{
scanf(“%d”, &arr1[i]) ;
}
Editor: DEBASIS DWIBEDY
Assignments
1. W.A.P to find the smallest and largest number in an array of n integers.
2. W.A.P to sort an array of n positive integers in descending order.
3. W.A.P to find the occurance of 1, 2, 3 in an array of following items
1, 2, 2, 3, 3, 2, 2, 1, 2, 1, 1, 1, 3, 2, 3, 3, 1, 2, 3, 1, 2, 3, 1.
4. W.A.P to find the mean and standard deviation of an array of n positive
integers.
5. Given are two one-dimensional arrays A and B which are sorted in
ascending order. W. A. P. to merge them into a single sorted array C that
contains every items from array A and B in ascending order.
6. Given an array of n positive integers. W.A.P to reverse the array elements.
Editor: DEBASIS DWIBEDY
Two-Dimensional Arrays
Editor: DEBASIS DWIBEDY
Definition
A 2-dimensional array represents a table of data in rows and columns
A table of items can be given one variable name using two subscripts
Eg: int m [5][5] ;
A 2-dimensional array is also called a matrix.
A 2-dimensional array is an amalgamation of several 1-D arrays.
Editor: DEBASIS DWIBEDY
Why to use a 2-D Array
Let’s consider that we need to store and print
the marks of 5 students in 5 subjects.
int main(void)
{
/* How long is the declaration and how many arrays are
used */
int std_1[5], std_2[5], std_3[5], std_4[5], std_5[5];
…
…
return 0;
}
We have to use 5 one-dimensional arrays of integer type with
5 rows to store 5 subjects marks of each students. (that many
arrays are hard to remember and maintain for a large program)
Editor: DEBASIS DWIBEDY
Why to use a 2-D Array
Can a single array be used to store and
display the marks of all 5 students ?
Yes, by a 2-D Array
Advantages
1. Number of 1-D array declarations can be reduced significantly.
2. It is convenient to remember and maintain a minimum number
of arrays.
Editor: DEBASIS DWIBEDY
Declaration
/* Declaration */
data_type array_name [row_size][column_size];
/* Example*/
int m [3][5] ; /* the compiler allocates 30 Bytes in contiguous memory locations */
Row 0
Row 1
Row 2
m[0][0] m[0][1] m[0][2] m[0][3] m[0][4]
m[1][0] m[1][1] m[1][2] m[1][3] m[1][4]
m[2][0] m[2][1] m[2][2] m[2][3] m[2][4]
0
1
2
0 1 2 3 4
Logical Representation of a 2-D Array
Accessing a 2-D array element by: array_name [row i][column j]
/* Example*/
printf ( “%d”, m [1][4] ) ; /* it will print value at location 2nd row and 5th column
Tabular
Form
Editor: DEBASIS DWIBEDY
Memory Layout
Lets consider the following 2-D array
Eg: int m [3][3] ;
How a 2-dimensional array is stored in the memory?
m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2]
Row 0 Row 1 Row 2
1000 1002 1004 1006 1008 1010 1012 1014 1016
Row-measure Representation of 2-D Array in Memory
printf(“The size of the array is %d Bytes”, sizeof(m)); /* The size of the array is 18 Bytes */
printf(“%u%u%u”, m+0, m+1, m+2)); /* 1000 1006 1012 */
Editor: DEBASIS DWIBEDY
Initialization
Method 1
/* Declaration*/
int m [2][2];
/*Initialization*/
m[0][0] = 40 ;
m[0][1] = 45 ;
m[1][0] = 50 ;
m[1][1] = 35 ;
Method 2
/* Declaration and
initialization*/
int m[2][2] = {
{40,45}, {50,35}
} ;
Method 3
/* Declaration and
initialization*/
int m[][2] = {
40, 45, 50, 35
} ;
Method 4
/* Declaration */
int m[2][2], i, j ;
/* Initialization */
printf (“Enter marks”) ;
for (i = 0 ; i < 2 ; i++)
{
for (j = 0 ; j < 2 ; j++)
scanf(“%d”, &m[i][j] );
}
Row size is optional, braces for
individual row is also optional,
but column size is compulsory
in the declaration and
initialization of a 2-D array.
Editor: DEBASIS DWIBEDY
Program-1
W.A.P to store and display 3 student marks of 3 different subjects.
#include<stdio.h>
void main()
{
/* Declaration */
int m[3][3], i, j ;
/* Store marks into m[3][3]*/
printf(“Enter marks of 3 studentsn”);
for(i = 0; i < 3; i++)
{
for (j = 0 ; j < 3 ; j++)
scanf(“%d”, &m[i][j]) ;
}
/* To know the size of the declared
m[3][3] */
printf (“%u”, sizeof(m) ) ;
/* Display the marks*/
for(i = 0 ; i < 3 ; i++)
{
for (j = 0 ; j < 3 ; j++)
{
printf(“%dt”, m[i][j]) ;
}
printf(“n”);
}
}
Editor: DEBASIS DWIBEDY
Program-2
W.A.P to print the largest number in a 2-D array and its position.
#include<stdio.h>
void main()
{
/* Logic*/
big = a[0][0], r = 0, c = 0 ;
for (i = 0 ; i < row_size ; i++)
{
for (j = 0 ; j < column_size ; j++)
{
if ( a[i][j] > big)
{
big = a[i][j];
r = i, c = j ; }
} }
/ * Print the Result * /
printf(“Largest=%d”, big ) ;
printf(The position of %d is %d th row
and %d th column”, big, r+1, c+1) ;
}
/* Declaration */
int a[][], i, j, big, row_size, column_size, r, c ;
/* Initialization of the Array a[][] */
printf (“Enter row and column sizen”) ;
scanf(“%d%d”, &row_size,
&column_size) ;
printf(“Enter elementsn”);
for(i = 0 ; i < row_size ; i++)
{
for (j = 0 ; j < column_size ; j++)
scanf(“%d”, &a[i][j]) ;
}
Editor: DEBASIS DWIBEDY
Transpose of a Matrix
Input Matrix
1
2
3
4
5
6
3 x 2
Interchanging the rows and columns
Resultant Matrix
1 2 3
4 5 6
2 x 3
/* Logic and print the resultant matrix*/
for (i = 0 ; i < column_size ; i++)
{
for (j = 0 ; j < row_size ; j++)
{
printf ( “ %dt”, a [j][i] ) ;
}
printf ( “ n” ) ;
}
Editor: DEBASIS DWIBEDY
Program-3
W.A.P to print the transpose of a matrix.
#include<stdio.h>
void main()
{
/* Logic and print the output array*/
for (i = 0 ; i < column_size ; i++)
{
for (j = 0 ; j < row_size ; j++)
{
printf ( “ %dt”, a [j][i] ) ;
}
printf ( “ n” ) ;
}
/* Declaration of 2-D Array and variables */
int a[][], i, j, row_size, column_size ;
/* Initialize and print the input items */
printf (“Enter row and column sizen”) ;
scanf(“%d%d”, &row_size,
&column_size) ;
printf(“Enter elementsn”);
for(i = 0 ; i < row_size ; i++)
{
for (j = 0 ; j < column_size ; j++)
scanf(“%d”, &a[i][j]) ;
printf( “ %d”, a[i][j] ) ;
Editor: DEBASIS DWIBEDY
Multiplication of two Matrices
Matrix m1
1
2
3
4
5
6
3 x 2
Resultant Matrix m3
1 2 3
4 5 6
2 x 3
/* Logic of matrix Multiplication */
for (i = 0 ; i < 3 ; i++)
{
for (j = 0 ; j < 3 ; j++)
{
sum = 0 ;
for ( k = 0; k < 2 ; k++ )
sum = sum + m1[i][k] * m2[k][j] ;
m3 [i][j] = sum ;
} }
X
Matrix m2
17 22 27
22 29 36
27 36 45
3 x 3
m3[0][0] = ( m1[0][0]* m2[0][0] ) + ( m1[0][1] * m2[1][0])
m3[0][1] = ( m1[0][0]* m2[0][1] ) + ( m1[0][1] * m2[1][1])
m3[0][2] = ( m1[0][0]* m2[0][2] ) + ( m1[0][1] * m2[1][2])
m3[1][0] = ( m1[1][0]* m2[0][0] ) + ( m1[1][1] * m2[1][0])
m3[1][1] = ( m1[1][0]* m2[0][1] ) + ( m1[1][1] * m2[1][1])
m3[1][2] = ( m1[1][0]* m2[0][2] ) + ( m1[1][1] * m2[1][2])
m3[2][0] = ( m1[2][0]* m2[0][0] ) + ( m1[2][1] * m2[1][0])
m3[2][1] = ( m1[2][0]* m2[0][1] ) + ( m1[2][1] * m2[1][1])
m3[2][2] = ( m1[2[0]* m2[0][2] ) + ( m1[2][1] * m2[1][2])
m X n n X p
m X p
i < m
j < p k < n
Editor: DEBASIS DWIBEDY
Program-4
W.A.P to show the multiplication of two 3 X 3 matrices.
#include<stdio.h>
void main()
{
/* Declaration of Arrays and variables */
int m1[3][3], m2[3][3], m3[3][3], i, j, k, sum;
/* Initialize and print items of m1 */
printf(“Enter elementsn”);
for(i = 0 ; i < 3 ; i++)
{
for (j = 0 ; j < 3 ; j++)
{
scanf(“%d”, &m1[i][j]) ;
printf( “ %dt”, m1[i][j] ) ;
}
printf (“ n”);
}
/* Initialize and print items of m2 */
printf(“Enter elementsn”);
for(i = 0 ; i < 3 ; i++)
{
for (j = 0 ; j < 3 ; j++)
{
scanf(“%d”, &m2[i][j]) ;
printf( “ %dt”, m2[i][j] ) ;
}
printf (“ n”);
}
Editor: DEBASIS DWIBEDY
Program-4 (contd..)
/* Print new matrx m3 containing the
product*/
printf(“The product of matrix m1 and
m2 is: n”) ;
for(i = 0 ; i < 3 ; i++)
{
for (j = 0 ; j < 3 ; j++)
{
printf( “ %dt”, m3[i][j] ) ;
}
printf (“ n”);
}
}
/* Logic of matrix Multiplication */
for (i = 0 ; i < 3 ; i++)
{
for (j = 0 ; j < 3 ; j++)
{
sum = 0 ;
for ( k = 0; k < 3 ; k++ )
{
sum = sum + m1[i][k] * m2[k][j] ;
}
m3 [i][j] = sum ;
}
}
Editor: DEBASIS DWIBEDY
Assignments
1. W.A.P to find the smallest and largest number in a n X n 2-D array.
2. W.A.P to find the 2nd smallest and 2nd largest number in a 3 X3 2-D array.
3. W.A.P to show the inverse of a 3 X 3 matrix.
4. W.A.P to show the multiplication of a m X n matrix with a n X P matrix.
5. A 6 X 6 matrix is entered through the key board. W.A.P to obtain the
determinant of this matrix.
6. W.A.P to add two 5 X 5 matrices and print the sum of elements of the
resultant matrix.
7. A 3 X 3 matrix is entered through key board. W.A.P to check whether
the input matrix is symmetric.

Más contenido relacionado

La actualidad más candente

Presentation on array
Presentation on array Presentation on array
Presentation on array topu93
 
Call by value
Call by valueCall by value
Call by valueDharani G
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementSreedhar Chowdam
 
Chapter 6 Balagurusamy Programming ANSI in c
Chapter 6  Balagurusamy Programming ANSI  in cChapter 6  Balagurusamy Programming ANSI  in c
Chapter 6 Balagurusamy Programming ANSI in cBUBT
 
C Pointers
C PointersC Pointers
C Pointersomukhtar
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Operators in Python
Operators in PythonOperators in Python
Operators in PythonAnusuya123
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Sameer Rathoud
 
第9回 大規模データを用いたデータフレーム操作実習(3)
第9回 大規模データを用いたデータフレーム操作実習(3)第9回 大規模データを用いたデータフレーム操作実習(3)
第9回 大規模データを用いたデータフレーム操作実習(3)Wataru Shito
 

La actualidad más candente (20)

Pointers in C
Pointers in CPointers in C
Pointers in C
 
Presentation on array
Presentation on array Presentation on array
Presentation on array
 
Recursion
RecursionRecursion
Recursion
 
Call by value
Call by valueCall by value
Call by value
 
C++ Arrays
C++ ArraysC++ Arrays
C++ Arrays
 
C Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory managementC Recursion, Pointers, Dynamic memory management
C Recursion, Pointers, Dynamic memory management
 
Chapter 6 Balagurusamy Programming ANSI in c
Chapter 6  Balagurusamy Programming ANSI  in cChapter 6  Balagurusamy Programming ANSI  in c
Chapter 6 Balagurusamy Programming ANSI in c
 
arrays of structures
arrays of structuresarrays of structures
arrays of structures
 
C Programming Unit-5
C Programming Unit-5C Programming Unit-5
C Programming Unit-5
 
C Pointers
C PointersC Pointers
C Pointers
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Operators in Python
Operators in PythonOperators in Python
Operators in Python
 
Tree Traversal
Tree TraversalTree Traversal
Tree Traversal
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Integration by parts
Integration by partsIntegration by parts
Integration by parts
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python Programming
Python Programming Python Programming
Python Programming
 
Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())Memory Management C++ (Peeling operator new() and delete())
Memory Management C++ (Peeling operator new() and delete())
 
第9回 大規模データを用いたデータフレーム操作実習(3)
第9回 大規模データを用いたデータフレーム操作実習(3)第9回 大規模データを用いたデータフレーム操作実習(3)
第9回 大規模データを用いたデータフレーム操作実習(3)
 
Structures
StructuresStructures
Structures
 

Similar a C_Arrays.pptx (20)

Array&amp;string
Array&amp;stringArray&amp;string
Array&amp;string
 
Fp201 unit4
Fp201 unit4Fp201 unit4
Fp201 unit4
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Array
ArrayArray
Array
 
Array
ArrayArray
Array
 
Arrays
ArraysArrays
Arrays
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdf
 
Arrays
ArraysArrays
Arrays
 
VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2VIT351 Software Development VI Unit2
VIT351 Software Development VI Unit2
 
Array
ArrayArray
Array
 
SPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in CSPL 10 | One Dimensional Array in C
SPL 10 | One Dimensional Array in C
 
Array notes
Array notesArray notes
Array notes
 
Arrays & Strings
Arrays & StringsArrays & Strings
Arrays & Strings
 
Arrays
ArraysArrays
Arrays
 
Array
ArrayArray
Array
 
Arrays In C
Arrays In CArrays In C
Arrays In C
 
Programming in c Arrays
Programming in c ArraysProgramming in c Arrays
Programming in c Arrays
 
Arrays
ArraysArrays
Arrays
 
C Programming : Arrays
C Programming : ArraysC Programming : Arrays
C Programming : Arrays
 
Arrays-Computer programming
Arrays-Computer programmingArrays-Computer programming
Arrays-Computer programming
 

Último

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptxMaritesTamaniVerdade
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdfssuserdda66b
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxDr. Sarita Anand
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 

Último (20)

2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdfVishram Singh - Textbook of Anatomy  Upper Limb and Thorax.. Volume 1 (1).pdf
Vishram Singh - Textbook of Anatomy Upper Limb and Thorax.. Volume 1 (1).pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

C_Arrays.pptx

  • 1. Editor: DEBASIS DWIBEDY ARRAYS in C Debasis Dwibedy Assistant Professor* Dept. CSE, VSSUT, Burla *Personal Web Site: www.sites.google.com/view/debasis-dwibedy
  • 2. Editor: DEBASIS DWIBEDY What is an Array An array is a fixed-size sequenced collection of related data items of same type sharing a common name. An array is a derived data type that holds a list of items of same type. Unlike the fundamental data types int, char, float, that holds only one value, an array holds a list of values in contiguous memory locations. Example 1: int arr [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; /* Array of first 10 natural numbers */ Example 2: float r [5] = {10.8, 9.6, 8.4, 11.5, 12.6}; /* Array of rate of interest of 5 banks */ Example 3: char name [8] = {‘D’, ‘E’, ‘B’, ‘A’, ‘S’, ‘I’, ‘S’, ‘0’} ; /* Array of characters*/
  • 3. Editor: DEBASIS DWIBEDY Types of Arrays We can use arrays to represent not only simple lists of values but also tables of data in two or three or more dimensions. Accordingly, we have following types of arrays. One –dimensional arrays Two –dimensional arrays Multi –dimensional arrays A list of same type items can be given one variable name using only one subscript, also known as the row-wise representation of data. Eg: int arr [10] ; A table of items can be given one variable name using two subscripts, also known as the row and column wise representation of data. Eg: int arr [3][3] ; C allows arrays of three or more dimensions. The exact limit is determined by the compiler. Eg: int arr [3][5][12] ;
  • 5. Editor: DEBASIS DWIBEDY Variable vs. Array Variable Array Declaration data_type variable_name; Eg. int mark ; Memory Representation mark Declaration data_type array_name [size] ; Eg. int mark [5] ; Memory Representation (column-measure order) 0 1 2 3 4 mark mark[0] mark[1] mark[2] mark[3] mark[4] 1000 1002 1004 1006 1008 Real Memory Addresses Base Address Values at Addresses Array Name
  • 6. Editor: DEBASIS DWIBEDY Why to use an Array Type Let’s consider that we need to store and print a list of 1000 students' marks of an integer type. int main(void) { /* How long is the declaration and how many variables used */ int studMark1, studMark2, studMark3, studMark4, …, …, studMark998, stuMark999, studMark1000; … … return 0; } We have to use 1000 variables of integer type to store and print the marks. (that many variables are hard to remember)
  • 7. Editor: DEBASIS DWIBEDY Initialization of an Array Method 1 /* Declaration*/ int mark[5]; /*Initialization*/ mark[0]=40; mark[1]=45; mark[2]=50; mark[3]=35; mark[4]=42; Method 2 /* Declaration and initialization*/ int mark[5]={40,45,50,35,42}; Method 3 /* Declaration and initialization*/ int mark []={40,45,50,35,42} ; Method 4 /* Declaration */ int mark [5], i ; /* Initialization */ printf (“Enter 5 marks”) ; for (i = 0 ; i < 5 ; i++) { scanf(“%d”, &mark[i]) ; } Not recommendable to omit the size of the array, while declaration and initialization take place at the same time.
  • 8. Editor: DEBASIS DWIBEDY Character Array and String /* Declaration and initialization*/ char name[9]={‘w’, ‘E’, ‘L’, ‘ ’, ‘C’, ‘O’, ‘M’, ‘E’, ‘0’}; ‘W’ ‘E’ ‘L’ ‘ ’ ‘C’ ‘O’ ‘M’ ‘E’ ‘0’ 0 1 2 3 4 5 6 7 8 /* Declaration and initialization*/ char name[9]={“WEL COME”}; Rule: The size of a character array must be one more than the number of characters to be stored in memory or to be displayed on the console. The extra space is required to store the “o” character to tell the compiler explicitly about the end of the array.
  • 9. Editor: DEBASIS DWIBEDY Array Initialization Tips Error 1 /* Initializers are more than the declared size*/ int mark[3]={40,45,50,35,42}; If we have more initializers, than the declared size of the array, then the compiler generates an error. No Error /* Initializers are less than the declared size*/ int mark[5]={40,45,50}; If we have less initializers, than the declared size of the array, then the compiler does not generate an error and allocates 0s to the vacant locations of the integer array and ‘0’ to the character array. No Error /* Any reference to the array outside the declared limit*/ int mark[5]={40,45,50, 35, 42}; printf(“%d”, mark[6]); It would not cause an error, it outputs a garbage value.
  • 10. Editor: DEBASIS DWIBEDY Run-Time Initialization of Array Any array can also be initialized at run time explicitly. This approach is useful for large arrays. Example /* Declaration */ int mark[100], i ; /* Initialization */ for(i=0; i<100; i++) { if (i < 50) mark[i]=45; else mark[i]=90; }
  • 11. Editor: DEBASIS DWIBEDY Skeleton of a Program Basic structure of a program that uses arrays. #include<stdio.h> void main() { /* Declaration of array and variables */ Declaration statements; /* Initialization of array and variables */ Initialization statements; /* Program Logic */ Logic statements; /* Print the result */ Using for loops to print the array elements; }
  • 12. Editor: DEBASIS DWIBEDY Program-1 W.A.P to display the sum of squares of any 10 real numbers. #include<stdio.h> void main() { /* Declaration */ int i ; float arr[10], value, total=0.0 ; /* Initialization of the Array*/ printf(“Enter values to the array”); for(i = 0; i < 10; i++) { scanf(“%f”, &value); arr[i] = value; } /* Print the Result*/ printf(“n total = %f”, total); } /* Computation of Total*/ for(i = 0; i < 10; i++) { total = total + arr[i] * arr[i]; }
  • 13. Editor: DEBASIS DWIBEDY Program-2 W.A.P that interchanges the odd and even positioned elements of an array. #include<stdio.h> void main() { /* Logic*/ for (i = 0 ; i < n ; i = i+2) { t = num [i] ; num [i] = num [i+1] ; num [i+1] = t ; } / * Print the Resultant Array * / for ( i = 0 ; i < n ; i++ ) { printf( “ %d”, num [i] ) ; } return 0 ; } /* Declaration */ int num[], i, n, t ; /* Initialization of the Array*/ printf (“Enter size of the arrayn”) ; scanf(“%d”, &n) ; printf(“Enter elementsn”); for(i = 0 ; i < n ; i++) { scanf(“%d”, &num[i]) ; }
  • 14. Editor: DEBASIS DWIBEDY Program-3 Enter 5 students marks and display the percentage obtained by each student as output. #include<stdio.h> void main() { /* Declaration */ int std[5], m1, m2, m3, m4, m5, i ; /* Logic */ for(i=0; i<5; i++) { printf(“Enter marks of 5 subjects of student %d”, i); scanf(“%d%d%d%d%d”, &m1, &m2, &m3, &m4, &m5); std[i]=(m1+m2+m3+m4+m5)/5; } /* Print Results*/ for(i=0; i<5; i++) { printf(“%d”, std[i]); } }
  • 15. Editor: DEBASIS DWIBEDY Program-4 Enter 5 students marks into an array and sort the marks in an ascending order. Logic Execution of Iteration 1 for(i = 0 ; i < 5 ; i++) { j = i ; for (k = i+1 ; k < 5 ; k++) { if (std [k] < std [i]) { j = k ; /* Swap the values of std [i] and std [j] */ temp = std [i] ; std [i] = std [j] ; std [j] = temp; } } 40 35 50 20 10 i, j k 40 35 50 20 10 k, j i 35 40 50 20 10 i j k 35 40 50 20 10 i j k 35 40 50 20 10 k, j i
  • 16. Editor: DEBASIS DWIBEDY Execution Continues 20 40 50 35 10 i j k 20 40 50 35 10 k, j i 10 40 50 35 20 i j k 10 40 50 35 20 i j k Termination of Iteration- 1 of outer For loop Execution of Iteration 2 10 40 50 35 20 i, j k
  • 17. Editor: DEBASIS DWIBEDY Program-4 (Code) Enter 5 students marks into an array and sort the marks in an ascending order. #include<stdio.h> void main() { /* Declaration */ int std [5] = {40, 35, 50, 20, 10} ; int i, j, k, temp ; /* Logic */ for(i = 0 ; i < 5 ; i++) { j = i ; for (k = i+1 ; k < 5 ; k++) { if (std [k] < std [i]) { j = k ; temp = std [i] ; std [i] = std [j] ; std [j] = temp; } } /* Print the sorted Array*/ for(i = 0 ; i < 5 ; i++) { printf(“%dn”, std[i]); } }
  • 18. Editor: DEBASIS DWIBEDY Program-5 Given an array of n integers. W.A.P to find whether a number is present in the array, if present, then print its position in the array. #include<stdio.h> int main() { /* Declaration */ int arr [], n, i, key ; /* To know size of the Array */ printf(“Enter the number of elements in the arrayn”) ; scanf(“%d”, &n); /* Initialization of the Array */ printf(“Enter %d numbersn”, n) ; for (i = 0 ; i < n ; i++) scanf(“%d”, &arr[i]); /* Search Logic */ printf(“Enter the number to searchn”); scanf(“%d”, &key); for (i = 0 ; i < n ; i++ ) { if (arr [i] = = key) { printf(“%d is present at position %d n”, key, i+1); break; } } if (i = = n) { printf (“%d is not present in the array”, key); return 0; }
  • 19. Editor: DEBASIS DWIBEDY Program-6 W.A.P to copy the contents of one array of size 5 into another in the reverse order. #include<stdio.h> void main() { /* Logic*/ for (i = 0, j = 4 ; i < 5 ; i++, j--) { arr2 [j] = arr1 [i] ; } / * Print the Resultant Array * / for ( i = 0 ; i < 5 ; i++ ) { printf( “ n%d”, arr2 [i] ) ; } return 0 ; } /* Declaration */ int arr1[5], arr2 [5], i, j ; /* Initialization of the Array 1*/ printf(“Enter 5 elements into array n”); for(i = 0 ; i < 5 ; i++) { scanf(“%d”, &arr1[i]) ; }
  • 20. Editor: DEBASIS DWIBEDY Assignments 1. W.A.P to find the smallest and largest number in an array of n integers. 2. W.A.P to sort an array of n positive integers in descending order. 3. W.A.P to find the occurance of 1, 2, 3 in an array of following items 1, 2, 2, 3, 3, 2, 2, 1, 2, 1, 1, 1, 3, 2, 3, 3, 1, 2, 3, 1, 2, 3, 1. 4. W.A.P to find the mean and standard deviation of an array of n positive integers. 5. Given are two one-dimensional arrays A and B which are sorted in ascending order. W. A. P. to merge them into a single sorted array C that contains every items from array A and B in ascending order. 6. Given an array of n positive integers. W.A.P to reverse the array elements.
  • 22. Editor: DEBASIS DWIBEDY Definition A 2-dimensional array represents a table of data in rows and columns A table of items can be given one variable name using two subscripts Eg: int m [5][5] ; A 2-dimensional array is also called a matrix. A 2-dimensional array is an amalgamation of several 1-D arrays.
  • 23. Editor: DEBASIS DWIBEDY Why to use a 2-D Array Let’s consider that we need to store and print the marks of 5 students in 5 subjects. int main(void) { /* How long is the declaration and how many arrays are used */ int std_1[5], std_2[5], std_3[5], std_4[5], std_5[5]; … … return 0; } We have to use 5 one-dimensional arrays of integer type with 5 rows to store 5 subjects marks of each students. (that many arrays are hard to remember and maintain for a large program)
  • 24. Editor: DEBASIS DWIBEDY Why to use a 2-D Array Can a single array be used to store and display the marks of all 5 students ? Yes, by a 2-D Array Advantages 1. Number of 1-D array declarations can be reduced significantly. 2. It is convenient to remember and maintain a minimum number of arrays.
  • 25. Editor: DEBASIS DWIBEDY Declaration /* Declaration */ data_type array_name [row_size][column_size]; /* Example*/ int m [3][5] ; /* the compiler allocates 30 Bytes in contiguous memory locations */ Row 0 Row 1 Row 2 m[0][0] m[0][1] m[0][2] m[0][3] m[0][4] m[1][0] m[1][1] m[1][2] m[1][3] m[1][4] m[2][0] m[2][1] m[2][2] m[2][3] m[2][4] 0 1 2 0 1 2 3 4 Logical Representation of a 2-D Array Accessing a 2-D array element by: array_name [row i][column j] /* Example*/ printf ( “%d”, m [1][4] ) ; /* it will print value at location 2nd row and 5th column Tabular Form
  • 26. Editor: DEBASIS DWIBEDY Memory Layout Lets consider the following 2-D array Eg: int m [3][3] ; How a 2-dimensional array is stored in the memory? m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2] Row 0 Row 1 Row 2 1000 1002 1004 1006 1008 1010 1012 1014 1016 Row-measure Representation of 2-D Array in Memory printf(“The size of the array is %d Bytes”, sizeof(m)); /* The size of the array is 18 Bytes */ printf(“%u%u%u”, m+0, m+1, m+2)); /* 1000 1006 1012 */
  • 27. Editor: DEBASIS DWIBEDY Initialization Method 1 /* Declaration*/ int m [2][2]; /*Initialization*/ m[0][0] = 40 ; m[0][1] = 45 ; m[1][0] = 50 ; m[1][1] = 35 ; Method 2 /* Declaration and initialization*/ int m[2][2] = { {40,45}, {50,35} } ; Method 3 /* Declaration and initialization*/ int m[][2] = { 40, 45, 50, 35 } ; Method 4 /* Declaration */ int m[2][2], i, j ; /* Initialization */ printf (“Enter marks”) ; for (i = 0 ; i < 2 ; i++) { for (j = 0 ; j < 2 ; j++) scanf(“%d”, &m[i][j] ); } Row size is optional, braces for individual row is also optional, but column size is compulsory in the declaration and initialization of a 2-D array.
  • 28. Editor: DEBASIS DWIBEDY Program-1 W.A.P to store and display 3 student marks of 3 different subjects. #include<stdio.h> void main() { /* Declaration */ int m[3][3], i, j ; /* Store marks into m[3][3]*/ printf(“Enter marks of 3 studentsn”); for(i = 0; i < 3; i++) { for (j = 0 ; j < 3 ; j++) scanf(“%d”, &m[i][j]) ; } /* To know the size of the declared m[3][3] */ printf (“%u”, sizeof(m) ) ; /* Display the marks*/ for(i = 0 ; i < 3 ; i++) { for (j = 0 ; j < 3 ; j++) { printf(“%dt”, m[i][j]) ; } printf(“n”); } }
  • 29. Editor: DEBASIS DWIBEDY Program-2 W.A.P to print the largest number in a 2-D array and its position. #include<stdio.h> void main() { /* Logic*/ big = a[0][0], r = 0, c = 0 ; for (i = 0 ; i < row_size ; i++) { for (j = 0 ; j < column_size ; j++) { if ( a[i][j] > big) { big = a[i][j]; r = i, c = j ; } } } / * Print the Result * / printf(“Largest=%d”, big ) ; printf(The position of %d is %d th row and %d th column”, big, r+1, c+1) ; } /* Declaration */ int a[][], i, j, big, row_size, column_size, r, c ; /* Initialization of the Array a[][] */ printf (“Enter row and column sizen”) ; scanf(“%d%d”, &row_size, &column_size) ; printf(“Enter elementsn”); for(i = 0 ; i < row_size ; i++) { for (j = 0 ; j < column_size ; j++) scanf(“%d”, &a[i][j]) ; }
  • 30. Editor: DEBASIS DWIBEDY Transpose of a Matrix Input Matrix 1 2 3 4 5 6 3 x 2 Interchanging the rows and columns Resultant Matrix 1 2 3 4 5 6 2 x 3 /* Logic and print the resultant matrix*/ for (i = 0 ; i < column_size ; i++) { for (j = 0 ; j < row_size ; j++) { printf ( “ %dt”, a [j][i] ) ; } printf ( “ n” ) ; }
  • 31. Editor: DEBASIS DWIBEDY Program-3 W.A.P to print the transpose of a matrix. #include<stdio.h> void main() { /* Logic and print the output array*/ for (i = 0 ; i < column_size ; i++) { for (j = 0 ; j < row_size ; j++) { printf ( “ %dt”, a [j][i] ) ; } printf ( “ n” ) ; } /* Declaration of 2-D Array and variables */ int a[][], i, j, row_size, column_size ; /* Initialize and print the input items */ printf (“Enter row and column sizen”) ; scanf(“%d%d”, &row_size, &column_size) ; printf(“Enter elementsn”); for(i = 0 ; i < row_size ; i++) { for (j = 0 ; j < column_size ; j++) scanf(“%d”, &a[i][j]) ; printf( “ %d”, a[i][j] ) ;
  • 32. Editor: DEBASIS DWIBEDY Multiplication of two Matrices Matrix m1 1 2 3 4 5 6 3 x 2 Resultant Matrix m3 1 2 3 4 5 6 2 x 3 /* Logic of matrix Multiplication */ for (i = 0 ; i < 3 ; i++) { for (j = 0 ; j < 3 ; j++) { sum = 0 ; for ( k = 0; k < 2 ; k++ ) sum = sum + m1[i][k] * m2[k][j] ; m3 [i][j] = sum ; } } X Matrix m2 17 22 27 22 29 36 27 36 45 3 x 3 m3[0][0] = ( m1[0][0]* m2[0][0] ) + ( m1[0][1] * m2[1][0]) m3[0][1] = ( m1[0][0]* m2[0][1] ) + ( m1[0][1] * m2[1][1]) m3[0][2] = ( m1[0][0]* m2[0][2] ) + ( m1[0][1] * m2[1][2]) m3[1][0] = ( m1[1][0]* m2[0][0] ) + ( m1[1][1] * m2[1][0]) m3[1][1] = ( m1[1][0]* m2[0][1] ) + ( m1[1][1] * m2[1][1]) m3[1][2] = ( m1[1][0]* m2[0][2] ) + ( m1[1][1] * m2[1][2]) m3[2][0] = ( m1[2][0]* m2[0][0] ) + ( m1[2][1] * m2[1][0]) m3[2][1] = ( m1[2][0]* m2[0][1] ) + ( m1[2][1] * m2[1][1]) m3[2][2] = ( m1[2[0]* m2[0][2] ) + ( m1[2][1] * m2[1][2]) m X n n X p m X p i < m j < p k < n
  • 33. Editor: DEBASIS DWIBEDY Program-4 W.A.P to show the multiplication of two 3 X 3 matrices. #include<stdio.h> void main() { /* Declaration of Arrays and variables */ int m1[3][3], m2[3][3], m3[3][3], i, j, k, sum; /* Initialize and print items of m1 */ printf(“Enter elementsn”); for(i = 0 ; i < 3 ; i++) { for (j = 0 ; j < 3 ; j++) { scanf(“%d”, &m1[i][j]) ; printf( “ %dt”, m1[i][j] ) ; } printf (“ n”); } /* Initialize and print items of m2 */ printf(“Enter elementsn”); for(i = 0 ; i < 3 ; i++) { for (j = 0 ; j < 3 ; j++) { scanf(“%d”, &m2[i][j]) ; printf( “ %dt”, m2[i][j] ) ; } printf (“ n”); }
  • 34. Editor: DEBASIS DWIBEDY Program-4 (contd..) /* Print new matrx m3 containing the product*/ printf(“The product of matrix m1 and m2 is: n”) ; for(i = 0 ; i < 3 ; i++) { for (j = 0 ; j < 3 ; j++) { printf( “ %dt”, m3[i][j] ) ; } printf (“ n”); } } /* Logic of matrix Multiplication */ for (i = 0 ; i < 3 ; i++) { for (j = 0 ; j < 3 ; j++) { sum = 0 ; for ( k = 0; k < 3 ; k++ ) { sum = sum + m1[i][k] * m2[k][j] ; } m3 [i][j] = sum ; } }
  • 35. Editor: DEBASIS DWIBEDY Assignments 1. W.A.P to find the smallest and largest number in a n X n 2-D array. 2. W.A.P to find the 2nd smallest and 2nd largest number in a 3 X3 2-D array. 3. W.A.P to show the inverse of a 3 X 3 matrix. 4. W.A.P to show the multiplication of a m X n matrix with a n X P matrix. 5. A 6 X 6 matrix is entered through the key board. W.A.P to obtain the determinant of this matrix. 6. W.A.P to add two 5 X 5 matrices and print the sum of elements of the resultant matrix. 7. A 3 X 3 matrix is entered through key board. W.A.P to check whether the input matrix is symmetric.