BLOG

our

  • GirlsCodeIt

Introduction to Loops

By Anjali Dubey


Suppose you want to execute a statement about 50 times. Typing the same statement again and again will not be an efficient way to execute the program.In such situations, we use something called the loop. A loop is a structure used in a program to execute a set of statements for a given number of times in order to carry out a specific task. So instead of typing the same statement you will just need to type a single statement to execute the program fifty times. A loop has four parts:


1. Control variable: A variable which starts with an initial value and determines the duration of the loop.

2. Test Condition: The condition on which the execution of the loop depends

3. Increment/Decrement: The change in the value of the control variable after every execution.

4. Body of the loop: They are the statements which are executed by the loop.




There are two kinds of loops:

1. Loops with fixed iterations(for loop)

2. Loops without fixed iterations(while loop, do while loop)



FOR LOOP

In this type of loop the number of iterations are repeated for a fixed interval of times.The control of the loop terminates after repeating the loop for the given interval of times.


Syntax:

for(a=1;a<=10;a++)

{

.

.

// statements to execute

.

.

.

}



WHILE LOOP

This is a condition controlled loop. The loop will continue to execute till the condition remains true and terminates immediately when it turns to false.


Syntax:

while(condition)

{

.

.

.

// statements to execute

.

.

.

}



DO WHILE LOOP

Do while loop is also used when the number of iterations are not fixed/specified. This loop executes the statements once before checking the condition and then checks the condition using the while loop from the second iteration.


Syntax:-

do

{

.

.

.

//statements to execute

.

.

.

}

while(condition)



💡 while loop is an entry controlled loop i.e it executes the statements after checking the condition whereas do while loop is an exit controlled loop i.e it executes the statements once before checking the condition and then checks the condition from the next iteration.



These are the three basic loops which are very commonly used in programs in various programming languages.They make the program more efficient and shorter and help in smooth execution of the program.Having a clear knowledge of these concepts allows us to use them in advanced programs and execute complex logic.


Feel free to leave any suggestions or queries down below in the comments!




4 views0 comments

Related Posts

See All