Java loops Examples

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;}

Comments

Popular posts from this blog

How to use logging in SpringBoot with code samples

Python While Loop with code samples

How to convert a List to a Set