Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MPO

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

LAB-1

/*
1. Write a simple C program to generate a random number without initializing the seed for
the random number generator {Within a span of "one second", if you keep running the
program multiple times, you should see the same random number output}
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
time_t t;
int random_number;

t = time(NULL);// Get the current time in seconds

srand((unsigned int) t);

random_number = rand();// Generate a random number

printf("Random number: %d\n", random_number);

return 0;
}

/*
2. Write a C program to generate a random number in C with initializing the seed for the
random number generator {With every run you should observe a differnt random number}.
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
int random_number;

// Seed the random number generator with the current time


srand(time(NULL));

// Generate a random number


random_number = rand();

printf("Random number: %d\n", random_number);

return 0;
}
/*
3. Write a simple C program to generate a random number between 0 and 9.
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
int random_number;

// Seed the random number generator with the current time


srand(time(NULL));

// Generate a random number between 0 and 9


random_number = rand() % 10;

printf("Random number between 0 and 9: %d\n", random_number);

return 0;
}

//4. Write a simple C program to generate a random number between 1 and 100.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
int random_number;

// Seed the random number generator with the current time


srand(time(NULL));

// Generate a random number between 1 and 100


random_number = (rand() % 100) + 1;

printf("Random number between 1 and 100: %d\n", random_number);

return 0;
}

//5. Write a C program to display the current time.

#include <stdio.h>
#include <time.h>

int main() {
// Declare a variable to hold the current time
time_t current_time;

// Get the current time


current_time = time(NULL);

// Convert the current time to string representation


char *time_str = ctime(&current_time);

// Print the current time


printf("Current time is: %s", time_str);

return 0;
}

//6. Write a C program to find the execution time of outputting Hello world 10 times and
10,000 times respectively.

#include <stdio.h>
#include <time.h>

void print_hello(int times) {


for (int i = 0; i < times; i++) {
printf("Hello, world!\n");
}
}

int main() {
clock_t start, end;
double cpu_time_used;

// Output "Hello, world!" 10 times


start = clock();
print_hello(10);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken to print Hello 10 times: %f seconds\n", cpu_time_used);

// Output "Hello, world!" 10,000 times


start = clock();
print_hello(10000);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("Time taken to print Hello 10,000 times: %f seconds\n", cpu_time_used);

return 0;
}

//7. Write a C program to populate a matrix of size 5*10 by generating random numbers in
the range 1 to 10. Display the matrix to the screen.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROWS 5
#define COLS 10

int main() {
int matrix[ROWS][COLS];
int i, j;

// Seed the random number generator with the current time


srand(time(NULL));

// Populate the matrix with random numbers in the range 1 to 10


for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
matrix[i][j] = (rand() % 10) + 1;
}
}

// Display the matrix


printf("Matrix of size %dx%d with random numbers in the range 1 to 10:\n", ROWS, COLS);
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%2d ", matrix[i][j]);
}
printf("\n");
}

return 0;
}

/* 8. Write a C program to populate a matrix of size 20*50 by generating random numbers in


the range 101 to 201. Display the matrix to the screen. Also determine the smallest, largest, as
well as the sum of all the elements of the matrix and display the results to the screen. Find the
total time taken for the execution of your computations and output the value. */

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ROWS 20
#define COLS 50

int main() {
int matrix[ROWS][COLS];
int i, j;
int smallest, largest, sum;
clock_t start, end;
double total_time;

// Seed the random number generator with the current time


srand(time(NULL));

// Populate the matrix with random numbers in the range 101 to 201
start = clock();
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
matrix[i][j] = (rand() % 101) + 101;
}
}
end = clock();

// Find smallest, largest, and sum of all elements


smallest = largest = sum = matrix[0][0];
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
int current = matrix[i][j];
sum += current;
if (current < smallest) {
smallest = current;
}
if (current > largest) {
largest = current;
}
}
}

// Display the matrix


printf("Matrix of size %dx%d with random numbers in the range 101 to 201:\n", ROWS, COLS);
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%4d ", matrix[i][j]);
}
printf("\n");
}

// Display smallest, largest, and sum of all elements


printf("\nSmallest element: %d\n", smallest);
printf("Largest element: %d\n", largest);
printf("Sum of all elements: %d\n", sum);

// Calculate total time taken for computations


total_time = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("\nTotal time taken for computations: %f seconds\n", total_time);

return 0;
}
LAB-2:
/*1. (i) Write a C program to search for a given element in a matrix. The program should take
a matrix and a target element as input, and it should output whether the element is present in
the matrix or not.
*/

#include <stdio.h>

#define ROWS 3
#define COLS 3

