for, while or do-while instead of recursion.
public class SumOfArray
{
public static void main(String[] args)
{
int[] arr = {4, 7, 1, 3, 6};
int sum = 0;
for(int i = 0; i < arr.length; i++)
{
sum += arr[i]; // adding each element
}
System.out.println("Total Sum: " + sum);
}
}
Total Sum: 21
public class CountEven
{
public static void main(String[] args)
{
int[] arr = {2, 5, 8, 11, 14};
int count = 0;
for(int i = 0; i < arr.length; i++)
{
if(arr[i] % 2 == 0)
{
count++;
}
}
System.out.println("Total Even Numbers: " + count);
}
}
Total Even Numbers: 3
public class BubbleSort
{
public static void main(String[] args)
{
int[] arr = {5, 3, 8, 1, 2};
for(int i = 0; i < arr.length - 1; i++)
{
for(int j = 0; j < arr.length - i - 1; j++)
{
if(arr[j] > arr[j+1])
{
// swap
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// print sorted array
for(int num : arr)
{
System.out.print(num + " ");
}
}
}
1 2 3 5 8
Try below programs using Iterative Approach in Java:
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.