In the following code, it works with the size of array (As written while defining the arrays arr and brr ) k/n (or k/m) as well as n/k (or m/k). I'm a beginner in C++ and according to my knowledge, size of an array must be an integer greater than zero. But here this statement goes wrong.
I've tried changing the length of an array to 0 due to the logic that n/k is not an integer and since c++ converts it to 0, writing 0 in place of n/k should be equivalent. But it isn't.
Also, when I run the code by asking the user for values of k,n,m instead of defining it in the source code itself, the code runs only when I write - n/k and m/k - k/n and m/k
And it shows the error "program.exe has stopped working. Windows is checking for a solution to the problem." when I have k/m irrespective that I have n/k or k/n.
I have tried using the debugger too (I'm using Codeblocks) but it did not give me any idea to why is the program still being executed when n/k is not an integer.
#include <iostream>
using namespace std;
int main()
{ int k=9;
int n=2;
int m=3;
int arr[n/k];
int brr[m/k];
for(int i=0;i<k/n;i++)
{int x= n*(i+1);
arr[i]=x;
}
for(int j=0; j<k/m; j++)
{
int y= m*(j+1);
brr[j]=y;
}
cout << "\n";
for(int i=0;i<k/n;i++)
{
cout<< arr[i] <<"\n";
}
cout << "\n";
for(int j=0; j<k/m; j++)
{
cout<< brr[j] <<"\n";
}
return 0;
}
As much as I know, the code should not work in case we write n/k and m/k. But it is. Why?
Note- this code was written to solve https://www.geeksforgeeks.org/count-common-elements-in-two-arrays-containing-multiples-of-n-and-m/ (though I have not completed writing the code to solve the problem fully)
Edit- As many comments have pointed out and given links to answers that explain why n/k is an integer (by integer division), I would like to clarify that the question is not that why n/k is rounded to an integer. The questions are
Why are n/k and k/n given same value in integer division (they aren't the same obviously but as the program works fine for both of them, they seem to be equivalent. Why is it so?)
- Yes n/k is integer division. So the answer should be 0 (because 2/9 would be truncated to 0). But when we replace n/k by 0, the code doesn't work.