Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Find the prime numbers within a range of numbers

C# Sharp For Loop: Exercise-34 with Solution

Write a program in C# Sharp to find the prime numbers within a range of numbers.

Pictorial Presentation:

C# Sharp Exercises: Find the prime numbers within a range of numbers

Sample Solution:

C# Sharp Code:

using System;  
public class Exercise34 
{  
    public static void Main()
{
    int num,i,ctr,stno,enno;
	
	Console.Write("\n\n");
    Console.Write("Find the prime numbers within a range of numbers:\n");
    Console.Write("---------------------------------------------------");
    Console.Write("\n\n");  	

    Console.Write("Input starting number of range: ");
    stno = Convert.ToInt32(Console.ReadLine()); 	
    Console.Write("Input ending number of range : ");
    enno = Convert.ToInt32(Console.ReadLine()); 	
    Console.Write("The prime numbers between {0} and {1} are : \n",stno,enno);
  
    for(num = stno;num<=enno;num++)
       {
         ctr = 0;

         for(i=2;i<=num/2;i++)
            {
             if(num%i==0){
                 ctr++;
                 break;
             }
        }
        
         if(ctr==0 && num!= 1)
             Console.Write("{0} ",num);
    }
    Console.Write("\n"); 
  } 
}

Sample Output:

Find the prime numbers within a range of numbers:                                                                                                         
---------------------------------------------------                                                                                                         
Input starting number of range: 1                                                                                                         
Input ending number of range : 50                                                                                                         
The prime numbers between 1 and 50 are :                                                                                                         
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47  

Flowchart:

Flowchart: Find the prime numbers within a range of numbers

C# Sharp Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a C# Sharp Program to display by Pascal's triangle
Next: Write a program in C# Sharp to display the first n terms of Fibonacci series.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.