Module 3 Arrays
Module 3 Arrays
ARRAYS
ARRAYS
•The outer loop will run from i = 0 to i < n – 1, where n is the number of elements in
the list.
•The inner loop will run from j = 0 to j < n – i – 1. It is because, after each iteration of
the outer loop, one element at the end (or at the start if the order is decreasing order)
will be in its right place so we can leave it as it is.
•In the inner loop, we will check if the arr[ j ] > arr[ j + 1 ].
• If it’s true, then we will swap places of these elements.
• If false, we will continue to the next iteration.
Algorithm Bubble sort
Step 1: start
Step 2: input array size n
Step 3 : input array elementS A[]
Step 4: set i=0, temp=0
Step 5: Repeat steps 6-10, while i<n-1
Step 6 :set j=0
Step 7: Repeat steps 8-9 while j<n-1-i
Step 8: if A[j]>A[j+1], then
temp= A[j]
A[j]= A[j+1]
A[j+1]=temp
Step 9:set j=j+1
Step 10: set i=i+1
Step 11: print sorted array elements
Step 12:end
Pseudocode bubble sort
Pseudocode Bubble sort
READ array size n
READ array elements A[]
FOR i=o to i< n-1 do
{
FOR j=0 to j<n-1-i do
{
IF A[j]>A[j+1] then
{
temp= A[j]
A[j]= A[j+1]
A[j+1]=temp
}
}
PRINT sorted array elements
}
BUBBLE SORT PROGRAM
#include<stdio.h>
int main()
{
int array[100], n, i, j, temp=0;
Syntax of 2D Array in C
#include<stdio.h>
int main()
{
int i, j, r, c, sum = 0, matrix[10][10];
printf(“Enter rows and columns of matrix\n”);
scanf(“%d%d”, &r, &c)
for (i = 0; i < r; ++i)
{
for (j = 0; j <c ; ++j)
{
scanf(" %d", &matrix[i][j]);
}
}
if(r==c)
{
for (i = 0; i < r; ++i)
{
for(j=0;j<c;j++)
{
If(i==j)
{
// calculating the main diagonal sum
sum = sum + matrix[i][j];
}}}
// printing the result
printf("\nMain diagonal elements sum is = %d\n", sum);
else
// if both rows and columns are not equal then it is
// not possible to calculate the sum
printf("not a square matrix\n");
return 0;
}
C Program to check whether a matrix is identity matrix or not
#include<stdio.h>
int main()
{
int a[20][20], r,c,i, j, flag=0;
printf(“Enter the order of matrix\n”);
scanf(“%d%d”, &r, &c);
printf(“Enter the elements of matrix\n”);
for (i = 0; i < r; ++i)
{
for (j = 0; j <c ; ++j)
{
scanf(" %d", &a[i][j]);
}
}
// checking for identity matrix
for (i = 0; i < r; ++i)
{
for (j = 0; j <c ; ++j)
{
if(a[i][j]!=0 && a[i][j] !=1)
{
flag=1;
break;
}
}
if(flag==0)
printf(“identity matrix\n”);
else
printf(“Not an identity matrix”);
return 0
}
C Program to find transpose of a matrix
• The transpose of a matrix is a new matrix that is obtained by
exchanging the rows and columns.
• Transpose is obtained by changing A[i][j] to A[j][i].
#include<stdio.h>
int main()
{
int a[20][20], transpose[20][20], r,c,i,j;
printf(“Enter the order of matrix\n”);
scanf(“%d%d”, &r, &c);