Monday, March 12, 2018

Loops in java

You remember that last week we discussed the three forms of programming:
  1. Sequential Programming
  2. Selective Programming
  3. Iterative Programming
Since we started these tutorials, we’ve been dealing with sequential programming. The flow of sequential programming is usually downward, from top to bottom, and each and every line of code is executed unless you tell the program not to.
Before move further Let see the Previous Tutorials


The other two forms are just ways of telling Java not to execute every line. Last week, we saw the way Selective Programming works in terms of selecting the particular lines to execute. Another way of doing this involves the last form of programming, called Iterative Programming. This form of programming involves the use of something called Loops.

A loop is just a piece of code that tells the computer to do something over and over again until a condition is met. For example, printing a message ten times, or counting from one to ten and maybe adding all the numbers together. Of course, it you wanted to do that, you could just as easily do this:
int add = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;
But this wouldn’t be efficient, especially when you’d like to count to a really high number, like a hundred or a thousand. An easier way to do this would be to tell the computer to go over one line of code multiple times until you reach 100. It then exits the code and continues running.

Note: If you don’t define your loop very well, it’s quite possible that it will loop infinitely. It will only stop when you stop the program manually, and if left to continue looping, it could eventually crash your system.

For Loops

Now that we have a basic idea of what loops are, let’s take some examples. Let me start by saying that there are different types of Loops in coding, so we’re going to start with one of the simplest: For Loops. I’m not exactly sure what the word ‘For’ in For Loops refers to, so I’ll just show you the standard format:


for(start value; end value; increment) 
{
  //code to execute;
}

So, after the keyword ‘for’, you put a parenthesis, then in that parenthesis; you put your start value (saved into a variable), your end value and your increment value. The increment value is just the value you have to add to get to the next value (e.g. to get from 1 to 2, you add 1. 1 therefore is the increment value). The increment value is usually 1 by default, but you can always change it if you want to.
After closing the parenthesis, you should put a curly bracket, then type in the code that you want to loop. After you close the curly bracket, you would have successfully written a For Loop.
Now, let’s look at some examples. Launch NetBeans and open a new Project or Class file. Name the file ForLoops and type the following:


What this is going to do is count out all the numbers from 0 to 10 and print them out on the system console. You start by creating two variables: startVal is your starting value of course, while endVal is the ending value. If you’re wondering why the ending value is being saved as 11 when we want to count to ten, don’t worry. It’ll all be explained later.

After creating our variables, we then put our ‘for’ keyword, and then in the brackets, we put in this:


startVal = 0; startVal < endVal; startVal++
Note, instead of creating the startVal variable outside the loop and then assigning iit a value separately, we could have done it all in the bracket:



int startVal = 0; startVal < endVal; startVal++
Now, we’ve initialized the starting value at 0, where we want to start the loop to start counting from. After a semi-colon (not a comma), we put a little conditional logic to use. This:


startVal < endVal
…just means that it should keep counting while the starting value is less than the end value (11). So the computer will keep counting the numbers one by one until it reaches 10, which is just one less than 11. This is why the value was at 11 and not at 10. Mind you, we could have saved the variable as 10 and just replaced (<) with (<=). That way, the code would look like this:


startVal <= endVal
This means that the system should count until the starting and ending values are equal to each other.
Now after the second semi-colon is this value:
startVal++
This, as I explained earlier, is the increment value. It’s just a way of saying “add 1 to the value of startVal, then keep adding 1 until the condition is met. Then after closing your parenthesis, you open a curly bracket and put a print statement with the name of your starting variable (startVal). This will print the values on the console in quick succession.

Now that we understand the loop, when we run it, we should get this as our output:



Quick note on the increment value: startVal++ means to count one by one by default. If you want to increase the value to count by, just remember that another way of writing our increment is this:


startVal = startVal + 1
Or this:


startVal += 1
So, if you want your code to count two by two, just change this:


startVal++
To this:


starVal += 2
Run it again, and you should get this:

So, anytime you need to increase your increment value, just change the value thee from 1 to whatever you need it to be.
So basically, what we’ve done is trap the print line in a loop. Whatever is in the curly bracket will be executed again and again until the condition in the parenthesis is met (in this case, until the number of loops is less the 11).

Now, let’s create something to add all these together. All we need to do is make a few additions to our code, so that it looks like this:

If you run it, the result on the output window should be 55. Notice the new variable ‘sum’ which is assigned the value 0. This is what will hold the value of the sum of all the numbers. We’ll get to why it’s 0 in a minute.
The loop itself is basically the same, in the parenthesis. The difference will be seen in the curly brackets, where we have this line:


sum = sum + startVal;
This just says ‘take the value of sum (which is 0), and add it to your starting value, then save the new value of sum into itself and keep adding it to the incrementing values of startVal’. Basically, since sum is 0, the first loop will add 0 to 1, which will be 1. The value 1 will be saved into the variable sum, only to be added to the incrementing value of startVal, which is 2. The addi tion of 1 and 2 is 3, which will add again with the next value (3) to give 6.
The cycle will continue until you get the final answer (55).
Now note that the print line is no longer in the loop. It is now outside the curly bracket. If I put it back in curly brackets and run it, you’ll get this:


See, if the print statement is in the loop, it will treat it as part of the loop, and print out the value of sum after each and every loop.

That’s enough about that. Let’s look at other types of loops.
While Loops
This is another form of loop. Its logic is a lot easier to understand than for loops. It basically says, ‘while this is going on, do this’. Here is the standard format of while loops:


while (condition) {
 //code;
 increment;
}
Now, let’s do what we did for For Loops in a while loop. Let’s count from 1 to 10. Just comment out your For Loop and put this:


Now, we have our variable, startVal at 0. We then put our ‘while’ keyword, in lower case, and then a bracket, with our condition. Since we want to count to ten, our condition is 0 less than or equal to 10. Once the number of loops is equal to 10, the code will stop looping. In curly brackets, we have a print statement, which will print out our startVal for as many times as it loops.
A major difference between the for and while loops is the positioning of the increment value. While the increment is in the bracket with the condition in For Loops, in While Loops, the increment is placed after the code, just before the closing bracket.
I’d show you how to get the sum of all ten numbers, but I figure you should be able to do that yourself, so I’ll just look at another form of loops.
Do…While Loops
I won’t spend much time on this, because it’s quite similar to the While Loop. It actually is just a While Loop with reverse logic. Where the While says “while this happens, do that”, the Do…While just says “do that while this happens”. It just says the same thing in a different way.

This is the basic structure of the Do…While:


do {
 //code;
  increment;
}while(condition);
If we want to print out ten numbers with this loop, all we have to do is this:

The major difference between while and do…while is that if your condition already happens to be met, the do…while will execute it at least once. The while, on the other hand, will just skip the code and not do anything at all.


Well, I think this was quite sufficient for today’s tutorial. I’m sur you’ll be able to make efficient use of everything we’ve done into practice. In fact, I think it’s time for some…
Homework!
Aww…homework? Why?! That’s probably what some of you are thinking. Well, I’ve got to test your progress somehow, don’t I. Don’t worry, it won’t be that hard, and it will put most of what you’ve learnt to practice.
What I want you to do is make a program that allows you to enter a number, and print out the times table for that number, using any of the looping techniques, be it for, while or do…while. If you can do that, be sure to post your code in the results, and I’ll be sure to put the solution in the next post.
If you have any issue and difficulty in any concept , leave us a comment . If you like the article please share it with your friends , colleagues.

Happy learning

Thanks for reading
Noeik


0 comments:

Post a Comment