int searchElement(int matrix[ROWS][COLS], int target) {


int i, j;

// Iterate through each element of the matrix


for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
// If the current element matches the target, return 1 (true)
if (matrix[i][j] == target) {
return 1;
}
}
}

// If the element is not found, return 0 (false)


return 0;
}

int main() {
int matrix[ROWS][COLS] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int target, found;

printf("Enter the target element to search: ");


scanf("%d", &target);

// Search for the target element in the matrix


found = searchElement(matrix, target);

if (found) {
printf("Element %d is present in the matrix.\n", target);
} else {
printf("Element %d is not present in the matrix.\n", target);
}

return 0;
}

/*(ii) Modify your code so that you convert the code into a function called search(). Signature
of search() can be as below:
int search(int mat[][], int rows, int cols, int key).
Let the search function return 0 on finding the key, and return -1 if the key is not present in
the matrix. Write a suitable main function which invokes search() and observe your results.
*/

#include <stdio.h>

int search(int mat[][3], int rows, int cols, int key) {


int i, j;

// Iterate through each element of the matrix


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
// If the current element matches the key, return 0
if (mat[i][j] == key) {
return 0;
}
}
}

// If the key is not found, return -1


return -1;
}

int main() {
int matrix[3][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int key, result;

printf("Enter the key to search: ");


scanf("%d", &key);

// Search for the key in the matrix


result = search(matrix, 3, 3, key);

if (result == 0) {
printf("Key %d is present in the matrix.\n", key);
} else {
printf("Key %d is not present in the matrix.\n", key);
}

return 0;
}

/*
2. (i) Write a C program to sort the elements of a matrix. The program should take a matrix
as input and display the sorted matrix.
*/
#include <stdio.h>
#define ROWS 3
#define COLS 3
// Function to sort the elements of a matrix
void sortMatrix(int matrix[ROWS][COLS]) {
int temp;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
for (int k = 0; k < ROWS; k++) {
for (int l = 0; l < COLS; l++) {
if (matrix[i][j] < matrix[k][l]) {
temp = matrix[i][j];
matrix[i][j] = matrix[k][l];
matrix[k][l] = temp;
}
}
}
}
}
}

// Function to display the matrix


void displayMatrix(int matrix[ROWS][COLS]) {
printf("Sorted Matrix:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int matrix[ROWS][COLS];

// Input matrix elements


printf("Enter the elements of the %dx%d matrix:\n", ROWS, COLS);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Sort the matrix


sortMatrix(matrix);

// Display the sorted matrix


displayMatrix(matrix);

return 0;
}
/*
(ii) Modify your code so that you convert the code into a function called sort(). Signature of
matrix_sort() can be as below:
int sort(int mat[][], int rows, int cols).
Let the return value of sort() be zero always. Write a suitable main() which invokes sort() and
observe your results.
*/

#include <stdio.h>

// Function to sort the elements of a matrix


int sort(int mat[][3], int rows, int cols) {
int temp;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
for (int k = 0; k < rows; k++) {
for (int l = 0; l < cols; l++) {
if (mat[i][j] < mat[k][l]) {
temp = mat[i][j];
mat[i][j] = mat[k][l];
mat[k][l] = temp;
}
}
}
}
}
return 0;
}

// Function to display the matrix


void displayMatrix(int mat[][3], int rows, int cols) {
printf("Sorted Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
}

int main() {
int mat[3][3];
int rows = 3;
int cols = 3;

// Input matrix elements


printf("Enter the elements of the %dx%d matrix:\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat[i][j]);
}
}
// Sort the matrix
sort(mat, rows, cols);

// Display the sorted matrix


displayMatrix(mat, rows, cols);

return 0;
}

/*
3. (i) Write a C program to interchange any two rows of a matrix. The user should input the
matrix, and the row numbers to be interchanged, and the program should display the
modified matrix.
*/

#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLS 10

// Function to interchange two rows of a matrix


void interchangeRows(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols, int row1, int
row2) {
if (row1 < 0 || row1 >= rows || row2 < 0 || row2 >= rows) {
printf("Invalid row numbers\n");
return;
}

for (int j = 0; j < cols; j++) {


int temp = matrix[row1][j];
matrix[row1][j] = matrix[row2][j];
matrix[row2][j] = temp;
}
}

// Function to display the matrix


