3
\$\begingroup\$

I made a simple matrix program that prints some data..I want to know how to reduce amount of lines with some functions or whatever, because there is so much if-s,and for loops.

Tried to make functions but almost every for loop is different, so that did not work.

#include <stdio.h>
main()
{
    int i,j,m,n,sMain,sAnti,sCol,sMainUp,sMainDown,sAntiUp,sAntiDown;
    int arr[30][30];

    printf("What dimensions of matrix you want?(1 number) ");
    scanf("%d",&m);
    n = m;

    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            printf("Type elements: ");
            printf("Element[%d,%d]: ",i,j);
            scanf("%d",&arr[i][j]);
        }
    }
    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
    sMain = 0;
    sAnti = 0;
    sMainUp = 0;
    sMainDown = 0;
    sAntiUp = 0;
    sAntiDown = 0;

    for(i = 0; i < m; i++){
        for(j = 0; j < n; j++){
            if(i == j){
                sMain += arr[i][j];
            }
            if((i + j) == (n - 1)){
                sAnti += arr[i][j];
            }
            if(i < j){
                sMainUp += arr[i][j];
            }
            if(i > j){
                sMainDown += arr[i][j];
            }
            if((i + j) < (n - 1)){
                sAntiUp += arr[i][j];
            }
            if((i + j) > (n - 1)){
                sAntiDown += arr[i][j];
            }
        }
    }
    sCol = 0;
    printf("Sum of what column you want? ");
    scanf("%d",&j);
    for(i = 0; i < m; i++){
        sCol += arr[i][j];
    }
    printf("Sum of main diagonal: %d.\n",sMain);
    printf("Sum of anti(counter) diagonal: %d.\n",sAnti);
    printf("Sum above main diagonal: %d.\n",sMainUp);
    printf("Sum under main diagonal: %d.\n",sMainDown);
    printf("Sum above anti diagonal: %d.\n",sAntiUp);
    printf("Sum under anti diagonal: %d.\n",sAntiDown);
    printf("Sum of %d. column is: %d.",j,sCol);

}
\$\endgroup\$
  • \$\begingroup\$ Welcome to Code Review! What task does this code accomplish? Please tell us, and also make that the title of the question via edit. Maybe you missed the placeholder on the title element: "State the task that your code accomplishes. Make your title distinctive.". Also from How to Ask: "State what your code does in your title, not your main concerns about it.". \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ May 17 at 22:38
3
\$\begingroup\$

Use Symbolic Constants Rather Than Numeric Constants
In most programming languages there is a way to define symbolic constants for numbers which makes the code more readable and easier to maintain. When raw numbers are used in code they are sometimes called Magic Numbers. Using Magic Numbers is generally considered a poor programming practice as discussed in this stackoverflow question.

While the number 30 isn't quite a magic number since it is used as the maximum dimensions for the arrays in the matrix, it would be beneficial to anyone that needs to read or maintain the code to define symbolic constants for it. This would allow anyone who needs to edit the code to change the maximum dimensions to change 1 number in 1 place.

In C this would be:

#define MAXIMUM_MATRIX_DIMENSION 30

and in C++ this would be:

const int MAXIMUM_MATRIX_DIMENSION = 30;

Then the integer array arr could be declared as:

int arr[MAXIMUM_MATRIX_DIMENSION][MAXIMUM_MATRIX_DIMENSION];

It then becomes very easy to change the maximum size of the matrix by only changing one line.

Meaningful Variable Names
The code might be easier to read if the variables m and n had more meaningful names, m could be matrixDimension. It's not really clear what n since it could also be `matrixDimension.

The code might also be more readable if the variable arr had a more meaningful name, perhaps baseMatrix.

Declare Variables as Needed
The C programming language now allows variables to be created where they are needed, for instance the variables i and j could be created within the for loops

    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            printf("Type elements: ");
            printf("Element[%d,%d]: ",i,j);
            scanf("%d",&arr[i][j]);
        }
    }

The variables used to contain the sums should also be declared where they are initialized.

Error Checking on Input
It is always better to check user input before using it to perform actions in the code. For example checking the size of the dimensions before using it as a control value in the previous loop. If the user enters a number less than 1 or greater than 29 the program will experience undefined behavior and may crash. If the number is 0 or less the loops will never execute and if the number is greater than 29 matrix values will be written to memory that hasn't been allocated to the arrays.

    m = -1;
    while (m < 1 or m >= MAXIMUM_MATRIX_DIMENSION)
    {
        printf("What dimensions of matrix you want?(1 integer number greater than 0 and less than %d) ", MAXIMUM_MATRIX_DIMENSION);
        scanf("%d",&m);
    }

Complexity
The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program.

There is also a programming principle called the Single Responsibility Principe that applies here. The Single Responsibility Principle states:

Every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function.

There are at least 4 possible functions in main() and possibly more. Each of the outer for loops is a good candidate for a function. The possible functions are:

  • Get the dimensions of the matrix
  • Get the individual values of the matrix
  • Print the matrix
  • Calculate and report the sums of the matrix columns, rows and diagonals (this could be 2 functions).
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.