+ 2

Can someone please explain this loop?

var x = [1, 2, 3, 4, 5]; var count = 0; for (var i = 1; i < 5; i ++) { if (x[i] >i ) count = count + 1; } //it outputs 4 but I'm still yet to figure out why?

31st Aug 2017, 9:37 AM
Elvis Ngboki
Elvis Ngboki - avatar
3 Respuestas
+ 1
Hi Duke, Going through the for loop and the x array starting with i = 1 we have; x[1] = 2, x[2] = 3 ... x[4] = 5 etc Each time x[i] is bigger than i Then because of that the count variable increments by 1. This happens 4 times. At i = 1; x[1] = 2, 2 > 1 hence count + 1 = 1, count is now 1 "" count + 1 = 2, count is now 2 "" "" At i = 4; x[4] = 5, 5 > 4 hence count + 1 = 4
31st Aug 2017, 9:45 AM
Jay
Jay - avatar
+ 2
Thanks a lot Jay. loops & iteration has always been a little bit confusing to me. it's clearer now; thanks.
31st Aug 2017, 10:00 AM
Elvis Ngboki
Elvis Ngboki - avatar
0
pls can some1 pls explain generics in codes
29th May 2018, 7:52 AM
shedrack slim
shedrack slim - avatar