Topics Discussed: While loops, do_while loops, counter controlled loops, loop syntax, loop scoping

Source Code Available Here


Loops
In this video I discuss two or the most important constructs in the entire language of java. In the next lesson I talk a bit more about for loops, which seem to be used a little more than while and do_while which we discussed here.


While loops
While loops are statements that will be repeated until either a break statement is reached, or until the condition is no longer true. Here’s a few examples of loops using while:


//syntax while(condition){ //do stuff }
//Examples below

int i=0;
while(i < 9){
     //do stuff
     i++; //increment i-- if you remove this statement, the loop will run infinitely.
}

boolean isTrue=true;
i=0; //reset 0 before the loop

while(isTrue){//while the boolean is true
     if(i > 10){
          isTrue = false;
}//end if
     i++; // increment i
}//End loop

i=0;//reset 0 before the loop
while (i < 10){
     System.out.println(i); //output the value of i each time through the loop
     i++; // increment i each time through the loop
}

In the examples above you’ll notice that we always have a ‘way out’ of the loop, that’s because there is a common error known as an ‘infinite loop’ in which your code executes endlessly because your loop is unable to exit.


Do_while loops
Do_while loops are the same basic idea as while loops, except that they execute the contents of the loop once before checking the conditional. These are very useful in making users enter certain values for their input, as seen below:


int aValue=0;
do{ // do these instructions
System.out.println("Enter a value 1 or greater for the variable: ");
aValue= input.nextInt();
}while(aValue < 1);//until this condition is no longer true.


Incrementing numbers
Any number that is of a type that can hold a whole number value can be incremented or decremented. In MOST cases you will be using “post-incrementing” which is seen as varName++; however, there are other ways of incrementing numbers:


++i; // pre-increment
i++; // post-increment (most-common)
--i; // pre-decrement
i--; // post-decrement (common while decrementing)

Each time you hit the statement i++;, you increase the value of i by the value of 1.

Note- This video is really hard, the next video is way easier to understand than this one… sorry about that, I got excited


Topics Discussed: For loops, nested for loops, nested for loop structure, nested loops

Source Code Available Here


For loops
For loops are similar in idea to a while statement, except that it contains a few other parts that need to be talked about after I give an example of the syntax and use of for loops:


for(int i=0; i<10; i++){
System.out.println(i);
}

The above code does 4 things, one of which is apparent, the println() statement, so we won’t talk about that. But the for statement can be a little confusing, but when we break it into parts it will make a lot more sense.

Parts of a for loop
Every loop has three parts, which are as follows:

  1. The initializer: This part of the loop is where we set or declare some variable for use. Typically you’ll see something set to 0 here if you’re counting up to a variable.
  2. The conditional:The conditional is the same as with a while loop. It should be a statement that evaluates to a true, false, or boolean(t/f) statement.
  3. The iterator:The iterator is the part of the for loop in which we increase, decrease, or otherwise change some aspect of the loop, usually to make the loop get closer to it’s conclusion.


Additional considerations of for loops
The syntax and usage of for loops can be a little tricky overall:


for(int i=0; i<10; i++){
     //null
}
System.out.println(i); //This will error

The above is an example of an error that I see quite often among my peers in college. Despite the initializer coming before the scope bracket, it is considered part of the scope of the loop. Therefore we can thing of the scope of a for loop being like this:

for{(int i=0; i<10; i++)
     //do stuff
}
rather than its existing structure.


Nested for structure
Nested for’s actually share syntax with nested if statements in terms of scoping and complexity. Granted there aren’t any else statements to take into consideration.

Taking a step back to sanity on this one, sorry about the difficulty of lesson 11


Topics Discussed: Using a loop to count something for us.

Source Code Available Here

HomeWork is Available Here


Casting numbers
Casting numbers is an important part of any programming language that has certain roles that numbers fall into. The basic idea is this: assume that you have two numbers that you would like to divide, let’s assume you have 12 items that you want to divide equally among 7 people, assuming that we were to type that problem into java as an integer, we would get the following:
12 / 7 = 1
We can clearly see that this is wrong, but when you think about it, it’s also right. An integer cannot possibly hold a decimal value, therefore it being > 1.5 does not mean it will be rounded or anything of the sort… everything after the decimal place is truncated and discarded. Thus 1.71 (12/7) becomes 1. The way to have this resolve as we would like is as follows:


