Loops in programming language is used to execute a statement or a set of statements for a number of times if the condition is satisfied, a loop keeps running until the condition becomes false.
There are generally two types of loops:
Entry controlled loops
1. while loop:
The condition is first checked at the start and increment/decrement is done in the body of the loop. While loop usually have boolean condition hence loop runs until boolean condition becomes false.
using System;
namespace Loops{
class Program{
int num = 0;
static void Main()
{
/* Syntax,
while(boolean condition){
Statements...
increament/decrement
} */
while(num<5){
Console.WriteLine("Hello ");
}
}
}
}
2. for Loop:
In for loop we need to do variable declaration, check condition and perform increment/decrement in a single line.
using System;
namespace Loops{
class Program{
static void Main()
{
/* Syntax,
for(declaration; condition; incre/decre,){
Statements...
} */
// Loop will run 5 times.
for(int i = 0; i<5; i++){
Console.WriteLine("Hello ");
}
}
}
}
Exit Controlled Loops:
In these type of loops condition is checked at the end of the loop body. Exit control loop run atleast once before stopping.
1. do-while loop:
It checks the condition at the end of the loop body. It runs atleast once if the condition is false.
using System;
namespace Loops{
class Program{
int num = 5;
static void Main()
{
/* Syntax,
do{
Statements...
increament/decrement
}while(condition); */
do{
Console.WriteLine("Hello ");
}while(num<5);
}
}
}