How to Create a For Loop in C#

  • Share
  • Print this article

In the C# language, the "for" statement is used to define a block of code that will execute a statement (or a block of statements) as long as a specific condition remains true. This means that, as long as the returned value remains within the set parameters, the statement will continue to run. This type of program construct is called a loop. In C#, for loops, or any other loop constructs, may be also nested, which means that a loop can be created, defined and executed within the body of another loop.

Instructions

    • 1

      Begin to create the loop structure with the "for" keyword. The for statement tells the compiler that the code that follows is a condition that defines how many times the loop will execute.

    • 2

      Enclose the conditional statement in parentheses. The conditional statement is comprised of three optional parts which are separated by semicolons: the initial value, the condition and the value of the tested variable. The semicolons are required even if parts of the conditional statement are omitted. If all three parts are omitted, the loop will execute endlessly.

    • 3

      Set an initial value for the conditional. To set the initial value, define a new variable preceded by its type and use the assignment operator (=) to give it a value. for(int i = 0;;)

    • 4

      Define the conditional statement. This is the condition that must remain true in order for the code in the loop block to keep iterating. The standard comparison operators, < and >, are used to evaluate the statement. for(int i = 0; i < 10 ;)

    • 5

      Modify the value of the variable being tested in the conditional statement. Increment operators are frequently used to increment or decrement the value of the variable. for(int i = 0; i < 10; ++i)

    • 6

      Enclose the statements to be iterated over in curly braces. If only one statement should be included in the loop, the curly braces can be omitted. for(int i = 0; i < 10; ++i) { Console.WriteLine(i) }

Tips & Warnings

  • Nest any other loop constructs you need within the outer loop. Your code block can contain as many loops as necessary to accomplish your given task. Loops can be nested infinitely, which can create a complex block of code.

Related Searches

Comments

Related Ads

Featured
View Mobile Site