i want to ask..
how to create 2D array by asking the user the value....
TQVM..
i want to ask..
how to create 2D array by asking the user the value....
TQVM..
Output:Code:#include <stdio.h> #include <stdlib.h> int *getrow(int length) { int i, ii, ch, *row=malloc(length*sizeof(int)); char buffer[16]; printf("Enter %d numbers seperated by commas\n" "(max 4 digits): ", length); for (i=0; i<length; i++) { ii=0; while ((ch=fgetc(stdin))!=',') { if (ch=='\n') break; buffer[ii]=ch; ii++; } buffer[ii]='\0'; row[i]=atoi(buffer); } return row; } void showmatrix (int *matrix[], int rows, int cols) { int i, ii; for (i=0; i<rows; i++) { for (ii=0; ii<cols; ii++) printf("%5d", matrix[i][ii]); printf("\n"); } } int main(int argc, char *argv[]) { int rows, cols, i, **matrix; if (argc<3) { printf("Usage \"%s [NO OF ROWS][NO OF COLS]\", eg %s 3 3\n",argv[0],argv[0]); return 0; } rows=atoi(argv[1]); cols=atoi(argv[2]); matrix=malloc(rows*sizeof(int*)); for (i=0; i<rows; i++) { /* LEAK: matrix[i]=malloc(cols*sizeof(int)); */ matrix[i]=getrow(cols); } showmatrix(matrix,rows,cols); for (i=0; i<rows; i++) free(matrix[i]); free(matrix); return 0; }
Code:[/root/C] ./a.out 2 4 Enter 4 numbers seperated by commas (max 4 digits): 999,-128, 9, 666 Enter 4 numbers seperated by commas (max 4 digits): 1024, 42, 0, 11 999 -128 9 666 1024 42 0 11
Last edited by MK27; 02-27-2009 at 08:48 AM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
Last edited by MK27; 02-27-2009 at 08:45 AM.
C programming resources:
GNU C Function and Macro Index -- glibc reference manual
The C Book -- nice online learner guide
Current ISO draft standard
CCAN -- new CPAN like open source library repository
3 (different) GNU debugger tutorials: #1 -- #2 -- #3
cpwiki -- our wiki on sourceforge
A C array is very simple, you can ask the user:
Easy isn't it?Code:int value; int array2d[10][5]; for(int k = 0; k < 10; k++){ for(int i = 0; i < 5; i++){ cout << "What is value for index i " << i << " inside the array k " << k << "?" << endl; cin << value; array2d[k][i] = value; } }
★ Inferno provides Programming Tutorials in a variety of languages. Join our Programming Forums. ★
execute's example is good if your 2D array is of a fixed size, but you would need to convert the example from using the C++ version of the standard input stream to the C version.
On the other hand, it seems that previous responses interpreted "how to create 2D array by asking the user the value" as "how to create 2D array after getting the dimensions from the user".
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)