October 26, 2024
Chicago 12, Melborne City, USA
C#

Using an If statement to find prime numbers


The following is a piece of code that shows an output stating whether a number, entered by a user, is a prime number or not.

#include <stdio.h>
#include <stdlib.h>

int a,b;
int main(void) {

 printf("Enter number: ");
 fflush(stdout);
 scanf("%d",&a);

 for (b = 2; b < a; b++)
 {
   if (a % b == 0)
    break;
 }

 if (b<a)
 {
   printf ("%d is divisible by %d\n", a, b);
 }

 else
 {
   printf ("%d is prime \n", a);
 }
return 0;
}

The piece of code, written above, is not mine and it identifies a prime number successfully everytime (i.e the printf statement of the else clause gets printed).

My understanding of the if statement is that an else clause in an if-else statement belongs to the nearest if statement which doesn’t already have an else clause. And so, having said that, I believe the else clause, in the above piece of code, belongs to the nearest if statement.

My question is this: If the user enters a prime number like 31 or 37 or any other prime number, how does the printf statement of the else clause get printed?
The condition if (b<a) (of the second if statement) will always be true considering that b will only be incremented to (a-1). And so if the user enters the number 31, the variable b will only be incremented to 30. Shouldn’t it be the case that the printf statement of the second if statement gets printed, regardless of whether the number entered by the user is prime or not, considering that the condition if (b<a) will always be true?

How does the above piece of code print all the prime numbers correctly, and therefore, work alright? (when, according to my limited understanding of the way the if statement works, it shouldn’t)



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video