Looping Statement in C

 Loops


 It helps to repeat a statement several times until the condition is satisfied.


Three types of Loops


  •  for loop

  •  while loop

  •  do…while loop

for loop


 If you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:


Syntax


for (initialization; condition; increment/decrement) {
  // code block to be executed
}

Statement 1 (initialization) is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 (increment/decrement) is executed (every time) after the code block has been executed.


#include<stdio.h>

int main()
{
    int i;
    for(i=0; i<5; i++)
    printf("%d ",i);
   
    return 0;
}

while loop


The while loop loops through a block of code as long as a specified condition is true:


Syntax:

Initialization;

while (condition)

 {
  // code block to be executed

Increment/decrement;
}


#include<stdio.h>

int main()
{
    int i=0;
    while(i<10){

    printf("%d ", i);
    i++;    
    }
    return 0;
}


do…while loop


It is an exit check loop

We will get the output at least once, even if the condition is false.


Syntax

Initialization;

do 

{
  // code block to be executed

increment/decrement;
}
while (condition);


#include<stdio.h>

int main()
{
    int i=3;
    do{
//      i = 3;
        printf("%d ", i);
        i++;
    }while(i<5);
    return 0;
}


UNCONDITIONAL STATEMENTS:


Break -> It temporarily terminates the program.

Continue -> It skips the program.

#include<stdio.h>

int main()
{
    int i;
    for(i=1; i<10; i++){
   
   
    if(i==5)
    continue; //skips the value
   
    if(i==7)
     break; //terminates the program temproraily
     printf("%d ",i);}
    return 0;
}


Goto -> These serve as a loop. It is a jump statement also referred to as an unconditional jump statement. The goto statement can jump from anywhere to anywhere within the syntax.


#include<stdio.h>

int main()
{
    int i =0;
    don:
        printf("%d ",i);
        i++;
   
    if(i!=5)
    {goto don;  }
    return 0;
}

Post a Comment

0 Comments