3

I'm new to programming and we just learned arrays in class.
We are tasked to create a C program without using global variables.

I created two functions, one for inputting the data and one for the operations (containing a menu). After making the user choose which operation he would like to do in the operations menu, it will display the result and return back to the menu.

I couldn't figure out how to make some of the variables readable by the operations function since we are not allowed to use global variables.

void matrix(){
int a, b, c, d, k, m, n, p, q, s=0, first[MAX][MAX], second[MAX][MAX], msum[MAX][MAX], firstt[MAX][MAX], secondt[MAX][MAX], prod[MAX][MAX];
system("CLS");
printf("/-----------------------------------------------------------------------------/\n"
       "\t\t\t\tMatrix\n"
       "/-----------------------------------------------------------------------------/\n");
printf("This program will multiply matrices (up to 3x3 matrix only).\n"
       "Please enter the number of rows of the first matrix: ");
scanf("%d", &m);
if(m>3){
    matrixerror();
}
printf("Please enter then number of columns of the first matrix: ");
scanf("%d", &n);
if(n>3){
    matrixerror();
}
printf("Please enter the number of rows of the second matrix: ");//Matrix 2
scanf("%d", &p);
if(p>3){
    matrixerror();
}
printf("Please enter then number of columns of the second matrix: ");
scanf("%d", &q);
if(q>3){
    matrixerror();
}
printf("\nPlease enter the elements of the first matrix:\n");
for(c=0; c<m; ++c)
    for(d=0; d<n; ++d){
        printf("Enter element a%d%d: ",c+1, d+1);
        scanf("%d", &first[c][d]);
    }
printf("\nPlease enter the elements of the second matrix:\n");   
for(c=0; c<p; ++c)
    for(d=0; d<q; ++d){
        printf("Enter element b%d%d: ",c+1, d+1);   
        scanf("%d", &second[c][d]);
    }

matrixmenu();
}

and the other one for the operations

void matrixmenu(){
system("CLS");
char choice;
printf("/-----------------------------------------------------------------------------/\n"
       "\t\t\t\tMatrix\n"
       "/-----------------------------------------------------------------------------/\n");

printf("\n"
       "\t1.  Add Matrices\n"
       "\t2.  Multiply Matrices\n"
       "\t3.  Transpose \n"
       "\tB.  Back \n");
printf("\n\tFirst matrix is : \n\t");
for(a=0; a<m; ++a)
    for(b=0; b<n; ++b){
        printf("%d  ", first[a][b]);
        if (b == n-1)
        printf("\n\n\t");
    }
printf("\n\tSecond matrix is : \n\t");
for(a=0; a<m; ++a)
    for(b=0; b<n; ++b){
        printf("%d  ", second[a][b]);
        if (b == n-1)
        printf("\n\n\t");
    }      
printf("\n");   
printf("/------------------------------------------------------------------------------/ ");
scanf("%s", &choice);
switch(choice){
    case '1':
        printf("\n\tThe sum of entered matrices is: \n\t");

        for (a = 0; a < m; a++){
            for (b = 0 ; b < n; b++){
                msum[a][b] = first[a][b] + second[a][b];
                printf("%d\t", msum[a][b]);
            }
            printf("\n\t");
        }
        printf("\n\t");
        system("PAUSE");
        matrixmenu();
        break;
    case '2':
        if (n != p){
            printf("\n\tError! Matrix cannot be multiplied!\n\t");
            system("PAUSE");
            matrixmenu();
        }
        for (c = 0; c < m; c++){
            for (d = 0; d < q; d++){
                for (k = 0; k < p; k++){
                    s = s + first[c][k]*second[k][d];
                }
            prod[c][d] = s;
            s = 0;
            }
        }
        printf("\n\tThe product matrix is:\n\t");
        for (c = 0; c < m; c++){
            for (d = 0; d < q; d++){
                printf("%d\t", prod[c][d]);
            }
            printf("\n\t");
        }   
        printf("\n\t");
        system("PAUSE");
        matrixmenu();
        break;
    case '3':
        for(a=0; a<m; ++a)//Tranposition
            for(b=0; b<n; ++b)
                firstt[b][a] = first[a][b];
        printf("\n\tThe transpose of the first matrix is:\n\t");
        for(a=0; a<n; ++a)
            for(b=0; b<m; ++b){
                printf("%d  ",firstt[a][b]);
            if(b==m-1)
            used    printf("\n\n\t");
        }
        for(a=0; a<p; ++a)//Tranposition
            for(b=0; b<q; ++b)
                secondt[b][a] = second[a][b];
        printf("\n\tThe transpose of the second matrix is:\n\t");
        for(a=0; a<n; ++a)
            for(b=0; b<m; ++b){
                printf("%d  ",secondt[a][b]);
            if(b==m-1)
                printf("\n\n\t");
            }   
        printf("\n\t");
        system("PAUSE");
        matrixmenu();
        break;
    case 'B':
    case 'b':
        mainmenu();
        break;
    default:
        matrixmenu();
        break;
}
}
Suraj Jain
  • 4,463
  • 28
  • 39

