Untitled

mail@pastecode.io avatar
unknown
plain_text
3 years ago
2.4 kB
3
Indexable
Never
#include <stdio.h>
#include <stdlib.h>

void printMatrix(int *matrix, int row, int column);
int largestValue(int *matrix, int row, int column, int *largest_row, int *largest_column);

int main(void)
{
    int stu_id = 70357003;

    int r, c;
    printf("Enter the size of row for a matrix: ");
    scanf("%d", &r);
    printf("Enter the size of column for a matrix: ");
    scanf("%d", &c);

    int mat[r][c];

    for(int i = 0; i < r; i++){
        for(int j = 0; j < c; j++){
            printf("Enter value for Matrix[%d][%d]: ", i+1, j+1);
            scanf("%d", &mat[i][j]);
        }
    }

    printMatrix(mat, r, c);

    int largest_row, largest_column;
    int max = largestValue(mat, r, c, &largest_row, &largest_column);
    printf("The largest value in this matrix is: %d\n", max);
    printf("The index of this value is Matrix[%d][%d]\n", largest_row, largest_column);

    printf("\n\nStudent ID: %d\n\n", stu_id);
    return 0;
}

void printMatrix(int *matrix, int row, int column){
    printf("Matrix in 2D format:\n");
    int count = 0;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < column; j++){
            printf("%d ", *(matrix + count));
            if(j == column - 1){
                printf("\n");
            }
            count++;
        }
    }
}

int largestValue(int *matrix, int row, int column, int *largest_row, int *largest_column){
    int temp_arr[100], count = 0;

    // Converting 2D array into 1D array
    for(int i = 0; i < row; i++){
        for(int j = 0; j < column; j++){
            temp_arr[count] = *(matrix + i*column + j);
            count++;
        }
    }

    // Bubble sort to obtain largest value
    for(int i = 0; i < count; i++){
        for(int j = 0; j < count - i - 1; j++){
            if(temp_arr[j] > temp_arr[j+1]){
                int temp = temp_arr[j];
                temp_arr[j] = temp_arr[j+1];
                temp_arr[j+1] = temp;
            }
        }
    }

    int largest_value = temp_arr[count-1];

    // Find max row and max column
    for(int i = 0; i < row; i++){
        for(int j = 0; j , column; j++){
            if(*(matrix + i*column + j) == largest_value){
                largest_row = i+1; // index of matrix have to + 1
                largest_column = j+1;
            }
        }
    }
    return largest_value;
}