Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • C# - Get Started
  • C# - Version History
  • C# - First Program
  • C# - Keywords
  • C# - Class and Objects
  • C# - Namespace
  • C# - Variables
  • C# - Implicitly-Typed Variables
  • C# - Data Types
  • Numbers
  • Strings
  • DateTime
  • Structure
  • Enum
  • StringBuilder
  • Anonymous Types
  • Dynamic Types
  • Nullable Types
  • C# - Value & Reference Types
  • C# - Interface
  • C# - Operators
  • C# - if else Statements
  • C# - Ternary Operator ?:
  • C# - Switch
  • C# - For Loop
  • C# - While Loop
  • C# - Do-while Loop
  • C# - Partial Class
  • C# - Static
  • C# - Array
  • Multidimensional Array
  • Jagged Array
  • C# - Indexer
  • C# - Generics
  • Generic Constraints
  • C# - Collections
  • ArrayList
  • List
  • SortedList
  • Dictionary
  • Hashtable
  • Stack
  • Queue
  • C# - Tuple
  • C# - ValueTuple
  • C# - Built-in Exceptions
  • Exception Handling
  • throw
  • Custom Exception
  • C# - Delegates
  • Func Delegate
  • Action Delegate
  • Predicate Delegate
  • Anonymous Methods
  • C# - Events
  • C# - Covariance
  • C# - Extension Method
  • C# - Stream I/O
  • C# - File
  • C# - FileInfo
  • C# - Object Initializer
  • OOP - Overview
  • Object-Oriented Programming
  • Abstraction
  • Encapsulation
  • Association & Composition
  • Inheritance
  • Polymorphism
  • Method Overriding
  • Method Hiding
  • C# - Solid Principles
  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle
  • Design Patterns
  • Singleton
  • Abstract Factory
  • Factory Method
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

C# for Loop


Updated on: June 17, 2020

Here, you will learn how to execute a statement or code block multiple times using the for loop, structure of the for loop, nested for loops, and how to exit from the for loop.

The for keyword indicates a loop in C#. The for loop executes a block of statements repeatedly until the specified condition returns false.

Syntax:
for (initializer; condition; iterator)//code block 

The for loop contains the following three optional sections, separated by a semicolon:

Initializer: The initializer section is used to initialize a variable that will be local to a for loop and cannot be accessed outside loop. It can also be zero or more assignment statements, method call, increment, or decrement expression e.g., ++i or i++, and await expression.

Condition: The condition is a boolean expression that will return either true or false. If an expression evaluates to true, then it will execute the loop again; otherwise, the loop is exited.

Iterator: The iterator defines the incremental or decremental of the loop variable.

The following for loop executes a code block 10 times.

Example: for Loop
for(int i = 0; i < 10; i++)
{
    Console.WriteLine("Value of i: {0}", i);
}
Try it
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9

In the above example, int i = 0 is an initializer where we define an int variable i and initialize it with 0. The second section is the condition expression i < 10, if this condition returns true then it will execute a code block. After executing the code block, it will go to the third section, iterator. The i++ is an incremental statement that increases the value of a loop variable i by 1. Now, it will check the conditional expression again and repeat the same thing until conditional expression returns false. The below figure illustrates the execution steps of the for loop.

The below figure illustrates the execution steps of the for loop.

for Loop Execution Steps

If a code block only contains a single statement, then you don't need to wrap it inside curly brackets , as shown below.

Example: for Loop
for(int i = 0; i < 10; i++)
    Console.WriteLine("Value of i: {0}", i);

An Initializer, condition, and iterator sections are optional. You can initialize a variable before for loop, and condition and iterator can be defined inside a code block, as shown below.

Example: for loop C#
int i = 0;

for(;;)
{
    if (i < 10)
    {
        Console.WriteLine("Value of i: {0}", i);
        i++;
    }
    else
        break;
}
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9

Since all three sections are optional in the for loop, be careful in defining a condition and iterator. Otherwise, it will be an infinite loop that will never end the loop.

Example: Infinite for Loop
for ( ; ; )
{
    Console.Write(1);
}
Output:
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1.....

The control variable for the for loop can be of any numeric data type, such as double, decimal, etc.

Example: Decimal for Loop
for (double d = 1.01D; d < 1.10; d+= 0.01D)
{
    Console.WriteLine("Value of i: {0}", d);
}
Try it
Output:
Value of i: 1.01
Value of i: 1.02
Value of i: 1.03
Value of i: 1.04
Value of i: 1.05
Value of i: 1.06
Value of i: 1.07
Value of i: 1.08
Value of i: 1.09

The steps part in a for loop can either increase or decrease the value of a variable.

Example: Reverse for Loop
for(int i = 10; i > 0; i--)
{
    Console.WriteLine("Value of i: {0}", i);
}
Try it
Output:
Value of i: 10
Value of i: 9
Value of i: 8
Value of i: 7
Value of i: 6
Value of i: 5
Value of i: 4
Value of i: 3
Value of i: 2
Value of i: 1

Exit the for Loop

You can also exit from a for loop by using the break keyword.

Example: break in for loop
for (int i = 0; i < 10; i++)
{
    if( i == 5 )
        break;

    Console.WriteLine("Value of i: {0}", i);
}
Try it
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4

Multiple Expressions

A for loop can also include multiple initializer and iterator statements separated by comma, as shown below.

Example: Multiple Expressions
for (int i = 0, j = 0; i+j < 5; i++, j++)
{
    Console.WriteLine("Value of i: {0}, J: {1} ", i,j);
}
Try it
Output:
Value of i: 0, J: 0
Value of i: 1, J: 1
Value of i: 2, J: 2

A for loop can also contain statements as an initializer and iterator.

Example: Initializer and Iterator Statements
int i = 0, j = 5;
for (Console.WriteLine($"Initializer: i={i}, j={j}"); 
    i++ < j--; 
    Console.WriteLine($"Iterator: i={i}, j={j}"))
    {
    }
Try it
Output:
Initializer: i=0, j=5
Iterator: i=1, j=4
Iterator: i=2, j=3
Iterator: i=3, j=2

Nested for Loop

C# allows a for loop inside another for loop.

Example: Nested for loop
for (int i = 0; i < 2; i++)
{
    for(int j =i; j < 4; j++)
        Console.WriteLine("Value of i: {0}, J: {1} ", i,j);
}
Try it
Output:
Value of i: 0, J: 0
Value of i: 0, J: 1
Value of i: 0, J: 2
Value of i: 0, J: 3
Value of i: 1, J: 1
Value of i: 1, J: 2
Value of i: 1, J: 3
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.