/********************************************************* * From C PROGRAMMING: A MODERN APPROACH, Second Edition * * By K. N. King * * Copyright (c) 2008, 1996 W. W. Norton & Company, Inc. * * All rights reserved. * * This program may be freely distributed for class use, * * provided that this copyright notice is retained. * *********************************************************/ /* prime.c (Chapter 9, page 190) */ /* Tests whether a number is prime */ #include /* Using hard coded numbers in a C progam is a bad practice that should be avoided. Here, we demonstrate that instead of using numebrs 1 and 0, define readable abbreviations. They are much easier to revise, if needed. */ #define TRUE 1 #define FALSE 0 int is_prime(int n) { int divisor; /* This example demonstrates that the body of a function may have more than one return statement. But when this function is called, only one return statement can ever be executed. */ if (n <= 1) return FALSE; for (divisor = 2; divisor * divisor <= n; divisor++) if (n % divisor == 0) { printf("The number %d has divisor %d\n",n,divisor); return FALSE; } return TRUE; } int main(void) { int n; printf("Enter a number: "); scanf("%d", &n); /* Notice that main contains a variable named n even though is_prime's argument is also named n. This is OK since the name of a parameter or a local variable in one function can be freely reused in any other function. */ if (is_prime(n)) printf("Prime\n"); else printf("Not prime\n"); return 0; }