void displayMatrix(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols) {
printf("Modified Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int matrix[MAX_ROWS][MAX_COLS];
int rows, cols, row1, row2;

// Input matrix dimensions


printf("Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &rows, &cols);

// Input matrix elements


printf("Enter the elements of the %dx%d matrix:\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Input rows to be interchanged


printf("Enter the row numbers to be interchanged (0 to %d): ", rows - 1);
scanf("%d %d", &row1, &row2);

// Interchange the rows


interchangeRows(matrix, rows, cols, row1, row2);

// Display the modified matrix


displayMatrix(matrix, rows, cols);

return 0;
}

/*
(ii) Make suitable modifications to your code so that you have function for the same.Write a
suitable main() which invokes your function and observe your results.
*/

#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLS 10

// Function to interchange two rows of a matrix


void interchangeRows(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols, int row1, int
row2) {
if (row1 < 0 || row1 >= rows || row2 < 0 || row2 >= rows) {
printf("Invalid row numbers\n");
return;
}

for (int j = 0; j < cols; j++) {


int temp = matrix[row1][j];
matrix[row1][j] = matrix[row2][j];
matrix[row2][j] = temp;
}
}

// Function to display the matrix


void displayMatrix(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols) {
printf("Modified Matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int matrix[MAX_ROWS][MAX_COLS];
int rows, cols, row1, row2;

// Input matrix dimensions


printf("Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &rows, &cols);

// Input matrix elements


printf("Enter the elements of the %dx%d matrix:\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Input rows to be interchanged


printf("Enter the row numbers to be interchanged (0 to %d): ", rows - 1);
scanf("%d %d", &row1, &row2);

// Interchange the rows


interchangeRows(matrix, rows, cols, row1, row2);

// Display the modified matrix


displayMatrix(matrix, rows, cols);

return 0;
}

/*
4. Implement a C function to find the transpose of a given matrix. The program should take a
matrix as input, computeits transpose, and display the result.
*/

#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLS 10

// Function to compute the transpose of a matrix


void transposeMatrix(int matrix[MAX_ROWS][MAX_COLS], int rows, int cols) {
int transpose[MAX_COLS][MAX_ROWS];

// Computing transpose
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
transpose[i][j] = matrix[j][i];
}
}

// Displaying the transpose


printf("Transpose of the matrix:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
}

int main() {
int matrix[MAX_ROWS][MAX_COLS];
int rows, cols;

// Input matrix dimensions


printf("Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &rows, &cols);

// Input matrix elements


printf("Enter the elements of the %dx%d matrix:\n", rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Compute and display the transpose of the matrix


transposeMatrix(matrix, rows, cols);

return 0;
}

/*
5. Implement a C program to multiply two integer matrices. The program should take two
matrices as input from the user and display the result. If the two matrices are not compatible
for multiplication, output an adequate message to the user.
*/

#include <stdio.h>

#define MAX_ROWS 10
#define MAX_COLS 10

// Function to multiply two matrices


void multiplyMatrices(int mat1[MAX_ROWS][MAX_COLS], int rows1, int cols1, int
mat2[MAX_ROWS][MAX_COLS], int rows2, int cols2) {
if (cols1 != rows2) {
printf("Matrices are not compatible for multiplication.\n");
return;
}

int result[MAX_ROWS][MAX_COLS];

// Initialize result matrix with zeros


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
result[i][j] = 0;
}
}

// Perform matrix multiplication


for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}

// Display the result matrix


printf("Result of matrix multiplication:\n");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
}

int main() {
int mat1[MAX_ROWS][MAX_COLS], mat2[MAX_ROWS][MAX_COLS];
int rows1, cols1, rows2, cols2;

// Input matrix dimensions for the first matrix


printf("Enter the number of rows and columns of the first matrix: ");
scanf("%d %d", &rows1, &cols1);

// Input matrix elements for the first matrix


printf("Enter the elements of the %dx%d first matrix:\n", rows1, cols1);
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
scanf("%d", &mat1[i][j]);
}
}

// Input matrix dimensions for the second matrix


printf("Enter the number of rows and columns of the second matrix: ");
scanf("%d %d", &rows2, &cols2);

// Input matrix elements for the second matrix


printf("Enter the elements of the %dx%d second matrix:\n", rows2, cols2);
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
scanf("%d", &mat2[i][j]);
}
}

// Multiply matrices and display result


multiplyMatrices(mat1, rows1, cols1, mat2, rows2, cols2);

return 0;
}

