for Loop
A for loop repeats something a set number of times, like doing exactly ten push-ups while counting. You say where to start, when to stop, and how to count.
In this page:
Syntax
for (int i = start; i <= end; i++)
{
// body
}
for Loop
A for loop repeats a block a known number of times, controlled by an initializer, a condition, and an increment step.
It's the standard choice when you know exactly how many iterations you need, such as walking through indices. All three parts of a for header are optional but conventionally used together.
Note:
Use
for when you need the loop index itself, not just each element.Example: for Loop
using System;
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine($"Count: {i}");
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
<=with an array length, likei <= arr.Length, which throwsIndexOutOfRangeException. - Changing the loop variable inside the loop body and skipping iterations.
- Putting a semicolon after
for (...);, making the loop body empty.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: