for and while β to process each element sequentially.
recursion;
therefore, it improves performance by saving both memory and execution time.
O(n)) or near-linear (O(n log n)).
1 to npublic 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
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.