/*
6. Develop a C program to subtract one matrix from another. Make sure they are compatible
by comparing their rows and columns; give an error message otherwise. The program should
populate both the matrices with random numbers between 20 and 50, display the matrices
first and later display the result matrix. How much time does your computation take?
Convert the code to a function and determine how much time the code takes when your
function is invoked by your main.
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_ROWS 10
#define MAX_COLS 10

// Function to generate a random number between min and max


int getRandomNumber(int min, int max) {
return rand() % (max - min + 1) + min;
}

int main() {
int mat1[MAX_ROWS][MAX_COLS], mat2[MAX_ROWS][MAX_COLS],
result[MAX_ROWS][MAX_COLS];
int rows, cols;

// Seed the random number generator


srand(time(NULL));

// Input matrix dimensions


printf("Enter the number of rows and columns of the matrices: ");
scanf("%d %d", &rows, &cols);

// Populate matrices with random numbers between 20 and 50


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mat1[i][j] = getRandomNumber(20, 50);
mat2[i][j] = getRandomNumber(20, 50);
}
}

// Subtract matrices and store the result


printf("Matrix 1:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat1[i][j]);
}
printf("\n");
}

printf("\nMatrix 2:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat2[i][j]);
}
printf("\n");
}

printf("\nResult:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] - mat2[i][j];
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

//6_1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX_ROWS 10
#define MAX_COLS 10

// Function to generate a random number between min and max


int getRandomNumber(int min, int max) {
return rand() % (max - min + 1) + min;
}

// Function to subtract one matrix from another


void subtractMatrices(int mat1[MAX_ROWS][MAX_COLS], int mat2[MAX_ROWS]
[MAX_COLS], int result[MAX_ROWS][MAX_COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
result[i][j] = mat1[i][j] - mat2[i][j];
}
}
}

int main() {
int mat1[MAX_ROWS][MAX_COLS], mat2[MAX_ROWS][MAX_COLS],
result[MAX_ROWS][MAX_COLS];
int rows, cols;

// Seed the random number generator


srand(time(NULL));

// Input matrix dimensions


printf("Enter the number of rows and columns of the matrices: ");
scanf("%d %d", &rows, &cols);

// Populate matrices with random numbers between 20 and 50


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
mat1[i][j] = getRandomNumber(20, 50);
mat2[i][j] = getRandomNumber(20, 50);
}
}

// Subtract matrices and store the result


printf("Matrix 1:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat1[i][j]);
}
printf("\n");
}

printf("\nMatrix 2:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", mat2[i][j]);
}
printf("\n");
}

printf("\nResult:\n");
subtractMatrices(mat1, mat2, result, rows, cols);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}
return 0;
}

LAB_3:
/*1. Hello from each thread */

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

// start of OpenMP parallel region


#pragma omp parallel
{
printf("Hello from thread %d\n",
omp_get_thread_num());
}
// OpenMP parallel region ends here
printf("\nI'm the master thread!\n");
return 0;
}

/***2. determine the total threads in the parallel region


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

// start of OpenMP parallel region


#pragma omp parallel
{

printf("Total threads executing the the parallel region = %d\n", omp_get_num_threads());


}
// OpenMP parallel region ends here
printf("\nI'm the master thread!\n");
return 0;
}

/*** 3. thread_id of each thread ***/

#include <stdio.h>
#include <omp.h>
int main() {
// start of OpenMP parallel region
#pragma omp parallel
{
printf("My thread id is %d\n", omp_get_thread_num());
}
// OpenMP parallel region ends here
printf("\nI'm the master thread!\n");
return 0;
}

/*
4. Write C code for the following using omp library:
1. Display a welcome message in a parallel bock and observe how many times it gets
displayed.
*/

#include <stdio.h>
#include <omp.h>

int main() {
int count = 0; // Variable to count the number of times the message is displayed

#pragma omp parallel


{
// Display welcome message
#pragma omp critical
{
printf("Welcome to parallel programming with OpenMP!\n");
count++;
}
}

printf("The welcome message was displayed %d times.\n", count);

return 0;
}

/*
5. Write C code for the following using omp library:
Modify the "omp4.c file" to print the thread id of the executing thread, with each disply
message.
*/

#include <stdio.h>
#include <omp.h>

int main() {
int count = 0; // Variable to count the number of times the message is displayed

#pragma omp parallel


{
// Get the thread ID
int tid = omp_get_thread_num();

// Display welcome message along with thread ID


#pragma omp critical
{
printf("Thread %d: Welcome to parallel programming with OpenMP!\n", tid);
count++;
}
}

//printf("The welcome message was displayed %d times.\n", count);

return 0;
}

/*
6. Write C code for the following using omp library:
Further modify the "omp6.c file" to print the total number of executing threads.
*/

#include <stdio.h>
#include <omp.h>

int main() {
int count = 0; // Variable to count the number of times the message is displayed

#pragma omp parallel


{
// Get the thread ID
int tid = omp_get_thread_num();

// Display welcome message along with thread ID


#pragma omp critical
{
printf("Thread %d: Welcome to parallel programming with OpenMP!\n", tid);
count++;
}
}

printf("The welcome message was displayed %d times.\n", count);

return 0;
}

/*
7. Create a parallel block. Compute the sum of numbers from zero to thread_id, and output
the sum to the screen. Run your code and observe the result.
*/

#include <stdio.h>
#include <omp.h>

int main() {
#pragma omp parallel
{
// Get the thread ID
int tid = omp_get_thread_num();
int sum = 0;
// Compute the sum of numbers from zero to thread_id
for (int i = 0; i <= tid; i++) {
sum += i;
}

// Output the sum to the screen


#pragma omp critical
{
printf("Thread %d: Sum from 0 to %d is %d\n", tid, tid, sum);
}
}

return 0;
}

LAB_5:
/*
Illustrate loop parallelism with the for loop by writing a program to calculate the sum of an
array in parallel using OpenMP. (Use a shared variable for the result and private variables
for loop indices).
*/

#include <stdio.h>
#include <omp.h>

#define ARRAY_SIZE 10

int main() {
int array[ARRAY_SIZE];
int sum = 0,i;

// Initialize the array with values


for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = i + 1;
}

// Parallel region to calculate the sum of the array


#pragma omp parallel for private(i) reduction(+:sum)
for (int i = 0; i < ARRAY_SIZE; i++) {
sum += array[i];
}

printf("The sum of the array elements is: %d\n", sum);

return 0;
}
/*
Implement a program to calculate the square of each element in an array in parallel using
OpenMP. Use shared variables for the input array and private variables for the parallel
for loop indices.
*/

#include <stdio.h>
#include <omp.h>

#define ARRAY_SIZE 10

int main() {
int array[ARRAY_SIZE];
int squares[ARRAY_SIZE];
int i;

// Initialize the array with values


for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = i + 1;
}

// Parallel region to calculate the square of each element in the array


#pragma omp parallel for private(i)
for (int i = 0; i < ARRAY_SIZE; i++) {
squares[i] = array[i] * array[i];
}

// Print the squares


printf("Square of each element in the array:\n");
for (int i = 0; i < ARRAY_SIZE; i++) {
printf("%d ", squares[i]);
}
printf("\n");

return 0;
}

/*
Create a parallel program to calculate the factorial of a number using OpenMP. Use a shared
variable for the result, and private variables for loop indices.
*/

#include <stdio.h>
#include <omp.h>

int main() {
int number = 10,i; // Number for which factorial will be calculated
unsigned long long factorial = 1; // Result variable, initialized to 1

// Parallel region to calculate the factorial


#pragma omp parallel for private(i) reduction(*:factorial)
for (int i = 1; i <= number; i++) {
factorial *= i;
}

printf("Factorial of %d is %llu\n", number, factorial);

return 0;
}

/*
Write a program to find the minimum element in an array in parallel using OpenMP. Use
shared variables for the array and the minimum value, and private variables for loop indices.
*/

#include <stdio.h>
#include <omp.h>

#define ARRAY_SIZE 1000

int main() {
int array[ARRAY_SIZE], i;
int min_value = __INT_MAX__; // Initialize min_value to maximum possible value

// Initialize the array with values


for (int i = 0; i < ARRAY_SIZE; i++) {
array[i] = i + 1;
}

// Parallel region to find the minimum element in the array


#pragma omp parallel for private(i) shared(min_value)
for (int i = 0; i < ARRAY_SIZE; i++) {
if (array[i] < min_value) {
#pragma omp critical
{
if (array[i] < min_value) {
min_value = array[i];
}
}
}
}

printf("Minimum element in the array: %d\n", min_value);

return 0;
}

/*
Implement a program to generate the Fibonacci series in parallel using OpenMP. Use shared
variables for the result array and private variables for each thread's local variables.
*/

#include <stdio.h>
#include <omp.h>
#define N 10 // Number of Fibonacci numbers to generate

int main() {
int fib[N];
fib[0] = 0;
fib[1] = 1;

// Parallel region to generate the Fibonacci series


#pragma omp parallel
{
int a = 0, b = 1;
int temp;

// Only one thread needs to compute the Fibonacci series


#pragma omp single
{
for (int i = 2; i < N; i++) {
temp = a + b;
a = b;
b = temp;
fib[i] = temp;
}
}
}

// Print the Fibonacci series


printf("Fibonacci series:\n");
for (int i = 0; i < N; i++) {
printf("%d ", fib[i]);
}
printf("\n");

return 0;
}

/*
Write a program to transpose a matrix in parallel using OpenMP. Use shared variables for
the input and output matrices and private variables for loop indices.
*/

#include <stdio.h>
#include <omp.h>

#define ROWS 3
#define COLS 3

int main() {
int matrix[ROWS][COLS] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int transposed[COLS][ROWS];

// Parallel region to transpose the matrix


#pragma omp parallel for collapse(2)
for (int i = 0; i < COLS; i++) {
for (int j = 0; j < ROWS; j++) {
transposed[i][j] = matrix[j][i];
}
}

// Print the original matrix


printf("Original Matrix:\n");
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

// Print the transposed matrix


printf("\nTransposed Matrix:\n");
for (int i = 0; i < COLS; i++) {
for (int j = 0; j < ROWS; j++) {
printf("%d ", transposed[i][j]);
}
printf("\n");
}

return 0;
}

LAB_6:
//Critical.c
#include <omp.h>
#include <stdio.h>

#define ARR_LEN 100

int main() {
int arr[ARR_LEN];
int sum = 0;

// Initialize array
for (int i = 0; i < ARR_LEN; ++i) {
arr[i] = i + 1;
}

#pragma omp parallel for shared(sum)


for (int i = 0; i < ARR_LEN; ++i)
{
#pragma omp critical
sum += arr[i];
}

printf("Sum: %d\n", sum);

return 0;
}

//Master.c
/*** Example: omp master directive ***/

#include <stdio.h>
#include <omp.h>

int main() {
int num_threads;
int thread_id;

#pragma omp parallel private(thread_id) shared(num_threads)


{
#pragma omp master
{
num_threads = omp_get_num_threads();
printf("Master thread (ID %d) is managing %d threads.\n", omp_get_thread_num(),
num_threads);
}

// All threads execute the following code


thread_id = omp_get_thread_num();
printf("Thread %d is saying hello Embedded!\n", thread_id);
}

return 0;
}

LAB_6:
/*
Write a multithreaded program to multiply every element in an array by a constant number.
Create “4” threads and print the thread number too with the results.
*/

#include <stdio.h>
#include <pthread.h>

#define ARRAY_SIZE 10
#define NUM_THREADS 4
#define CONSTANT 2

int array[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

void *multiply(void *thread_id) {


int tid = *((int *)thread_id);
int start = tid * (ARRAY_SIZE / NUM_THREADS);
int end = start + (ARRAY_SIZE / NUM_THREADS);

for (int i = start; i < end; i++) {


array[i] *= CONSTANT;
printf("Thread %d: Result at index %d = %d\n", tid, i, array[i]);
}

return NULL;
}

int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];

for (int i = 0; i < NUM_THREADS; i++) {


thread_ids[i] = i;
pthread_create(&threads[i], NULL, multiply, (void *)&thread_ids[i]);
}

for (int i = 0; i < NUM_THREADS; i++) {


pthread_join(threads[i], NULL);
}

return 0;
}

/*
Write a multithreaded program to add two arrays.
Create “4” threads and print the thread number with each computation that is done.
*/

#include <stdio.h>
#include <pthread.h>

#define ARRAY_SIZE 10
#define NUM_THREADS 4

int array1[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


int array2[ARRAY_SIZE] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int result[ARRAY_SIZE];

void *add_arrays(void *thread_id) {


int tid = *((int *)thread_id);
int start = tid * (ARRAY_SIZE / NUM_THREADS);
int end = start + (ARRAY_SIZE / NUM_THREADS);

for (int i = start; i < end; i++) {


result[i] = array1[i] + array2[i];
printf("Thread %d: Result at index %d = %d\n", tid, i, result[i]);
}
return NULL;
}

int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];

for (int i = 0; i < NUM_THREADS; i++) {


thread_ids[i] = i;
pthread_create(&threads[i], NULL, add_arrays, (void *)&thread_ids[i]);
}

for (int i = 0; i < NUM_THREADS; i++) {


pthread_join(threads[i], NULL);
}

return 0;
}

/*
Create two functions, one to add two arrays and one to multiply two arrays. Write a program
that will call these two functions in two separate threads. Also display their thread ids
*/

#include <stdio.h>
#include <pthread.h>

#define ARRAY_SIZE 5

int array1[ARRAY_SIZE] = {1, 2, 3, 4, 5};


int array2[ARRAY_SIZE] = {6, 7, 8, 9, 10};
int result_add[ARRAY_SIZE];
int result_multiply[ARRAY_SIZE];

void *add_arrays(void *thread_id) {


int tid = *((int *)thread_id);

for (int i = 0; i < ARRAY_SIZE; i++) {


result_add[i] = array1[i] + array2[i];
printf("Thread %d (Addition): Result at index %d = %d\n", tid, i, result_add[i]);
}

return NULL;
}

void *multiply_arrays(void *thread_id) {


int tid = *((int *)thread_id);

for (int i = 0; i < ARRAY_SIZE; i++) {


result_multiply[i] = array1[i] * array2[i];
printf("Thread %d (Multiplication): Result at index %d = %d\n", tid, i, result_multiply[i]);
}
return NULL;
}

