Check Harshad Number in C#

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
Digit-sum divisibility

What you’ll learn

  • What a Harshad number (Niven number) is: divisible by the sum of its digits.
  • How to write IsHarshadNumber in C# with a simple digit-sum loop and modulo check.
  • How to list Harshad numbers in a range (1–20) and verify results with a live preview.

Overview

Harshad numbers are a gentle interview warm-up: add the digits, then test divisibility. No recursion, no cycles — just modular arithmetic and a digit loop you will reuse in many other problems.

Two programs

Single check for 18 and a range scan 120.

Live preview

Type a positive integer and see digit sum plus the divisibility verdict.

Also called Niven

Same definition — divisibility by digit sum — under two common names.

Prerequisites

Digit extraction with % 10 and / 10, modulo, and while loops.

  • using System;, static methods, bool return types, string interpolation.
  • Know that a % b == 0 means a is evenly divisible by b.

What is a Harshad number?

A Harshad number (also called a Niven number) is a positive integer that is divisible by the sum of its decimal digits.

For 18: digits sum to 1 + 8 = 9, and 18 ÷ 9 = 2 with no remainder — so 18 is Harshad. For 11: digit sum is 2, but 11 is not divisible by 2.

18 18 % 9 = 0
11 11 % 2 ≠ 0
10 sum = 1

Formal rule

Let S(n) be the sum of decimal digits of positive integer n. Then n is Harshad when S(n) > 0 and n mod S(n) = 0.

18

S(18) = 9 and 18 mod 9 = 0 → Harshad.

Quick examples

18 Harshad
Sum
9, 18 ÷ 9 = 2
11 Not
Sum
2, 11 ÷ 2 has remainder

Harshad numbers 1–20: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20.

Live preview

Enter a positive integer. The widget computes the digit sum and checks divisibility.

Try 18 (Harshad) or 11 (not Harshad).

Live result
Press “Check Harshad” to evaluate.

Algorithm

Goal: return whether positive n is Harshad.

Save the original

Store originalNumber = n before you peel digits off n.

Sum the digits

While n > 0: add n % 10 to a running sum, then n /= 10.

Test divisibility

Return originalNumber % sumOfDigits == 0 when sumOfDigits > 0.

📜 Pseudocode

Pseudocode
function isHarshad(n):  // n > 0
    original ← n
    sum ← 0
    while n > 0:
        sum ← sum + (n mod 10)
        n ← floor(n / 10)
    return (original mod sum) = 0
1

Single check: is 18 Harshad?

Classic reference solution: compute digit sum, then test originalNumber % sumOfDigits == 0.

c#
using System;

class Program
{
    static bool IsHarshadNumber(int number)
    {
        if (number <= 0)
        {
            return false;
        }

        int originalNumber = number;
        int sumOfDigits = 0;

        while (number > 0)
        {
            sumOfDigits += number % 10;
            number /= 10;
        }

        return originalNumber % sumOfDigits == 0;
    }

    static void Main()
    {
        int number = 18;

        if (IsHarshadNumber(number))
        {
            Console.WriteLine($"{number} is a Harshad number.");
        }
        else
        {
            Console.WriteLine($"{number} is not a Harshad number.");
        }
    }
}

Explanation

The loop destroys number while building sumOfDigits, so we keep originalNumber for the final modulo test.

return originalNumber % sumOfDigits == 0;

Core test. Harshad means zero remainder when dividing by the digit sum.

2

Harshad numbers from 1 to 20

Reuses IsHarshad inside a for loop to print every Harshad number in the range — same output as the reference tutorial.

c#
using System;

class Program
{
    static bool IsHarshad(int number)
    {
        if (number <= 0)
        {
            return false;
        }

        int sumOfDigits = 0;
        int originalNumber = number;

        while (number > 0)
        {
            sumOfDigits += number % 10;
            number /= 10;
        }

        return originalNumber % sumOfDigits == 0;
    }

    static void Main()
    {
        Console.WriteLine("Harshad numbers in the range 1 to 20:");

        for (int i = 1; i <= 20; i++)
        {
            if (IsHarshad(i))
            {
                Console.Write($"{i} ");
            }
        }

        Console.WriteLine();
    }
}

Explanation

Numbers 11, 13, 14, etc. fail the divisibility test. Single-digit values always pass because the digit sum equals the number itself.

Beyond the basics

Extract SumOfDigits. Pull digit summing into its own method — you will reuse it in Armstrong, Disarium, and divisor problems.

Console input. Wrap with int.TryParse when reading from Console.ReadLine().

Interview: state the definition, walk through 18, mention 0 and negatives as out-of-scope, then write the digit loop.

❓ FAQ

A positive integer that is divisible by the sum of its decimal digits. It is also called a Niven number.
Yes. Digit sum is 1 + 8 = 9, and 18 ÷ 9 = 2 with no remainder.
No. Digit sum is 1 + 1 = 2, and 11 is not divisible by 2.
Yes for 1–9. Each number n is divisible by n (the only digit).
Yes. Digit sum is 1 + 0 = 1, and every integer is divisible by 1.
Harshad numbers are defined for positive integers. Zero has digit sum 0, which would cause division by zero — reject or handle separately.
Happy numbers repeat sum of squares of digits until reaching 1. Harshad numbers only check one step: divisibility by the digit sum.

🔄 Input / output examples

Change number in Main, or read from the console after validation.

InputDigit sumVerdict
11Harshad
101Harshad
123Harshad (12 ÷ 3 = 4)
189Harshad (18 ÷ 9 = 2)
112Not Harshad
134Not Harshad

Edge cases and pitfalls

The logic is simple, but two corners need explicit handling in production code.

Zero

0

Digit sum is 0 — dividing by zero throws. Return false or reject early.

Negative

n < 0

Outside the usual definition — return false or use Math.Abs only if your spec allows it.

Single digit

19

Always Harshad: n % n == 0 when the only digit is n.

Overwrite

Losing the original

If you forget originalNumber, the digit loop leaves number == 0 and the modulo test is wrong.

⏱️ Time and space complexity

OperationTimeExtra space
Single checkO(log n) digitsO(1)
Range 1–20 scanO(20 × log n)O(1)

Digit count grows with the number of decimal places — logarithmic in the value of n.

Summary

  • Definition: positive n divisible by the sum of its decimal digits (Niven number).
  • C#: sum digits in a loop, then original % sum == 0.
  • Classic demo: 18 is Harshad; 11 is not.
Did you know?

A Harshad number is also called a Niven number. The name comes from the Sanskrit word harsha, meaning joy. Every single-digit positive integer from 1 through 9 is Harshad, because the number equals the sum of its only digit.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful