The for loop in C# is useful for iterating over arrays and for sequential processing. That is the statements within the code block of a for loop will execute a series of statements as long as a specific condition remains true.
Syntax:
for(initialization; condition; step)statement
initialization : Initialize the value of variable. condition : Evaluate the conditionstep : Step taken for each execution of loop body
The for loop initialize the value before the first step. Then checking the condition against the current value of variable and execute the loop statement and then perform the step taken for each execution of loop body.
int count = 4;
for (int i = 1; i < = count; i++)
{
MessageBox.Show("Current value of i is - " + i);
}
The output of the code as follows :
Current value of i is - 2
Current value of i is - 3
Current value of i is - 4
The loop will execute four times because we set the condition i is less than or equal to count.
for (int i = 1; i < = count; i++)
initialization : int i = 1 Initialize the variable i as 1, that is when the loop starts thevalue of i is set as 1
condition : i < = count Set the condition i < =count , that is the loop will execute up towhen the value of i < = 4 (four times)
step : i++Set the step for each execution of loop block as i++ ( i = i +1)
All of the expressions of the for loop statements are optional. The following statement is used to write an infinite loop.
for (; ; )
{
// statements
}
Here the loop will execute infinite times because there is no initialization , condition and steps.
using System;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int count = 4;
for (int i = 1; i < = count; i++)
{
MessageBox.Show("Current value of i is - " + i);
}
}
}
}Advertisement