0% found this document useful (0 votes)
16 views39 pages

Array

The document explains the concept of arrays as a data structure for organizing and storing similar data types efficiently. It covers array declaration, initialization, accessing, updating elements, and traversing arrays using loops, along with examples in C programming. Additionally, it discusses the types of arrays, including one-dimensional and multi-dimensional arrays, and provides insights on sorting arrays.

Uploaded by

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

Array

The document explains the concept of arrays as a data structure for organizing and storing similar data types efficiently. It covers array declaration, initialization, accessing, updating elements, and traversing arrays using loops, along with examples in C programming. Additionally, it discusses the types of arrays, including one-dimensional and multi-dimensional arrays, and provides insights on sorting arrays.

Uploaded by

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

Arrays:

Take a situation in which we have 18 students in a class and we have


been asked to write a program that reads and prints the marks of all
these 18 students.
So, we will need 18 integer variables with different names…

Now to read values for these 18 different variables, we must have 18


read statements.
Similarly, to print the value of these variables, we need 18 write
statements.

For a matter of 18 or 30 variables, then it might be acceptable for the


programmer to follow this approach.
But would it be possible to follow this approach if we have to read and
print marks of the students
i) in the entire course , e.g., 180 students,
ii) In the entire college, e.g., 1500 students,
iii) In the entire university, e.g., 10000 students
The answer is no,

To process large amount of data, we need a data structure known as


array.
Data Structure: Data structure is a format for organizing and storing
data. Also each data structure is designed to
organize data to suit a specific purpose.
So, array is the data structure which you can visualize as follows:

An array as a large chunk of memory divided into smaller block of


memory and each block is capable of storing a data value of same type.

10 23 5 7 68 1 4 87 9

This array consists of 9 data values.


Those are all integer type....

10 23 5 7 68 1 4 87 9

‘a’ ‘b’ ‘c’ ‘d’ ‘e’

‘a’ ‘d’ 3.5 5 ‘f’ 34 3

Array:
An array is a collection of similar data elements. These data elements
have the same data type. The elements of the array are stored in
consecutive memory locations and are referenced by an index, also
known as the subscript.
Index is an ordinal number which is used to identify an element of the
array.
Declaration of Array:

To create an array, define the data type (like int) and specify the name
of the array followed by square brackets [].

Syntax of Array-

data_type array_name[array_size];

e.g.- int arr[5]; or int marks[5];

So, // declare an array by specifying size in [].


int my_array1[20];
char my_array2[5];
// declare an array by specifying user defined size.
int size = 20;
int my_array3[size];

Example:
int main()
{
// declaring array of integers
int arr_int[5];
// declaring array of characters
char arr_char[5];
return 0;
}
Array Initialization:

The simplest way to initialize an array is by using the index of each


element. We can initialize each element of the array by using the
index.

e.g.-
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;

Example:
#include<stdio.h>
int main(){
int i=0;
int marks[5]; //declaration of array
marks[0]=80; //initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Array Initialization with Declaration:
Initialize the array along with its declaration. We use an initializer list
to initialize multiple elements of the array. An initializer list is the list
of values enclosed within braces { } separated by a comma.

data_type array_name [size] = {value1, value2, ... valueN};

e.g.- int arr[5]={2,4,8,12,16};

Array Initialization with Declaration without Size:


Initialize an array using an initializer list, we can skip declaring the size
of the array as the compiler can automatically deduce the size of the
array in these cases. The size of the array in these cases is equal to the
number of elements present in the initializer list as the compiler can
automatically deduce the size of the array.

e.g. data_type array_name[] = {1,2,3,4,5};

Example:
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60}; //declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}
Array Initialization after Declaration (Using Loops):

Initialize the array after the declaration by assigning the initial value
to each element individually. We can use for loop, while loop, or do-
while loop to assign the value to each element of the array.

e.g. - for (int i = 0; i < N; i++)


{
array_name[i] = valuei;
}

