c-sharp
  1. c-sharp-program-to-display-prime-numbers-between-two-intervals

Program to Display Prime Numbers Between Two Intervals - (C# Basic Programs)

The program to display prime numbers between two intervals is a common exercise in programming, especially for beginners. In this tutorial, we will discuss a C# program to display prime numbers between two intervals.

Syntax

The syntax for the program to display prime numbers between two intervals in C# is as follows:

for (int i = startInterval; i <= endInterval; i++) {
   bool isPrime = true;

   for (int j = 2; j <= Math.Sqrt(i); j++) {
      if (i % j == 0) {
         isPrime = false;
         break;
      }
   }

   if (isPrime && i != 1) {
      Console.Write(i + " ");
   }
}

Example

using System;

namespace PrimeNumbers
{
    class Program
    {
        static void Main(string[] args)
        {
            int startInterval, endInterval;

            Console.WriteLine("Enter the start interval: ");
            startInterval = int.Parse(Console.ReadLine());

            Console.WriteLine("Enter the end interval: ");
            endInterval = int.Parse(Console.ReadLine());

            Console.WriteLine($"Prime numbers between {startInterval} and {endInterval}: ");

            for (int i = startInterval; i <= endInterval; i++)
            {
                bool isPrime = true;

                for (int j = 2; j <= Math.Sqrt(i); j++)
                {
                    if (i % j == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }

                if (isPrime && i != 1)
                {
                    Console.Write(i + " ");
                }
            }

            Console.ReadLine();
        }
    }
}

Output

Enter the start interval:
10
Enter the end interval:
50
Prime numbers between 10 and 50: 
11 13 17 19 23 29 31 37 41 43 47

Explanation

The program takes two inputs from the user: start interval and end interval. It then initializes a loop that runs through all the numbers within the specified interval. For each number, the program checks whether it is a prime number or not using the nested loop. If the number is prime, it is printed on the screen.

Use

This C# program helps beginners practice looping statements and conditional statements. It also helps in understanding how to check whether a number is prime or not.

Summary

In this tutorial, we discussed a C# program to display prime numbers between two intervals. We have seen the syntax, examples, explanation, use, and output of the program. Practicing such exercises can help beginners solidify their understanding of basic programming concepts and build confidence in their coding abilities.

Published on: