1. Aggregating With Loops
Aggregation
Aggregation means we are taking multiple values and combining them in some way. Because loop scope ends at the close curly, aggregation problems require that you create a variable before the loop. Let's look at a few examples:
Sequential Sum
Sum the numbers from 1 to 100. We do this by creating an int called sum, and adding each number from 1 to 100 using a loop. Then, we will print sum after the loop is done.
public class MyProgram { public static void main(String[] args) { int sum = 0; for(int i = 1; i <= 100 ; i++) { sum = sum + i; //same as sum += i; } System.out.println(sum); } }
Sum of Squares
Sum all square numbers that are under 1000. We do this by creating a sum, and adding the square of each number i where i*i is at most 1000.
public class MyProgram { public static void main(String[] args) { int sum = 0; for(int i = 1; i*i < 1000 ; i++) { sum += i*i; } System.out.println(sum); } }
Compound Interest
Calculate how much money you will have if you start with 1000 dollars and receive 5 percent image per year for 100 years.
Although this solution uses double to represent money, you should not use floating point values for currency in actual applications. This is because floating point numbers have rounding errors that will accumulate over time:
public class MyProgram { public static void main(String[] args) { double money = 1000; for(int i = 0; i < 100 ; i++) { //this loops 100 times money *= 1.05; } System.out.println(money); } }
Compound Interest 2
Calculate how many years it would take to double your money with 5 percent interest:
This is a great example where we use both money and year in the for loop declaration:
public class MyProgram { public static void main(String[] args) { int year = 0; for(double money = 1; money < 2; year++) { money *= 1.05; } System.out.println(year); } }
Again, avoid using floating point numbers to represent money in actual applications.