NOTICE ISP is back up.. Stay tuned for class status for Thursday 2017-03-23
Free Java Tutorials >> Table of contents >> Loop Algorithms

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.



			
Run

2. Double Loop Algorithms

Print Multiplication Table

Let's print the following grid:

//1 2 3 4 5
//2 4 6 8 10
//3 6 9 12 15
//4 8 12 16 20
//5 10 15 20 25

Here's the solution code, where we have two loops. Both execute 5 times, and since one loop is in the other, the program outputs 25 numbers:

public class MyProgram {
    public static void main(String[] args) {
		for(int i = 1; i <= 5; i++) {
			for(int j = 1; j <= 5; j++) {
				System.out.print(i*j);
				System.out.print(" ");
				//we could also do System.out.print((i*j)+" ");
				//we will learn more about connecting Strings
				//together, "Concatenation", later
			}
			System.out.println(""); //Add a new line
		}
    }
}

Triangle

Let's print the following shape:

//*
//**
//***
//****
//*****
public class MyProgram {
    public static void main(String[] args) {
		for(int i = 1; i <= 5; i++) {
			//This is an inline for loop
			//the System.out.print("*") is the body of the loop
			for(int j = 1; j <= i; j++) System.out.print("*"); 
			
			//This is not part of the "j" for loop:
			System.out.println(""); //Add a new line
		}
    }
}

The above algorithm is particularly interesting since the inner loop executes more often as the i variable increases.

Rotated Number Table

Print the following table:

//1 6 11 16 21 
//2 7 12 17 22 
//3 8 13 18 23 
//4 9 14 19 24 
//5 10 15 20 25 

Here's the solution:

public class MyProgram {
    public static void main(String[] args) {
		for(int i = 1; i <= 5; i++) {
		    for(int j = 0; j < 5; j++) System.out.print((i+j*5)+" ");
		    System.out.println("");
		}
    }
}


			
Run

3. Prime Numbers

Prime Check

To check if a number is prime, you need to check whether it has any factors between 2 and itself (excluding itself). To do this, we will create a boolean that assumes the number is prime. Then, if even one of the numbers between 2 and itself divide into the number, we will set the boolean to false. This is a very common algorithm when just one case sets a value to false:

public class MyProgram {
    public static void main(String[] args) {
		int number = 171; 
		boolean isPrime = true;
		for(int i = 2; i*i <= number; i++) {
			if( number % i == 0 ) { //if number is divisible by i then it's not prime:
				isPrime = false;
			}
		}
		System.out.println(isPrime);
    }
}

Prime Enumeration

Print all prime numbers between 2 and 1000. Prime numbers are very important in computing, but we can find them by running the previous prime-check algorithm in a loop. Let's check all the numbers between 2 and 1000 and see if they are prime:

public class MyProgram {
    public static void main(String[] args) {
		for(int number = 2; number <= 1000; number++) {
			boolean isPrime = true;
			for(int i = 2; i*i <= number; i++) {
				if( number % i == 0 ) { //if number is divisible by i then it's not prime:
					isPrime = false;
				}
			}
			if(isPrime) {
				System.out.println(number);
			}
		}
    }
}

We see a powerful strategy here on building more complex algorithms, which is that we can use simple algorithms inside of larger algorithms. Later on, we will learn techniques to apply this to very large applications.



			
Run

4. Number Digits

Summing Digits

Sum the digits of the number 123456. We will need to use the modulo (%) operator in a clever way. First, we will add 6 to a sum, then we will divide number by 10 to get 12345. Then, we will add 5 into sum. Each time, we will mod by 10 to get the ones digit, and we will divide by 10 to cut off another digit:

public class MyProgram {
    public static void main(String[] args) {
		int number = 123456; 
		int sum = 0;
		for(int num = number; num > 0; num /= 10) {
			sum += num % 10;
		}
		System.out.println(sum); //prints 21
    }
}

Finding numbers with digit sum

Print all number from 1 to 1000 whose digits sum to 10. Like the primes problem from earlier, we can combine a loop with the sum-digits algorithm:

public class MyProgram {
    public static void main(String[] args) {
		for(int number = 1; number <= 1000; number++) {
			int sum = 0;
			for(int num = number; num > 0; num /= 10) {
				sum += num % 10;
			}
			if(sum == 10) {
				System.out.println(number);
			}
		}
    }
}


			
Run

Previous: Loops

Next: Arrays