Example:
int main()
{
// array initialization using initializer list
int arr[5] = { 10, 20, 30, 40, 50 };
// array initialization using initializer list without
specifying size
int arr1[] = { 1, 2, 3, 4, 5 };
// array initialization using for loop
float arr2[5];
for (int i = 0; i < 5; i++)
{
arr2[i] = (float)i * 2.1;
}
return 0;
}
Access the Elements of an Array:
To access an array element, refer to its index number.
Array indexes start with 0: [0] is the first element. [1] is the second
element, etc.

array_name [index];
One thing to note is that the indexing in the array always starts with 0,
i.e., the first element is at index 0 and the last element is at N – 1
where N is the number of elements in the array.

e.g.- int myNumbers[] = {25, 50, 75, 100};


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

// Outputs 25
This statement accesses the value of the first element [0] in
myNumbers.

Example:
int main()
{
// array declaration and initialization
int arr[5] = { 15, 25, 35, 45, 55 };
// accessing element at index 2 i.e 3rd element
printf("Element at arr[2]: %d\n", arr[2]);
// accessing element at index 4 i.e last element
printf("Element at arr[4]: %d\n", arr[4]);
// accessing element at index 0 i.e first element
printf("Element at arr[0]: %d", arr[0]);
return 0;
}
Update Array Element:
We can update the value of an element at the given index i in a similar
way to accessing an element by using the array subscript operator [ ]
and assignment operator =.

array_name[i] = new_value;

e.g.- myNumbers[0] = 33;

Example:
int myNumbers[] = {25, 50, 75, 100};
myNumbers[0] = 33;
printf("%d", myNumbers[0]);

// Now outputs 33 instead of 25

Array Traversal:
Traversal is the process in which we visit every element of the data
structure. For C array traversal, we use loops to iterate through each
element of the array.

Array Traversal using for Loop


e.g.- for (int i = 0; i < n; i++)
{
array_name[i];
}
Example:
int main()
{
// array declaration and initialization
int arr[5] = { 10, 20, 30, 40, 50 };
// modifying element at index 2
arr[2] = 100;
// traversing array using for loop
printf("Elements in Array: ");
for (int i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Input and Output Array Elements:


Array values can be stored by taking input from the user and storing
them in the array.
e.g.- // input an integer element and store it in 1st position of
the array
scanf("%d", &my_array[0]);
// input a float element and store it in ith position of the
array
scanf("%f", &my_array[i-1]);

Similarly, array elements can also be displayed in the output using the
printf() method. The index is specified indicating the position of the
element to be printed.
e.g.- // print the element stored at 1st position or 0th index
printf("%d", my_array[0]);
// print the element stored at ith position or (i - 1)th index
printf("%d", my_array[i-1]);
Example:
#include <stdio.h>
int main()
{
// declare an array.
int my_array[20], n;
printf("Enter the number of array elements:\n");
scanf(“%d”, &n);
// input array elements.
printf("Enter array elements:\n");
int i;
for (i = 0; i < n; i++)
{
Printf(“\n my_array [%d] = ”, i);
scanf("%d", &my_array[i]);
}
printf("\n The array elements are:\n");
// print array elements.
for (i = 0; i <= n; i++)
{
printf("my_array[%d] = %d\t ", i, my_array[i]);
}
return 0;
}
int marks [5] = {90, 45, 67, 85, 78 };
90 45 67 85 78
[0] [1] [2] [3] [4]
int marks [] = {91, 54, 67, 95, 87 };
91 54 67 95 87
[0] [1] [2] [3] [4]

int marks [5] = {90, 45 }; **Rest of the elements are filled with 0s
90 45 0 0 0
[0] [1] [2] [3] [4]
int marks [5] = {0};
0 0 0 0 0
[0] [1] [2] [3] [4]
Array Size & Address of element:

To get the size of an array, you can use the sizeof operator.
e.g.-
int myNumbers[] = {10, 25, 50, 75, 100};
int length = sizeof(myNumbers) / sizeof(myNumbers[0]);
printf("%d", length);

Find out how many elements an array has, you can use the formula
(which divides the size of the array by the size of one array element).

So if you are writing the code like this,----

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


printf("%lu", sizeof(myNumbers));

The result show 20 instead of 5.


It is because the sizeof operator returns the size of a type in bytes.

We know int type is usually 4 bytes, so from the above example,


4 x 5 (4 bytes x 5 elements) = 20 bytes.

Given an array int myNumbers[] = {10,25,50,75,100}. and if the base


address is 1000, then

10 25 50 75 100
myNumbers [0] [1] [2] [3] [4]
1000 1002 1004 1006 1008
Example of use of size of the array:

#include <stdio.h>
int main()
{
// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
int i;
// Get the length of the array
int length = sizeof(ages) / sizeof(ages[0]);
// Create a 'lowest age' variable and assign the first array element of
ages to it
int lowestAge = ages[0];
// Loop through the elements of the ages array to find the lowest age
for (i = 0; i < length; i++)
{
// Check if the current age is smaller than current the 'lowest age'
if (lowestAge > ages[i])
{
// If the smaller age is found, update 'lowest age' with that
element
lowestAge = ages[i];
}
}
// Output the value of the lowest age
printf("The lowest age in the array is: %d", lowestAge);
return 0;
}
Types of Array:

The number of subscript determines the dimensionality of the


array. We can use arrays to represent not only list of values but also
tables of data in two or more dimensions.
So, we have different types of arrays based on its dimensional.

 One-dimensional arrays / Single-dimensional arrays


 Two-dimensional arrays / Double-dimensional arrays
 Multi-dimensional arrays

One – Dimensional arrays:

A list of items can be given one variable name using only one subscript
and such a variable is called one-dimensional array or single-
dimensional variable.

Syntax: data-type array-name[size];

The data-type specifies the type of elements such as int, float or char.
And the size indicates the maximum number of elements that can be
stored in that array.

E.g.: int a[5] ;


here a is an array containing 5 integer elements.
char name[20];
here name is an array containing 20 characters.

Note: character strings are as simple as array of characters. And every


string should be terminated by null character (‘\0’).
Example :
int main()
{
int a[ 20], i, n, sum=0;
printf (“Enter number of elements : ”);
scanf (“%d”, &n);
printf(“Enter %d elements : ”, n);
for(i=0; i<n; i++)
{
scanf(“%d”,&a [ i ]); // run time initialization
}
/* finding the sum of array a[] */
for(i=0; i<n; i++)
{
sum = sum + a[ i ];
}
printf(“\n Sum of n elements of array a[] is %d”, sum);
return 0;
}

Using array of characters

#include <stdio.h>
int main()
{
// creating array of character
char arr[8] = { 'A', 's', 'a', 'n', 's', 'o', 'l', '\0' };
// printing string
int i = 0;
while (arr[i])
{
printf("%c", arr[i++]);
}
return 0;
}
Sorting an array:
An array of size 10 is initialized. The array elements are sorted in
descending order using the bubble sort algorithm.
Example:
#include <stdio.h>
int main()
{
int i, j, temp;
// initialize an array.
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
// print unsorted array.
printf("Original array is: \n");
for (i = 0; i < 10; i++)
{
printf("%d ", my_array[i]);
}
// sort the array elements in descending order.
for (i = 0; i < 10; i++)
{
for (j = i + 1; j < 10; j++)
{
if (my_array[j] > my_array[i])
{
temp = my_array[i];
my_array[i] = my_array[j];
my_array[j] = temp;
}
}
}
// print the sorted elements.
printf("\n\nSorted array in descending order is: \n");
for (i = 0; i < 10; i++)
{
printf("%d ", my_array[i]);
}
return 0;}
Inserting an element in an array:
Inserting an element in array means adding a new data element to an
existing array.
If the element has to be inserted at the end of the existing array, then
the task of inserting is quite simple.We just have to add 1 to the
upper_bound and assing the value.

So, algorithm for this:


Step1: Set upper_bound = upper_bound+1
Step2: Set A[upper_bound] = VAL
Step3: EXIT

Suppose, data[] is an array that is declared as int data[20]; and


contains the following values:

data[] = { 12, 23, 45, 65, 75, 84, 98, 100 };

Then,
Calculate the length of the array.
Find the upper bound and lower bound

12 23 45 65 75 84 98 100

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


Algorithm to insert an element at a specified position of an
array:

The algorithm INSERT will be declared as INSERT ( A, N, POS, VAL).


The arguments are
1. A, the array in which the element has to be inserted,
2. N, the number of elements in the array,
3. POS, the position at which the element has to be inserted
4. VAL, the value that has to be inserted.

Step1: [INITIALIZATION] SET I = N


Step2: Repeat Steps3 and 4 while I >= POS
Step3: SET A [ I+1 ] = A [ I ]
Step4: SET I = I - 1
[ END OF LOOP ]
Step5: SET N = N + 1
Step6: SET A [POS] = VAL
Step7: EXIT
Example:

#include <stdio.h>
int main()
{
int i, n, element, pos, arr[10];
// initialize an array.
printf("\n Enter the number of elements in the array: ");
scanf(“%d”, &n);
//arr[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
printf(“\n Enter the values”);
for( i=0; i<n; i++)
{
scanf(“%d”, &arr[i]);
}
// input index where the element is to be inserted.
printf("Enter the position at which the number has to be added: ");
scanf("%d", &pos);
// input the element to be inserted.
printf("Enter the element to be inserted: ");
scanf("%d", &element);
if (pos > 10)
{
printf("Input is invalid !");
}
else
{
// right shifting array elements.
for (i = n-1; i >= pos; i--)
arr[i + 1] = arr[i];
// insert the element at "pos".
arr[pos] = element;
n++;
printf("\n The array after insertion of %d is: ", element);
// print array elements.
for (i = 0; i <n; i++)
printf("\t % d ", arr[i]);
}
return 0;
}
Deleting an element from an array:
Deleting an element from array means removing a data element from
an already existing array.

If the element has to be deleted from the end of the existing array,
then the task of deletion is quite simple.We just have to subtract 1
from the upper_bound.

So, algorithm for this:


Step1: Set upper_bound = upper_bound - 1
Step2: EXIT

Algorithm to delete an element from the middle of an array:

The algorithm DELETE will be declared as DELETE ( A, N, POS).


The arguments are
1. A, the array from which the element has to be deleted,
2. N, the number of elements in the array,
3. POS, the position from which the element has to be deleted.

Step1: [INITIALIZATION] SET I = POS


Step2: Repeat Steps3 and 4 while I <= N - 1
Step3: SET A [ I ] = A [ I + 1 ]
Step4: SET I = I + 1
[ END OF LOOP ]
Step5: SET N = N - 1
Step6: EXIT
Example:

#include <stdio.h>
int main()
{
int i, n, pos, arr[10];
// initialize an array.
printf("\n Enter the number of elements in the array: ");
scanf(“%d”, &n);
//arr[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
printf(“\n Enter the element of the array: ”);
for( i=0; i<n; i++)
{
scanf(“%d”, &arr[i]);
}
// input index where the element is to be deleted.
printf("Enter the position from which the number has to be deleted: ");
scanf("%d", &pos);
// element to be deleted.
if (pos > 10)
{
printf("Input is invalid !");
}
else
{
// left shifting array elements.
for (i = pos; i < n-1; i++)
arr[i] = arr[i+1];
n--;
printf("\n The array after deletion is: ");
// print array elements.
for (i = 0; i <n; i++)
printf("\t Array[%d] = % d ",i, arr[i]);
}
return 0;
}
Merging two arrays:

Merging two arrays in a third array means first copying the contents
of the first array into the third array and then copying the contents of
the second array into the third array.
Hence the merge array contains contents of the first array followed by
the contents of the second array.
E. g. Unsorted array…

Array 1 90 56 89 77 69

Array 2 45 88 76 99 12 58

Array 3
90 56 89 77 69 45 88 76 99 12 58

Logic is
index = 0;
for (i = 0 ; i < n1; i++)
{
arr3 [index] = arr1 [ i ];
index++;
}
for (i = 0 ; i < n2; i++)
{
arr3 [index] = arr2 [ i ];
index++;
}

for (i = 0 ; i < m; i++)


{
printf (“\t Arr [%d] = %d”, i, arr3 [ i ]);
}
Searching for a value in an array:

Searching means to find whether a particular value is present in the


array or not.
If the value is present in the array then searching is said to be
successful and the searching process gives the location of that value in
the array.
Otherwise if the value is not present in the array, the searching
process displays the appropriate message and in this case searching is
said to be unsuccessful.

There are two popular method for searching the array elements.
One is linear search and the second is binary search.

Linear search also called sequential search, is a very simple method


and comparing every element of the array one by one in sequence
until a match is found.

int A[ ] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5}; , and search value VAL = 7,

A [0] != VAL

10 8 2 7 3 4 9 1 6 5

A [1] != VAL

10 8 2 7 3 4 9 1 6 5

A [2] != VAL

10 8 2 7 3 4 9 1 6 5

A [3] = VAL

10 8 2 7 3 4 9 1 6 5
ALGORITHM:
LINEAR_SEARCH (A, N, VAL)

Step 1: [ INITIALIZE] SET POS = -1


Step 2: [ INITIALIZE] SET I = 1
Step 3: Repeat Step 4 while I <= N
Step 4: IF A [ I ] = VAL
SET POS = I
PRINT POS
Go to Step 6
[END OF IF]
[END OF LOOP]
Step 5: IF POS = -1
PRINT “VALUE IS NOT PRESENT IN THE ARRAY”
[END OF IF]
Step 6: EXIT

Binary Search is a searching algorithm that works efficiently with a


sorted list.
ALGORITHM:
BINARY_SEARCH (A, lower_bound, upper_bound, N, VAL)
Step 1: [ INITIALIZE] SET BEG = lower_bound, END = upper_bound, POS = -1
Step 2: Repeat Step 3 and 4 while BEG <= END
Step 3: SET MID = (BEG + END) / 2
Step 4: IF A [ MID ] = VAL, then
POS = MID
PRINT POS
Go to Step 6
ELSE IF A[ MID ] > VAL, then
SET END = MID - 1
ELSE
SET BEG = MID + 1
[END OF IF]
[END OF LOOP]
Step 5: IF POS = -1, then
PRINT “VALUE IS NOT PRESENT IN THE ARRAY”
[END OF IF]
Step 6: EXIT
Example:

#include <stdio.h>
int main()
{
int i, element;
// initialize an array.
int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};
printf("Enter element to be searched:\n");
// input element to be searched.
scanf("%d", &element);
// traverse the array to search the element.
for (i = 0; i <= 9; i++)
{
if (my_array[i] == element)
{
// print the index at which the element is found.
printf("Element found at index %d", i);
break();
}
}
// if the element is not found.
if (i == 10)
{
printf("\nElement not found!");
}
return 0;
}
Print the largest and second largest element of the array

#include<stdio.h>
void main ()
{
int arr[100],i,n,largest,sec_largest;

printf("Enter the size of the array?");


scanf("%d",&n);

printf("Enter the elements of the array?");


for(i = 0; i<n; i++)
{
scanf("%d",&arr[i]);
}
// int my_array[10] = {11, 6, 10, 50, 32, 56, 15, 98, 43, 22};

largest = arr[0];
sec_largest = arr[1];

for(i=0;i<n;i++)
{
if(arr[i]>largest)
{
sec_largest = largest;
largest = arr[i];
}
else if (arr[i]>sec_largest && arr[i]!=largest)
{
sec_largest=arr[i];
}
}
printf("largest = %d, second largest = %d",largest,sec_largest);

}
Multidimensional Array

The array is declared with one value of size in square brackets , it is


called one dimensional array.
In a one dimensional array, each element is identified by its index or
subscript.
It is also possible for arrays to have two or more dimensions. The two
dimensional array is also called a matrix, i.e. declare with more indices
to simulate a two, three or multidimensional array.

So, if you want to store data as a tabular form, like a table with rows
and columns, you need to get familiar with multidimensional arrays.
A multidimensional array is basically an array of arrays.

Two-Dimensional Arrays, 2D- array


A 2-dimensional array or 2-D array is the simplest form of multi-
dimensional array.
Each element in a 2-D array can be represented as a separate 1-D
array.
A 2-D array contains a certain number of rows and columns and the
total number of array elements can be found by multiplying the
number of rows and columns.
For example, if the array is my_array[2][3], then the total number of
elements in the array is 6.
2D array is also known as a matrix (a table of rows and columns).

Syntax to Declare a 2-Dimensional Array

dataType arrayName[no_of_rows][no_of_columns];

i.e. array_name[size1] [size2];

Eg. int arr[4][3];

// 5 x 10 matrix --> int my_array1[5][10];

// 3 x 3 square matrix --> float my_array2[3][3];

// 2 x 1 matrix --> char my_array3[2][1];

Matrix form for 2D array ( row_col[3][4] )


Initialization of 2D Array

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};

int arr[ ][5] = {


{1,2,3,4,5},
{10,20,30,40,50},
{5,10,15,20,25}
};

int my_array[][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90};
int my_array[3][] = {10, 20, 30 ,40, 50, 60, 70, 70, 80, 90};
// invalid: second dimension must be specified.

int matrix[2][3] = { 1, 4, 2, 3, 6, 8 };

The first dimension represents the number of rows [2], while the
second dimension represents the number of columns [3]. The values
are placed in row-order, and can be visualized like this:
Memory Map of a 2-Dimensional Array

So, Initialization for this:

int stud[4][2] = {
{ 1234, 56 },
{ 1212, 33 },
{ 1434, 80 },
{ 1312, 78 }
};

or

int stud[4][2] = { 1234, 56, 1212, 33, 1434, 80, 1312, 78 } ;

main( )
{
int s[4][2] = { { 1234, 56 }, { 1212, 33 }, { 1434, 80 }, { 1312, 78 } } ;
int i ;
for ( i = 0 ; i <= 3 ; i++ )
printf ( "\nAddress of %d th 1-D array = %u", i, s[i] ) ;
}
Access the Elements of a 2D Array
To access an element of a two-dimensional array, you must specify the
index number of both the row and column.
Example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

printf("%d", matrix[0][2]); // Outputs 2

Change Elements in a 2D Array


To change the value of an element, refer to the index number of the
element in each of the dimensions:

change the value of the element in the first row (0) and first column
(0):
Example
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };
matrix[0][0] = 9;

printf("%d", matrix[0][0]); // Now outputs 9 instead of 1

Loop Through a 2D Array


To loop through a multi-dimensional array, you need one loop for
each of the array's dimensions.
Example:
int matrix[2][3] = { {1, 4, 2}, {3, 6, 8} };

int i, j;
for (i = 0; i < 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("%d\n", matrix[i][j]);
}
}
Two-dimensional array example

1. Example of Printing Elements of Two-dimensional Array

#include <stdio.h>
int main () {

/* an array with 5 rows and 2 columns*/


int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
int i, j;

/* output each array element's value */


for ( i = 0; i < 5; i++ ) {
for ( j = 0; j < 2; j++ ) {
printf("a[%d][%d] = %d\n", i,j, a[i][j] );
}
}

return 0;
}

OUTPUT:
a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8
2. Example of Printing Two-dimensional Array as Matrix in
Row and Columns.
#include <stdio.h>
void main ()
{
int arr[3][3],i,j;
for (i=0;i<3;i++)
{
for (j=0;j<3;j++)
{
printf("Enter a[%d][%d]: ",i,j);
scanf("%d",&arr[i][j]);
}
}
printf("\n printing the elements ....\n");
for(i=0;i<3;i++)
{
printf("\n");
for (j=0;j<3;j++)
{
printf("%d\t",arr[i][j]);
}
}
}
OUTPUT: Enter a[0][0]: 56
Enter a[0][1]: 10
Enter a[0][2]: 30
Enter a[1][0]: 34
Enter a[1][1]: 21
Enter a[1][2]: 34
Enter a[2][0]: 45
Enter a[2][1]: 56
Enter a[2][2]: 78

printing the elements .…

