Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a basic matrix in C (input by user !)

Tags:

c

matrix

I'm trying to ask the user to enter the number of columns and rows they want in a matrix, and then enter the values in the matrix... I'm going to let them insert numbers one row at a time.

How can I create such function ?

#include<stdio.h>
main(){

int mat[10][10],i,j;

for(i=0;i<2;i++)
  for(j=0;j<2;j++){
  scanf("%d",&mat[i][j]);
  } 
for(i=0;i<2;i++)
  for(j=0;j<2;j++)
  printf("%d",mat[i][j]);

}

This works for entering the numbers, but it displays them all in one line... The issue here is that I don't know how many columns or rows the user wants, so I cant print out %d %d %d in a matrix form...

Any thoughts?

Thanks :)

like image 525
NLed Avatar asked May 05 '10 20:05

NLed


1 Answers

How about the following?

First ask the user for the number of rows and columns, store that in say, nrows and ncols (i.e. scanf("%d", &nrows);) and then allocate memory for a 2D array of size nrows x ncols. Thus you can have a matrix of a size specified by the user, and not fixed at some dimension you've hardcoded!

Then store the elements with for(i = 0;i < nrows; ++i) ... and display the elements in the same way except you throw in newlines after every row, i.e.

for(i = 0; i < nrows; ++i)
{
   for(j = 0; j < ncols ; ++j) 
   {
      printf("%d\t",mat[i][j]);
   }
printf("\n");
}
like image 69
Jacob Avatar answered Sep 30 '22 01:09

Jacob