Tuesday, May 17, 2011

9. Looping Structures


Missing Facts:
Before you start off with this chapter, there is a little you need to know about Math Operators in Java.

A Simple Program:
Let us write a simple program that calculates the sum of two numbers:

PROBLEM:
Now what if I wanted to write a program that would calculate the sum of the first 'n' numbers? What we want is:
S = 1 + 2 + 3 + .... + n

A simple approach to solve this problem would be to do the following:

1. Create new variable 's = 0'. This would store the sum of numbers.
2. Create a variable 'i = 1'. This is the first term of the series given above.
3. Add 'i' to 's'.
4. Increase value of 'i' by 1.
5. Repeat steps 3 and 4 till 'i' becomes equal to 'n'.

SOLUTION:
As we see above, the last step tells us to repeat the previous steps. This is achieved by a process called 'LOOPING'.
As the name suggests, we create a sort of a LOOP that keeps repeating itself. This is explained more clearly by the picture below:
A 'Loop'
LOOPING:
1. The 'while' loop-
The first, and the most basic loop in Java is the 'while' loop. It has the following syntax:
while(condition)
{
Step 1;
Step 2;
}
Thus, following the steps that we have discussed in the 'PROBLEM' section above, this is what our program would look like:


2. The 'for' loop-
The 'for' loop is different in the respect that it runs for a SPECIFIC NUMBER OF TIMES, whereas the 'while' loop runs while the given CONDITION IS MET.
A 'for' loop has the following syntax:
for(initialization; condition; increment/decrement)
{
Step 1;
Step 2;
}

Thus, using the steps discussed above, the same program can be rewritten using a 'for' loop in the following manner:


EXTRAS:
There exists a third looping structure that is a variation of the 'while' loop, called the 'do-while' loop. It's syntax is given below:

do
{
Step 1;
Step 2;
}while(condition);

Now its your turn to make some programs, and practice the concepts that we have discussed above.
A few good practice problems would be:
1. A program that prints all odd/even numbers upto 'n'.
2. A program that prints the first n terms of the fibonacci sequence.
____________________________________________________________________

Do tell me if you are able to keep pace with the tutorial, and if you would like to see any kind of change in the teaching style.
As always, feel free to ask your doubts in the comments section below.

No comments:

Post a Comment