0% found this document useful (0 votes)
25 views

Array

The document discusses arrays and their properties. It defines arrays as collections of similar data items stored in contiguous memory locations that can be randomly accessed using an index number. The key points are: 1. Arrays allow storing multiple values of the same type using one variable name. 2. Each element has the same size and type and they are stored consecutively in memory. 3. Common operations on arrays include traversal, insertion, deletion, searching, and updating elements. 4. Algorithms and programs in C language are presented for performing basic array operations like traversal, insertion, and deletion.

Uploaded by

Mahh Angle
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Array

The document discusses arrays and their properties. It defines arrays as collections of similar data items stored in contiguous memory locations that can be randomly accessed using an index number. The key points are: 1. Arrays allow storing multiple values of the same type using one variable name. 2. Each element has the same size and type and they are stored consecutively in memory. 3. Common operations on arrays include traversal, insertion, deletion, searching, and updating elements. 4. Algorithms and programs in C language are presented for performing basic array operations like traversal, insertion, and deletion.

Uploaded by

Mahh Angle
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 172

ARRAYS By

Prof. Amalendu Bag


ARRAYS
I. Arrays are defined as the collection of similar types of data items stored
at contiguous memory locations.
II. It is one of the simplest data structures where each data element can be
randomly accessed by using its index number.
III. For example, if we want to store the marks of a student in 6 subjects,
then we don't need to define a different variable for the marks in different
subjects.
IV. Instead, we can define an array that can store the marks in each subject
at the contiguous memory locations.
PROPERTIES OF ARRAY
There are some of the properties of an array that are listed as follows :
1. Each element in an array is of the same data type and carries the same size that
is 4 bytes.
2. Elements in the array are stored at contiguous memory locations from which the
first element is stored at the smallest memory location.
3. Elements of the array can be randomly accessed since we can calculate the
address of each element of the array with the given base address and the size of
the data element.
REPRESENTATION OF AN
ARRAY
We can represent an array in various ways in different programming
languages.
As an illustration, let's see the declaration of array in C language -
REPRESENTATION OF AN
ARRAY
As per the above illustration, there are some of the following important points -
I. Index starts with 0.
II. The array's length is 10, which means we can store 10 elements.
III. Each element in the array can be accessed via its index.
WHY ARE ARRAYS REQUIRED?
Arrays are useful because -
1. Sorting and searching a value in an array is easier.
2. Arrays are best to process multiple values quickly and easily.
3. Arrays are good for storing multiple values in a single variable – 
In computer programming, most cases require storing a large number of data of a
similar type.
To store such an amount of data, we need to define a large number of variables.
It would be very difficult to remember the names of all the variables while writing
the programs.
Instead of naming all the variables with a different name, it is better to define an
array and store all the elements into it.
MEMORY ALLOCATION OF AN
ARRAY
As stated above, all the data elements of an array are stored at contiguous
locations in the main memory.
The name of the array represents the base address or the address of the first
element in the main memory.
Each element of the array is represented by proper indexing.
We can define the indexing of an array in the below ways -
1. 0 (zero-based indexing): The first element of the array will be arr[0].
2. 1 (one-based indexing): The first element of the array will be arr[1].
3. n (n - based indexing): The first element of the array can reside at any
random index number.
MEMORY ALLOCATION OF AN
ARRAY
MEMORY ALLOCATION OF AN
ARRAY
I. In the above image, we have shown the memory allocation of an array arr of size 5.
II. The array follows a 0-based indexing approach.
III. The base address of the array is 100 bytes. It is the address of arr[0].
IV. Here, the size of the data type used is 4 bytes.
V. Therefore, each element will take 4 bytes in the memory.
HOW TO ACCESS AN ELEMENT
FROM THE ARRAY?
We required the information given below to access any random element from the
array -
1. Base Address of the array.
2. Size of an element in bytes.
3. Type of indexing, array follows.
The formula to calculate the address to access an array element -
Byte address of element A[i]  = base address + size * ( i - first index)
Here, size represents the memory taken by the primitive data types.
As an instance, int takes 2 bytes, float takes 4 bytes of memory space in C
programming. 
HOW TO ACCESS AN ELEMENT
FROM THE ARRAY?
We can understand it with the help of an example -
Suppose an array, A[-10 ..... +2 ] having Base address (BA) = 999 and size of
an element = 2 bytes, find the location of A[-1].
L(A[-1]) = 999 + 2 x [(-1) - (-10)]
= 999 + 18
= 1017
BASIC OPERATIONS
Now, let's discuss the basic operations supported in the array -
1. Traversal - This operation is used to print the elements of the array.
2. Insertion - It is used to add an element at a particular index.
3. Deletion - It is used to delete an element from a particular index.
4. Search - It is used to search an element using the given index or by the
value.
5. Update - It updates an element at a particular index.
6. Merging-It merges the elements of two array
TRAVERSAL OPERATION
I. This operation is performed to traverse through the array elements.
II. It prints all array elements one after another
ALGORITHM
Write an algorithm to print all array elements one after another
ALGORITM
Algorithm: Array Traversing
Input: An array A of size n
Output: None (just traversing the array)
ALGORITM
1. Initialize a variable i = 0
2. While i <= n, do steps 3-4
3. Print A[i]
4. i=i+1
5. End while loop
6. End
EXAMPLE
1. Print the input array
A=<18,30,15,70,12>
PROGRAM
Write a program to print all array elements one after another in C
PROGRAM
#include <stdio.h>
int main()
{
int arr[100];
int size;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
printf("The elements of the array are:\n");
PROGRAM
for (int i = 0; i < size; i++)
{
printf("Arr[%d] = %d,  ", i, Arr[i]);  
}
return 0;
}
OUTPUT
INSERTION OPERATION
I. This operation is performed to insert one or more elements into the array.
II. As per the requirements, an element can be added at the beginning, end,
or at any index of the array.
III. Now, let's see the implementation of inserting an element into the array.
ALGORITHM
Write an algorithm to insert an element can be added at the beginning, end,
or at any index of the array where array may be defined as user input
ALGORITHM
Algorithm: Inserting an Element in an Array
Input:
- An array A of size n
- An integer element to insert
- An integer index i to insert the element at
(optional)
Output: The updated array A with the element
inserted
ALGORITHM
1. Initialize a variable new array of size n+1
2. Initialize a variable j = 0
3. If i is not given, set i = 0 (insert at the beginning)
4. If i < 0 or i > n, output an error message and terminate the
algorithm
5. While j < i, do steps 6-7
6. Set new array[j] = A[j]
7. j=j+1
8. Set new array[i] = element
9. While i <= n, do steps 10-11
10. Set new array[i+1] = A[i]
11. i=i+1
12. Output the updated array new array
13. End
EXAMPLE
1. Insert an element 25 at 4th position of the array
A=<18,30,15,70,12>
ASSIGNMENT
1. Insert an element 25 at beginning of the array A=<18,30,15,70,12>
2. Insert an element 25 at end of the array A=<18,30,15,70,12>
3. Insert an element 25 at 5th position of the array A=<18,30,15,70,12>
4. Insert an element 25 at 2nd position of the array A=<18,30,15,70,12>
PROGRAM
Write a program in C to insert an element can be added at the beginning,
end, or at any index of the array where array may be defined as user input
PROGRAM
#include <stdio.h>
int main()
{
int arr[100];
int size, pos, val;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter the elements of the array:\n");
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
PROGRAM
printf("Enter the position where you want to insert the element: ");
scanf("%d", &pos);
printf("Enter the value to be inserted: ");
scanf("%d", &val);
// shift elements to the right from the last element to pos
for (int i = size; i >= pos; i--)
{
arr[i] = arr[i-1];
}
PROGRAM
// insert the value at the desired position
arr[pos-1] = val;
size++; // increment the size of the array
printf("The updated array is:\n");
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
DELETION OPERATION
As the name implies, this operation removes an element from the array and
then reorganizes all of the array elements.
ALGORITHM
write an algorithm to removes an element from the array at any positions
and then reorganizes all of the array elements where array may be defined
as user input.
ALGORITHM
Algorithm: Removing an Element from an Array
Input:
- An array A of size n
- An integer index i to remove the element at
Output: The updated array A with the element removed
ALGORITHM
1. If i < 0 or i >= n, output an error message and terminate the algorithm
2. Initialize a variable j = i
3. While j < n-1, do steps 4-5
4. Set A[j] = A[j+1]
5. Increment j by 1
6. Set A[n-1] = 0 (or null, depending on the type of array)
7. Output the updated array A
8. End
EXAMPLE
1. Delete an element 15 from the array
A=<18,30,15,70,12>
PROGRAM
write a program in C to removes an element from the array at any positions
and then reorganizes all of the array elements where array may be defined
as user input.
PROGRAM
#include <stdio.h>
int main()
{
int arr[100];
int size, pos;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter the elements of the array:\n");
PROGRAM
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter the position of the element to be deleted: ");
scanf("%d", &pos);
PROGRAM
// shift elements to the left from pos+1 to size-1
for (int i = pos-1; i < size-1; i++)
{
arr[i] = arr[i+1];
}
size--; // decrement the size of the array
printf("The updated array is:\n");
PROGRAM
for (int i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
ASSIGNMENT
1. Delete an element 18 of the array A=<18,30,15,70,12>
2. Delete an element 30 of the array A=<18,30,15,70,12>
3. Delete an element 12 of the array A=<18,30,15,70,12>
4. Delete an element 70 of the array A=<18,30,15,70,12>
SEARCH OPERATION
This operation is performed to search an element in the array based on the
value or index.
ALGORITHM
write an algorithm to search an element in the array based on the value or
index where array may be defined as user input
ALGORITHM
Algorithm: Searching for an Element in an Array
Input:
- An array A of size n
- An integer element to search for
- An integer index i to search at (optional)
Output:
- If searching by value:
- The index of the first occurrence of the element in the array
- Or, an error message if the element is not found in the array
- If searching by index:
- The value of the element at the given index
- Or, an error message if the index is out of bounds of the array
ALGORITHM
1. If i is not given, set i = -1 (search by value)
2. If i < -1 or i >= n, output an error message and terminate the algorithm
3. If i is not -1, output A[i] and terminate the algorithm
4. Initialize a variable j = 0
5. While j < n, do steps 6-8
6. If A[j] equals the element, output j and terminate the algorithm
7. Increment j by 1
8. Output an error message indicating that the element was not found in the array
9. End
PROGRAM
write a program in C to search an element in the array based on the value
or index where array may be defined as user input
PROGRAM
#include <stdio.h>
int main()
{
int arr[100];
int size, choice, value, index, i;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter the elements of the array:\n");
PROGRAM
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
printf("Enter your choice:\n");
printf("1. Search by value\n");
printf("2. Search by index\n");
scanf("%d", &choice);
PROGRAM
switch (choice)
{
case 1:
printf("Enter the value to be searched: ");
scanf("%d", &value);
for (i = 0; i < size; i++)
{
if (arr[i] == value)
{
printf("%d is present at position %d.\n", value, i+1);
break;
}
}
P R OGRAM

if (i == size)
{
printf("%d is not present in the array.\n", value);
}
break;
case 2:
printf("Enter the index to be searched: ");
scanf("%d", &index);
if (index < size) {
printf("Element at index %d is %d.\n", index, arr[index]);
}
else
{
printf("Invalid index.\n");
PROGRAM
}
break;
default:
printf("Invalid choice.\n");
break;
}

return 0;
}
UPDATE OPERATION
This operation is performed to update an existing array element located at
the given index.
ALGORITHM
write an algorithm to update an existing array element located at the given index
where array may be defined as user input
ALGORITHM
Algorithm: Updating an Element in an Array
Input:
- An array A of size n
- An integer index i to update
- A new value v for the element at index i
Output:
- The updated array A
ALGORITHM
1. If i < 0 or i >= n, output an error message and terminate the algorithm
2. Set A[i] = v
3. Output the updated array A
4. End algorithm
PROGRAM
write a program to update an existing array element located at the given
index where array may be defined as user input.
PROGRAM
#include <stdio.h>
int main()
{
int arr[100];
int size, index, value, i;
printf("Enter the size of the array: ");
scanf("%d", &size);
printf("Enter the elements of the array:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
PROGRAM
printf("Enter the index to be updated: ");
scanf("%d", &index);
if (index < size)
{
printf("Enter the new value: ");
scanf("%d", &value);
arr[index] = value;
printf("The updated array is:\n");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
PROGRAM
printf("\n");
}
Else
{
printf("Invalid index.\n");
}
return 0;
}
MERGING OF ARRAY
Merging two arrays means combining the elements of two separate arrays into a
new array.
 The resulting array contains all the elements from both arrays in a sorted order.
ALGORITHM
Write an algorithm to Merge of elements of two array
ALGORITHM
function mergeArrays(arr1, arr2):
1. result = []
2. i=0
3. j=0
4. while i < length(arr1) AND j < length(arr2):
5. if arr1[i] < arr2[j]:
6. result.append(arr1[i])
7. i += 1
8. else:
9. result.append(arr2[j])
10. j += 1
ALGORITHM
11. while i < length(arr1):
12. result.append(arr1[i])
13. i += 1
14. while j < length(arr2):
15. result.append(arr2[j])
16. j += 1
17. return result
PROGRAM
#include <stdio.h>
void merge_arrays(int arr1[], int arr2[], int size1, int size2)
{
int result[size1 + size2];
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2)
{
if (arr1[i] <= arr2[j])
{
result[k] = arr1[i];
i++;
}
PROGRAM
else
{
result[k] = arr2[j];
j++;
}
k++;
}
while (i < size1)
{
result[k] = arr1[i];
i++;
k++;
}
PROGRAM
while (j < size2)
{
result[k] = arr2[j];
j++;
k++;
}
printf("Merged array: ");
for (int i = 0; i < size1 + size2; i++)
{
printf("%d ", result[i]);
}
}
PROGRAM
int main()
{
int size1, size2;
printf("Enter size of first array: ");
scanf("%d", &size1);
int arr1[size1];
printf("Enter elements of first array: ");
for (int i = 0; i < size1; i++)
{
scanf("%d", &arr1[i]);
}
PROGRAM
printf("Enter size of second array: ");
scanf("%d", &size2);
int arr2[size2];
printf("Enter elements of second array: ");
for (int i = 0; i < size2; i++)
{
scanf("%d", &arr2[i]);
}
merge_arrays(arr1, arr2, size1, size2);
return 0;
}
TIME COMPLEXITY OF ARRAY
OPERATIONS
Operation Time Complexity

Access O(1)

Search O(n)

Insertion O(n)

Deletion O(n)

Merging O(m + n)

Update O(n)
SPACE COMPLEXITY OF
ARRAY OPERATIONS
In array, space complexity is O(n).
For Merging it is O(m+n)
ADVANTAGES OF ARRAY
I. Array provides the single name for the group of variables of the same
type. Therefore, it is easy to remember the name of all the elements of an
array.
II. Traversing an array is a very simple process; we just need to increment
the base address of the array in order to visit each element one by one.
III. Any element in the array can be directly accessed by using the index
DISADVANTAGES OF ARRAY
I. Array is homogenous. It means that the elements with similar data type can be
stored in it.
II. In array, there is static memory allocation that is size of an array cannot be
altered.
III. There will be wastage of memory if we store less number of elements than the
declared size.
TWO-DIMENSIONAL ARRAY
I. Two-Dimensional array can be defined as an array of arrays.
II. The Two-Dimensional array is organized as matrices which can be represented as
the collection of rows and columns.
III. However, Two-Dimensional arrays are created to implement a relational database
look alike data structure.
IV. It provides ease of holding bulk of data at once which can be passed to any
number of functions wherever required.
HOW TO DECLARE TWO-
DIMENSIONAL ARRAY
The syntax of declaring two dimensional array is very much similar to that
of a one dimensional array, given as follows:
Datatype array_name[max_rows][max_columns];
Example
int arr[max_rows][max_columns];   
IT PRODUCES THE DATA STRUCTURE WHICH LOOKS LIKE FOLLOWING.
IT PRODUCES THE DATA STRUCTURE
WHICH LOOKS LIKE FOLLOWING.

I. Above image shows the two dimensional array, the elements are
organized in the form of rows and columns.
II. First element of the first row is represented by a[0][0] where the number
shown in the first index is the number of that row while the number shown
in the second index is the number of the column.
HOW DO WE ACCESS DATA IN
A TWO-DIMENSIONAL ARRAY
I. Due to the fact that the elements of Two-Dimensional arrays can be random
accessed.
II. Similar to one dimensional arrays, we can access the individual cells in a Two-
Dimensional array by using the indices of the cells. There are two indices
attached to a particular cell, one is its row number while the other is its column
number.
III. However, we can store the value stored in any particular cell of a Two-
Dimensional array to some variable x by using the following syntax.
int x = a[i][j]; 
where i and j is the row and column number of the cell respectively   
INITIALIZING TWO
DIMENSIONAL ARRAYS
#include <stdio.h>
int main()
{
int m, n;
printf("Enter the number of rows: ");
scanf("%d", &m);
printf("Enter the number of columns: ");
scanf("%d", &n);
INITIALIZING TWO
//DIMENSIONAL ARRAYS
Create a 2D array with m rows and n columns
int array_2d[m][n];
// Prompt the user to input the values of the array
printf("Enter the elements of the array:\n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d", &array_2d[i][j]);
}
}
INITIALIZING TWO DIMENSIONAL ARRAYS
// Print the array to verify its contents
printf("The array is:\n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%d ", array_2d[i][j]);
}
printf("\n");
}

return 0;
}
MAPPING TWO DIMENSIONAL
ARRAY TO ONE DIMENSIONAL
ARRAY
I. When it comes to map a Two dimensional array, most of us might think that why this
mapping is required.
II. However, Two dimensional arrays exists from the user point of view.
III. Two dimensional arrays are created to implement a relational database table lookalike
data structure, in computer memory, the storage technique for Two dimensional array is
similar to that of an one dimensional array.
IV. The size of a two dimensional array is equal to the multiplication of number of rows and
the number of columns present in the array.
V. We do need to map two dimensional array to the one dimensional array in order to store
them in the memory.
VI. A 3 X 3 two dimensional array is shown in the following image.
VII. However, this array needs to be mapped to a one dimensional array in order to store it
into the memory.
MAPPING TWO DIMENSIONAL
ARRAY TO ONE DIMENSIONAL
ARRAY
MAPPING TWO DIMENSIONAL
ARRAY TO ONE DIMENSIONAL
ARRAY
There are two main techniques of storing Two Dimensional array elements
into memory
1. Row Major ordering
2. Column Major ordering
ROW MAJOR ORDERING
I. According to the column major ordering, all the columns of the 2D array
are stored into the memory contiguously.
II. The memory allocation of the array which is shown in in the above image
is given as follows.
ROW MAJOR ORDERING
I. First, the 1st row of the array is stored into the memory completely, then
the 2nd row of the array is stored into the memory completely and so on till
the last row.
COLUMN MAJOR ORDERING
I. According to the column major ordering, all the columns of the 2D array
are stored into the memory contiguously.
II. The memory allocation of the array which is shown in in the above image
is given as follows.
COLUMN MAJOR ORDERING
I. First, the 1st column of the array is stored into the memory completely,
then the 2nd row of the array is stored into the memory completely and so
on till the last column of the array.
CALCULATING THE ADDRESS OF THE RANDOM
ELEMENT OF A TWO DIMENSIONAL ARRAY

