In java, How to check and print how many times the for loop iterates? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

In java, How to check and print how many times the for loop iterates?

20th Jul 2018, 7:22 AM
Nathan
Nathan - avatar
2 Answers
+ 4
You can use a global variable to check how many times a loop ran int count = 0; for(int i = 2; i < 8; i+=2){ count++; } System.out.println(count); This will print the number of times the loop ran, which is 3 in this case.
20th Jul 2018, 8:04 AM
Vedant Bang
Vedant Bang - avatar
+ 3
if you use some complex and/or not easy calculable condition in for loop, you can use simply an counter var: int counter= 0; for( // for conditions){ counter++; } Obliviously you have to handle loop breaks and "jump" (if needed)
20th Jul 2018, 8:06 AM
KrOW
KrOW - avatar