Java loops Examples
Posted On
Posted By admin
In this blog post, I am going to demonstrate all of Java’s loops. I am going to write loops that prints the sum of numbers in a List.
For Loop
private static int sumFor(List<Integer> numbers){ int sum = 0; for(int i=0; i < numbers.size();i++){ sum += numbers.get(i); } return sum; }
For Each Loop
private static int sumForEach(List<Integer> numbers){ int sum = 0; for(int num:numbers){ sum += num; } return sum; }
While Loop
private static int sumWhile(List<Integer> numbers){ int sum = 0; int i = 0; while (i < numbers.size()){ sum += numbers.get(i); i++; } return sum; }
Do While Loop
private static int sumDoWhile(List<Integer> numbers){ int sum = 0; int i = 0; do{ sum += numbers.get(i); i++; }while (i < numbers.size()); return sum; }
If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my Java course here
Also, if you'd like to test your Java knowledge, do check out my practice tests course here
Also, if you'd like to test your Java knowledge, do check out my practice tests course here
If you like this post, please do let me know via the comments box below. You can also connect with me via my Facebook Page or subscribe to my Youtube channel!