You are on page 1of 4

Lab 2

C program to sort the array of elements in ascending order using bubble sort
method.
Answer:
#include <stdio.h>

// Function to perform bubble sort


void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
// Swap if the element found is greater than the next element
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

// Function to print an array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


printArray(arr, n);

// Call the bubbleSort function


bubbleSort(arr, n);

printf("Sorted array in ascending order: ");


printArray(arr, n);

return 0;
}

Java Program to multiply two matrices


Answer:
public class MatrixMultiplication {
public static void main(String[] args) {
// Initialize the first matrix
int firstMatrix[][] = { {1, 2, 3}, {4, 5, 6} };
int firstRows = 2, firstCols = 3;

// Initialize the second matrix


int secondMatrix[][] = { {7, 8}, {9, 10}, {11, 12} };
int secondRows = 3, secondCols = 2;

// Check if the number of columns in the first matrix is equal to the number of
rows in the second matrix
if (firstCols != secondRows) {
System.out.println("The matrices cannot be multiplied with each other.");
return;
}

// Initialize the result matrix


int resultMatrix[][] = new int[firstRows][secondCols];

// Perform matrix multiplication


for (int i = 0; i < firstRows; i++) {
for (int j = 0; j < secondCols; j++) {
for (int k = 0; k < firstCols; k++) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}

// Print the result matrix


System.out.println("Product of the matrices:");
for (int i = 0; i < firstRows; i++) {
for (int j = 0; j < secondCols; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}

You might also like