C - LOOPS


Loops

In some situations a block of code needs to be executed several numbers of times. Generally, statements are executed sequentially:
The first function in the statement is executed first, followed by the second, and so on.
Loop statement allows to execute a statement or a group of statements multiple times.
General form of loop statements in most of the programming languages are given below:-
Following types of loops are present in c language to handle looping requirements:-

Sr.No.
Loop Type & Description
1
Repeats a statement or group of statements while a given condition is true. The condition is tested before executing the loop body.
2
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
3
It is more similar to while statement, except that the condition is tested at the end of the loop body.
4
we can use one or more than one loop inside any other while, for, or do..while loop.

Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, each and every automatic objects that were created in that scope are destroyed.
C supports the following loop control statements.
Sr.No.
Control Statement & Description
1
It terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.(statement just after the loop).
2
Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
3
Controls are transferred to the labelled statements with the help of goto statement.

The Infinite Loop
If a given condition in a loop is always true for that the loop becomes an infinite loop. For this purpose traditionally the for loop is used. Since none of the three expressions that form the 'for' loop are required, we can make an endless loop by leaving the conditional expression empty.
#include <stdio.h>

int main () {

   for( ; ; ) {
      printf("This loop will run forever.\n");
   }

   return 0;
}
When the conditional expression is absent, it is assumed to be true. We may have an initialization and increment expression, but we as a C programmer more commonly use the for(;;) construct to signify an infinite loop.
NOTE – we can terminate an infinite loop by pressing Ctrl + C keys.







No comments:

Post a Comment