Question: Write a c program to perform array multiplication?
Array multiplication is a common operation in many programming tasks, such as matrix multiplication, image processing, and linear algebra. In this blog post, we will learn how to write a C program to perform array multiplication using pointers and dynamic memory allocation.
First, let us define what array multiplication is. Given two arrays A and B of the same size n, the array multiplication C = A * B is defined as follows:
C[i] = A[i] * B[i] for i = 0, 1, ..., n-1
For example, if A = [1, 2, 3] and B = [4, 5, 6], then C = [4, 10, 18].
To write a C program to perform array multiplication, we need to do the following steps:
1. Declare three pointers to store the addresses of the arrays A, B, and C.
2. Ask the user to enter the size of the arrays and store it in a variable n.
3. Allocate memory for the arrays A, B, and C using the malloc function and check for errors.
4. Ask the user to enter the elements of the arrays A and B and store them using pointer arithmetic.
5. Perform array multiplication by looping through the arrays A and B and storing the result in C using pointer arithmetic.
6. Display the result array C using pointer arithmetic.
7. Free the memory allocated for the arrays A, B, and C using the free function.
The following is a possible implementation of the above steps in C:
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Declare three pointers to store the addresses of the arrays
int *A, *B, *C;
// Declare a variable to store the size of the arrays
int n;
// Ask the user to enter the size of the arrays
printf("Enter the size of the arrays: ");
scanf("%d", &n);
// Allocate memory for the arrays A, B, and C using malloc and check for errors
A = (int *)malloc(n * sizeof(int));
if (A == NULL)
{
printf("Memory allocation failed for A.\n");
exit(1);
}
B = (int *)malloc(n * sizeof(int));
if (B == NULL)
{
printf("Memory allocation failed for B.\n");
exit(1);
}
C = (int *)malloc(n * sizeof(int));
if (C == NULL)
{
printf("Memory allocation failed for C.\n");
exit(1);
}
// Ask the user to enter the elements of the arrays A and B
printf("Enter the elements of array A: ");
for (int i = 0; i < n; i++)
{
scanf("%d", A + i); // Equivalent to scanf("%d", &A[i])
}
printf("Enter the elements of array B: ");
for (int i = 0; i < n; i++)
{
scanf("%d", B + i); // Equivalent to scanf("%d", &B[i])
}
// Perform array multiplication by looping through the arrays A and B
for (int i = 0; i < n; i++)
{
*(C + i) = *(A + i) * *(B + i); // Equivalent to C[i] = A[i] * B[i]
}
// Display the result array C
printf("The result of array multiplication is: ");
for (int i = 0; i < n; i++)
{
printf("%d ", *(C + i)); // Equivalent to printf("%d ", C[i])
}
printf("\n");
// Free the memory allocated for the arrays A, B, and C
free(A);
free(B);
free(C);
return 0;
Comments
Post a Comment
let's start discussion