Due to the fact that, there are two different techniques of storing the two
dimensional array into the memory, there are two different formulas to
calculate the address of a random element of the Two Dimensional array.
1. By Row Major Order
2. By Column major order
BY ROW MAJOR ORDER
If array is declared by a[m][n] where m is the number of rows while n is the
number of columns, then address of an element a[i][j] of the array stored in
row major order is calculated as,
Address(a[i][j]) = B. A. + (i * n + j) * size   
where, B. A. is the base address or the address of the first element of the
array a[0][0] .
PROBLEM
a[10...30, 55...75], base address of the array (BA) = 0, size of an element = 4 bytes . 
 Find the location of a[15][68].   
Ans: 
Address(a[15][68]) = 0 +((15 - 10) x (68 - 55 + 1) + (68 - 55)) x 4  
= (5 x 14 + 13) x 4  
= 83 x 4   
= 332   
BY COLUMN MAJOR ORDER
If array is declared by a[m][n] where m is the number of rows while n is the
number of columns, then address of an element a[i][j] of the array stored in
row major order is calculated as,
Address(a[i][j]) = ((j*m)+i)*Size + BA   
where BA is the base address of the array.
PROBLEM
A [-5 ... +20][20 ... 70], BA = 1020, Size of element = 8 bytes. 
Find the location of a[0][30].   
Ans: 
Address (A[0][30]) = ((30-20) x 24 + 5)  x 8 + 1020  
 =  245 x 8 + 1020 
= 2980 bytes   
MULTIDIMENSIONAL ARRAYS
I. We can say a Multidimensional array is an array of arrays.
II. Two Dimensional arrays is also a multidimensional array.
III. In a Multi-Dimensional array, elements of an array are arranged in the
form of rows and columns.
IV. Multidimensional array stores elements in tabular form which is also
known as in row-major order or column-major order.
DECLARATION OF MULTI-
DIMENSIONAL ARRAY
Syntax
data_type array_name[size1][size2]….[sizeN];
1. data_type: It defines the type of data that can be held by an array. Here data_type
can be int, char, float. etc.
2. array_name: Name of the array
3. size1, size2,… ,sizeN: Sizes of the dimensions
PICTORIAL REPRESENTATION OF A
MULTIDIMENSIONAL ARRAY

number_of_arrays: number of arrays which flow in the z-axis


rows: number of the rows in the y-axis
columns: number of the columns flow in the x-axis
PICTORIAL REPRESENTATION OF A
MULTIDIMENSIONAL ARRAY
PROGRAM IN C TO IMPLEMENT THREE-
DIMENSIONAL ARRAY

#include <stdio.h>
int main()
{
int x, y, z;
printf("Enter the size of the three-dimensional array: ");
scanf("%d%d%d", &x, &y, &z);
// Create a three-dimensional array with x, y, and z dimensions
int array_3d[x][y][z];
// Prompt the user to input the values of the array
printf("Enter the elements of the array:\n");
PROGRAM IN C TO IMPLEMENT THREE-
DIMENSIONAL ARRAY
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
for (int k = 0; k < z; k++)
{
scanf("%d", &array_3d[i][j][k]);
}
}
}
P R O G R A M I N C T O I M P L E M E N T T H R E E - D I M E N S I O N A L A R R AY

