Reading from user into array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • blackmustang01gt
    New Member
    • Oct 2006
    • 1

    Reading from user into array

    I am lost on my homework and need help .... here is what I am trying to do and the code I am working on is below it
    Write a program for Matrix addition for two 3 by 3 matrices. -Take the input from the user. -Print both the input matrices and the output matrix.

    #include<stdio. h>
    main()
    {
    int aArray[3][3];
    int bArray[3][3];
    int cArray[3][3];
    int a,b,c,d,e,f;

    for(c = 0; c==2 ; c++)
    {
    for(d = 0; d==2 ;d++)
    {
    printf("enter values for Array 1: /n");
    scanf("%d", aArray[c][d]);
    }
    }

    for(e = 0; e==2;e++)
    {
    for(f = 0; f==2; f++)
    {
    printf("enter values for Array 2");
    scanf("%d", bArray[e][f]);
    }
    }

    for(a = 0; a==2;a++)
    {
    for(b = 0; b==2;b++)
    {
    cArray[a][b] = aArray[a][b] + bArray[a][b];
    }
    }

    printf("%d\n", cArray);
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    int a,b,c,d,e,f;

    You don't need all these variables, 2 will do the job, you can reuse them

    for(c = 0; c==2 ; c++)

    All your loops are like this, they don't work. This basically says, set c to 0, if c is equal to 2 continue executing the loop, at the end of each iteration increment c. As you can see the loop will never execute because c != 2 on the first attempt to run the loop. This would normally be written as

    for(c = 0; c<3 ; c++)

    Reading as set c to 0, if c is less than 3 continue executing the loop, at the end of each iteration increment c.

    3 is a mgic number in your code, you should #define it.

    It would be better if you indicated which element the input request was for by outputing c and d.

    printf("%d\n", cArray);

    This wont work, you will get the value of the pointer pointing at cArray. If you want to output the matrix then you will need to use 2 loops to get the value of every element and print it in the same way you use 2 loops to input every element and to do the addition.

    Comment

    • dtimes6
      New Member
      • Oct 2006
      • 73

      #3
      #include<stdio. h>
      main()
      {
      int N = 3;
      int aArray[N][N];
      int bArray[N][N];
      int cArray[N][N];
      int a,b;

      for(a = 0; a!=N ; a++)
      {
      for(b = 0; b!=N ;b++)
      {
      printf("enter values for Array 1: /n");
      scanf("%d", aArray[a][b]);
      }
      }

      for(a = 0; a!=N;a++)
      {
      for(b = 0; b!=N; b++)
      {
      printf("enter values for Array 2");
      scanf("%d", bArray[a][b]);
      }
      }

      for(a = 0; a!=N;a++)
      {
      for(b = 0; b!=N;b++)
      {
      cArray[a][b] = aArray[a][b] + bArray[a][b];
      }
      }

      printf("%d\n", cArray);
      }

      Comment

      Working...