Select Page

Welcome to “Java Diaries” a series in which I document my self-teaching of Java as both a record of what I’ve done and a reference for me to check back on later – hopefully aiding the information I’ve been consuming to sink in. Click here to view all posts in this series.

Hello everyone, welcome to the first post of 2019. I hope you had a wonderful break and I’m excited to see what 2019 brings. Since the last post on Switch Statements I hadn’t made much progress through the Udemy course though I did manage to cover off the For Loop. The for loop on the surface is quite simple and very powerful, but when I started combining if statements WITH the for loop things started to get a little confusing, luckily the Udemy course I follow sets a lot of unguided challenges which makes you really think about what you are trying to achieve and what you have learnt so far so after completing these challenges I started to find it easier. But first, what isloop?

A loop is a piece of code that executes statements repeatedly until a certain, specified, condition is met.

For Loop Flow Chart

for loop is comprised of 4 elements.

for (initialisation, termination, increment) {
}
  1. We have the keyword for
  2. We then define the intialisation of the loop (ie, we state what the beginning value is)
  3. We state when we want the loop to terminate. 
  4. Lastly, we state the increment we want the original value to increase by each time the code goes around.

Here’s a simple example:

for (int i=1, i<10, i++) {
    System.out.println("The current value of i is " + i);
}

The console output for this loop would be:

The current value of i is 1
The current value of i is 2
The current value of i is 3
The current value of i is 4
The current value of i is 5
The current value of i is 6
The current value of i is 7
The current value of i is 8
The current value of i is 9
The current value of i is 10

Initiliasation: In the above example we initiliased the for loop with an int named and set it’s value to 1.

Termination: We then told the for loop to keep running whilst is less than 10. Once this condition is false we terminate the code.

Increment: Whilst the loop is running we set increment of i++ which means we want the value of to increase by 1.

Let’s apply this to the above flow chart.

For Loop Flow Chart With Example

TIP: The condition has to evaluate as false before the code will stop.

Challenge section header

After we ran through a couple of exercises the main challenge was to create a method that would detect all the odd numbers between a range of values and then sum all these odd numbers together.

To do this I had to create two methods, one which would see whether a number was odd, and then one which would sum all odd numbers together.

The first method was called isOdd and worked as follows:

public static boolean isOdd(int number) {

    if (number < 0) {
    //   System.out.println("Number invalid");
        return false;
    } else if (number % 2 == 0) {
    //   System.out.println("Number is even");
        return false;
    } else {
     // System.out.println("Number is odd");
        return true;
    }

}
  • If the number was less than 0 then this would return false as we only want to deal with numbers above zero.
  • The else if statement checked to see if what was left over after dividing the number by 2 equalled 0. If it did equal zero (number % 2 == 0) then this meant it was an even number (not an odd one) so it would return false.
  • The final else said that if you had gotten past these two previous tests then the number must be odd, so return true.

Now this was working it was time to create the sumOdd method:

    public static int sumOdd(int start, int end) {

        int sum = 0;

        if ((start < 0 || end < start)) {
            return -1;
        }
            for (int i = start; i <= end; i++) {

                if (isOdd(i)) {

                    sum += i;
                }


        }

        return sum;

    }
}
  • First we create a new int variable named sum and give it a value of 0. This is a running sum total of every odd number we have found between the ranges specified.
  • Then we have a validation check using an if statement which checks whether start is less than 0 or whether the value of end is less than start. If either of these conditions are true we will return an error indicator of -1.
  • If the method arguments get past this validation check then a for loop is created. The initialisation variable is set to whatever argument “start” is using init i = start;
  • The loop is set to terminate when i is no longer less than or equal to the end parameter.
  • Each time the loop runs the value of i gets incremented by 1 using i++.
  • Every time the loop runs it checks whether the value of i is an odd number using the isOdd method.
  • If isOdd is true, the value of i is added to the sum variable and the loop starts again.
  • If isOdd is false, the loop runs again from the beginning, after incrementing i by 1.
  • Once the for loop terminates, the value of sum is returned.

We would then call the sumOdd method from within our main method by using the following code:

System.out.println(sumOdd(88, 5103));

Running the above code would print the following value to the console:

6510768

I really struggled with this challenge for one stupid reason…a typo!

Instead of returning false if the number was even it was returning true, it’s funny how such a simple typo can cause such an annoyance!

For Loops were very interesting to learn about and I’m looking forward to the next topic.

See you in the next one!

Last Post Button