Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

C# Tutorial

C# HOME C# Intro 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 C# While Loop C# For Loop C# Break/Continue C# Arrays

C# Methods

C# Methods C# Method Parameters C# Method Overloading C# Scope C# Recursion

C# Classes

C# OOP C# Classes/Objects C# Class Members C# Constructors C# this Keyword C# Access Modifiers C# Properties C# Static C# Inheritance C# Polymorphism C# Abstraction C# Interface C# Enums C# Structs

C# Errors

C# Errors C# Debugging C# Exceptions

C# Data Structures

C# Data Structures C# List C# Dictionary C# HashSet C# Stack C# Queue

C# Advanced

C# Files C# Date and Time C# Nullable Types C# Generics C# Lambda C# LINQ

C# Cert

C# Certificate

C# How To

C# How Tos

C# Examples

C# Examples C# Compiler C# Exercises C# Quiz C# Practice Problems C# Server C# Syllabus C# Study Plan


C# Recursion


Share

Recursion

Recursion means that a method calls itself.

Why would a method call itself? Some problems contain a smaller copy of the same problem. For example, to count down from 5, you say "5", and then you count down from 4. To count down from 4, you say "4", and then you count down from 3, and so on.

A recursive method does one small step, and then calls itself to do the rest:

Example

static void Countdown(int number)
{
  if (number > 0)
  {
    Console.WriteLine(number);
    Countdown(number - 1);
  }
}

static void Main(string[] args)
{
  Countdown(5);
}

Try it Yourself »

Example explained

Countdown(5) prints 5 and calls Countdown(4).
Countdown(4) prints 4 and calls Countdown(3), and so on.
At last, Countdown(0) does nothing, because 0 > 0 is false. Then the calls stop.


Halting Condition

Every recursive method needs a halting condition: a condition where the method stops calling itself.

In the example above, the method stops when number becomes 0. It works like the condition in a while loop.

Without a halting condition, the method calls itself forever:

Example

static void Countdown(int number)
{
  Console.WriteLine(number);
  Countdown(number - 1);  // Never stops
}

Each method call uses a little memory. After many thousands of calls, there is no more memory for new calls, and the program crashes with a "stack overflow" error.



Sum of Numbers

A recursive method can also return a value. This method adds all numbers from 1 to 10:

Example

static int Sum(int number)
{
  if (number > 0)
  {
    return number + Sum(number - 1);
  }
  else
  {
    return 0;
  }
}

static void Main(string[] args)
{
  int result = Sum(10);
  Console.WriteLine(result);
}

Try it Yourself »

Example explained

Sum(10) returns 10 + Sum(9).
Sum(9) returns 9 + Sum(8), and so on.
Sum(0) returns 0. This is the halting condition, so the calls stop.

Then all the numbers are added together: 10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0, which is 55.


Factorial

The factorial of a number is the number multiplied by every whole number below it, down to 1. For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1, which is 120.

This is the same idea: the factorial of 5 is 5 times the factorial of 4:

Example

static int Factorial(int number)
{
  if (number > 1)
  {
    return number * Factorial(number - 1);
  }
  else
  {
    return 1;
  }
}

static void Main(string[] args)
{
  Console.WriteLine(Factorial(5));
}

Try it Yourself »

Here, the halting condition is when number is 1: Factorial(1) returns 1, and the calls stop.



Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.