Friday 26 June 2020

Loop concepts

Understanding Loop concepts

In programming, some statements are required to be executed several number of times. Suppose programmer has to execute some statements (like print statement) huge number of the times , but writing the statement huge number of times is a way more time consuming and considerably increases the lines of code.  To make this handy, loop comes into play.

Loop is one of the most powerful and basic building blocks of computer programming. Loop let you write code which needs to be repeated several times in a very efficient way. Just write the code once with some loop conditions and run the code any given number of times.

Loop consists of body and iterating conditions:

Loop body holds the code which needs to execute many times,                                                                       Iterating conditions allows you to write start, stop and iteration  conditions for the code.

Here is the general syntax for the loop:

Loop(start; stop; iteration) {

//  statements

//  statements

}

How loop works

First starts with the start value followed by checking stop condition, if the condition holds true then enters to the loop body and start executing statements inside body and after executing the last statement inside loop body , again the executing pointer moves to the top of the loop statement and perform the iteration condition followed by checking the stop condition and if the condition holds true same steps will be performed until the stop condition becomes false and after getting the false stop condition,  the executing pointer moves to the next statement after loop statement.

Example explaining the working of the loop using for loop:

for( start=0; start<5; start++ ) {

   printf(“loop concepts”);     // prints the string five times

}                                                                                                                                        

Steps:

  •  start=0 and check if start < 5; true
  •  enter inside the loop body and execute print statement
  •  move to the top of for loop statement and increment the start by 1 and check if start < 5; true.
       Repeat the 2nd and 3rd steps until start < 5 becomes false, after that jump out of the loop.

  Output:

loop concepts

loop concepts

loop concepts

loop concepts

loop concepts

10 comments: