Loops in C – II

What are Loops ?

Loops is an interesting concept that is used to repeat the program any number of times. It relays on the condition given for how many times to be repeated. We have three loops 

1. for loop

2. while loop

3. do while loop

Loops are categorised into two types:

1. Pre-test Loops

2. Post-test Loops 

What are pre-test loops?

After the initialization, the condition is firstly verified and then the loop is repeated if it is true, and terminated if it is false. The loops for, and while belong to this.

What are post-test loops?

After the initialization, the loop body is firstly executed and then the condition is verified. The loop runs accordingly, repeating if true and terminating when false.The loop do-while belongs to this.

What are loops used for?

Loops are used to repeat the program any number of times. It rescues the programmer from the extra time and efforts he has to spent on the program to repeat. Imagine a program you have to repeat for 3 times, copy and paste is fine but if it is for 30 time this is not advisable. Loops can repeat a function infinite number of times.

What is for loop?

This loop is used to repeat the code any number of times. It relays on the condition given for the function to be repeated. This falls under pre-test loops.

Syntax:

for( initialization; condition; increment/decrement )

{

// loop body- code to be repeated

}

Initialization – declaring the value of the variable to be used for the condition.

Condition – given according to how many times the loop has to be repeated.

Increment – increases the value of variable by one for the loop to run.

Decrement – decreases the value of variable by one for the loop to run.

 Note: for loop does not include a semicolon(;) in it’s syntax. But it is not a syntactical error if it is added insted performs a different task. When semicolon is included, the loop is not executed but runs with increment/decrement done, and output is given when the condition goes wrong.