int main() {
pthread_t thread_add, thread_multiply;
int thread_id_add = 1;
int thread_id_multiply = 2;

// Create thread for array addition


pthread_create(&thread_add, NULL, add_arrays, (void *)&thread_id_add);

// Create thread for array multiplication


pthread_create(&thread_multiply, NULL, multiply_arrays, (void *)&thread_id_multiply);

// Wait for both threads to finish


pthread_join(thread_add, NULL);
pthread_join(thread_multiply, NULL);

return 0;
}

/*
Write a multithreaded program to multiply every element in the array by a constant. The
even numbered threads should multiply the elements in the even indices of the array and the
odd numbered threads should multiply the elements present in the odd indices of the array.
(Assume 0 to be the starting even index).
*/

#include <stdio.h>
#include <pthread.h>

#define ARRAY_SIZE 10
#define CONSTANT 2
#define NUM_THREADS 2

int array[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

void *multiply_array(void *thread_id) {


int tid = *((int *)thread_id);
int start, end;

if (tid % 2 == 0) { // Even numbered thread


start = 0;
end = ARRAY_SIZE;
} else { // Odd numbered thread
start = 1;
end = ARRAY_SIZE;
}

for (int i = start; i < end; i += 2) {


array[i] *= CONSTANT;
printf("Thread %d: Result at index %d = %d\n", tid, i, array[i]);
}

return NULL;
}

int main() {
pthread_t threads[NUM_THREADS];
int thread_ids[NUM_THREADS];

for (int i = 0; i < NUM_THREADS; i++) {


thread_ids[i] = i;
pthread_create(&threads[i], NULL, multiply_array, (void *)&thread_ids[i]);
}

for (int i = 0; i < NUM_THREADS; i++) {


pthread_join(threads[i], NULL);
}

return 0;
}

/*
Write a multithreaded program that will take two numbers as input from the user, num1 and
num2. The program should list out all the numbers between 0 and num2 which are divisble by
num1. (parallelise the for loop)
*/

#include <stdio.h>
#include <omp.h>

int main() {
int num1, num2;

// Input num1 and num2 from the user


printf("Enter num1: ");
scanf("%d", &num1);
printf("Enter num2: ");
scanf("%d", &num2);

// Parallel region to list out numbers divisible by num1


#pragma omp parallel
{
#pragma omp for
for (int i = 0; i <= num2; i++) {
if (i % num1 == 0) {
printf("%d ", i);
}
}
}

printf("\n");
return 0;
}

/*
Write a multithreaded program that will compare two arrays, and print all the common
elements and their count.
*/

#include <stdio.h>
#include <pthread.h>

#define ARRAY_SIZE 10

int array1[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};


int array2[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//int array2[ARRAY_SIZE] = {5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
int common_elements[ARRAY_SIZE];
int count = 0;

void *compare_arrays(void *arg) {


int tid = *((int *)arg);

for (int i = 0; i < ARRAY_SIZE; i++) {


if (array1[i] == array2[i]) {
common_elements[count++] = array1[i];
}
}

return NULL;
}

int main() {
pthread_t thread;
int thread_id = 1;

pthread_create(&thread, NULL, compare_arrays, (void *)&thread_id);


pthread_join(thread, NULL);

if (count == 0) {
printf("No common elements found.\n");
} else {
printf("Common elements and their count:\n");
for (int i = 0; i < count; i++) {
printf("%d ", common_elements[i]);
}
printf("\nCount: %d\n", count);
}

return 0;
}
/*
Write a multithreaded program that will find the repetition of a number within a n*n order
square matrix. (Let the intilization of the matrix be done within the parallel region by just
one thread.Let the number to be searched be input by the user before entering the parallel
region).
*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_SIZE 100

int matrix[MAX_SIZE][MAX_SIZE];
int n;
int target;
int repetition_count = 0;

void *search_repetition(void *arg) {


int tid = *((int *)arg);

// Each thread searches its portion of the matrix for repetitions of the target number
for (int i = tid; i < n; i += n) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == target) {
repetition_count++;
}
}
}

return NULL;
}

int main() {
// Input the size of the square matrix and the target number from the user
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
printf("Enter the number to search for: ");
scanf("%d", &target);

// Input matrix elements


printf("Enter the elements of the square matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Number of threads to use is equal to the user input for now


int pthread_num_threads = n;

// Create threads
pthread_t threads[pthread_num_threads];
int thread_ids[pthread_num_threads];
for (int i = 0; i < pthread_num_threads; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, search_repetition, (void *)&thread_ids[i]);
}

// Wait for all threads to finish


for (int i = 0; i < pthread_num_threads; i++) {
pthread_join(threads[i], NULL);
}

// Print the repetition count


printf("The repetition count of the number %d in the matrix is: %d\n", target, repetition_count);

return 0;
}

/*
Write a multithreaded program to compute the sum of all the elements in a matrix. Let each
thread should determine the partial sum of a column. Let the number of threads working
together be equal to the number of columns.
*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_ROWS 100


#define MAX_COLS 100

int matrix[MAX_ROWS][MAX_COLS];
int row_count, col_count;
int total_sum = 0;

void *compute_column_sum(void *arg) {


int col_index = *((int *)arg);
int local_sum = 0;

// Compute the sum of the column assigned to this thread


for (int i = 0; i < row_count; i++) {
local_sum += matrix[i][col_index];
}

// Add the local sum to the total sum


__sync_fetch_and_add(&total_sum, local_sum);

return NULL;
}

int main() {
// Input the size of the matrix from the user
printf("Enter the number of rows in the matrix: ");
scanf("%d", &row_count);
printf("Enter the number of columns in the matrix: ");
scanf("%d", &col_count);

// Input matrix elements


printf("Enter the elements of the matrix:\n");
for (int i = 0; i < row_count; i++) {
for (int j = 0; j < col_count; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Create threads equal to the number of columns


pthread_t threads[col_count];
int thread_ids[col_count];
for (int i = 0; i < col_count; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, compute_column_sum, (void *)&thread_ids[i]);
}

// Wait for all threads to finish


for (int i = 0; i < col_count; i++) {
pthread_join(threads[i], NULL);
}

// Print the total sum


printf("Total sum of all elements in the matrix: %d\n", total_sum);

return 0;
}

/*
Write a multithreaded program to compute the sum of two n*n square order matrices.
Let the intilization of the matrix be done with in the parallel region, just by only one thread
*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_SIZE 10

int matrix1[MAX_SIZE][MAX_SIZE];
int matrix2[MAX_SIZE][MAX_SIZE];
int result[MAX_SIZE][MAX_SIZE];
int n; // Size of the matrices

void *compute_sum(void *args) {


int start_row = *((int *)args);
for (int i = start_row; i < start_row + n; i++) {
for (int j = 0; j < n; j++) {
result[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

pthread_exit(NULL);
}

int main() {
printf("Enter the size of the square matrices: ");
scanf("%d", &n);

// Initialize matrix1 and matrix2 with random values


srand(time(NULL)); // Seed for random number generation
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix1[i][j] = rand() % 10; // Generating random numbers between 0 and 9
matrix2[i][j] = rand() % 10;
}
}

// Create threads to compute the sum of matrices


pthread_t threads[MAX_SIZE];
int thread_args[MAX_SIZE];

for (int i = 0; i < n; i++) {


thread_args[i] = i;
pthread_create(&threads[i], NULL, compute_sum, &thread_args[i]);
}

// Join threads
for (int i = 0; i < n; i++) {
pthread_join(threads[i], NULL);
}

// Displaying the matrices


printf("Matrix 1:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix1[i][j]);
}
printf("\n");
}

printf("Matrix 2:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix2[i][j]);
}
printf("\n");
}
// Displaying the sum matrix
printf("Sum Matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

/*
Write a mulithreaded program to multiply every element in a matrix with a constant number.
The numbers in even rows should be multiplied by even numbered threads, and the number
in odd rows should be multiplied by odd numbered threads. Print the thread number after
each multiplication.
*/

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define MAX_SIZE 100

int matrix[MAX_SIZE][MAX_SIZE];
int result[MAX_SIZE][MAX_SIZE];
int n, constant;

void *multiply_matrix(void *arg) {


int tid = *((int *)arg);

// Determine if the current thread is even or odd


int is_even_thread = tid % 2 == 0;

// Iterate through rows assigned to this thread


for (int i = is_even_thread ? 0 : 1; i < n; i += 2) {
// Multiply elements in the row by the constant
for (int j = 0; j < n; j++) {
result[i][j] = matrix[i][j] * constant;
printf("Thread %d: Multiplying matrix[%d][%d] = %d by constant %d\n", tid, i, j, matrix[i]
[j], constant);
}
}

return NULL;
}

int main() {
// Input the size of the square matrix and the constant number from the user
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
printf("Enter the constant number to multiply with: ");
scanf("%d", &constant);

// Input matrix elements


printf("Enter the elements of the square matrix:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}

// Create threads equal to the number of rows


pthread_t threads[n];
int thread_ids[n];
for (int i = 0; i < n; i++) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, multiply_matrix, (void *)&thread_ids[i]);
}

// Wait for all threads to finish


for (int i = 0; i < n; i++) {
pthread_join(threads[i], NULL);
}

// Print the resulting matrix after multiplication


printf("Resulting matrix after multiplication:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", result[i][j]);
}
printf("\n");
}

return 0;
}

You might also like