Functions, arrays and matrices: Difference between revisions

From Applied Science
(Created page with "After learning how to use functions, arrays and matrices, it's time to learn how to use arrays and matrices as function's parameters. A matrix with 10 columns and 10 rows can store up to 100 values, but a function doesn't make 100 calls when we use that matrix in that function. We can have a function with 100 parameters, but if they are all part of a matrix it's much simpler to just use the matrix and then reference to it by a single name. To explain why matrices and ar...")
 
No edit summary
Tag: wikieditor
 
Line 9: Line 9:




<div style="text-align:center;">
<center>'''What comes below requires knowledge about arrays, matrices and functions'''</center>
'''What comes below requires knowledge about arrays, matrices and functions'''
</div>




* '''Function that counts how many times a number occurs in an array'''
* '''Function that counts how many times a number occurs in an array'''
 
<source lang="c">
<div class="code">
/* receives the array, the max number of elements to compare and the value x
<span class="codecomment">/* receives the array, the max number of elements to compare and the value x to be compared against all array's values */</span><br />
  to be compared against all array's values */
int count (int array[], int ind_max, int x) {<div style="margin-left:1.5em;">
int count (int array[], int ind_max, int x) {
int i, found = 0;
    int i, found = 0;
 
   
for (i = 0; i < ind_max; i++)<br />
    for (i = 0; i < ind_max; i++)
if (array[i] == x)<br />
        if (array[i] == x)
found++;
            found++;


return found;
return found;
</div>
}
}
</div>
</source>
<div style="margin-left:1.5em;">
 
Pretty simple. It's just one comparison operation and a counter.
Pretty simple. It's just one comparison operation and a counter.
</div>




* '''Functions that counts how many lines of a matrix have all elements with the same value'''
* '''Functions that counts how many lines of a matrix have all elements with the same value'''
<div class="code">
<source lang="c">
include <stdio.h>
include <stdio.h>


<span class="codecomment">/* Counts how many matri'x rows have the same number in all columns. If the element of one row is different from the element of the same row and in the next column, stop. If the loop wasn't broken, then all elements of that row are the same, then count one row found */</span><br />
/* Counts how many matri'x rows have the same number in all columns
int count (int matrix[][max], int imax, jmax) {<div style="margin-left:1.5em;">
  If the element of one row is different from the element of the same row
int i, row_count = 0;
  and in the next column, stop
for (i = 0; i < imax; i++) {<div style="margin-left:1.5em;">
  If the loop wasn't broken, then all elements of that row are the same,
for (j = 0; j < jmax - 1; j++)  
  then count one row found */
if (matrix[i][j] != matrix[i][j + 1]) break;
int count (int matrix[][max], int imax, jmax) {
</div>
    int i, row_count = 0;
if (j == jmax) row_count++;
   
</div>
    for (i = 0; i < imax; i++) {
}<br />
        for (j = 0; j < jmax - 1; j++)
return row_count;<br />
              if (matrix[i][j] != matrix[i][j + 1]) break;
       
        if (j == jmax)
            row_count++;
    }
 
return row_count;
}
}
</div>
</source>
<div style="margin-left:1.5em;">
 
The algorithm is pretty simple, but be careful with the counter! Pay a lot of attention to the indexes' counters! As an exercise, try to modify it to the following problems:
The algorithm is pretty simple, but be careful with the counter! Pay a lot of attention to the indexes' counters! As an exercise, try to modify it to the following problems:
count how many matrix's rows are equal to a number x; count columns rather than rows.
count how many matrix's rows are equal to a number x; count columns rather than rows.
</div>
</source>




* '''Function that does the product of two matrices'''
* '''Function that does the product of two matrices'''
<div class="code">
<source lang="c">
<span class="codecomment">/* Receives the matrix a, of n rows and max columns and the matrix b of n rows and m colums. Multiply a and b, storing the result in matrix c, of n rows and mm columns. If m columns doesn't match nn rows, return 0 without multiplying the matrices */</span><br />
/* Receives the matrix a, of n rows and max columns
int multmat (int a[][max], int b[][max], int c[][max], int n, int m, int nn, int mm) {<br />
  and the matrix b of n rows and m colums.
int i, j, k = 0;<br />
  Multiply a and b, storing the result in matrix c,
if (m != nn) return 0;
  of n rows and mm columns.
  If m columns doesn't match nn rows, return 0
  without multiplying the matrices */