2 Answers2

2

You Can Pass Address of variable to function in which you want to work with that variable .

Let us take an example , suppose

#include<stdio.h>

void testing(int *);

int main(){

  int  x = 3;
  printf("%d\n" , x);

  testing(&x);
  printf("%d" , x);

   }

  void testing(int *j){
     *j = 8;
   }

Output Would Be 3 8 , now x is changed in caller function because you passed the address of x (&x) to the function testing and by using *j you are dereferencing that address and storing 8 in the address that j is pointing to , so in effect x changes because you stored its address in a pointer that now points to that address and then you passed that address to other function and where you dereferenced that address (Dereferencing a pointer means getting the value that is stored in the memory location pointed by the pointer. The operator * is used to do this, and is called the dereferencing operator) and changed the value that is stored .

For More Information Look At This Question What does "dereferencing" a pointer mean?

Community
  • 1
  • 1
Suraj Jain
  • 4,463
  • 28
  • 39
-1

Arrays can be passed as arguments to functions; the function will receive just a pointer to the first element, which you will then be able to index like the original array. The first element of a two-dimensional matrix is a one-dimensional matrix;

Typically, the size of the array must be provided as well, as an integer.

In your case the sizes are known and constant (MAX), but you need 2 "sizes", i.e. the number of rows and columns, per matrix anyway. You can simply pass them on as well.

The program below demonstrates passing a standard array, and additionally presents a feature of modern C, variable length arrays.

#include<stdio.h>

#define MAX 100

// Pass  a matrix with constant number of columns
// known at compile time, and the number of columns 
// and rows we actually use.

// Both declarations are ok. The first index is ignored.

//void print(int mat[MAX][MAX])
void print(int mat[][MAX], int usedRows, int usedCols)
{
    for(int row=0; row<MAX && row<usedRows; row++)
    {
        for(int col=0; col<MAX && col<usedCols; col++)
        {
            printf("%5d", mat[row][col]);
        }
        printf("\n");
    }
}

// Pass a variable length array, together with its 
// dimensions. Both declarations are ok.

// void printVar(int rows, int cols, int vm[rows][cols])
void printVar(int rows, int cols, int vm[][cols])
{
    // demonstrate run-time sizeof(vm[row]).
    // one could use the sizeof construct instead of cols.
    printf("vla row length is %zd (cols: %d)\n",
            sizeof(vm[0])/sizeof(int), cols);

    for(int row=0; row<rows; row++)
    {

        for(int col=0; col<cols; col++)
        {
            printf("%5d", vm[row][col]);
        }
        printf("\n");
    }
}

int main() 
{
    // matrix size known at compile time;
    // we fill only the first 3 rows and columns.
    int m[MAX][MAX] 
        =   {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
            };
    // print the compile-time sized matrix. Function needs to know
    // how many rows and columns we actually used.  
    print(m, 3, 3);

    // Now use a feature of modern C: variable length arrays.
    {
        int numRows, numCols;

        printf("Now variable length array: ");
        printf("Please input two numbers, num rows and num columns: ");
        if( scanf("%d %d", &numRows, &numCols) != 2) 
        { 
            fprintf(stderr, "input error, aborting\n"); 
            return 1; 
        }

        // now define the matrix with the size the user requested.
        int varMat[numRows][numCols];

        // fill it with some data (cannot hard code, becase I
        // don't know the dimensions!)
        for(int row=0; row<numRows; row++)
        {
            for(int col = 0; col < numCols; col++)
            {
                varMat[row][col] = row * numCols + col + 1;
            }
        }

        // And use the function for variable length array to print.
        printVar(numRows, numCols, varMat);
    }
    return 0;
}

Sample session:

$ gcc -std=c11 -Wall -o matrixfuncs matrixfuncs.c && ./matrixfuncs
    1    2    3
    4    5    6
    7    8    9
Now variable length array: Please input two numbers, num rows and num columns: 2 7
vla row length is 7 (cols: 7)
    1    2    3    4    5    6    7
    8    9   10   11   12   13   14

A nicer solution would be to define a struct holding a pointer to such a matrix and the two numbers in a single piece of data which can easier be copied around, but I must assume that structs will be covered after arrays in your course.

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62
  • I liked my program and thought it answers the OP's question nicely. If the downvoter could point out possible improvements to the answer I'd appreciate it, as would the OP. – Peter - Reinstate Monica Mar 01 '17 at 06:28