Home > front end >  How can i do this in c arrays?
How can i do this in c arrays?

Time:07-05

3 arrays of size 3x3 with integer data will be defined. The first two arrays will be filled with random numbers, while the elements of the 3rd array will be the sum of the elements of these two arrays (eg result[i][j] = first[i][j] second[i][j] ). All the latest sequences will be printed to the screen. How can i do this in c language ?

wrong code:

int main () {
    int i,j;
    int a [3][3] ;
    int b [3][3]  ;
    int c [3][3] =  {a [3][3]     b [3][3]};
    srand(time(NULL));
    printf ("\nElements of array are:\n");
    for (i = 0; i < 3; i  ){
        for(j=0; j<3; j  ){

            a[i][j]=rand() 1;
            b[i][j]=rand() 1;
            printf ("\n",a[i][j],b[i][j],c[i][j]);
        }
    }
}

CodePudding user response:

Here's a revised code (haven't run it) Added some comments for the few changes i made.

int main ()
{
    int a [3][3];
    int b [3][3];
    int c [3][3]; //removed initialization

    srand(time(NULL));
    printf ("\nElements of array are:\n");

    for (int i = 0; i < 3; i  )
    {
        for(int j=0; j<3; j  )
        {
            a[i][j] = (rand() % 10)   1;
            b[i][j] = (rand() % 10)   1;
            c[i][j] = a[i][j]   b[i][j]; //do the sum here
            printf ("%d, %d, %d\n",a[i][j],b[i][j],c[i][j]); //added formating to printf
        } 
     }
}
  • Related