From the very beginning of computer or its predecessor that is the automated calculating machines, the primary goal of the scientists was to create a machine which can do the repetitive tasks accurately. For example I a human being is asked to manually add 1000 numbers every day then you can be sure that most humans will start making errors because we are not good at doing repetitive tasks.
Therefore every computer is good at this ie repetitive task. If you ask it to do the same task 4000 times you can be rest assured that each time it will do that task consistently and accurately without any chance of variation or error.In computer terminology repetition is also known as iteration or simply put it is called a loop. Say for example we had these lines
START
DISPLAY “Hello World”
STOP
If I had to print “Hello World” 10 times then I have two options either to write the statement 10 times or create a loop. The first option is not feasible because it beats the purpose of using a computer.
Therefore the only option is to create a loop. A loop by definition is set of instruction that forces the computer to do one or more lines of instructions repeatedly for n number of times. Please remember most often loops have a starting and ending point just like when we count anything. Let us look at the Java’s implementation of a loop or iteration
The lines inside the inner purple box are called a loop construct. If we break it down it is quite simple to understand
Part 1
int i=1 means that this is our starting point a variable has been given a value of one to signify that we will count from 1
Part 2
i<=10 means that the value of i will change until it is less than or equal to 10 in other words we will count from 1 to 10. This is called the condition or the limit. If this condition becomes false then the loop will terminate.
Part 3
i++ means that each time we have to increment the value of i we will increment it by one just like normal counting 1,2,3,4…10
These three parts instruct the CPU to repeat these lines until i become greater than 10 and each time increment i’s value by one. The really interesting part is that each time it increments the value it will repeat the lines written inside the body of this statement (the opening and closing braces). Thus step one will be when i gets the value of 1 it will print Hello World then it will increment the value of i by one to make it 2, check the condition if i is less than or equal to 10 if it is true it will print Hello World, this is step2 again it will increment the value by one, check the condition and if true it will print Hello World. These steps will be repeated until the value of I becomes greater than 10 which will make the condition false and the loop will terminate. To illustrate this point let me repeat the above program with the value of i with the message
The output of this program will clearly illustrate my point
No comments:
Post a Comment