56 10 30
34 21 34
45 56 78
3. Example of finding Sum and Product of Two 2 Matrices
#include <stdio.h>
int main()
{
// declaring arr1 and arr2.
int arr1[2][2], arr2[2][2];
int sum[2][2], product[2][2];
// reading input for arr1 from the user.
printf("Enter the elements of arr1 : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("arr1[%d][%d] :", i, j);
scanf("%d", &arr1[i][j]);
}
printf("\n");
}
// reading input for arr2 from the user.
printf("Enter the elements of arr2: \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
printf("arr2[%d][%d] :", i, j);
scanf("%d", &arr2[i][j]);
}
printf("\n");
}
// adding the corresponding array elements.
printf("Sum array is : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
sum[i][j] = arr1[i][j] + arr2[i][j];
//print the sum array
printf("%d\t", sum[i][j]);
}
printf("\n");
}
// multiplying the corresponding array elements.
printf("Product array is : \n");
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
product[i][j] = arr1[i][j] * arr2[i][j];
// print the product array.
printf("%d\t", product[i][j]);
}
printf("\n");
}
return 0;
}

OUTPUT:
Enter the elements of arr1 :
arr1[0][0] : 2
arr1[0][1] : 4

arr1[1][0] : 2
arr1[1][1] : 3

Enter the elements of arr2:


arr2[0][0] : 1
arr2[0][1] : 2

arr2[1][0] : 3
arr2[1][1] : 6

Sum array is :
3 6
5 9

Product array is :
2 8
6 18
4. Example of Multiplication of Two-dimensional Array Matrix

#include<stdio.h>
int main(){
int mat1[3][3] = { {2, 4, 1} , {2, 3, 9} , {3, 1, 8} };
int mat2[3][3] = { {1, 2, 3} , {3, 6, 1} , {2, 4, 7} };
int mat3[3][3], sum=0, i, j, k;

for(i=0; i<3; i++){


for(j=0; j<3; j++){
sum=0;
for(k=0; k<3; k++)
sum = sum + mat1[i][k] * mat2[k][j];
mat3[i][j] = sum;
}
}
printf("\nMatrix 1 ...\n");
for(i=0; i<3; i++){
for(j=0; j<3; j++)
printf("%d\t", mat1[i][j]);
printf("\n");
}
printf("\nMatrix 2 ...\n");
for(i=0; i<3; i++){
for(j=0; j<3; j++)
printf("%d\t", mat2[i][j]);
printf("\n");
}
printf("\nMultiplication of the two given Matrices: \n");
for(i=0; i<3; i++){ OUTPUT: Matrix 1 ...
2 4 1
for(j=0; j<3; j++) 2 3 9
printf("%d\t", mat3[i][j]); 3 1 8
printf("\n"); Matrix 2 ...
} 1 2 3
3 6 1
return 0; 2 4 7
}
Multiplication of the two given Matrices:
16 32 17
29 58 72
22 44 66
5. Example of Transpose of a Matrix.
#include <stdio.h>
int main()
{
// declaring the matrices.
int arr[10][10], transpose[10][10];
// reading the input from the user.
printf("Enter elements of the arr\n");
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
scanf("%d", &arr[i][j]);
// copy the array element into another element.
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
transpose[j][i] = arr[i][j];
printf("Transpose of the arr:\n");
//print the transpose of the arr
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
printf("%d\t", transpose[i][j]);
printf("\n");
}
return 0;
}
OUTPUT:
Enter elements of the arr

12
34

Transpose of the arr:

1 3
2 4
Three-Dimensional Array

Students[hall][row][column]

Eg.-
int arr[3][4][2] = {
{
{ 2, 4 },
{ 7, 8 },
{ 3, 4 },
{ 5, 6 }
},
{
{ 7, 6 },
{ 3, 4 },
{ 5, 3 },
{ 2, 3 }
},
{
{ 8, 9 },
{ 7, 2 },
{ 3, 4 },
{ 5, 1 },
}
};

Example:
#include<stdio.h>
void main()
{
int a[5][5][5];
inti,j,k,x,y,z;
printf("\n Enter the size of a 3D array ");
scanf("%d%d%d",&x,&y,&z);
printf("\n Enter values into a 3D array of size %dx%dx%d \n",x,y,z);
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
for(k=0;k<z;k++)
{
scanf("%d",&a[i][j][k]);
}
}
}
printf("\n A three dimensional array is :\n");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
for(k=0;k<z;k++)
{
printf(" %d",a[i][j][k]);
}
printf("\n");
}
printf("\n\n");
}
return 0;
}

You might also like