tags:

views:

207

answers:

3

Hi there,

Im 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...Im 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 inputting the numbers, but it displays them all in one line... The issue here is that I dont know how many columns or rows the user wants, so I cant print out %d %d %d in a matrix form ..

Any thoughts ?

Thanks :)

+1  A: 

You need to dynamically allocate your matrix. For instance:

int* mat;
int dimx,dimy;
scanf("%d", &dimx);
scanf("%d", &dimy);
mat = malloc(dimx * dimy * sizeof(int));

This creates a linear array which can hold the matrix. At this point you can decide whether you want to access it column or row first. I would suggest making a quick macro which calculates the correct offset in the matrix.

Yann Ramin
@theatrus: Thanks for replying, the code you presented is simpler in context but more advanced, I dont know these codes yet (malloc etc.) Thanks :)
ZaZu
+2  A: 

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");
}
Jacob
@Jacob Thanks thats exactly what I was looking for !!! Wow its so simple, just adding another printf statement for a new line .. legend !! thanks !!Oh and btw, yes I agree with storing the size of rows and columns, I only had problems with creating the matrix itself so I didnt include the code, but thanks for sharing extra info !! More is always helpful :) :)
ZaZu
@DM Ah I see, good to be of help! Also, don't forget the tab for the columns, i.e. `printf("%d\t",mat[i][j]);` Also, the link I included explains using `malloc` for 2D arrays in detail so you should consider implementing that ... for fun, at least :)
Jacob
Hmm I didnt know about the \t for tabbing columns, what does it do ? cant I use a float and use 5.2%f for example ?
ZaZu
+1  A: 

need a

for(i=0;i<2;i++)
{
  for(j=0;j<2;j++)
  {
     printf("%d",mat[i][j]);
  }
  printf("\n");
}
Keith Nicholas
@Keith Nicholas : thanks for replying, yes that is the way jacob explained it, thanks for replying !! :)
ZaZu