For Loop
For Loop
using a for loop. This program can be run in any C# environment, like Visual Studio or an
online compiler.
using System;
class Program
{
static void Main()
{
// Using a for loop to print numbers from 1 to 10
for (int i = 1; i <= 10; i++)
{
Console.WriteLine("Number: " + i);
}
}
}
Explanation:
• for (int i = 1; i <= 10; i++): This is a loop that initializes i at 1, runs as long as i is less
than or equal to 10, and increments i by 1 after each iteration.
• Console.WriteLine("Number: " + i);: This outputs the current value of i to the
console.
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
Output:
Counting down from 10 to 1:
10
9
8
7
6
5
4
3
2
1
using System;
class Program
{
static void Main()
{
int sum = 0;
for (int i = 1; i <= 10; i++)
{
sum += i;
}
Console.WriteLine("Sum of numbers from 1 to 10 is: " + sum);
}
}
Output:
using System;
class Program
{
static void Main()
{
int rows = 5;
Console.WriteLine("Star pattern:");
for (int i = 1; i <= rows; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("*");
}
Console.WriteLine();
}
}
}
Output:
Star pattern:
*
**
***
****
*****