C# For Loop - c# - c# tutorial - c# net
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.
Syntax:
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 :
C# Sample Code - C# Examples:
Code Explanation:
- 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.
- 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.
- Here Console.ReadLine(); specifies to reads input from the console. When the user presses enter, it returns a string.
Sample C# examples - Output :
- 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".