// Print the array to verify its contents


printf("The array is:\n");
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
for (int k = 0; k < z; k++)
{
printf("%d ", array_3d[i][j][k]);
}
P RO G RA M I N C TO I M P L E M E N T T H RE E - DI M E N SI O NA L AR RAY

printf("\n");
}
printf("\n");
}
return 0;
}
EXERCISE
Write a C Program of the following
1. Addition of two matrices
2.Subtraction of two matrices
3.Find out the sum of each row and column of an Matrix
4. Find out Transpose of a matrix
5.Find the Multiplication of two Matrices
6. Write a program to read a set of integers for a square matrix and then decide whether the
matrix represent a magic square or not (A Magic square is a square matrix of integers such
that the sum of every rows, the sum of every column and sum of each diagonal are equal)
7. Find the Inverse of a matrix
ADDITION OF TWO
MATRICES
#include <stdio.h>
int main()
{
int rows, columns, i, j;
int matrix1[10][10], matrix2[10][10], sum[10][10];
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
printf("Enter the elements of matrix 1:\n");
ADDITION OF TWO
MATRICES
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf("%d", &matrix1[i][j]);
}
}
ADDITION OF TWO
MATRICES
printf("Enter the elements of matrix 2:\n");
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf("%d", &matrix2[i][j]);
}
}
ADDITION OF TWO
MATRICES
// Adding two matrices
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
ADDITION OF TWO
MATRICES
// Printing the resultant matrix
printf("Sum of the matrices:\n");
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
printf("%d ", sum[i][j]);
}
printf("\n");
}