12/7.0; // 1.71.....

Now there’s a lot of different ways that you can cast numbers like this, here is a non-complete list of ways that you can cast integers into doubles for a moment:


 double a=0, b=0, c=0, d=0, e=0, f=0, g=0;
       
       a = 12/7;
       b = 12.0/7;
       c = 12/7.0;
       d = 12.0/7.0;
       e = (double)(12)/7;
       f = 12/(double)(7);
       g = (double)(12)/(double)(7);

       System.out.println("a = "+ a);
       System.out.println("b = "+ b);
       System.out.println("c = "+ c);
       System.out.println("d = "+ d);
       System.out.println("e = "+ e);
       System.out.println("f = "+ f);
       System.out.println("g = "+ g);

The output of the above is as follows:

Program output:
a = 1.0
b = 1.7142857142857142
c = 1.7142857142857142
d = 1.7142857142857142
e = 1.7142857142857142
f = 1.7142857142857142
g = 1.7142857142857142


Using a loop to increment a number
Essentially, we’re taking a number defined outside the scope of the loop and incrementing it by the counter of the loop:


int total=0;

for (int i=0; i<10; i++){
     total += i;
}

In the above example we are incrementing total by using the contents of i each time through the loop. If we preserve i for use outside the loop we can easily find the average by dividing out total by the final value of i.


Topics Discussed: More loop practice, sentinel / dummy record loops, breaking out of loops

Source Code Available Here


Sentinel control loops
A sentinel loop is a loop that is controlled by a ‘false’ value. These will be much more useful when we get into more advanced types of data storage (especially arrays, lists, arraylists, etc.). The program will run until this value comes up. Let let’s assume for a moment that we have some values that we want to iterate through:


Values we want to iterate through: 1, 7, 17, 43, 123,12,19, 4, 190, 23, 26, 44, 92, 81, 77, 41,4, 0

Now, with all those values a counter controlled loop just wouldn’t cut it since our values will vary so widely. Assuming that we didn’t know the number of entries the user was entering we would have one last option on how to end the loop, by adding a value onto the end of the data

New dataset: 1, 7, 17, 43, 123, 12,19, 4, 190, 23, 26, 44, 92, 81, 77, 41, 4, 0, -999

Now we can fashion a loop (in pseudocode) to take advantage of this oddball value:

while(x != -999){
     //process next record
}


The break statement
The break statement is used as a way to break out of a loop, it’s syntax is really quite simple, but it’s implementation can be tricky at times. To call the break statement in a program simply add break; while you’re in a loop. This will break out of the inner-most loop, example:

while(condition){
     while(condition2){
          if (condition==true){
               break;// this break will break out of the inner while but will stay inside the outer while.
          }//endif
     }//end inner while
//end outer while

In the above example it’s obvious that the break statement can give us additional control in our loops, but it comes at the cost of complexity. There will be some times in the future where we will have much more complicated loops where breaking out of one will return us to another at a strange point. Be certain that you plan your loops / breaks with care as they are tempestuous at best.


Topics Discussed: Case logic, case structure, case scope, breaking, case fallthrough, case study calculator

Source Code Available Here


Case Logic
Case logic is tremendously useful in cases where you might have something like a menu where a user selects something from a set of options. The basic syntax of a case is as follows:


int x = input.nextInt();
switch (x){  //x could be anything, int, double, char, etc.
     case 0:{  //this will execute if x = 0
     //do stuff
     break;
     }//end case 0

     case 1:{  //this will execute if x = 1
     //do stuff
     break;
     }//end case 1

     case 2:{  //this will execute if x = 2
     //do stuff
     break;
     }//end case 2

     case 3:{ //this will execute if x = 3
     //do stuff
     break;
     }//end case 3

     default:{ //this will happen if none of the other cases are true
     //do stuff
     }//end default
}  //End switch

Cases don’t offer much in terms of functionality that you couldn’t have accomplished with just if / else statements. The primary advantage that you have with cases is structure and readability. You can look at a case and immediately tell what it is doing, whereas a complex if might take a lot more time / effort to comprehend.