DevAcademia
C++C#CPythonJava
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction
  • C# Basics

  • C# Introduction
  • C# Get Started
  • C# Syntax
  • C# Output
  • C# Comments
  • C# Variables
  • C# Data Types
  • C# Type Casting
  • C# User Input
  • C# Operators
  • C# Math
  • C# Strings
  • C# Booleans
  • C# If...Else
  • C# Switch Statement
  • C# While Loop
  • C# For Loop
  • C# Break and Continue
  • C# Arrays
  • C# Files
  • C# OOP

  • C# OOP Introduction
  • C# Classes and Objects
  • C# Class Members
  • C# Constructors
  • C# Destructors
  • C# Access Modifiers
  • C# Properties
  • C# Inheritance
  • C# Polymorphism
  • C# Abstraction
  • C# Interfaces
  • C# Enums
  • C# Exceptions
  • C# Quizzes

  • C# Quiz Introduction

Loading Cs tutorial…

Loading content
C# BasicsTopic 31 of 55
←PreviousPrevNextNext→

C# For Loop - Complete Guide

Introduction to For Loops

The for loop in C# is a control flow statement that executes a block of code repeatedly for a specified number of iterations. It is most useful when the number of iterations is known beforehand.

The for loop consists of three parts: initialization, condition, and iteration. This structure makes it ideal for iterating through arrays, collections, and performing counter-based tasks.

Basic For Loop Syntax

A for loop has initialization, condition, and iteration expressions inside parentheses:

Example
using System;

namespace ForLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Print numbers 1 to 5
            for (int i = 1; i <= 5; i++)
            {
                Console.WriteLine("Number: " + i);
            }

            // Counting backwards
            Console.WriteLine("\nCounting backwards:");
            for (int i = 5; i >= 1; i--)
            {
                Console.WriteLine("Number: " + i);
            }

            // Step by 2
            Console.WriteLine("\nEven numbers between 0 and 10:");
            for (int i = 0; i <= 10; i += 2)
            {
                Console.WriteLine("Even: " + i);
            }

            // Multiples of 5
            Console.WriteLine("\nMultiples of 5:");
            for (int i = 5; i <= 25; i += 5)
            {
                Console.WriteLine("Multiple: " + i);
            }

            // Calculate sum
            int sum = 0;
            for (int i = 1; i <= 10; i++)
            {
                sum += i;
            }
            Console.WriteLine($"\nSum of numbers 1 to 10: {sum}");
        }
    }
}
Output
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Counting backwards:
Number: 5
Number: 4
Number: 3
Number: 2
Number: 1

Even numbers between 0 and 10:
Even: 0
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10

Multiples of 5:
Multiple: 5
Multiple: 10
Multiple: 15
Multiple: 20
Multiple: 25

Sum of numbers 1 to 10: 55

For Loop with Arrays and Collections

For loops are often used with arrays and collections:

Example
using System;

namespace ForLoopWithArrays
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] numbers = { 10, 20, 30, 40, 50 };
            Console.WriteLine("Array elements:");
            for (int i = 0; i < numbers.Length; i++)
            {
                Console.WriteLine($"Index {i}: {numbers[i]}");
            }

            // Calculate stats
            int[] scores = { 85, 92, 78, 90, 88 };
            int total = 0, highest = scores[0], lowest = scores[0];
            for (int i = 0; i < scores.Length; i++)
            {
                total += scores[i];
                if (scores[i] > highest) highest = scores[i];
                if (scores[i] < lowest) lowest = scores[i];
            }
            double average = (double)total / scores.Length;
            Console.WriteLine($"\nStats - Total: {total}, Average: {average:F1}, Highest: {highest}, Lowest: {lowest}");

            // 2D array
            int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
            Console.WriteLine("\n2D Array elements:");
            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    Console.Write($"{matrix[row, col]} ");
                }
                Console.WriteLine();
            }

            // Strings
            string text = "Hello";
            Console.WriteLine("\nString characters:");
            for (int i = 0; i < text.Length; i++)
            {
                Console.WriteLine($"Character {i}: '{text[i]}' (ASCII: {(int)text[i]})");
            }

            // Reverse string
            string reversed = "";
            for (int i = text.Length - 1; i >= 0; i--)
            {
                reversed += text[i];
            }
            Console.WriteLine($"\nOriginal: {text}, Reversed: {reversed}");
        }
    }
}
Output
Array elements:
Index 0: 10
Index 1: 20
Index 2: 30
Index 3: 40
Index 4: 50

Stats - Total: 433, Average: 86.6, Highest: 92, Lowest: 78

2D Array elements:
1 2 3 
4 5 6 
7 8 9 

String characters:
Character 0: 'H' (ASCII: 72)
Character 1: 'e' (ASCII: 101)
Character 2: 'l' (ASCII: 108)
Character 3: 'l' (ASCII: 108)
Character 4: 'o' (ASCII: 111)

Original: Hello, Reversed: olleH

Advanced For Loop Techniques

For loops can be extended to handle more complex patterns:

Example
using System;

namespace AdvancedForLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            // Multiple variables
            for (int i = 0, j = 10; i < j; i++, j--)
            {
                Console.WriteLine($"i: {i}, j: {j}");
            }

            // Infinite loop with break
            int counter = 0;
            for (;;)
            {
                Console.WriteLine("Iteration: " + (counter + 1));
                if (++counter >= 5) break;
            }

            // Multiplication table
            for (int i = 1; i <= 5; i++)
            {
                for (int j = 1; j <= 5; j++)
                {
                    Console.Write($"{i * j,4}");
                }
                Console.WriteLine();
            }

            // Continue statement
            for (int i = 1; i <= 10; i++)
            {
                if (i % 2 == 0) continue;
                Console.WriteLine("Odd: " + i);
            }

            // Divisible by 3 or 5
            for (int i = 1; i <= 20; i++)
            {
                if (i % 3 == 0 || i % 5 == 0)
                {
                    Console.WriteLine($"{i} is divisible by 3 or 5");
                }
            }

            // External control
            bool shouldContinue = true;
            for (int i = 1; shouldContinue && i <= 100; i++)
            {
                Console.WriteLine("Processing: " + i);
                if (i >= 7) shouldContinue = false;
            }
        }
    }
}
Output
i: 0, j: 10
i: 1, j: 9
i: 2, j: 8
i: 3, j: 7
i: 4, j: 6

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

Odd: 1
Odd: 3
Odd: 5
Odd: 7
Odd: 9

3 is divisible by 3 or 5
5 is divisible by 3 or 5
6 is divisible by 3 or 5
9 is divisible by 3 or 5
10 is divisible by 3 or 5
12 is divisible by 3 or 5
15 is divisible by 3 or 5
18 is divisible by 3 or 5
20 is divisible by 3 or 5

Processing: 1
Processing: 2
Processing: 3
Processing: 4
Processing: 5
Processing: 6
Processing: 7
Test your knowledge: C# For Loop - Complete Guide
Quiz Configuration
4 of 8 questions
Sequential
Previous allowed
Review enabled
Early close allowed
Estimated time: 5 min
C# BasicsTopic 31 of 55
←PreviousPrevNextNext→