Algorithm
Certainly! In C#, a for
loop is a control flow statement that allows you to repeatedly execute a block of code a certain number of times. The basic syntax of a for
loop is as follows:
csharp
for (initialization; condition; iteration)
{
// Code to be repeated
}
-
initialization
: This is where you initialize the loop variable. It is executed only once at the beginning of the loop. -
condition
: This is the loop continuation condition. As long as this condition is true, the loop will continue to execute. If the condition becomes false, the loop terminates. -
iteration
: This is the expression that is executed after each iteration of the loop. It is usually used to update the loop variable.
Code Examples
#1 C# Programming for Loop
Code -
C# Programming
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i=1; i < =5; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
}
}
Copy The Code &
Try With Live Editor
Output
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5
#2 for loop to compute sum of first n natural numbers in C# programming
Code -
C# Programming
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
int n = 5,sum = 0;
for (int i=1; i < =n; i++)
{
// sum = sum + i;
sum += i;
}
Console.WriteLine("Sum of first {0} natural numbers = {1}", n, sum);
}
}
}
Copy The Code &
Try With Live Editor
Output
#3 multiple initialization and iterator expressions in C# programming
Code -
C# Programming
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i=0, j=0; i+j < =5; i++, j++)
{
Console.WriteLine("i = {0} and j = {1}", i,j);
}
}
}
}
Copy The Code &
Try With Live Editor
Output
i = 1 and j = 1
i = 2 and j = 2
#4 for loop without initialization and iterator statement in C # programming
Code -
C# Programming
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
int i = 1;
for ( ; i < =5; )
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
i++;
}
}
}
}
Copy The Code &
Try With Live Editor
Output
C# For Loop: Iteration 2
C# For Loop: Iteration 3
C# For Loop: Iteration 4
C# For Loop: Iteration 5
#5 Infinite for loop in C# Programming
Code -
C# Programming
using System;
namespace Loop
{
class ForLoop
{
public static void Main(string[] args)
{
for (int i=1 ; i>0; i++)
{
Console.WriteLine("C# For Loop: Iteration {0}", i);
}
}
}
}
Copy The Code &
Try With Live Editor
Demonstration
C# programming for loop