June 30, 2023 (11mo ago)

Programming Fundamentals: Loops

Today we will be learning about a fundamental programming concept known as loops. As the name suggests us, we use loops to loop or repeat some task over and over again. Let's take an example and see how loops work.

Let's say that you want to print "Hello World!!" ten times, to do this you will have to write the print statement ten times and it'll become repetitive. Now if you wanted to print it a hundred times it would be much more tedious. So instead of writing the same thing over & over again, we will use loops.

Let's look at how a for loop works.

A for loop have three main parts: the initialization, the condition & the updation. We also have a special variable(let's say i) which controls the flow of the loop. First, we initialize i and check if the condition is satisfied or not. If the condition is satisfied the body of the loop gets executed and after that, we update the value of i. If at any point the condition is not satisfied then we break out of the loop.

The structure of for loop is like:

for (initialisation; condition; updation) {
	//body of the loop

If we had to print “Hello World!!” ten times then we can write something like:

for (int i = 0; i < 10; ++i) {
	cout << “Hello World!!” << endl;

The variable i gets initialised with value 0. Since 0 is less than 10 the condition is satisfied and the body of loop gets executed, hence we print “Hello World!!” and we update the value of i to 1. This process repeats itself until the value of i is 9. After that when the value of i becomes 10, the condition “i < 10” is not satisfied and we break out of the loop.

Apart from the for loop, we also have while and do - while loops which also work in a similar fashion.