0

I want to create a two dimensional array where number of rows and columns are fixed and column values will be taken from console input.

void main() {
    int myArray[3][5];
    int i;
    int a, b, c, d, e; // for taking column values

    for (i = 0; i < 3; i++) { // i represents number of rows in myArray
        printf("Enter five integer values: ");
        // taking 5 integer values from console input
        scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);

        // putting values in myArray
        myArray[i][1] = a;
        myArray[i][2] = b;
        myArray[i][3] = c;
        myArray[i][4] = d;
        myArray[i][5] = e;
    }
    // print array myArray values (this doesn't show the correct output)
    for (i = 0; i < 3; i++) {
        printf("%d\t %d\t %d\t %d\t %d\t", &myArray[i][1], &myArray[i][2],
               &myArray[i][3], &myArray[i][4], &myArray[i][5]);
        printf("\n");
    }
}

when I run this program, it takes input correctly, but doesn't show the array output as expected. How could I do this, any idea? please help.

NetVipeC
  • 4,402
  • 1
  • 17
  • 19
Esika
  • 31
  • 1
  • 3
  • 6

3 Answers3

2

Your second dimension is declared from myArray[i][0] to myArray[i][4]. Its not from myArray[i][1] to myArray[i][5]

Ranald Lam
  • 496
  • 4
  • 9
1

You had unnecessary & operators in final print. I also removed your a, b, c, d, e variables in order to make the code more concise. You can scanf the values in the arrays directly passing the address of each element.

#include <stdio.h>
void main()
{
    int myArray[3][5];
    int i;

    for(i=0; i<3; i++){ //i represents number of rows in myArray
        printf("Enter five integer values: ");
        //taking 5 integer values from console input
        scanf("%d %d %d %d %d",&myArray[i][0], &myArray[i][1], &myArray[i][2], &myArray[i][3], &myArray[i][4]);  // you can directly scan values in your matrix

    }


    for(i=0; i<3; i++){
        printf("%d\t %d\t %d\t %d\t %d\t\n", myArray[i][0], myArray[i][1], myArray[i][2], myArray[i][3], myArray[i][4]); // no need for the & sign which returns the address of the variable
    }

}
Igor Pejic
  • 3,658
  • 1
  • 14
  • 32
  • thanks for the solution. I have one more thing to know. Is it possible that in the two dimensional array row values will be integer and column values will be float/double? Suppose in my array row means student's roll number and column represents several tutorial numbers then is it possible to take integer number for roll and float/double for tutorial number? – Esika Sep 17 '14 at 16:14
0

Try using %1d

#include <stdio.h>

int main(void) 
{
    int i;
    int x[5];

    printf("Enter The Numbers: ");

    for(i = 0; i < 5; i++)
    {
        scanf("%1d", &x[i]);
    }

    for(i = 0; i < 5; i++)
    {
        printf("%d\n", x[i]);
    }

    return 0;
}
pablo1977
  • 4,281
  • 1
  • 15
  • 41
TerryG
  • 309
  • 1
  • 10