Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
OOPS in C#
C# Data Types
Boxing and Unboxing in C#
Garbage Collection in C#
C# - Conditional Statements
C# - Loops
Interfaces in C#
Generics in C#
Collections in C#
C# 8.0 new features
C# Singleton Design Pattern
C# Factory Design Pattern
LINQ in C#
C# - Program to Find Prime Numbers
C# - Fibonacci Sequence
C# - Factorial of a number
C# - Recursive methods
C# - Anonymous Methods
C# - String Methods
C# TDD - XUnit
C# TDD - NUnit
C# Multiton Design Pattern
C# Facade Design Pattern
C# Abstract Factory Design Pattern
C# Decorator Design Pattern
C# Composite Design Pattern

C# - Program to Find Prime Numbers



Here is a simple C# program that finds and prints prime numbers within a given range:

csharp
using System;

class Program
{
    static void Main()
    {
        int start = 1;
        int end = 100;

        Console.WriteLine("Prime numbers between {0} and {1} are:", start, end);
        for (int i = start; i <= end; i++)
        {
            if (IsPrime(i))
            {
                Console.Write(i + " ");
            }
        }
    }

    // Method to check if a number is prime
    static bool IsPrime(int num)
    {
        if (num <= 1) return false;
        if (num == 2) return true; // 2 is a prime number
        if (num % 2 == 0) return false; // even numbers greater than 2 are not prime

        for (int i = 3; i <= Math.Sqrt(num); i += 2)
        {
            if (num % i == 0) return false;
        }

        return true;
    }
}

Explanation:

  1. Main Method:

    • Defines the range of numbers (from start to end).

    • Loops through each number in this range and checks if it is prime using the IsPrime method.

    • If a number is prime, it prints the number.

  2. IsPrime Method:

    • Checks if the number is less than or equal to 1 (not prime).

    • Checks if the number is exactly 2 (prime).

    • Checks if the number is an even number greater than 2 (not prime).

    • For odd numbers greater than 2, it checks divisors from 3 to the square root of the number. If any divisor evenly divides the number, it's not prime.

This program can be easily modified to find primes in any range by changing the start and end variables. Let me know if you have any specific requirements or need further customization!




All rights reserved | Privacy Policy | Sitemap