In this assignment the user has to input a matrix and then the program has to show that matrix and the transpose of it. I've got that part running. My teacher added a tweak. Basically when the user inputs the matrix the program has to only ask the number of columns. And then from there when the user has to input the matrix in matrix form. like for example i tell the program there are 2 columns then i write 12 23

#include<stdio.h>

main()
{
  int m, n, c, d, matrix[10][10], transpose[10][10];

  printf("Enter the number of rows and columns of matrix ");
  scanf("%d%d",&m, &n);
  printf("Enter the elements of matrix \n");

  for( c = 0 ; c < m ; c++ )
    {
      for( d = 0 ; d < n ; d++ )
        {
          scanf("%d",&matrix[c][d]);
        }
    }


  printf("\nHere is your matrix:\n");
  for(c=0;c<m;c++)
    {
      for(d=0;d<n;d++)
        {

          printf("%d ",matrix[c][d]);
        }
      printf("\n");
    }

  for( c = 0 ; c < m ; c++ )
    {
      for( d = 0 ; d < n ; d++ )
        {
          transpose[d][c] = matrix[c][d];
        }
    }

  printf("Transpose of entered matrix :-\n");

  for( c = 0 ; c < n ; c++ )
{
      for( d = 0 ; d < m ; d++ )
        {
          printf("%d\t",transpose[c][d]);
        }
      printf("\n");
    }
  printf("The product of matrix and transpose is %d:", matrix[c][d] * transpose[c][d]);

  return 0;
}

4 5
so then it understands there are 2 rows. I have NO IDEA! here is my code.

Recommended Answers

All 2 Replies

count the rows as the data is entered. When you enter a negative value then stop the loop. For example:

int row = 0;
int value = 0;
int done = 0;
while( !done && row < 10)
{
   int i;
   for(i = 0; i < cols; i++)
   {
      scanf("%d", &value);
      if( value < 0)
      {
         done = 1;
         break;
      }
      array[row][i] = value;
    }
}

Are you limited to a square matrix, or does the program need to support any MxN matrix size? The former is simple enough because the columns and rows match. The latter can be done with dynamic memory (the more general but harder option) or a "large enough" 2D array where the dimensions are something like 100x100 and you only use a subset of it as if the dimensions were smaller.

Judging from your description, the row size is dependent on the input, so when the user stops entering rows, that's how many rows you have. I'd wager that your teacher wants you to start simulating arrays with pointers and dynamic memory though. Here's a basic method for creating such a matrix:

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

int main(void)
{
    int **matrix = NULL, m = 0, n;
    int i, j;

    printf("Enter the number of columns: ");
    fflush(stdout);
    scanf("%d", &n);

    while (1) {
        printf("Enter a row: ");
        fflush(stdout);

        /* Allocate a new row */
        matrix = realloc(matrix, (m + 1) * sizeof *matrix);
        matrix[m] = malloc(n * sizeof *matrix[m]);

        for (i = 0; i < n; ++i) {
            if (scanf("%d", &matrix[m][i]) != 1)
                break;
        }

        if (i != n) {
            /* Didn't read a full row */
            free(matrix[m]);
            break;
        }

        ++m; /* Recognize the new row */
    }

    /* Test output to see if it worked */
    for (i = 0; i < m; ++i) {
        for (j = 0; j < n; ++j)
            printf("%4d", matrix[i][j]);

        putchar('\n');
    }

    /* Free the columns */
    for (i = 0; i < m; ++i)
        free(matrix[i]);

    free(matrix); /* Free the rows */

    return 0;
}

This is important, I omitted error checking for input and allocation failure so as not to obscure the logic. In real code you should never accept input from the user or a file without checking for failure. For example:

if (scanf("%d", &n) != 1) {
    /* n is not valid, scanf() failed */
}

Allocation failure isn't very likely because the system will have been brought to its knees long before malloc() returns NULL on a normal request, but it's still best practice to check for NULL. This is especially important with realloc() because if you blindly assign the result to the same pointer you're resizing, you could potentially lose all of the data if realloc() returns NULL. So a temporary pointer is needed:

int **temp = realloc(matrix, (m + 1) * sizeof *matrix);

if (!temp) {
    /* Reallocation failed */
}

/* Reallocation succeeded */
matrix = temp;
matrix[m] = malloc(n * sizeof *matrix[m]);

if (!matrix[m]) {
    /* Allocation failed */
}

It should go without saying that in the failure cases you should attempt to recover if possible. However, in many cases it's simply not possible to recover from an insufficient memory error, so you'd terminate the application gracefully.

Another important thing to notice is that any memory you dynamically allocate should have a corresponding free. At the end of my program, all of the rows are freed (corresponding to each malloc() call) and then the array of row pointers is freed. For a short running program it's not especially important because most systems will free any memory you request on termination, but for long running programs it's very important and still best practice in all cases.

Note also that if a full row isn't read, I assume that's a break case for the input loop and free the partial row.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.