return 0;
}
SUBTRACTION OF TWO
MATRICES
#include <stdio.h>
int main()
{
int rows, columns, i, j;
int matrix1[10][10], matrix2[10][10], difference[10][10];
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
printf("Enter the elements of matrix 1:\n");
SUBTRACTION OF TWO
MATRICES
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter the elements of matrix 2:\n");
SUBTRACTION OF TWO
MATRICES
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf("%d", &matrix2[i][j]);
}
}
SUBTRACTION OF TWO
MATRICES
// Subtracting two matrices
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
difference[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
SUBTRACTION OF TWO
MATRICES
// Printing the resultant matrix
printf("Difference of the matrices:\n");
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
printf("%d ", difference[i][j]);
}
printf("\n");
}
return 0;
}
FIND OUT THE SUM OF EACH ROW AND
COLUMN OF AN MATRIX
#include <stdio.h>
int main()
{
int rows, columns, i, j;
int matrix[10][10], rowSum[10] = {0}, colSum[10] = {0};
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
printf("Enter the elements of the matrix:\n");
FIND OUT THE SUM OF EACH ROW AND
COLUMN OF AN MATRIX
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf("%d", &matrix[i][j]);
rowSum[i] += matrix[i][j];
colSum[j] += matrix[i][j];
}
}
FIND OUT THE SUM OF EACH ROW AND
COLUMN OF AN MATRIX
// Printing the sum of each row
printf("Sum of each row:\n");
for (i = 0; i < rows; i++)
{
printf("%d ", rowSum[i]);
}
FIND OUT THE SUM OF EACH ROW AND
COLUMN OF AN MATRIX
// Printing the sum of each column
printf("\nSum of each column:\n");
for (j = 0; j < columns; j++)
{
printf("%d ", colSum[j]);
}
return 0;
}
FIND OUT TRANSPOSE OF A
MATRIX
#include <stdio.h>
int main()
{
int rows, columns, i, j;
int matrix[10][10], transpose[10][10];
printf("Enter the number of rows: ");
scanf("%d", &rows);
printf("Enter the number of columns: ");
scanf("%d", &columns);
printf("Enter the elements of the matrix:\n");
FIND OUT TRANSPOSE OF A
MATRIX
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
scanf("%d", &matrix[i][j]);
}
}
FIND OUT TRANSPOSE OF A
MATRIX
// Finding the transpose of the matrix
for (i = 0; i < rows; i++)
{
for (j = 0; j < columns; j++)
{
transpose[j][i] = matrix[i][j];
}
}
FIND OUT TRANSPOSE OF A
MATRIX
// Printing the transpose of the matrix
printf("Transpose of the matrix:\n");
for (i = 0; i < columns; i++)
{
for (j = 0; j < rows; j++)
{
printf("%d ", transpose[i][j]);
}
printf("\n");
}

return 0;
}
MULTIPLICATION OF TWO
MATRICES
#include <stdio.h>
int main()
{
int rows1, columns1, rows2, columns2, i, j, k;
int matrix1[10][10], matrix2[10][10], result[10][10];
printf("Enter the number of rows for matrix 1: ");
scanf("%d", &rows1);
printf("Enter the number of columns for matrix 1: ");
scanf("%d", &columns1);
printf("Enter the elements of matrix 1:\n");
MULTIPLICATION OF TWO
MATRICES
for (i = 0; i < rows1; i++)
{
for (j = 0; j < columns1; j++)
{
scanf("%d", &matrix1[i][j]);
}
}
printf("Enter the number of rows for matrix 2: ");
scanf("%d", &rows2);
printf("Enter the number of columns for matrix 2: ");
scanf("%d", &columns2);
MULTIPLICATION OF TWO
MATRICES
if (columns1 != rows2)
{
printf("Error: Invalid input. Number of columns in matrix 1 must be equal
to number of rows in matrix 2.\n");
return 1;
}
printf("Enter the elements of matrix 2:\n");
MULTIPLICATION OF TWO
MATRICES
for (i = 0; i < rows2; i++)
{
for (j = 0; j < columns2; j++)
{
scanf("%d", &matrix2[i][j]);
}
}
MULTIPLICATION OF TWO
MATRICES
// Multiplying the two matrices
for (i = 0; i < rows1; i++)
{
for (j = 0; j < columns2; j++)
{
result[i][j] = 0;
for (k = 0; k < columns1; k++)
{
MULTIPLICATION OF TWO
MATRICES
if (k >= rows2) // Handle mismatched dimensions by skipping elements
{
continue;
}
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
 
MULTIPLICATION OF TWO
MATRICES
// Printing the result matrix
printf("Resultant matrix:\n");
for (i = 0; i < rows1; i++)
{
for (j = 0; j < columns2; j++)
{
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}
MAGIC SQUARE
#include <stdio.h>
#define MAX_SIZE 10
int main()
{
int n, i, j, sum, diag_sum1 = 0, diag_sum2 = 0;
int row_sum[MAX_SIZE] = {0}, col_sum[MAX_SIZE] = {0};
int matrix[MAX_SIZE][MAX_SIZE];
printf("Enter the size of the square matrix (max size: %d): ", MAX_SIZE);
scanf("%d", &n);
MAGIC SQUARE
if (n < 1 || n > MAX_SIZE)
{
printf("Error: Invalid matrix size.\n");
return 1;
}

printf("Enter the elements of the matrix:\n");


MAGIC SQUARE
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
scanf("%d", &matrix[i][j]);
}
}
MAGIC SQUARE
// Calculate row sums, column sums, and diagonal sums
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
row_sum[i] += matrix[i][j];
col_sum[j] += matrix[i][j];
MAGIC SQUARE
if (i == j)
{
diag_sum1 += matrix[i][j];
}
if (i + j == n - 1)
{
diag_sum2 += matrix[i][j];
}
}
}
MAGIC SQUARE
// Check if all sums are equal
sum = row_sum[0];
for (i = 1; i < n; i++)
{
if (row_sum[i] != sum || col_sum[i] != sum)
{
printf("The matrix is not a magic square.\n");
return 0;
}
}
MAGIC SQUARE
if (diag_sum1 != sum || diag_sum2 != sum)
{
printf("The matrix is not a magic square.\n");
return 0;
}
printf("The matrix is a magic square!\n");
return 0;
}
INVERSE OF A MATRIX
#include <stdio.h>
#define MAX_SIZE 10
int main()
{
int n, i, j, k;
double temp;
printf("Enter the size of the matrix (max size: %d): ", MAX_SIZE);
scanf("%d", &n);
if (n < 1 || n > MAX_SIZE)
{
printf("Error: Invalid matrix size.\n");
return 1;
}
INVERSE OF A MATRIX
double matrix[MAX_SIZE][MAX_SIZE * 2];
printf("Enter the elements of the matrix:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
scanf("%lf", &matrix[i][j]);
}
}
INVERSE OF A MATRIX
// Append the identity matrix to the right of the input matrix
for (i = 0; i < n; i++)
{
for (j = n; j < 2 * n; j++)
{
if (i == j - n)
{
matrix[i][j] = 1.0;
} else {
matrix[i][j] = 0.0;
}
}
}
INVERSE OF A MATRIX
// Perform row operations to transform the left half of the matrix into the
identity matrix
for (i = 0; i < n; i++)
{
temp = matrix[i][i];
for (j = i; j < 2 * n; j++)
{
matrix[i][j] /= temp;
}
INVERSE OF A MATRIX
for (j = 0; j < n; j++)
{
if (i != j)
{
temp = matrix[j][i];
for (k = i; k < 2 * n; k++)
{
matrix[j][k] -= matrix[i][k] * temp;
}
}
}
}
INVERSE OF A MATRIX
// Extract the right half of the matrix (the inverse of the input matrix)
double inverse[MAX_SIZE][MAX_SIZE];
for (i = 0; i < n; i++)
{
for (j = n; j < 2 * n; j++)
{
inverse[i][j - n] = matrix[i][j];
}
}
INVERSE OF A MATRIX
// Print the inverse matrix
printf("The inverse of the matrix is:\n");
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
printf("%f ", inverse[i][j]);
}
printf("\n");
}

