Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

for: practical reference

for: practical reference: for combines initialization, a condition, and an iteration step.

Version: C# language; verified against C# 14 reference

Syntax

for /* grammar-specific form */

for combines initialization, a condition, and an iteration step.

Use it for indexed loops and precise control of the step.

Changing the counter in the body makes termination harder to reason about.

Any of the three clauses may be empty; no condition means an infinite loop.

The complete program actually uses for; its exact expected stdout is 6.

Examples

using System;
using System.Buffers;
using System.Collections.Concurrent;
using System.Collections.Frozen;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using Number = System.Int32;

var sum = 0; for (var i = 1; i <= 3; i++) sum += i; Console.WriteLine(sum);

Result

6

The complete program actually uses `for`; its exact expected stdout is `6`.

Sources