int multmat (int a[][max], int b[][max], int c[][max], int n, int m, int nn, int mm) {
    int i, j, k = 0;
 
    if (m != nn)
        return 0;


for (i = 0; i < n; i++)<div style="margin-left:1.5em;">
    for (i = 0; i < n; i++)
for (j = 0; j < m; j++) {<div style="margin-left:1.5em;">
          for (j = 0; j < m; j++) {
c[i][j] = 0;<br />
              c[i][j] = 0;
for (k = 0; k < mm; k++) c[i][j] += a[i][k] * b[k][j];
             
</div>
              for (k = 0; k < mm; k++)
                    c[i][j] += a[i][k] * b[k][j];
          }
}
}
</div>
}
}
</div>
</source>
<div style="margin-left:1.5em;">
The algorithm obeys to the rule of matrix multiplication. It's a bit hard to track it because there are three loops in cascade. In this case the performance has been traded for a sequence of operations that clearly matches the way matrix multiplication would be done on paper.  
The algorithm obeys to the rule of matrix multiplication. It's a bit hard to track it because there are three loops in cascade. In this case the performance has been traded for a sequence of operations that clearly matches the way matrix multiplication would be done on paper.  


Return 0 is used to tell the program that the multiplication cannot be done. This is a classical example of a function which includes some check to prevent some incorrect operation to be done if the input is invalid.
Return 0 is used to tell the program that the multiplication cannot be done. This is a classical example of a function which includes some check to prevent some incorrect operation to be done if the input is invalid.
</div>

Latest revision as of 23:44, 21 January 2025

After learning how to use functions, arrays and matrices, it's time to learn how to use arrays and matrices as function's parameters. A matrix with 10 columns and 10 rows can store up to 100 values, but a function doesn't make 100 calls when we use that matrix in that function. We can have a function with 100 parameters, but if they are all part of a matrix it's much simpler to just use the matrix and then reference to it by a single name.

To explain why matrices and arrays have the first pair of brackets left empty, an explanation about how arrays are stored in memory and about pointers is required. For the moment we can learn how to use arrays and functions without having to worry about that.

Errors of logic:

  • The same with arrays and matrices when used without functions;
  • Errors related to the operations with matrices and arrays can often cause your program to crash;
  • It's not possible to return a matrix or array, that is going to be explained when we study pointers.


What comes below requires knowledge about arrays, matrices and functions


  • Function that counts how many times a number occurs in an array
/* receives the array, the max number of elements to compare and the value x
   to be compared against all array's values */
int count (int array[], int ind_max, int x) {
    int i, found = 0;
    
    for (i = 0; i < ind_max; i++)
         if (array[i] == x)
             found++;

return found;
}

Pretty simple. It's just one comparison operation and a counter.


  • Functions that counts how many lines of a matrix have all elements with the same value
include <stdio.h>

/* Counts how many matri'x rows have the same number in all columns
   If the element of one row is different from the element of the same row
   and in the next column, stop
   If the loop wasn't broken, then all elements of that row are the same,
   then count one row found */
int count (int matrix[][max], int imax, jmax) {
    int i, row_count = 0;
    
    for (i = 0; i < imax; i++) {
         for (j = 0; j < jmax - 1; j++)
              if (matrix[i][j] != matrix[i][j + 1]) break;
         
         if (j == jmax)
             row_count++;
    }

return row_count;
}

The algorithm is pretty simple, but be careful with the counter! Pay a lot of attention to the indexes' counters! As an exercise, try to modify it to the following problems: count how many matrix's rows are equal to a number x; count columns rather than rows. </source>


  • Function that does the product of two matrices
/* Receives the matrix a, of n rows and max columns
   and the matrix b of n rows and m colums.
   Multiply a and b, storing the result in matrix c,
   of n rows and mm columns.
   If m columns doesn't match nn rows, return 0
   without multiplying the matrices */
int multmat (int a[][max], int b[][max], int c[][max], int n, int m, int nn, int mm) {
     int i, j, k = 0;

     if (m != nn)
         return 0;

     for (i = 0; i < n; i++)
          for (j = 0; j < m; j++) {
               c[i][j] = 0;
              
               for (k = 0; k < mm; k++)
                    c[i][j] += a[i][k] * b[k][j];
          }
}
}

The algorithm obeys to the rule of matrix multiplication. It's a bit hard to track it because there are three loops in cascade. In this case the performance has been traded for a sequence of operations that clearly matches the way matrix multiplication would be done on paper.

Return 0 is used to tell the program that the multiplication cannot be done. This is a classical example of a function which includes some check to prevent some incorrect operation to be done if the input is invalid.