return 0;
}
EXERCISE ON STRINGS
Write a C Program of the following
1. Uses of gets() function
2. Use of putchar() function
3.Use of puts functions
4.Finding the length of the string using strlen() function and without using strlen() function
5. Program for string concatenation without using the function strcat() and with using strcat()
6.Reversing a string
7.Write a program to check whether the given string is palindrome or not
8.IIIustrate of string comparison without using strcmp() or using strcmp().
9.Write a Program to get a substring from an entered string
10. write a program to converts strings into lowercase using strlwr()
11. write a program to converts strings into uppercase using strupr()
12. Program to sort strings of name
13. Write a Program to search for a pattern in a string
PROGRAMS
Q1. Write a C Program for Uses of gets() function
#include <stdio.h>
int main()
{
char name[50];
printf("Enter your name: ");
gets(name);
printf("Hello, %s!\n", name);
return 0;
}
PROGRAMS
Q2. Write a C Program for Use of putchar() function
#include <stdio.h>
int main()
{
char input[50];
int i = 0;
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
while (input[i] != '\0')
{
putchar(input[i]);
i++;
}

return 0;
}
PROGRAMS
Q3. Write a C Program for Use of puts functions
#include <stdio.h>
int main()
{
char input[50];
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
puts(input);
return 0;
}
PROGRAMS
Q4. Write a C Program to Find the length of the string using strlen()
function and without using strlen() function
#include <stdio.h>
#include <string.h>
int main()
{
char input[50];
// Using strlen()
printf("Enter a string: ");
fgets(input, sizeof(input), stdin);
printf("Using strlen(): The length of the string is %ld\n",
strlen(input));
PROGRAMS
// Without using strlen()
int i = 0;
while (input[i] != '\0')
{
i++;
}
printf("Without using strlen(): The length of the string is %d\n", i);
return 0;
}
PROGRAMS
5. Program for string concatenation without using the function strcat()
and with using strcat()

