Can anyone explain to me, why the below codes have different output?
void GenerateMatrix(int mat[][MaxSize],int ran[],const int rows,const int cols) { int i,k=0; while (i<rows) { int j=0; while (j<cols) { mat[i][j]=ran[k]; j,k++; } i++; } } and the correct one
void GenerateMatrix(int mat[][MaxSize],int ran[],const int rows,const int cols) { int k=0; for (int i=0; i<rows;i++) { for (int j=0; j<cols;j++) { mat[i][j]=ran[k]; k++; } } } the ran[] is an array declared in main()
int main() { srand(time(NULL)); int a[10]; for (int i=0;i<10;i++) { a[i]={(rand() % 20-0+1)+1}; cout<<a[i]<<endl; } . . . } the first one always output strange random numbers, not in the range of random numbers I set for a[] in main(). The second one is correct. I have change the scope of declaration of k in the first one function, still the same. I'm just wondering witch part result in this?
j,k++;to do? Did you debug to observe whether the variables change as you intended?int i, k = 0is equivalent toint i; int k = 0soiis uninitialized when you are accessing it, triggering undefined behavior. You probably meantint i = 0, k = 0.j,k++is equivalent tok++(assuming the evaluation ofjdoesn't have side-effects), not a very useful statement.j,k++if I want to increase both counter variables at the same time?j++; k++;?