Loops in C

What are the loops in Programming and what are they use for?

Suppose you have given a task to print your name 5 times. Simple right?

You can just print your name 5 times in the main function. But in programming, you don’t want to write the same code for doing the same task because when you code, it is too impractical. To avoid repetition of the task, we use loops.

Loops in C

In every loop structure, there is always a block of a condition in which you write the condition of running the loop. Suppose, if you want to print your name 5 times, there has to be the condition so that it knows that the name is printed 5 times. We will see it’s implementation when we discuss individual loops.

There are three types of loops in C that you can use, these are:

  1. For loop
  2. While loop
  3. Do While loop.

For Loop

The syntax of for loop is –

for(initialisation, expression, updation){Body of loop}

For example –

for(int i = 0; i < 4; i++) {
print(“Your name”);
}

The initialization of i = 0 will initialize the value ‘0’ to the variable i. Next, it checks the condition, if it’s true then it executes the statement in the body of the loop and updates the variable. If the condition is false, it simply doesn’t execute the statements written in the body of the loop and exits the loop.

While Loop

The syntax of while loop is-

while(condition) {
}

For example –

int i = 0;
while( i< 4) {
print("Your name");
i++;
}

Because you can only write condition in the while loop bracket, the initialization of the variable has to be done before the while loop. You can update the variable inside the while loop.

do-While loop

The syntax of do-while loop is

do {
}
while(condition);

For example –

int i=0;
do {

print("Your Name");
i++;
}
while( i< 4);

In this loop, the block inside “do” will execute at least one time even if the condition is false. That’s the difference between while and do-while loop.

Now I think you should be able to print your name 5 times using different types of loops. There are some simple questions that may occur explained here.

What happens if the condition remains always true?

The loop will execute infinitely. Some example of an infinite loop in C are :

while(1) {}

for ( ; ; ) {
}

for (int i=0; i < 4; i--) {
}

Can we create a loop inside another loop?

Yes, we can. Those are called nested loops but I think a discussion about these will require another article.

I think that’s it for this article. More tutorials on C will follow so do check out this blog. For any problem or feedback, do write about it in the comment section.

Leave a Comment

Your email address will not be published. Required fields are marked *

Share This
Scroll to Top