C# For Loop - c# - c# tutorial - c# net

C# For Loop

C# For Loop

What is for loop in C# ?

  • For loop statement is executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
 C For Loop Statement


for(initialization counter; test counter; increment counter) 
    code to be executed;
 c sharp for  loop

c sharp for loop

Syntax Explanation:

  • initialization: It is used to initialize the counter variables.
  • test counter: Evaluate for each loop iteration. If it evaluates to be TRUE, the loop continues. If it evaluates to be FALSE, the loop ends.
  • increment: It increase the loopcounter with a new value. It is evaluating at the end of each iteration.
  • execute the statement: It executes the statements.

Possible for loops :

for (int counter = 0, val1 = 10;  counter < val1; counter++)
for ( ; counter < 100; counter+=10)   // No initialization
for (int j = 0;   ;    j++)           // No conditional expression
for ( ; j < 10;  counter++, j += 3)   // Compound update
for (int aNum = 0; aNum < 101;  sum += aNum, aNum++)  // Null loop body
for (int j = 0,k = 10; j < 10 && k > 0;  counter++, j += 3)  

C# Sample Code - C# Examples:

using System;

namespace wikitechy_for_loop
staticvoid Main(string[] args)
for (int n = 5; n <= 10; n = n + 1)

Console.WriteLine("value of n is : {0}", n);


Code Explanation:

 C# for loop structure
  1. Here for (int n = 5; n <= 10; n=n + 1)int n=5 is an integer variable. which means the expression, (n>=10),conditionis true. Therefore, the conslole.writeLine namespace statement is executed, and n=n+1 gets incremented by 1 and becomes 10.
  2. In this example Console.WriteLine,the Main method specifies its behavior with the statement "value of n is: {0}".AndWriteLine is a method of the Console class defined in the System namespace. This statement reasons the message""value of n is: {0}"to be displayed on the screen.
  3. Here Console.ReadLine(); specifies to reads input from the console. When the user presses enter, it returns a string.

Sample C# examples - Output :

 C# for loop strcture output
  1. Here in this output the value of n is:5,6,7,8,9,10 will be printed until it reaches the last element "10".

Related Searches to C# For Loop

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.