#include <stdio.h>
#include <string.h>
int main()
{
char str1[50], str2[50], str3[100];
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
PROGRAMS
// Concatenate the two strings without using strcat()
int i = 0, j = 0;
while (str1[i] != '\0')
{
str3[i] = str1[i];
i++;
}
while (str2[j] != '\0')
{
str3[i] = str2[j];
i++;
j++;
}
str3[i] = '\0';
printf("Concatenated string without using strcat(): %s\n", str3);
PROGRAMS
// Concatenate the two strings without using strcat()
int i = 0, j = 0;
while (str1[i] != '\0')
{
str3[i] = str1[i];
i++;
}
while (str2[j] != '\0')
{
str3[i] = str2[j];
i++;
j++;
}
str3[i] = '\0';
printf("Concatenated string without using strcat(): %s\n", str3);
PROGRAMS

// Concatenate the two strings using strcat()


strcpy(str3, str1);
strcat(str3, str2);

printf("Concatenated string using strcat(): %s\


n", str3);

return 0;
}
PROGRAM
6.Reversing a string
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int len, i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
PROGRAM
// Remove the newline character from the input string
len = strlen(str);
if (str[len - 1] == '\n')
{
str[len - 1] = '\0';
}
PROGRAM
// Reverse the string
for (i = 0; i < len / 2; i++)
{
char temp = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = temp;
}
printf("Reversed string: %s\n", str);
return 0;
}
PROGRAM
7.Write a program to check whether the given string is palindrome or not
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
int len, i, j, is_palindrome = 1;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
PROGRAM
// Remove the newline character from the input string
len = strlen(str);
if (str[len - 1] == '\n')
{
str[len - 1] = '\0';
}
PROGRAM
// Check if the string is a palindrome
j = len - 1;
for (i = 0; i < len / 2; i++)
{
if (str[i] != str[j])
{
is_palindrome = 0;
break;
}
j--;
}
PROGRAM
// Print the result
if (is_palindrome)
{
printf("The string is a palindrome.\n");
}
else
{
printf("The string is not a palindrome.\n");
}
return 0;
}
PROGRAM
8.IIIustrate of string comparison without using strcmp() or using strcmp().
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100], str2[100];
int len1, len2, i, is_equal = 1, cmp;
// Reading input strings from the user
printf("Enter the first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter the second string: ");
fgets(str2, sizeof(str2), stdin);
PROGRAM
// Removing the newline character from the input strings
len1 = strlen(str1);
if (str1[len1 - 1] == '\n')
{
str1[len1 - 1] = '\0';
}
len2 = strlen(str2);
if (str2[len2 - 1] == '\n')
{
str2[len2 - 1] = '\0';
}
PROGRAM
// Comparing the strings without using strcmp()
if (len1 != len2)
{
is_equal = 0;
}
else
{
for (i = 0; i < len1; i++)
{
if (str1[i] != str2[i])
{
PROGRAM
is_equal = 0;
break;
}
}
}
// Comparing the strings using strcmp()
cmp = strcmp(str1, str2);
// Printing the results
if (is_equal)
{
printf("The strings are equal (without using strcmp()).\n");
}
PROGRAM
else
{
printf("The strings are not equal (without using strcmp()).\n");
}
if (cmp == 0)
{
printf("The strings are equal (using strcmp()).\n");
} else {
printf("The strings are not equal (using strcmp()).\n");
}
return 0;
}
PROGRAM
9.Write a Program to get a substring from an entered string
#include <stdio.h>
#include <string.h>
int main()
{
char str[100], substr[100];
int start, length, i;
// take input for string
printf("Enter a string: ");
scanf("%[^\n]", str);
PROGRAM
// take input for starting index and length of substring
printf("Enter starting index and length of substring: ");
scanf("%d %d", &start, &length);
// copy substring to substr
for (i = 0; i < length && str[start+i] != '\0'; i++)
{
substr[i] = str[start+i];
}
substr[i] = '\0';
// print the substring
printf("Substring: %s\n", substr);
return 0;
}
PROGRAM
10. write a program to converts strings into lowercase using strlwr()
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
// take input for string
printf("Enter a string: ");
scanf("%[^\n]", str);
// convert string to lowercase using strlwr()
strlwr(str);
// print the lowercase string
printf("Lowercase string: %s\n", str);
return 0; }
PROGRAM
11. write a program to converts strings into uppercase using strupr()
#include <stdio.h>
#include <string.h>
int main()
{
char str[100];
// take input for string
printf("Enter a string: ");
scanf("%[^\n]", str);
// convert string to uppercase using strupr()
strupr(str);
// print the uppercase string
printf("Uppercase string: %s\n", str);
return 0;}
PROGRAM
12. Program to sort strings of name
#include <stdio.h>
#include <string.h>
#define MAX_NAMES 5
#define MAX_LENGTH 20
int main()
{
char names[MAX_NAMES][MAX_LENGTH];
char temp[MAX_LENGTH];
int i, j;
// take input for names
printf("Enter %d names:\n", MAX_NAMES);
PROGRAM
for (i = 0; i < MAX_NAMES; i++)
{
scanf("%s", names[i]);
}
// sort the names in alphabetical order
for (i = 0; i < MAX_NAMES-1; i++)
{
for (j = i+1; j < MAX_NAMES; j++)
{
if (strcmp(names[i], names[j]) > 0)
{
PROGRAM
// swap the names
strcpy(temp, names[i]);
strcpy(names[i], names[j]);
strcpy(names[j], temp);
}
}
}
// print the sorted names
printf("Sorted names:\n");
for (i = 0; i < MAX_NAMES; i++)
{
printf("%s\n", names[i]);
}
return 0;}
PROGRAM
13.Write a Program to search for a pattern in a string
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
char pattern[20];
char *result;
// take input for string and pattern
printf("Enter a string: ");
fgets(string, sizeof(string), stdin);
printf("Enter a pattern to search: ");
fgets(pattern, sizeof(pattern), stdin);
PROGRAM
12.Write a Program to search for a pattern in a string
// remove newline character from input
string[strcspn(string, "\n")] = '\0';
pattern[strcspn(pattern, "\n")] = '\0';
// search for pattern in string
result = strstr(string, pattern);
if (result == NULL)
{
printf("Pattern not found in string.\n");
} else {
printf("Pattern found at position %ld in string.\n", result - string);
}
return 0;
}
ENJOY…………….
Thank You

You might also like