In C# programming, the for loop is a type of loop that is used to execute a block of code repeatedly as long as the condition remains true. In C# , a for loop is also known as an exit-controlled loop because it checks the condition before the loop body executes. It is used to loop part of the program several times.
Syntax
It has the following syntax.
for (initialization; condition; updation)
{
// code to be executed
}
In this syntax,
- Initialization: It is used to initialize the variable at once.
- Condition: This block is used to check the condition of the program. If the program condition is matched, the block of code is executed. If the program condition doesn't match, it exits the loops.
- Updation: This block is used for updating the loop variable value, whether it increments or decrements.
Flow Diagram for a for Loop
As we can see in the flow chart, use the following steps to implement a for loop in C#.
- First, we have to initialize the value.
- Next, we proceed to the while loop.
- After that, we check the given condition of the program. If the given condition becomes true, it executes the block of code. If the given condition becomes false, it does not execute the block of the loop and terminates the loop.
- End of the program.
- If the given condition becomes true, it executes the block of code.
- If the given condition becomes false, it does not execute the block of the loop and terminates the loop.
C# for Loop Example
Let us take an example to illustrate the for loop in C#.
Example
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 10; i++) // C# for loop
{
Console.WriteLine(i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Explanation:
In this example, we print the numbers 1 to 10 by using a for loop. Here, we initialize the integer value i=1. After that, it checks the given condition (i<10). If the given condition is true, it prints the value of i. If the given condition is false, it terminates the loop.
Factorial Number Program Using a for Loop
Let us take an example to find the factorial of a given number using a for loop in C#.
Example
using System;
class Program
{
static void Main()
{
int num_ber, factorial = 1;
Console.WriteLine("Please input the number:");
num_ber = int.Parse(Console.ReadLine());
for (int i = 1; i <= num_ber; i++) // using for loop
{
factorial *= i;
}
Console.WriteLine($"The factorial of {num_ber} is {factorial}");
}
}
Output:
Please input the number:
6
The factorial of 6 is 720
Explanation:
In this example, we are using a for loop to print the factorial number. First, we have taken the integer value num and fact. The user entered the number to calculate the factorial. After that, we use the for loop and print the output by using the Console.WriteLine function.
Multiplication Table Using a for loop in C#
Let us take an example to print the table by using the for loop statements.
Example
using System;
class Program
{
static void Main()
{
int num_ber;
Console.Write("Enter a Number: ");
num_ber = int.Parse(Console.ReadLine());
for (int i = 1; i <= 10; i++) // for loop
{
Console.WriteLine($"{num_ber} * {i} = {num_ber * i}");
}
}
}
Output:
Enter a Number: 6
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
6 * 10 = 60
Explanation:
In this example, we have taken the integer data type num_ber. After that, we assign the value n=1. The user entered the number to perform the multiplication table. After that, we use a for loop and create the logic to multiply numbers. Finally, we use the Console.WriteLine function to print the output.
C# Nested for Loop
In C# programming, the nested for loop is a type of loop statement where one for loop is inside another for loop. The inner loop finishes all of its iterations each time the outer loop runs at least once. In other words, the inner loop completes all its steps before the outer loop runs at least once.
Syntax:
It has the following syntax.
for(initialization; condition; increment)
{
for(initialization; condition; increment)
{
// statement of inner loop
}
// statement of outer loop
}
Flow Diagram of Nested for Loop
C# Nested for Loop Example
Let us take an example to illustrate the Nested for loop in C#.
Example
using System;
class Program
{
static void Main()
{
for (int i = 1; i <= 3; i++) // outer for loop
{
for (int j = 1; j <= 3; j++) // inner for loop
{
Console.WriteLine($"{i} {j}"); // display the value
}
}
}
}
Output:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Explanation:
In this example, we are using a nested for loop to print the numbers. First, we have taken the two integer variables i and j. Here, i represents the outer loop that controls the rows, and the inner loop represents the inner loop that controls the columns. After that, it prints the output in 9 lines that shows each pair of values.
C# Pyramid Program Using Nested for Loops
Let us take an example to print the pyramid pattern using nested for loops in C#.
Example
using System;
class Program
{
static void Main()
{
Console.Write("Enter the Number of rows: ");
int n = int.Parse(Console.ReadLine());
// Outer loop
for (int i = 0; i < n; i++)
{
// Inner loop
for (int j = 0; j <= i; j++)
{
Console.Write("* "); // stars Printing
}
Console.WriteLine(); // moves to the new line after every row
}
}
}
Output:
Enter the Number of rows: 6
*
* *
* * *
* * * *
* * * * *
* * * * * *
Explanation:
In this example, we have created the pyramid program using a nested for loop statement. First, we have taken the two integer variables i and j. After that, it prompts the user to input the number of rows and uses a nested loop. The outer loop is used to control the number of rows, whereas the inner loop is used to print the stars in increasing order each time.
C# Inverted Pyramid Program Using Nested for Loops
Let us take an example to print the pyramid pattern using a nested for loop in C#.
Example
using System;
class Program
{
static void Main()
{
Console.Write("Enter the Number of rows: ");
int n = int.Parse(Console.ReadLine());
// Outer loop
for (int i = 0; i < n; i++)
{
// Inner loop
for (int j = n; j > i; j--)
{
Console.Write("* "); // stars printing
}
Console.WriteLine(); // moves to the new line after every row
}
}
}
Output:
Enter the Number of rows: 8
* * * * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Explanation:
In this example, we have created the inverted pyramid program using a nested for loop statement. First, it prompts the user to input the number of rows and uses a nested loop. The outer loop is used to control the number of rows, whereas the inner loop is used to print the stars in decreasing order each time.
C# Infinite for Loop
In C#, if we remove the initialization, condition, and update expression, it will result in an infinite loop. In other words, if we use a double semicolon in the for loop, it will be executed infinite times.
Syntax
It has the following syntax.
for( ; ; )
{
// code to be executed
}
C# Infinite for Loop Example
Let us take an example to illustrate an infinite for loop in C#.
Example
using System;
class Program
{
static void Main()
{
for (;;) // infinite for loop
{
Console.Write("Hello! C# Tutorial"); // prints without newline
}
}
}
Output:
Hello! C# Tutorial
Hello! C# Tutorial
Hello! C# Tutorial
Hello! C# Tutorial
Explanation:
In this example, we have built the program using an infinite 'for' loop. The loop is defined as 'for (;;)', which runs endlessly because it has no condition. Inside the loop, we repeatedly print "Hello C# Tutorial" to the console.
C# foreach Loop
In C# programming, the foreach loop is a loop that is used to work with collections like strings , arrays and arrays of objects, etc. It works on the basis of items. The foreach loop is an element-based loop, which means to fetches each element from the collection one by one.
Syntax
It has the following syntax.
foreach (datatype variable in collection)
{
// Code to be executed
}
In this syntax,
- Datatype: It represents the type of elements in the collection (such as int, string, etc).
- Datatype: It represents the type of elements in the collection (such as int, string, etc).
- Collection: It represents the collection of an array.
C# for each loop Example:
Let us take an example to illustrate the for each loop in C#.
Example
using System;
class Program
{
static void Main()
{
// Define an array of fruits
string[] fruits = { "Apple", "Banana", "Orange", "Mango" };
// Use a foreach loop to iterate through the array
foreach (string fruit in fruits)
{
Console.WriteLine("Fruit: " + fruit);
}
}
}
Output:
Fruit: Apple
Fruit: Banana
Fruit: Orange
Fruit: Mango
Explanation:
In this example, we use the foreach loop to iterate over items in the collection. First, we have created an array named fruits and stored some fruits. After that, we have used the for loop to iterate the items from the array. Finally, we are using the Console.WriteLine function to print the output.
Conclusion
In conclusion, the C# for Loop statement allows us to solve the critical problem in programming. It is essential for performing the repeat action in programs. It is beneficial for programmers to perform dynamic calculations.
C# for Loop FAQs
1) What is a for loop in C#?
In C#, a for loop is used to execute the block of code repeatedly as long as the condition remains true. It is the entry-controlled loop and is used to loop part of the program several times.
2) What is the difference between the for loop and the while loop in C#?
The main difference between the for loop and the while loop is.
| For Loop | While Loop |
|---|---|
| The variable is initialized within the loop. | The variable is initialized outside the loop. |
| The syntax of for loop is for( ; ; ); | The syntax of while loop is while(condition) { } |
3) Can we use the break and continue keywords in a for loop in C#?
Yes, the break and continue keywords can be used within for loop.
4) What is the nested for loop in C#?
In C#, a nested for loop is a type of loop statement where a for loop is inside another for loop. Before the outer loop moves to its next iteration, the inner loop must finish all of its iterations. In other words, the inner loop finishes all its steps before the outer leave runs at least once.
5) What is a foreach loop in C#?
In C#, the foreach loop is a loop that is used to work with collections like strings, arrays and arrays of objects, etc. It works on the basis of items. The foreach loop is an element-based loop, which means to fetches each element from the collection one by one.