Shared Code

by salsabilalimahmoud·16 views·Jun 9, 2026Open in Playground →
main.cu
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
/*
Name : Salsabil Ali
ID : 2300127
*/

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

#define N 3

__global__ void matmul(const int *A, const int *B, int *C) {
    int cx = threadIdx.x;
    int ry = threadIdx.y;

    if (ry < N && cx < N) {
        int v = 0;
        for (int k = 0; k < N; ++k) {
            v += A[ry * N + k] * B[k * N + cx];
        }
        C[ry * N + cx] = v;
    }
}

int main() {
    size_t bytes = N * N * sizeof(int);
    int *h_A = (int *)malloc(bytes);
    int *h_B = (int *)malloc(bytes);
    int *h_C = (int *)malloc(bytes);

    for (int i = 0; i < N * N; ++i) {
        h_A[i] = 1;
        h_B[i] = 1;
    }

    int *d_A, *d_B, *d_C;
    cudaMalloc(&d_A, bytes);
    cudaMalloc(&d_B, bytes);
    cudaMalloc(&d_C, bytes);

    cudaMemcpy(d_A, h_A, bytes, cudaMemcpyHostToDevice);
    cudaMemcpy(d_B, h_B, bytes, cudaMemcpyHostToDevice);

    dim3 threads(N, N);
    dim3 blocks(1, 1);

    matmul<<<blocks, threads>>>(d_A, d_B, d_C);

    cudaMemcpy(h_C, d_C, bytes, cudaMemcpyDeviceToHost);
    
    printf("Result Matrix C:\n");
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            printf("%d ", h_C[i * N + j]);
        }
        printf("\n");
    }

    cudaFree(d_A); cudaFree(d_B); cudaFree(d_C);
    free(h_A); free(h_B); free(h_C);

    return 0;
}

Comments (0)

to post comments and vote
No comments yet. Be the first to share your thoughts!