DEV Community

loading...

C : Loops and Control Statements

supriya2371997 profile image Supriya Kolhe ・5 min read
  1. What are loops?
  2. Types (entry and exit controlled loop)
  3. What is infinite/endless loop?
  4. Types of loop constructs (while, do...while, for)
  5. For loop in more detail
  6. Nested loop
  7. What are Loop Control Statements
  8. Types (break, continue, goto)

1.Loops : Loop executes the sequence of statements many times until the stated condition becomes false. A loop consists of two parts, a body of a loop and a control statement. The control statement is a combination of some conditions that direct the body of the loop to execute until the specified condition becomes false. The purpose of the loop is to repeat the same code a number of times.

2.Types: Depending upon the position of a control statement in a program, looping in C is classified into two types:
2.1 Entry controlled loop : also called as pre-checking loop. A condition is checked before executing the body of a loop.
2.2 Exit controlled loop : also called as post-checking loop. A condition is checked after executing the body of a loop.
image

3. what is infinite/endless loop?
->The loop that does not stop executing and processes the statements number of times is called as an "infinite loop". An infinite loop is also called as an "Endless loop".
->some characteristics of an infinite loop:
** No termination condition is specified. **
** The specified conditions never meet. **

->Thus, to avoid this situation the control conditions must be well defined and specified otherwise the loop will execute an infinite number of times.
->The for loop is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop is required, you 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;
}
Enter fullscreen mode Exit fullscreen mode

4. Types of loop constructs:-
4.1 while:
->It is an entry-controlled loop. In while loop, a condition is evaluated before processing a body of the loop. If a condition is true then and only then the body of a loop is executed. After the body of a loop is executed then control again goes back at the beginning, and the condition is checked if it is true, the same process is executed until the condition becomes false. Once the condition becomes false, the control goes out of the loop.
->In while loop, if the condition is not true, then the body of a loop will not be executed, not even once.

while (testExpression) 
{
    // the body of the loop 
}
Enter fullscreen mode Exit fullscreen mode
/*Example: */
#include <stdio.h>
int main()
{
    int i = 1;

    while (i <= 5)
    {
        printf("%d\n", i);
        ++i;
    }

    return 0;
}
Enter fullscreen mode Exit fullscreen mode

4.2 Do while:
->It is more like a while statement, except that it tests the condition at the end of the loop body.
->it terminates with a semi-colon (;)
->The body of do...while loop is executed at least once.
->After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.

do
{
   // the body of the loop
}
while (testExpression);
Enter fullscreen mode Exit fullscreen mode
/*Example: */
#include<stdio.h>
#include<conio.h>
int main()
{
    int num=1;  
    do  
    {
        printf("%d\n",2*num);
        num++;      
    }while(num<=10);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

4.3 For:
->step1: In this initialization, statement is executed only once.
->step2: The condition is a Boolean expression that tests and compares the counter to a fixed value after each iteration, stopping the for loop when false is returned.
->step3: The incrementation/decrementation increases (or decreases) the counter by a set value and again the test expression is evaluated.
->step4: This process goes on until the test expression is false. When the test expression is false, the loop terminates.

for (initial value; condition; incrementation or decrementation ) 
{
  statements;
}
Enter fullscreen mode Exit fullscreen mode
/*Example:*/
#include<stdio.h>
int main()
{
    int number;
    for(number=1;number<=10;number++)   
    {
        printf("%d\n",number);      
    }
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

5.For loop in more detail:
->for loop can have multiple expressions separated by commas in each part.

for (x = 0, y = num; x < y; i++, y--) { 
  statements; 
}
Enter fullscreen mode Exit fullscreen mode

->we can skip the initial value expression, condition and/or increment by adding a semicolon.

int i=0;
int max = 10;
for (; i < max; i++) {
  printf("%d\n", i);
}
Enter fullscreen mode Exit fullscreen mode

6.Nested Loop:-using one loop inside another loop.
->nested for loop:

for ( init; condition; increment ) {

   for ( init; condition; increment ) {
      statement(s);
   }
   statement(s);
}
Enter fullscreen mode Exit fullscreen mode

->nested while loop:

while(condition) {

   while(condition) {
      statement(s);
   }
   statement(s);
}
Enter fullscreen mode Exit fullscreen mode

->nested do while loop:

do {
   statement(s);

   do {
      statement(s);
   }while( condition );

}while( condition );
Enter fullscreen mode Exit fullscreen mode

->you can put any type of loop inside any other type of loop. For example, a 'while' loop can be inside a 'for' loop or vice versa.

#include <stdio.h>
int main() {
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++) 
{
  for (j = 0; j <= max; j++) 
  { 
    printf("%d x %d = %d\n", i, j, i*j);
  }
  printf("\n");
}
}//main end
Enter fullscreen mode Exit fullscreen mode

NOTE : In some versions of 'C,' the nesting is limited up to 15 loops, but some provide more.

7.Loop Control Statements :change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed.

8.1 Break :
->Terminates the loop or switch statement and transfers execution to the statement immediately following the loop or switch.

break;
Enter fullscreen mode Exit fullscreen mode

->The break statement is almost always used with if...else statement inside the loop.

#include <stdio.h>
int main() 
{
int num = 5;
while (num > 0) 
  {
  if (num == 3)
    break;
  printf("%d\n", num);
  num--;
}
}
Enter fullscreen mode Exit fullscreen mode

8.2 Continue : The continue statement skips the current iteration of the loop and continues with the next iteration. Its syntax is:

continue;
Enter fullscreen mode Exit fullscreen mode

->The continue statement is almost always used with the if...else statement.

#include <stdio.h>
int main() 
{
int nb = 7;
while (nb > 0) 
{
  nb--;
  if (nb == 5)
    continue;
 printf("%d\n", nb);
}
}
Enter fullscreen mode Exit fullscreen mode

8.3 Go to:
->Transfers control to the labeled statement.
->The label is an identifier. When the goto statement is encountered, the control of the program jumps to label: and starts executing the code.
->Here label can be any plain text except C keyword and it can be set anywhere in the C program above or below to goto statement.

goto label;
... .. ...
... .. ...
label: 
statement;
Enter fullscreen mode Exit fullscreen mode
/*Example:*/
#include <stdio.h>

int main () {

   int a = 10;
   LOOP:do 
       {
         if( a == 15) 
         {
             a = a + 1;
             goto LOOP;
         }
         printf("value of a: %d\n", a);
         a++;
       }while( a < 20 );
   return 0;
}
Enter fullscreen mode Exit fullscreen mode

NOTE : Use of the goto statement is highly discouraged in any programming language because it makes it difficult to trace the control flow of a program, making the program hard to understand and hard to modify. Any program that uses a goto can be rewritten to avoid them.

Discussion (0)

Forem Open with the Forem app