Repeating any task many times is a boring stuff. And error may be introduced while repeating for a longer time period.
But computer can repeat any stuff over and over again without any error, and never get bored!
Let’s write a sequence which makes computer to repeat a task five times for us:
OK Computer[main()]:
Repeat 5 times
Display “Awesome!”
Output:
Awesome! Awesome! Awesome! Awesome! Awesome!
In c language, if programmer wants to implement above task into his code form then below is the details:
main()
{
for(int i=0;i<5;i++)
puts("Awesome!");
}
Output:
Awesome!
Awesome!
Awesome!
Awesome!
Awesome!
It would take a lot of time and effort to perform repetitive tasks if computers couldn't repeat them for us.
Where to use repeat
Imagine Tom wanted to prepare burger for him and his friend. Sounds simple but it requires a few repetitive steps.
Get four Buns
Put vegetables on Bun 1
Put vegetables on Bun 2
Put chicken on Bun 3
Put chicken on Bun 4
Place Bun 1 & 3 over each other
Place Bun 2 & 4 over each other
Looks tricky?
Now imagine Tom had to make these burgers for 20 more friends. Tom say does let’s actually make 20 burgers with the shortcut:
Repeat 20 times
Get two Buns
Put vegetables on first Bun
Put chicken on second Bun
Place the Buns over each other
Loops
This repetition of steps is known as loops.
As a computer programmer, one should be able to identify repetitive tasks and wrap them up in loops.
Some of the repetitive tasks are
- counting one to hundred
- issuing movie tickets at counter
- filling water bottles at a tap
Count based loops
In such loops, exactly how many times the loop has to be repeated is known before starting the task.
In other words, in many situations one might have to repeat a particular task a set number of times.
For example, if a teacher has to do the following task repeatedly for 50 students:
- from mark sheet add individual subject marks
- display total marks
Repeat for 50 times
Get the marks sheet
Add individual subject marks
Display the total marks
Condition controlled loops: while loop
If programmer doesn't know how many times a sequence has to be repeated? In such situations programmer use the until condition loop or while condition loop.
Counting the balls in a bag is a good example for this type of loop.
Open the bag
Repeat until the bag is empty
Put your hand in the bag
Draw one ball out
The until loop or while loop is condition controlled loop which repeat until the condition is reached.
Summary
The repetitive tasks can be handled better by using loops.
The loops can have fixed number of repetitions.
The loops can have conditioned number of repetitions [until a condition is met].
PS: I have composed this post-series based on my pdf eBook on playstore:
Basics of Computer, Programming and C
The series is posted continuously one each next day, and reader can found any post by referring blogs’ time line tab.
--till next post, bye-bye and take care.
No comments:
Post a Comment