Write C# program to check whether a number is Prime number or not using while & for loop


Introduction

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.

techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Check whether a number is Prime number or not using while loop

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. public class csharpExercise
  7. {
  8. static void Main(string[] args)
  9. {
  10. int num, i, f;
  11.  
  12. /*Reading number
  13.   */
  14.  
  15. Console.Write("Enter any number: ");
  16. num = Convert.ToInt32(Console.ReadLine());
  17.  
  18. f = 0;
  19. i = 2;
  20. while (i <= num / 2)
  21. {
  22. if (num % i == 0)
  23. {
  24. f = 1;
  25. break;
  26. }
  27. i++;
  28. }
  29. if (f == 0)
  30. Console.WriteLine(num+" is a Prime Number");
  31. else
  32. Console.WriteLine(num + " is not a Prime Number");
  33.  
  34.  
  35. Console.ReadLine();
  36. }
  37. }

Check whether a number is Prime number or not for while loop

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. public class csharpExercise
  7. {
  8. static void Main(string[] args)
  9. {
  10. int num, i, f;
  11.  
  12. /*Reading number
  13.   */
  14.  
  15. Console.Write("Enter any number: ");
  16. num = Convert.ToInt32(Console.ReadLine());
  17.  
  18. f = 0;
  19. for (i = 2; i <= num / 2; i++)
  20. {
  21. if (num % i == 0)
  22. {
  23. f = 1;
  24. break;
  25. }
  26. }
  27. if (f == 0)
  28. Console.WriteLine(num+ " is a Prime Number");
  29. else
  30. Console.WriteLine(num+" is a Not Prime Number");
  31.  
  32. Console.ReadLine();
  33. }
  34. }

Result

C# language techstudy

     





Related Topics




Popular Posts