Subscribe to Stuck in an Infiniteloop        RSS Feed
-----

3 2 1 Initalization

Icon Leave Comment
A trend today has been not initializing values before using them. Now, the compiler will normally throw an error or warning so you get a heads up before seeing:

2 x 3 = 2111157549437

Which is a horrible feeling. And the strong urge to repeat grade school math.

The particularly nasty culprit is Mr. Array. Consider the following:

int size;
cout << "Etner array size :";
cin size;

int arrOne [size][size];
int arrTwo [size][size];
int arrThree[size][size]; //UNINITIALIZED! Red flag! 

//input for array one
 for ( int i = 1; i <= size; i++ )    {
         for ( int j = 1; j <= size; j++ ){
      cout << "Matrix 1, ([ row ][ column ]) [" << i << "][" << j << "] = ";      
       cin >> arrOne[ i ][ j ];
      cout << endl;
      }
   }

//input for array two
 for ( int i = 1; i <= size; i++ )    {
         for ( int j = 1; j <= size; j++ ){
      cout << "Matrix 1, ([ row ][ column ]) [" << i << "][" << j << "] = ";      
       cin >> arrTwo[ i ][ j ];
      cout << endl;
      }
   }

//Multiplying the two matrices to make the third
for ( int i = 1; i <= size; i++ )    {    
      for ( int j = 1; j <= size; j++) {
          for ( j = 1; j <= size; j++) {
       arrThree[ i ] [j] += ( arrOne[ i ][ j ]* arrTwo[ j ][ i ]);
       cout << arrThree[ i ][j] << "  ";
        if (  j % 3 == 0 ) {
             cout << endl;
             }  
         }
     }
}



There is no telling what could be in there. Maybe a monster! So we must initialize all values (even if its just to zero for safety purposes) to keep the goblins asleep.

//Goes right after variable initialization
//****************Fill Arr3 with zeros*************
 for ( int i = 1; i <= size; i++ )    {    
      for ( int j = 1; j <= size; j++) {
         arrThree[ i ][j] = 0;
      }
}




Off topic: How cool is blog code highlighting??
-------------------------------------------------------
KYA out.

0 Comments On This Entry

 

January 2022

S M T W T F S
      1
2345678
9101112131415
161718192021 22
23242526272829
3031     

Tags

    Recent Entries

    Recent Comments

    Search My Blog

    18 user(s) viewing

    18 Guests
    0 member(s)
    0 anonymous member(s)