Why do we use statement if(count > 0)

In this code Why do we use statement if(count > 0) as code works perfectly fine without it and I dont get what purpose count serves at all in this code.

Also why do we put [top] when introducing int right in this code…

Hey @code_breaker-1001, can you please share your code using the online IDE (cb.lk/ide)
The values might repeat if we dont add the count>0 condition. So in order to prevent that from happening we use this condition

Sir I have removed all count related stuff


This is the link of the code
Could you pls explain why count is imp in more detail. I dont get it.

One updation in your code is that right should be initialised with the last column, so it would be:
int right = arr[0].length - 1;

Now coming to the essence of the count variable, if we dont use it, there might be some repetitions in the values.

Take this matrix for example:
int[][] arr =
{ { 11, 12, 13, 14, 15, 16 },
{ 21, 22, 23, 24, 25, 26 },
{ 31, 32, 33, 34, 35, 36 },
{ 41, 42, 43, 44, 45, 46 },
{ 51, 52, 53, 54, 55, 56 } };

Without using the count variable we get the output as:
11, 12, 13, 14, 15, 16, 26, 36, 46, 56, 55, 54, 53, 52, 51, 41, 31, 21, 22, 23, 24, 25, 35, 45, 44, 43, 42, 32, 33, 34, 33, END

As you can see that the value 33 is repeated twice, so we need the count variable to avoid this.

1 Like

Ohhhh
Thank you so much
I got it.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

Sir can u just tell me if using dir here is imp? Cause code is iteself in a loop so I dont need to give direction to go to next condition.

yes giving dir is imp as code is in a loop for a particular row or colum we are writing code for a particular row or column so we need to specify the dir so that the work for that dir should be done properly.

Sir but instead of giving dir writiing code in proper order should be enough right? As each dir just points to the next loop. Also I tried quite a few cases without it and faced no issues in any of them. Incase there is such a case can u send an example?

Yes you can do that but in that case you have to write 4 for loops. Code will also run absolutely fine

Sir with dir aso we have to write 4 loops. Is that not the case?

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.