Loop in c

Types of loop.
1) for loop
2)while loop
3)do-while loop.

1)for loop.
For loop is used to repeat the block of code.

Syntax of for loop.

for(init;condition; increment/decrement)
{
 //Code
}

init:
First initialise the variable at the starting of loop.

Condition:

If the condition is true,the body of loop will execute.If the condition is false,the body of loop will not execute.

Increment/decrement:

Increment/decrement is done at the end of the loop

Work of for loop

First the initialisation of variable is done
Then condition is check if condition is false ,loop will terminate.if condition is true, the loop will execute.Thenafterincrement/ decrement is done.

The loop will execute till condition is true.

Example of for loop

#include<stdio.h>
int main()
{
   int i;
   for(i =10;i>0;i--)
    {
       Printf("%d",i)
     }
    return 0;
}
  
Output

10 9 8 7 6 5 4 3 2 1


2)while loop


Syntax:

While(condition)
{
   //Code
}

Working of while loop

In while loop the condition is check before the execution of code inside body of while loop.if the condition is false,loop is termimated.if condition is true program will execute.

Example

#include<studio.h>
int main()
{
   int i=0;
   while(i<10)
    {
       Printf("i=%d/n",i);
       i++;
     }
   return 0;
}

Output 

i=0
i=1
i=2
i=3
i =4
i=5
i=6
i =7
i=8
i =9

3) do-while loop.

In for loop and while loop we see that the condition is check in top of loop,but in do-while loop the condition is check in bottom of loop.

So in do-while loop the code inside the body of loop execute at least once.

Syntax:

do
{
    //statement 
}while(condition)

Example:

#include<stdio.h>
int main()
{
   int i=1;
   do
   {
       printf("%d\n",i);
       i++;
    }while(i<6)
   return 0;
}

Output


2
3
4
5


  




No comments:

Post a Comment

Loop in c

Types of loop . 1) for loop 2)while loop 3)do-while loop. 1)for loop . For loop is used to repeat the block of code. Syntax of for ...