C++ Program Debugging -


i seem having problems program. compiles fine, when first loop asks me positive integer asks me again suppose too. hops down blank space , wont run further until enter number not suppose do. when enter number goes , asks me enter integer suppose problem is, infinite amount of times until quit program. suggestions why happening?

/* search entries of n x n matrix mat in rowwise order entry item */ #include <iostream>  using namespace std;  int main(void)  {   int n=10, item, row=3, col=3, mat[row][col]; bool found;  (int row = 0; row < 3; row++)         (int col = 0; col < 3; col++)         {                 cout << "enter positive integer :  ";                         cin >> row;                 cout << " enter positive integer : ";                 cin >> mat[row][col];         }  cout << "enter positive integer want searched: ";         cin >> item;   for(int i=0; i<row; ++i) {      for(int j=0; j<col; ++j)      {           if(mat[row][col] == item)               found = true;           else                found = false;      }   }  if(found==true)   cout << "item found" ; else     cout << "item found ";  return 0; } 

the line for (int cols = 0; cols < 5; col++) increments variable col, not cols. since cols 0, loop never terminate.

you've done same in for (int rows = 0; rows < 5; row++). infinite loops occur due typos in loop conditions ;)

i point out logic errors during search:

for(int i=0; i<row; ++i) {      for(int j=0; j<col; ++j)      {           if(mat[row][col] == item)               found = true;           else                found = false;     }   } 

when loop ends, found true if mat[row-1][col-1] == item (the last element). heck, row , col never change in loop repeatedly checking exact same element every time! should expect more funky program behavior if don't grasp on variable names. recommend adding debug statements see how variables being modified throughout program (aka: cout << "rows = " << rows << endl;, , cout << "i = " << << endl;, etc). you're preparing recipe disaster when reuse variables.

disclaimer: reusing variables not bad thing. however, it's best avoid until have stronger understanding of variables.


Comments

Popular posts from this blog

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

html - How to style widget with post count different than without post count -

url rewriting - How to redirect a http POST with urlrewritefilter -