For loop in C#
For loop is control statement. It is a keyword used for repetitive execution of statement. For loop executes a block of statements repeatedly until the specified condition returns true/false value. It is one of the easiest loop and mostly used.
The syntax of for loop is
for(variable declaration/initialization; condition; steps(increment/decrement))
{
//statements
}
Flowchart of for loop
- Variable declaration= integer type. Example: int i; int j; Initialization = the beginning value of the variable. Example: i=0; i=20 etc.
- Condition: The condition in loop is Boolean expression which returns either True or False. Example: i<10; i<=20; I > 5; I >=10 ;
- Increment / decrement : It defines increment or decrement part: It executes only when the condition is satisfied.
Example:
i++ , i-- ,i=i+2, i=i-2
Example of for loop
for ( int i=0; i<=10;i++)
for (i=2;i<=20; i=i+2)
for (i=10; i>=0 ; i--)
Question: How to display pyramid using for loop in C# ?
Solution:
using System;
namespace Star_Pyramid
{
class Program
{
static void Main(string[] args)
{
int i, j, k, n;
Console.WriteLine("how many number of pyramid do you want");
n = int.Parse(Console.ReadLine());
for (i = 1; i <= n; i++)
{
for ( j = 1; j <=(n - i) / 2; j++)
{
Console.Write(" ");
}
for ( k = 1; k <= i-1; k++)
{
Console.Write(" * ");
Console.Write(" ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
Output of above program is shown below