Loops (Programming Fundamentals part-5)
Let me ask you something interesting before learning about loops. Do you like doing same thing again and again? Do you like to study same topic for 12 hours straight or would you like it if I tell you to fill a bucket with water but one single drop at a time and do nothing else until it’s done. Probably not Right! It may sound a bit scary. Actually, it is scary, but we have to do it in programming and in fact many times BUT there is a catch to it.
Let's understand loops
Let's say for some unknown reason you want to create a program that say “I love you” a hundred times. How would you do that? That's where loops come into play.
if loops were not there you would have to write printf("I LOVE YOU") a hundred times but with loops you can do it in very few lines. I will use C for explaining
int i = 1;
while(i<101){
printf("I LOVE YOU");
i++;
}In this code above we are saying that run the code in block until i is not bigger than 101. Block of code will run till the condition mentioned in () is true. When it becomes false it stops.
Get Pixel and Code’s stories in your inbox
Join Medium for free to get updates from this writer.
Explaining in steps for better understanding:
- Creating a variable
iand assigning it value1. - Creating a while loop.
- Adding condition to check if
iis smaller than101. - Writing
printf("I LOVE YOU")in code block. - Writing
i++to add1inievery time it runs. Firstly,iis1as we declared. Loop runs for the first time it becomes2. After second turn it becomes3. Whenibecomes equal to101the code of block no longer runs becauseiis no longer smaller than101. It is equal now.
There are other types of loops like for, do while. We will do it some other day when we learn C. Today we are only learning fundamentals of all programming language.







